content stringlengths 23 1.05M |
|---|
using Rabbit.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ExceptionLess.WebHook.Abstractions
{
public interface IWebHookProvider : ISingletonDependency
{
string Name { get; }
Task ProcessAsync(ExceptionLessEventModel model, IDictionary<string, string> parameters);
}
} |
using System;
using Xilium.CefGlue;
using Xilium.CefGlue.Common.Handlers;
namespace WebViewControl {
partial class WebView {
private class InternalKeyboardHandler : KeyboardHandler {
private WebView OwnerWebView { get; }
public InternalKeyboardHandler(WebView webView) {
OwnerWebView = webView;
}
protected override bool OnPreKeyEvent(CefBrowser browser, CefKeyEvent keyEvent, IntPtr os_event, out bool isKeyboardShortcut) {
var handler = OwnerWebView.KeyPressed;
if (handler != null && !browser.IsPopup) {
handler(keyEvent, out var handled);
isKeyboardShortcut = false;
return handled;
}
return base.OnPreKeyEvent(browser, keyEvent, os_event, out isKeyboardShortcut);
}
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Xunit;
namespace NuGet.Protocol.Plugins.Tests
{
public class CloseRequestHandlerTests
{
[Fact]
public void Constructor_ThrowsForNullPlugin()
{
var exception = Assert.Throws<ArgumentNullException>(
() => new CloseRequestHandler(plugin: null));
Assert.Equal("plugin", exception.ParamName);
}
[Fact]
public void CancellationToken_IsNone()
{
var handler = new CloseRequestHandler(Mock.Of<IPlugin>());
Assert.Equal(CancellationToken.None, handler.CancellationToken);
}
[Fact]
public void Dispose_DisposesDisposables()
{
using (var test = new CloseRequestHandlerTest())
{
}
}
[Fact]
public void Dispose_IsIdempotent()
{
using (var test = new CloseRequestHandlerTest())
{
test.Handler.Dispose();
test.Handler.Dispose();
}
}
[Fact]
public async Task HandleResponseAsync_ThrowsForNullConnection()
{
using (var test = new CloseRequestHandlerTest())
{
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => test.Handler.HandleResponseAsync(
connection: null,
request: new Message(
requestId: "a",
type: MessageType.Request,
method: MessageMethod.Close,
payload: null),
responseHandler: Mock.Of<IResponseHandler>(),
cancellationToken: CancellationToken.None));
Assert.Equal("connection", exception.ParamName);
}
}
[Fact]
public async Task HandleResponseAsync_ThrowsForNullRequest()
{
using (var test = new CloseRequestHandlerTest())
{
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => test.Handler.HandleResponseAsync(
Mock.Of<IConnection>(),
request: null,
responseHandler: Mock.Of<IResponseHandler>(),
cancellationToken: CancellationToken.None));
Assert.Equal("request", exception.ParamName);
}
}
[Fact]
public async Task HandleResponseAsync_ThrowsForNullResponseHandler()
{
using (var test = new CloseRequestHandlerTest())
{
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => test.Handler.HandleResponseAsync(
Mock.Of<IConnection>(),
new Message(
requestId: "a",
type: MessageType.Request,
method: MessageMethod.Close,
payload: null),
responseHandler: null,
cancellationToken: CancellationToken.None));
Assert.Equal("responseHandler", exception.ParamName);
}
}
[Fact]
public async Task HandleResponseAsync_ThrowsIfCancelled()
{
using (var test = new CloseRequestHandlerTest())
{
await Assert.ThrowsAsync<OperationCanceledException>(
() => test.Handler.HandleResponseAsync(
Mock.Of<IConnection>(),
new Message(
requestId: "a",
type: MessageType.Request,
method: MessageMethod.Close,
payload: null),
Mock.Of<IResponseHandler>(),
new CancellationToken(canceled: true)));
}
}
[Fact]
public async Task HandleResponseAsync_ClosesPlugin()
{
using (var test = new CloseRequestHandlerTest())
{
test.Plugin.Setup(x => x.Close());
await test.Handler.HandleResponseAsync(
Mock.Of<IConnection>(),
new Message(
requestId: "a",
type: MessageType.Request,
method: MessageMethod.Close,
payload: null),
Mock.Of<IResponseHandler>(),
CancellationToken.None);
test.Plugin.Verify(x => x.Close(), Times.Once);
}
}
private sealed class CloseRequestHandlerTest : IDisposable
{
internal CloseRequestHandler Handler { get; }
internal Mock<IPlugin> Plugin { get; }
internal CloseRequestHandlerTest()
{
Plugin = new Mock<IPlugin>(MockBehavior.Strict);
Plugin.Setup(x => x.Dispose());
Handler = new CloseRequestHandler(Plugin.Object);
}
public void Dispose()
{
Handler.Dispose();
GC.SuppressFinalize(this);
Plugin.Verify(x => x.Dispose(), Times.Once);
}
}
}
}
|
using System;
using Il2CppDummyDll;
using UnityEngine;
// Token: 0x020003E3 RID: 995
[Token(Token = "0x20003E3")]
public class HatParent : MonoBehaviour
{
// Token: 0x170002E7 RID: 743
// (get) Token: 0x0600149C RID: 5276 RVA: 0x00002050 File Offset: 0x00000250
// (set) Token: 0x0600149D RID: 5277 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x170002E7")]
public HatBehaviour Hat
{
[Token(Token = "0x600149C")]
[Address(RVA = "0x277A30", Offset = "0x276E30", VA = "0x10277A30")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
get
{
return null;
}
[Token(Token = "0x600149D")]
[Address(RVA = "0x277A50", Offset = "0x276E50", VA = "0x10277A50")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
set
{
}
}
// Token: 0x170002E8 RID: 744
// (set) Token: 0x0600149E RID: 5278 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x170002E8")]
public Color color
{
[Token(Token = "0x600149E")]
[Address(RVA = "0x3BB570", Offset = "0x3BA970", VA = "0x103BB570")]
set
{
}
}
// Token: 0x170002E9 RID: 745
// (set) Token: 0x0600149F RID: 5279 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x170002E9")]
public bool flipX
{
[Token(Token = "0x600149F")]
[Address(RVA = "0x3BB5C0", Offset = "0x3BA9C0", VA = "0x103BB5C0")]
set
{
}
}
// Token: 0x060014A0 RID: 5280 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A0")]
[Address(RVA = "0x3BB1F0", Offset = "0x3BA5F0", VA = "0x103BB1F0")]
public void SetHat(HatBehaviour hat, int color)
{
}
// Token: 0x060014A1 RID: 5281 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A1")]
[Address(RVA = "0x3BB100", Offset = "0x3BA500", VA = "0x103BB100")]
public void SetHat(int color)
{
}
// Token: 0x060014A2 RID: 5282 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A2")]
[Address(RVA = "0x3BB210", Offset = "0x3BA610", VA = "0x103BB210")]
public void SetIdleAnim()
{
}
// Token: 0x060014A3 RID: 5283 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A3")]
[Address(RVA = "0x3BB170", Offset = "0x3BA570", VA = "0x103BB170")]
public void SetHat(string hatId, int color)
{
}
// Token: 0x060014A4 RID: 5284 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A4")]
[Address(RVA = "0x3BB0A0", Offset = "0x3BA4A0", VA = "0x103BB0A0")]
internal void SetFloorAnim()
{
}
// Token: 0x060014A5 RID: 5285 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A5")]
[Address(RVA = "0x3BAFD0", Offset = "0x3BA3D0", VA = "0x103BAFD0")]
internal void SetClimbAnim()
{
}
// Token: 0x060014A6 RID: 5286 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A6")]
[Address(RVA = "0x3BAC10", Offset = "0x3BA010", VA = "0x103BAC10")]
public void LateUpdate()
{
}
// Token: 0x060014A7 RID: 5287 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A7")]
[Address(RVA = "0x3BB030", Offset = "0x3BA430", VA = "0x103BB030")]
internal void SetColor(int color)
{
}
// Token: 0x060014A8 RID: 5288 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A8")]
[Address(RVA = "0x3BB4E0", Offset = "0x3BA8E0", VA = "0x103BB4E0")]
internal void SetMaskLayer(int layer)
{
}
// Token: 0x060014A9 RID: 5289 RVA: 0x00002053 File Offset: 0x00000253
[Token(Token = "0x60014A9")]
[Address(RVA = "0x2E74A0", Offset = "0x2E68A0", VA = "0x102E74A0")]
public HatParent()
{
}
// Token: 0x04001541 RID: 5441
[Token(Token = "0x4001541")]
[FieldOffset(Offset = "0xC")]
public SpriteRenderer BackLayer;
// Token: 0x04001542 RID: 5442
[Token(Token = "0x4001542")]
[FieldOffset(Offset = "0x10")]
public SpriteRenderer FrontLayer;
// Token: 0x04001543 RID: 5443
[Token(Token = "0x4001543")]
[FieldOffset(Offset = "0x14")]
public SpriteRenderer Parent;
// Token: 0x04001544 RID: 5444
[Token(Token = "0x4001544")]
[FieldOffset(Offset = "0x18")]
[Attribute(Name = "CompilerGeneratedAttribute", RVA = "0x952B0", Offset = "0x946B0")]
private HatBehaviour <Hat>k__BackingField;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NDO;
using NDO.Mapping;
using Moq;
namespace NdoDllUnitTests
{
[TestFixture]
public class UpdateRankTests
{
Dictionary<string, Mock<Type>> types = new Dictionary<string,Mock<Type>>();
[Test]
public void TestRank()
{
Type t1;
Type t2;
List<Class> classes = new List<Class>();
Class cls1 = new Class(null);
cls1.FullName = "ShopFachklassen.AllgemeinZugabeGutschein";
t1 = cls1.SystemType = CreateType( cls1.FullName ).Object;
var oid = new ClassOid(cls1);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls1.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls1);
rel1Mock.Setup( t => t.Bidirectional ).Returns( true );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls1.Relations;
relations.Add( relation );
relation.FieldName = "code";
relation.ReferencedTypeName = "ShopFachklassen.GutscheinCode";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls1 );
Class cls2 = new Class(null);
cls2.FullName = "ShopFachklassen.GutscheinCode";
t2 = cls2.SystemType = CreateType( cls2.FullName ).Object;
cls2.Oid = oid;
Mock<Relation>rel2Mock = new Mock<Relation>(cls1);
rel2Mock.Setup( t => t.Bidirectional ).Returns( true );
relation = rel2Mock.Object;
relations = (List<Relation>)cls2.Relations;
relations.Add( relation );
relation.FieldName = "gutschein";
relation.ReferencedTypeName = "ShopFachklassen.Gutschein";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = false;
relation.HasSubclasses = false;
rel1Mock.Setup( r => r.ForeignRelation ).Returns( rel2Mock.Object );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls2 } );
rel2Mock.Setup( r => r.ForeignRelation ).Returns( rel1Mock.Object );
rel2Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls1 } );
classes.Add( cls2 );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[t2] == 0 );
Assert.That( updateRank[t1] == 1 );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[t2] == 0 );
Assert.That( updateRank[t1] == 1 );
}
[Test]
public void TestHttpUtil()
{
string s = "abc/d \\ üÜöÖäÄß";
string encoded = NDO.HttpUtil.HttpUtility.UrlEncode( s );
Assert.AreEqual( s, NDO.HttpUtil.HttpUtility.UrlDecode( encoded ) );
}
[Test]
public void TestRanknDirNoPoly()
{
Type tMitarbeiter;
Type tReise;
List<Class> classes = new List<Class>();
Class cls = new Class(null);
cls.FullName = "Mitarbeiter";
tMitarbeiter = cls.SystemType = CreateType( cls.FullName ).Object;
var oid = new ClassOid(cls);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls);
rel1Mock.Setup( t => t.Bidirectional ).Returns( false );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls.Relations;
relations.Add( relation );
relation.FieldName = "reisen";
relation.ReferencedTypeName = "Reise";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.List;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls );
cls = new Class( null );
cls.FullName = "Reise";
tReise = cls.SystemType = CreateType( cls.FullName ).Object;
oid = new ClassOid( cls );
cls.Oid = oid;
classes.Add( cls );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { classes[1] } );
rel1Mock.Setup( r => r.ForeignRelation ).Returns( (Relation)null );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tReise] == 1 );
Assert.That( updateRank[tMitarbeiter] == 0 );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tReise] == 1 );
Assert.That( updateRank[tMitarbeiter] == 0 );
}
[Test]
public void TestRank1nNoPoly()
{
Type tMitarbeiter;
Type tReise;
List<Class> classes = new List<Class>();
Class cls1 = new Class(null);
cls1.FullName = "Mitarbeiter";
tMitarbeiter = cls1.SystemType = CreateType( cls1.FullName ).Object;
var oid = new ClassOid(null);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls1.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls1);
rel1Mock.Setup( t => t.Bidirectional ).Returns( true );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls1.Relations;
relations.Add( relation );
relation.FieldName = "reisen";
relation.ReferencedTypeName = "Reise";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.List;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls1 );
Class cls2 = new Class( null );
cls2.FullName = "Reise";
tReise = cls2.SystemType = CreateType( cls2.FullName ).Object;
oid = new ClassOid( cls2 );
cls2.Oid = oid;
Mock<Relation> rel2Mock = new Mock<Relation>(cls2);
rel2Mock.Setup( t => t.Bidirectional ).Returns( true );
relation = rel2Mock.Object;
relations = (List<Relation>)cls2.Relations;
relations.Add( relation );
relation.FieldName = "mitarbeiter";
relation.ReferencedTypeName = "Mitarbeiter";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = false;
relation.HasSubclasses = false;
classes.Add( cls2 );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls2 } );
rel1Mock.Setup( r => r.ForeignRelation ).Returns( rel2Mock.Object );
rel2Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls1 } );
rel2Mock.Setup( r => r.ForeignRelation ).Returns( rel1Mock.Object );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tReise] == 1 );
Assert.That( updateRank[tMitarbeiter] == 0 );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tReise] == 1 );
Assert.That( updateRank[tMitarbeiter] == 0 );
}
[Test]
public void TestRank1nNotAutoincremented()
{
Type tMitarbeiter;
Type tReise;
List<Class> classes = new List<Class>();
Class cls1 = new Class(null);
cls1.FullName = "Mitarbeiter";
tMitarbeiter = cls1.SystemType = CreateType( cls1.FullName ).Object;
var oid = new ClassOid(cls1);
// Mitarbeiter ist nicht autoincremented
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = false } );
cls1.Oid = oid;
var oid2 = new ClassOid(null);
oid2.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
Mock<Relation> rel1Mock = new Mock<Relation>(cls1);
rel1Mock.Setup( t => t.Bidirectional ).Returns( true );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls1.Relations;
relations.Add( relation );
relation.FieldName = "reisen";
relation.ReferencedTypeName = "Reise";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.List;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls1 );
Class cls2 = new Class( null );
cls2.FullName = "Reise";
tReise = cls2.SystemType = CreateType( cls2.FullName ).Object;
cls2.Oid = oid2;
Mock<Relation> rel2Mock = new Mock<Relation>(cls2);
rel2Mock.Setup( t => t.Bidirectional ).Returns( true );
relation = rel2Mock.Object;
relations = (List<Relation>) cls2.Relations;
relations.Add( relation );
relation.FieldName = "mitarbeiter";
relation.ReferencedTypeName = "Mitarbeiter";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = false;
relation.HasSubclasses = false;
classes.Add( cls2 );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls2 } );
rel1Mock.Setup( r => r.ForeignRelation ).Returns( rel2Mock.Object );
rel2Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls1 } );
rel2Mock.Setup( r => r.ForeignRelation ).Returns( rel1Mock.Object );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tReise] == 0 );
Assert.That( updateRank[tMitarbeiter] == 1 );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tReise] == 0 );
Assert.That( updateRank[tMitarbeiter] == 1 );
}
[Test]
public void TestRank1nRightPoly()
{
Type tMitarbeiter;
Type tReise;
List<Class> classes = new List<Class>();
Class cls1 = new Class(null);
cls1.FullName = "Mitarbeiter";
tMitarbeiter = cls1.SystemType = CreateType( cls1.FullName ).Object;
var oid = new ClassOid(cls1);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls1.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls1);
rel1Mock.Setup( t => t.Bidirectional ).Returns( true );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls1.Relations;
relations.Add( relation );
relation.FieldName = "reisen";
relation.ReferencedTypeName = "ReiseBase";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.List;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls1 );
Class cls2 = new Class( null );
cls2.FullName = "Reise";
tReise = cls2.SystemType = CreateType( cls2.FullName ).Object;
oid = new ClassOid( cls2 );
cls2.Oid = oid;
Class cls2Base = new Class(null);
cls2Base.FullName = "ReiseBase";
cls2Base.SystemType = CreateType( cls2Base.FullName ).Object;
cls2Base.Oid = oid;
classes.Add( cls2Base );
Mock<Relation> rel2Mock = new Mock<Relation>(cls2);
rel2Mock.Setup( t => t.Bidirectional ).Returns( true );
relation = rel2Mock.Object;
relations = (List<Relation>) cls2.Relations;
relations.Add( relation );
relation.FieldName = "mitarbeiter";
relation.ReferencedTypeName = "Mitarbeiter";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = false;
relation.HasSubclasses = false;
classes.Add( cls2 );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls2, cls2Base } );
rel1Mock.Setup( r => r.ForeignRelation ).Returns( rel2Mock.Object );
rel2Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls1 } );
rel2Mock.Setup( r => r.ForeignRelation ).Returns( rel1Mock.Object );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
int maRank = updateRank[tMitarbeiter];
Assert.That( updateRank[tReise] > maRank );
Assert.That( updateRank[cls2Base.SystemType] > maRank );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
maRank = updateRank[tMitarbeiter];
Assert.That( updateRank[tReise] > maRank );
Assert.That( updateRank[cls2Base.SystemType] > maRank );
}
[Test]
public void TestRank1DirNoPoly()
{
Type tMitarbeiter;
Type tAdresse;
List<Class> classes = new List<Class>();
Class cls1 = new Class(null);
cls1.FullName = "Mitarbeiter";
tMitarbeiter = cls1.SystemType = CreateType( cls1.FullName ).Object;
var oid = new ClassOid(cls1);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls1.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls1);
rel1Mock.Setup( t => t.Bidirectional ).Returns( false );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls1.Relations;
relations.Add( relation );
relation.FieldName = "adresse";
relation.ReferencedTypeName = "Adresse";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls1 );
Class cls2 = new Class( null );
cls2.FullName = "Adresse";
tAdresse = cls2.SystemType = CreateType( cls2.FullName ).Object;
cls2.Oid = oid; // We can use the same oid, since the code asks only for autoincremented columns
classes.Add( cls2 );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls2 } );
rel1Mock.Setup( r => r.ForeignRelation ).Returns( (Relation) null );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tMitarbeiter] == 1 );
Assert.That( updateRank[tAdresse] == 0 );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tMitarbeiter] == 1 );
Assert.That( updateRank[tAdresse] == 0 );
}
[Test]
public void TestRank1DirNotAutoincremented()
{
Type tMitarbeiter;
Type tAdresse;
List<Class> classes = new List<Class>();
Class cls1 = new Class(null);
cls1.FullName = "Mitarbeiter";
tMitarbeiter = cls1.SystemType = CreateType( cls1.FullName ).Object;
var oid = new ClassOid(cls1);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls1.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls1);
rel1Mock.Setup( t => t.Bidirectional ).Returns( false );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls1.Relations;
relations.Add( relation );
relation.FieldName = "adresse";
relation.ReferencedTypeName = "Adresse";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls1 );
Class cls2 = new Class( null );
cls2.FullName = "Adresse";
tAdresse = cls2.SystemType = CreateType( cls2.FullName ).Object;
var oid2 = new ClassOid(cls2);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = false } );
cls2.Oid = oid2;
classes.Add( cls2 );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls2 } );
rel1Mock.Setup( r => r.ForeignRelation ).Returns( (Relation) null );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tMitarbeiter] == 0 );
Assert.That( updateRank[tAdresse] == 1 );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
Assert.That( updateRank[tMitarbeiter] == 0 );
Assert.That( updateRank[tAdresse] == 1 );
}
[Test]
public void TestRank1DirRightPoly()
{
Type tMitarbeiter;
Type tAdresse;
List<Class> classes = new List<Class>();
Class cls1 = new Class(null);
cls1.FullName = "Mitarbeiter";
tMitarbeiter = cls1.SystemType = CreateType( cls1.FullName ).Object;
var oid = new ClassOid(cls1);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls1.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls1);
rel1Mock.Setup( t => t.Bidirectional ).Returns( false );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls1.Relations;
relations.Add( relation );
relation.FieldName = "adresse";
relation.ReferencedTypeName = "AdresseBase";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.Element;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls1 );
Class cls2Base = new Class(null);
cls2Base.FullName = "AdresseBase";
cls2Base.SystemType = CreateType( cls2Base.FullName ).Object;
cls2Base.Oid = oid;
classes.Add( cls2Base );
Class cls2 = new Class( null );
cls2.FullName = "Adresse";
tAdresse = cls2.SystemType = CreateType( cls2.FullName ).Object;
cls2.Oid = oid; // We can use the same oid, since the code asks only for autoincremented columns
classes.Add( cls2 );
rel1Mock.Setup( r => r.ReferencedSubClasses ).Returns( new List<Class> { cls2, cls2Base } );
rel1Mock.Setup( r => r.ForeignRelation ).Returns( (Relation) null );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
int maRank = updateRank[tMitarbeiter];
Assert.That( updateRank[cls2Base.SystemType] < maRank );
Assert.That( updateRank[tAdresse] < maRank );
classes.Reverse();
classRank = new ClassRank();
updateRank = classRank.BuildUpdateRank( classes );
maRank = updateRank[tMitarbeiter];
Assert.That( updateRank[cls2Base.SystemType] < maRank );
Assert.That( updateRank[tAdresse] < maRank );
}
[Test]
public void RankDictionaryWorksWithTheGivenMocks()
{
Type t1;
Type t2;
List<Class> classes = new List<Class>();
// Create two classes with an arbitrary relation
// Class 1
Class cls = new Class(null);
cls.FullName = "Mitarbeiter";
t1 = cls.SystemType = CreateType( cls.FullName ).Object;
var oid = new ClassOid(cls);
oid.OidColumns.Add( new OidColumn( oid ) { AutoIncremented = true } );
cls.Oid = oid;
Mock<Relation> rel1Mock = new Mock<Relation>(cls);
rel1Mock.Setup( t => t.Bidirectional ).Returns( false );
Relation relation = rel1Mock.Object;
List<Relation> relations = (List<Relation>)cls.Relations;
relations.Add( relation );
relation.FieldName = "reisen";
relation.ReferencedTypeName = "Reise";
relation.RelationName = string.Empty;
relation.Multiplicity = RelationMultiplicity.List;
relation.Composition = true;
relation.HasSubclasses = false;
classes.Add( cls );
// Class 2
cls = new Class( null );
cls.FullName = "Reise";
t2 = cls.SystemType = CreateType( cls.FullName ).Object;
cls.Oid = oid;
rel1Mock.Setup( r => r.ForeignRelation ).Returns( (Relation) null );
classes.Add( cls );
ClassRank classRank = new ClassRank();
var updateRank = classRank.BuildUpdateRank( classes );
// Make sure, that the types returned by the list
// are equal to the types we assigned to the Class objects
var list = updateRank.Keys.ToList();
var tx = list[0];
var ty = list[1];
Assert.That( tx.GetHashCode() != ty.GetHashCode() );
Assert.That( !tx.Equals( ty ) );
Assert.That( tx.Equals(t1) && ty.Equals(t2) || tx.Equals( t2 ) && ty.Equals( t1 ) );
Assert.That( !tx.Equals( t1 ) && !ty.Equals( t2 ) || !tx.Equals( t2 ) && !ty.Equals( t1 ) );
// Make sure, that indexing the updateRank dictionary works
int rank = updateRank[t1]; // Will throw an exception, if indexing doesn't work
Assert.That( rank == 0 || rank == 1 ); // Expected result with two classes...
}
public Mock<Type> CreateType( string typeName )
{
if (types.ContainsKey( typeName ))
return types[typeName];
var type = MockType.CreateType( typeName );
types.Add( typeName, type );
return type;
}
[Test]
public void TestRelationEquality()
{
}
[Test]
public void TypeMocksWorkAsExpected()
{
Mock<Type> type = CreateType( "ShopFachklassen.AllgemeinZugabeGutschein" );
Assert.That( type.Object.FullName == "ShopFachklassen.AllgemeinZugabeGutschein" );
Assert.That( type.Object.Name == "AllgemeinZugabeGutschein" );
Mock<Type> type2 = CreateType( type.Object.FullName );
Assert.That( type.Object.Equals( type2.Object ) );
// This expression is used by the .NET Framework's implementation of Equals.
Assert.That( object.ReferenceEquals( type.Object.UnderlyingSystemType, type2.Object.UnderlyingSystemType ) );
}
}
}
|
namespace HaloEzAPI.Abstraction.Enum.Halo5
{
public enum Faction
{
Unknown,
UNSC,
Covenant,
Promethean,
Banished,
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using ZimLabs.TableCreator;
namespace Demo
{
internal static class Program
{
private static void Main()
{
var data = CreateDummyList().OrderByDescending(o => o.Id);
var tableString = data.CreateTable(OutputType.Default, true);
Console.WriteLine(tableString);
Console.WriteLine("");
Console.WriteLine("Done");
Console.ReadLine();
}
private static IEnumerable<Person> CreateDummyList()
{
var filePath = Path.GetFullPath("MOCK_DATA.json");
var content = File.ReadAllText(filePath, Encoding.UTF8);
return JsonConvert.DeserializeObject<List<Person>>(content);
}
public static IReadOnlyCollection<Person> CreateErrorList()
{
return new List<Person>
{
new Person
{
Id = 1,
Name = "Andreas",
Mail = "Test@test.mail",
Birthday = new DateTime(1985, 7, 12)
}
};
}
}
internal sealed class Person
{
[Appearance(TextAlign = TextAlign.Right)]
public int Id { get; set; }
[Appearance(Name = "First name")]
public string Name { get; set; }
[Appearance(Name = "Last name")]
public string LastName { get; set; }
[Appearance(Name = "E-Mail")]
public string Mail { get; set; }
[Appearance(Ignore = true)]
public string Gender { get; set; }
public string JobTitle { get; set; }
[Appearance(Format = "yyyy-MM-dd")]
public DateTime Birthday { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StadisticsGUI : MonoBehaviour
{
public TMPro.TextMeshProUGUI FoodGUI;
public TMPro.TextMeshProUGUI LifeGUI;
}
|
#region License
/* **************************************************************************************
* Copyright (c) Librame Pong All rights reserved.
*
* https://github.com/librame
*
* You must not remove this notice, or any other, from this software.
* **************************************************************************************/
#endregion
using RulesEngine.Interfaces;
using System.Linq;
using System.Text.Json.Serialization;
namespace Teaching.Partner
{
/// <summary>
/// 规则选项。
/// </summary>
public class RuleOptions
{
/// <summary>
/// 规则名称。
/// </summary>
public string? Name { get; set; }
/// <summary>
/// 文件名称。
/// </summary>
public string? FileName { get; set; }
/// <summary>
/// 支持的文件扩展名集合。
/// </summary>
public string? SupportedFileExtensions { get; set; }
/// <summary>
/// 规则引擎对象。
/// </summary>
[JsonIgnore]
public IRulesEngine? Engine { get; set; }
/// <summary>
/// 是否为支持的文件扩展名。
/// </summary>
/// <param name="extension">给定的文件扩展名。</param>
/// <returns>返回布尔值。</returns>
public bool IsSupportedFileExtension(string extension)
#pragma warning disable CS8629 // 可为 null 的值类型可为 null。
=> (bool)SupportedFileExtensions?.Split(',').Contains(extension);
#pragma warning restore CS8629 // 可为 null 的值类型可为 null。
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlaynitePersistPlugin.Providers
{
/// <summary>
/// Cloud Provider Interface.
/// </summary>
public interface ICloudProvider
{
/// <summary>
/// Connect to the cloud provider.
/// </summary>
void Connect();
/// <summary>
/// Sync games data to provider.
/// </summary>
/// <param name="archiveFile">The archive of games data.</param>
void SyncTo(string path, string archiveFile);
/// <summary>
/// Get games data from provider.
/// </summary>
/// <param name="archiveFile">The archive of games data.</param>
/// <param name="downloadPath">The location to download the games archive to.</param>
void SyncFrom(string archiveFile, string downloadPath);
}
}
|
using System;
using UnityEditor.Experimental.GraphView;
namespace PeartreeGames.EvtGraph.Editor
{
public class EvtNode : Node
{
public Guid ID;
}
} |
using System;
namespace Jinaga.Definitions
{
public abstract class Chain
{
public abstract bool IsTarget { get; }
public abstract SetDefinition TargetSetDefinition { get; }
public abstract string SourceFactType { get; }
public abstract string TargetFactType { get; }
public abstract Type SourceType { get; }
}
public class ChainStart : Chain
{
private readonly SetDefinition setDefinition;
public ChainStart(SetDefinition setDefinition)
{
this.setDefinition = setDefinition;
}
public override bool IsTarget => setDefinition is SetDefinitionTarget;
public override SetDefinition TargetSetDefinition => setDefinition;
public override string SourceFactType => setDefinition.FactType;
public override string TargetFactType => setDefinition.FactType;
public override Type SourceType => setDefinition.Type;
public override string ToString()
{
return "start";
}
}
public class ChainRole : Chain
{
private readonly Chain prior;
private readonly string role;
private readonly string targetFactType;
public ChainRole(Chain prior, string role, string targetFactType)
{
this.prior = prior;
this.role = role;
this.targetFactType = targetFactType;
}
public Chain Prior => prior;
public string Role => role;
public override bool IsTarget => prior.IsTarget;
public override SetDefinition TargetSetDefinition => prior.TargetSetDefinition;
public override string SourceFactType => prior.SourceFactType;
public override string TargetFactType => targetFactType;
public override Type SourceType => prior.SourceType;
public override string ToString()
{
return $"{prior}.{role}";
}
}
} |
using System;
namespace Modulr.Models;
[Flags]
public enum Role
{
User = 0, // Redundant.
Admin = 1,
Banned = 2
} |
// Copyright © Conatus Creative, Inc. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE.md in the project root for license terms.
using System;
using Pixel3D.P2P.Diagnostics;
namespace Pixel3D.Network.Test
{
internal class ConsoleLogHandler : NetworkLogHandler
{
public override void HandleLidgrenMessage(string message)
{
var fgc = Console.ForegroundColor;
var bgc = Console.BackgroundColor;
Console.ForegroundColor = ConsoleColor.Gray;
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.WriteLine(message);
Console.ForegroundColor = fgc;
Console.BackgroundColor = bgc;
}
public override void HandleMessage(string message)
{
var fgc = Console.ForegroundColor;
var bgc = Console.BackgroundColor;
Console.ForegroundColor = ConsoleColor.Gray;
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.WriteLine(message);
Console.ForegroundColor = fgc;
Console.BackgroundColor = bgc;
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using HelpScout.Conversations;
using HelpScout.Conversations.Models.Create;
using Xunit;
using Xunit.Abstractions;
using ConversationStatus = HelpScout.Conversations.ConversationStatus;
namespace HelpScout.Tests.Conversations
{
[Collection("HelpScout collection")]
public class ConversationEndpointTests : EndpointTestBase
{
public ConversationEndpointTests(HelpScoutClientFixture setup, ITestOutputHelper helper) : base(setup, helper)
{
conversationEndpoint = Client.Conversations;
}
private readonly ConversationEndpoint conversationEndpoint;
private static ConversationSearchQuery CreateSearchCriteria()
{
var query = new ConversationSearchQuery
{
MailBoxs = {Constants.MailBoxId.ToString()},
Status = ConversationStatus.Pending,
SortField = ConversationSortField.CreatedAt
};
return query;
}
[Fact]
public async Task Getting_conversation_from_invalid_id_should_throw_Exception()
{
await Assert.ThrowsAsync<HelpScoutException>(() => conversationEndpoint.Get(1254444455));
}
[Fact]
public async Task Should_be_able_to_create_conversation_and_delete()
{
var req = Setup.ConversationCreateRequest();
req.Customer.Email = Setup.Faker.Internet.Email();
req.Type = ConversationType.Email;
req.Tags = new List<string> {"test-1"};
req.Status = HelpScout.Conversations.Models.Create.ConversationStatus.Pending;
var id = await conversationEndpoint.Create(req);
var actual = await conversationEndpoint.Get(id);
Assert.Contains(actual.Tags, a => a.Tag == "test-1");
Assert.Equal(req.Subject, actual.Subject);
Assert.Equal("email", actual.Type);
Assert.Equal(req.MailboxId, actual.MailboxId);
Assert.Equal("pending", actual.Status);
await conversationEndpoint.Delete(id);
Assert.True(true);
}
[Fact]
public async Task Should_have_some_conversation_or_no_Conversation()
{
var result = await conversationEndpoint.List(CreateSearchCriteria());
Assert.True(result.Size == 50);
}
}
} |
using Microsoft.EntityFrameworkCore;
namespace TPHWithConventions
{
public class BankContext : DbContext
{
private const string ConnectionString = @"server=(localdb)\MSSQLLocalDb;" +
"Database=ThriveLocalBank;Trusted_Connection=True";
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(ConnectionString);
}
public DbSet<Payment> Payments { get; set; } = default!;
public DbSet<CreditcardPayment> CreditcardPayments { get; set; } = default!;
public DbSet<CashPayment> CashPayments { get; set; } = default!;
}
}
|
using DTStacks.DataType.Templates;
namespace DTStacks.DataType.ROS.Messages.sensor_msgs
{
[System.Serializable]
public class RegionOfInterest : Message
{
public uint x_offset;
public uint y_offset;
public uint height;
public uint width;
public bool do_rectify;
}
}
|
using System.Collections.Generic;
namespace BcGov.Fams3.SearchApi.Contracts.PersonSearch
{
public interface PersonSearchRejected : PersonSearchAdapterEvent
{
IEnumerable<ValidationResult> Reasons { get; }
}
} |
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
namespace Midnight.Core
{
[System.Serializable]
public class ActionEvent : UnityEvent<float> { }
public class GameAction : MonoBehaviour
{
[SerializeField] UnityEvent onStart;
[SerializeField] ActionEvent onProgress;
[SerializeField] ActionEvent onEnd;
[SerializeField] ActionEvent onCancel;
public Coroutine StartAction(Func<bool> shouldContinue, float maxDuration = 0)
{
onStart.Invoke();
return StartCoroutine(HandleHold(shouldContinue, maxDuration));
}
private IEnumerator HandleHold(Func<bool> shouldContinue, float maxDuration)
{
float progress = 0;
while (shouldContinue() && progress < maxDuration)
{
progress += 1f;
onProgress.Invoke(progress / maxDuration);
yield return new WaitForEndOfFrame();
}
if (progress < maxDuration)
{
onCancel.Invoke(progress);
}
else
{
onEnd.Invoke(progress);
}
}
private bool Noop() { return false; }
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="//fonts.googleapis.com/css?family=Open+Sans:400,300,700" rel="stylesheet" type="text/css"/>
<link href="~/Content/app.css" rel="stylesheet"/>
</head>
<body ng-app="app">
@RenderBody()
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
@RenderSection("Scripts", required: false)
<script src="~/Scripts/libs/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/libs/angular.min.js"></script>
<script src="~/Scripts/libs/angular-route.min.js"></script>
<script src="~/Scripts/app/directives/search-panel-directive.js"></script>
<script src="~/Scripts/app/services/search-service.js"></script>
<script src="~/Scripts/app/app-config.js"></script>
<script src="~/Scripts/app/controllers/home-controller.js"></script>
<script src="~/Scripts/app/app.js"></script>
</body>
</html>
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BracedFramework
{
public class Openable : MonoBehaviour
{
public Animator Animator;
[ReadOnly] [SerializeField] bool _isOpen = false;
public bool IsOpen { get => _isOpen; private set => _isOpen = value; }
public void Close()
{
Animator.SetTrigger("Close");
IsOpen = false;
}
public void Open()
{
Animator.SetTrigger("Open");
IsOpen = true;
}
}
} |
using EMS.Event_Services.API.Context.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace EMS.Event_Services.API.Context.EntityConfigurations
{
class InstructorForEventsEntityTypeConfiguration
: IEntityTypeConfiguration<InstructorForEvent>
{
public void Configure(EntityTypeBuilder<InstructorForEvent> builder)
{
builder.ToTable("InstructorForEvent");
builder.HasKey(ci => new { ci.EventId, ci.InstructorId });
builder.HasOne(bc => bc.Event)
.WithMany(b => b.InstructorForEvents)
.HasForeignKey(bc => bc.EventId)
.OnDelete(DeleteBehavior.NoAction);
builder.HasOne(bc => bc.Instructor)
.WithMany(c => c.InstructorForEvents)
.HasForeignKey(bc => bc.InstructorId)
.OnDelete(DeleteBehavior.NoAction);
}
}
} |
using System;
public class LocalConfigManager : ILocalConfigManamger
{
public void SaveValue(string key, float value)
{
_SaveValue(key, value);
}
public void SaveValue(string key, string value)
{
_SaveValue(key, value);
}
public void SaveValue(string key, int value)
{
_SaveValue(key, value);
}
public float LoadValue(string key, float defaultValue)
{
return _LoadValue(key, defaultValue);
}
public string LoadValue(string key, string defaultValue)
{
return _LoadValue(key, defaultValue);
}
public int LoadValue(string key, int defaultValue)
{
return _LoadValue(key, defaultValue);
}
public void DeleteValue(string key)
{
_DeleteValue(key);
}
public void SaveImmediately()
{
UnityEngine.PlayerPrefs.Save ();
}
private void _SaveValue(string key, float value)
{
if (value.Equals(UnityEngine.PlayerPrefs.GetFloat(key))) { return; }
IsModify = true;
UnityEngine.PlayerPrefs.SetFloat(key, value);
}
private void _SaveValue(string key, string value)
{
if (value.Equals(UnityEngine.PlayerPrefs.GetString(key))) { return; }
IsModify = true;
UnityEngine.PlayerPrefs.SetString(key, value);
}
private void _SaveValue(string key, int value)
{
if (value.Equals(UnityEngine.PlayerPrefs.GetInt(key))) { return; }
IsModify = true;
UnityEngine.PlayerPrefs.SetInt(key, value);
}
private float _LoadValue(string key, float defaultValue)
{
return UnityEngine.PlayerPrefs.GetFloat(key, defaultValue);
}
private string _LoadValue(string key, string defaultValue)
{
return UnityEngine.PlayerPrefs.GetString(key, defaultValue);
}
private int _LoadValue(string key, int defaultValue)
{
return UnityEngine.PlayerPrefs.GetInt(key, defaultValue);
}
private void _DeleteValue(string key)
{
UnityEngine.PlayerPrefs.DeleteKey(key);
}
public bool IsInited { get { return true; } }
public bool IsModify { set { bModify = value; } get { return bModify; }}
private bool bModify = false;
} |
using System;
namespace Hikipuro.Text.Tokenizer {
/// <summary>
/// トークン 1 つ分.
/// </summary>
/// <typeparam name="TokenType">トークンの種類.</typeparam>
public class Token<TokenType> where TokenType : struct {
/// <summary>
/// トークンの種類.
/// </summary>
public TokenType Type;
/// <summary>
/// マッチしたテキスト.
/// </summary>
public string Text;
/// <summary>
/// マッチした文字列の位置.
/// </summary>
public int Index;
/// <summary>
/// マッチした文字列の行番号.
/// </summary>
public int LineNumber;
/// <summary>
/// 行の文字位置.
/// </summary>
public int LineIndex;
/// <summary>
/// 追加されたリスト.
/// </summary>
public TokenList<TokenType> TokenList;
/// <summary>
/// タグ.
/// ユーザー側でトークンに目印を付けるために使用する.
/// ライブラリ側では値をセットしない.
/// </summary>
public object Tag;
/// <summary>
/// 加工前のマッチした文字列.
/// </summary>
string rawText;
/// <summary>
/// 加工前のマッチした文字列 (読み取り専用).
/// </summary>
public string RawText {
get { return rawText; }
}
/// <summary>
/// マッチしたテキストの長さ.
/// </summary>
public int Length {
get { return Text.Length; }
}
/// <summary>
/// Index + Length の位置.
/// </summary>
public int RightIndex {
get { return Index + Text.Length; }
}
/// <summary>
/// LineIndex + Length の位置.
/// </summary>
public int RightLineIndex {
get { return LineIndex + Text.Length; }
}
/// <summary>
/// このトークンが, リスト内の最後の要素かチェックする.
/// </summary>
public bool IsLast {
get {
if (TokenList == null) {
return false;
}
return TokenList.Last(0) == this;
}
}
/// <summary>
/// 1 つ次の要素を取得する.
/// </summary>
/// <returns>1 つ次の要素.</returns>
public Token<TokenType> Next {
get {
if (TokenList == null) {
return null;
}
return TokenList.Next(this);
}
}
/// <summary>
/// 1 つ前の要素を取得する.
/// </summary>
/// <returns>1 つ前の要素.</returns>
public Token<TokenType> Prev {
get {
if (TokenList == null) {
return null;
}
return TokenList.Prev(this);
}
}
/// <summary>
/// TokenMatch オブジェクトから Token オブジェクトを作成する.
/// </summary>
/// <param name="tokenMatch">作成元の TokenMatch オブジェクト.</param>
/// <returns>Token オブジェクト.</returns>
public static Token<TokenType> FromTokenMatch(TokenMatch<TokenType> tokenMatch) {
Token<TokenType> token = new Token<TokenType>(tokenMatch.RawText);
token.Type = tokenMatch.Type;
token.Text = tokenMatch.Text;
token.Index = tokenMatch.Index;
token.LineNumber = tokenMatch.LineNumber;
token.LineIndex = tokenMatch.LineIndex;
return token;
}
/// <summary>
/// コンストラクタ.
/// </summary>
public Token() {
}
/// <summary>
/// コンストラクタ.
/// </summary>
/// <param name="text">マッチした文字列.</param>
public Token(string text) {
rawText = text;
this.Text = text;
}
/// <summary>
/// デストラクタ.
/// </summary>
~Token() {
TokenList = null;
Tag = null;
}
/// <summary>
/// このトークンが, 引数で指定された種類と一致するかチェックする.
/// </summary>
/// <param name="tokenType">トークンの種類.</param>
/// <returns>true: 一致, false: 一致しない.</returns>
public bool IsTypeOf(TokenType tokenType) {
return Type.Equals(tokenType);
}
/// <summary>
/// このトークンが, 引数で指定されたグループに属するかチェックする.
/// </summary>
/// <param name="tokenTypeGroup">チェックするグループ.</param>
/// <returns>true: 属している, false: 属していない.</returns>
public bool IsMemberOf(TokenTypeGroup<TokenType> tokenTypeGroup) {
if (tokenTypeGroup == null) {
return false;
}
return tokenTypeGroup.Contains(Type);
}
/// <summary>
/// 開始位置同士の距離を文字数で取得する.
/// </summary>
/// <param name="token">比較用のトークン.</param>
/// <returns>文字数.</returns>
public int GetDistance(Token<TokenType> token) {
return Math.Abs(Index - token.Index);
}
/// <summary>
/// このトークンの位置が, 引数で指定されたトークンよりも前にあるかチェックする.
/// </summary>
/// <param name="token">比較用のトークン.</param>
/// <returns>true: 前にある, false: 後ろにある.</returns>
public bool IsBefore(Token<TokenType> token) {
return Index < token.Index;
}
/// <summary>
/// このトークンの位置が, 引数で指定されたトークンよりも後にあるかチェックする.
/// </summary>
/// <param name="token">比較用のトークン.</param>
/// <returns>true: 後ろにある, false: 前にある.</returns>
public bool IsAfter(Token<TokenType> token) {
return Index > token.Index;
}
/// <summary>
/// このトークンの位置が, 引数で指定されたトークンと隣接しているかチェックする.
/// </summary>
/// <param name="token">比較用のトークン.</param>
/// <returns>true: 隣接している, false: 隣接していない.</returns>
public bool IsNeighbor(Token<TokenType> token) {
if (this.IsBefore(token)) {
return Index + RawText.Length == token.Index;
}
return token.Index + token.RawText.Length == Index;
}
}
}
|
namespace Juce.Core.Factories
{
public interface IFactory<TDefinition, TCreation>
{
bool TryCreate(TDefinition definition, out TCreation creation);
}
}
|
/*
* Copyright 2022 Rapid Software LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*
*
* Product : Rapid SCADA
* Module : ScadaAdminCommon
* Summary : Represents an instance that includes of one or more applications
*
* Author : Mikhail Shiryaev
* Created : 2018
* Modified : 2021
*/
using Scada.Admin.Lang;
using System;
using System.IO;
using System.Linq;
using System.Xml;
namespace Scada.Admin.Project
{
/// <summary>
/// Represents an instance that includes of one or more applications.
/// <para>Представляет экземпляр, включающий из одно или несколько приложений.</para>
/// </summary>
public class ProjectInstance
{
/// <summary>
/// The default instance name.
/// </summary>
public const string DefaultName = "Default";
private string instanceDir; // the instance directory inside the project
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
public ProjectInstance()
{
ID = 0;
Name = "";
ServerApp = new ServerApp();
CommApp = new CommApp();
WebApp = new WebApp();
AllApps = new ProjectApp[] { ServerApp, CommApp, WebApp };
DeploymentProfile = "";
InstanceDir = "";
}
/// <summary>
/// Gets or sets the instance identifier.
/// </summary>
public int ID { get; set; }
/// <summary>
/// Gets or sets the name of the instance.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets the Server application in the project.
/// </summary>
public ServerApp ServerApp { get; }
/// <summary>
/// Gets the Communicator application in the project.
/// </summary>
public CommApp CommApp { get; }
/// <summary>
/// Gets the Webstation application in the project.
/// </summary>
public WebApp WebApp { get; }
/// <summary>
/// Gets all applications in the project.
/// </summary>
public ProjectApp[] AllApps { get; }
/// <summary>
/// Gets or sets the name of the deployment profile.
/// </summary>
public string DeploymentProfile { get; set; }
/// <summary>
/// Gets or sets the instance directory inside the project.
/// </summary>
public string InstanceDir
{
get
{
return instanceDir;
}
set
{
instanceDir = ScadaUtils.NormalDir(value);
Array.ForEach(AllApps, app => app.InitAppDir(instanceDir));
}
}
/// <summary>
/// Gets or sets a value indicating whether all the application configurations are loaded.
/// </summary>
public bool ConfigLoaded
{
get
{
return AllApps.All(app => !app.Enabled || app.ConfigLoaded);
}
set
{
foreach (ProjectApp app in AllApps)
{
app.ConfigLoaded = value;
}
}
}
/// <summary>
/// Loads the instance configuration from the XML node.
/// </summary>
public void LoadFromXml(XmlNode xmlNode)
{
if (xmlNode == null)
throw new ArgumentNullException(nameof(xmlNode));
ID = xmlNode.GetChildAsInt("ID");
Name = xmlNode.GetChildAsString("Name");
if (xmlNode.SelectSingleNode("ServerApp") is XmlElement serverAppElem)
ServerApp.LoadFromXml(serverAppElem);
if (xmlNode.SelectSingleNode("CommApp") is XmlElement commAppElem)
CommApp.LoadFromXml(commAppElem);
if (xmlNode.SelectSingleNode("WebApp") is XmlElement webAppElem)
WebApp.LoadFromXml(webAppElem);
DeploymentProfile = xmlNode.GetChildAsString("DeploymentProfile");
}
/// <summary>
/// Saves the instance configuration into the XML node.
/// </summary>
public void SaveToXml(XmlElement xmlElem)
{
if (xmlElem == null)
throw new ArgumentNullException(nameof(xmlElem));
xmlElem.AppendElem("ID", ID);
xmlElem.AppendElem("Name", Name);
ServerApp.SaveToXml(xmlElem.AppendElem("ServerApp"));
CommApp.SaveToXml(xmlElem.AppendElem("CommApp"));
WebApp.SaveToXml(xmlElem.AppendElem("WebApp"));
xmlElem.AppendElem("DeploymentProfile", DeploymentProfile);
}
/// <summary>
/// Loads configuration of all the applications if needed.
/// </summary>
public bool LoadAppConfig(out string errMsg)
{
foreach (ProjectApp app in AllApps)
{
if (app.Enabled && !(app.ConfigLoaded || app.LoadConfig(out errMsg)))
return false;
}
errMsg = "";
return true;
}
/// <summary>
/// Creates all project files required for the instance.
/// </summary>
public bool CreateInstanceFiles(out string errMsg)
{
try
{
Directory.CreateDirectory(InstanceDir);
foreach (ProjectApp app in AllApps)
{
if (app.Enabled && !app.CreateConfigFiles(out errMsg))
return false;
}
errMsg = "";
return true;
}
catch (Exception ex)
{
errMsg = ex.BuildErrorMessage(AdminPhrases.CreateInstanceFilesError);
return false;
}
}
/// <summary>
/// Deletes all project files of the instance.
/// </summary>
public bool DeleteInstanceFiles(out string errMsg)
{
try
{
if (Directory.Exists(InstanceDir))
Directory.Delete(InstanceDir, true);
errMsg = "";
return true;
}
catch (Exception ex)
{
errMsg = ex.BuildErrorMessage(AdminPhrases.DeleteInstanceFilesError);
return false;
}
}
/// <summary>
/// Renames the instance.
/// </summary>
public bool Rename(string newName, out string errMsg)
{
try
{
if (string.IsNullOrEmpty(newName))
throw new ArgumentException(AdminPhrases.InstanceNameEmpty, nameof(newName));
if (!AdminUtils.NameIsValid(newName))
throw new ArgumentException(AdminPhrases.InstanceNameInvalid, nameof(newName));
DirectoryInfo directoryInfo = new(InstanceDir);
string newInstanceDir = Path.Combine(directoryInfo.Parent.FullName, newName);
directoryInfo.MoveTo(newInstanceDir);
InstanceDir = newInstanceDir;
Name = newName;
errMsg = "";
return true;
}
catch (Exception ex)
{
errMsg = ex.BuildErrorMessage(AdminPhrases.RenameInstanceError);
return false;
}
}
}
}
|
[CompilerGeneratedAttribute] // RVA: 0x15A130 Offset: 0x15A231 VA: 0x15A130
private sealed class MonsterHutManager.<>c__DisplayClass14_0 // TypeDefIndex: 9942
{
// Fields
public int j; // 0x10
// Methods
// RVA: 0x2177270 Offset: 0x2177371 VA: 0x2177270
public void .ctor() { }
// RVA: 0x2178830 Offset: 0x2178931 VA: 0x2178830
internal bool <SetMonsterHutMonsterData>b__0(FriendMonsterIDAndHouseID dat) { }
}
|
//
// Synuit.Blockchain.Api - Blockchain/Cryptocurrency Api's for .NET
// Copyright © 2017-2018 Synuit Software. All Rights Reserved.
//
using System;
//
namespace Synuit.Blockchain.Api.Coin.Exceptions
{
[Serializable]
public class CoinApiException : Exception
{
public CoinApiException(string message) : base(message) { }
}
}
|
using System;
using System.Diagnostics;
using NTFSLib.Objects.Enums;
namespace NTFSLib.Objects.Attributes
{
public class AttributeVolumeInformation : Attribute
{
public ulong Reserved { get; set; }
public byte MajorVersion { get; set; }
public byte MinorVersion { get; set; }
public VolumeInformationFlags VolumeInformationFlag { get; set; }
public override AttributeResidentAllow AllowedResidentStates
{
get
{
return AttributeResidentAllow.Resident;
}
}
internal override void ParseAttributeResidentBody(byte[] data, int maxLength, int offset)
{
base.ParseAttributeResidentBody(data, maxLength, offset);
Debug.Assert(maxLength >= 16);
Reserved = BitConverter.ToUInt64(data, offset);
MajorVersion = data[offset + 8];
MinorVersion = data[offset + 9];
VolumeInformationFlag = (VolumeInformationFlags)BitConverter.ToUInt16(data, offset + 10);
}
}
} |
using System;
using System.Net;
using System.Text;
namespace KodiAndroid.Logic.Service
{
public class HttpClientService
{
public string PostReqest(string file, string url)
{
var wc = new WebClient();
string responseString;
try
{
var dataBytes = Encoding.UTF8.GetBytes(file);
var responseBytes = wc.UploadData(new Uri(url), "POST", dataBytes);
responseString = Encoding.UTF8.GetString(responseBytes);
}
catch (WebException ex)
{
if (ex.Status != WebExceptionStatus.ProtocolError)
{
responseString = ex.Message;
}
else
{
responseString = "Status Code : " + ((HttpWebResponse) ex.Response).StatusCode +
"Status Description " + ((HttpWebResponse) ex.Response).StatusDescription;
}
}
finally
{
wc.Dispose();
}
return responseString;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BusinessObjects;
using BusinessObjects.Table;
using System.Data.Objects.DataClasses;
using Facade.Table;
namespace Controllers.Models
{
public class FillMasterPageViewData : ActionFilterAttribute
{
private ModelEntities modelEntities = new ModelEntities();
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.HttpContext.Session == null) return;
var curPageId = String.IsNullOrEmpty(filterContext.HttpContext.Session["PageId"].ToString())
? 1 : int.Parse(filterContext.HttpContext.Session["PageId"].ToString());
var result = filterContext.Result as ViewResult;
if (result == null) return;
FillMainMenu(result);
FillEvents(result);
FillBanners(result, curPageId);
FillSubMenu(result, curPageId);
base.OnActionExecuted(filterContext);
}
private void FillSubMenu(ViewResult result, int curPageId)
{
IQueryable<MenuAndPage> pages = modelEntities.MenuAndPages.Select(m => m).Where(m => m.Id == curPageId);
foreach (MenuAndPage page in pages)
{
EntityCollection<MenuAndPage> subPages = page.SubPages;
IOrderedEnumerable<MenuAndPage> subPagesQuery = subPages.Select(m => m).OrderBy(m => m.MenuSortOrder);
result.ViewData["SubMenu"] = subPagesQuery;
result.ViewData["Message"] = page.Text;
result.ViewData["Title"] = page.Title;
break;
}
}
private void FillEvents(ViewResult result)
{
IQueryable<News> events = modelEntities.News.Where(n => n.NewsCategory.Id == 2);
result.ViewData["Events"] = events;
}
private void FillMainMenu(ViewResult result)
{
IQueryable<MenuAndPage> allPages = modelEntities.MenuAndPages.Select(m => m).OrderBy(m => m.MenuSortOrder);
result.ViewData["MainMenu"] = allPages;
}
private void FillBanners(ViewResult result, int curPageId)
{
Many2ManyLinkFacade m2MFacade = new Many2ManyLinkFacade();
List<Many2ManyLink> m2mLinkList = m2MFacade.GetMany2ManyLinkList("MenuAndPages");
foreach (Many2ManyLink m2ml in m2mLinkList)
{
if (m2ml.LinkedTableName == "Banners")
{
result.ViewData["Banners"] = m2MFacade.GetLinkedTableData(m2ml, curPageId.ToString());
}
}
}
}
}
|
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is AgateLib.
//
// The Initial Developer of the Original Code is Erik Ylvisaker.
// Portions created by Erik Ylvisaker are Copyright (C) 2006-2009.
// All Rights Reserved.
//
// Contributor(s): Erik Ylvisaker
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using AgateLib.Geometry;
namespace AgateLib.BitmapFont
{
/// <summary>
/// FontMetrics is a class which describes everything needed to render a font
/// from a bitmap image.
/// </summary>
public sealed class FontMetrics : IDictionary<char, GlyphMetrics>, ICloneable
{
Dictionary<char, GlyphMetrics> mGlyphs = new Dictionary<char, GlyphMetrics>();
/// <summary>
/// Constructs an empty font metrics object.
/// </summary>
public FontMetrics()
{ }
/// <summary>
/// Performs a deep copy.
/// </summary>
/// <returns></returns>
public FontMetrics Clone()
{
FontMetrics retval = new FontMetrics();
foreach (KeyValuePair<char, GlyphMetrics> v in this.mGlyphs)
{
retval.Add(v.Key, v.Value.Clone());
}
return retval;
}
#region IDictionary<char,GlyphMetrics> Members
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Add(char key, GlyphMetrics value)
{
mGlyphs.Add(key, value);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool ContainsKey(char key)
{
return mGlyphs.ContainsKey(key);
}
/// <summary>
///
/// </summary>
public ICollection<char> Keys
{
get { return mGlyphs.Keys; }
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Remove(char key)
{
return mGlyphs.Remove(key);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool TryGetValue(char key, out GlyphMetrics value)
{
return mGlyphs.TryGetValue(key, out value);
}
/// <summary>
/// Returns a collection of the value.
/// </summary>
public ICollection<GlyphMetrics> Values
{
get { return mGlyphs.Values; }
}
/// <summary>
/// Returns a specified glyph metrics.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public GlyphMetrics this[char key]
{
get
{
return mGlyphs[key];
}
set
{
mGlyphs[key] = value;
}
}
#endregion
#region ICollection<KeyValuePair<char,GlyphMetrics>> Members
void ICollection<KeyValuePair<char, GlyphMetrics>>.Add(KeyValuePair<char, GlyphMetrics> item)
{
((ICollection<KeyValuePair<char, GlyphMetrics>>)mGlyphs).Add(item);
}
/// <summary>
/// Clears the list.
/// </summary>
public void Clear()
{
mGlyphs.Clear();
}
bool ICollection<KeyValuePair<char, GlyphMetrics>>.Contains(KeyValuePair<char, GlyphMetrics> item)
{
return ((ICollection<KeyValuePair<char, GlyphMetrics>>)mGlyphs).Contains(item);
}
void ICollection<KeyValuePair<char, GlyphMetrics>>.CopyTo(KeyValuePair<char, GlyphMetrics>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<char, GlyphMetrics>>)mGlyphs).CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns the number of glyphs.
/// </summary>
public int Count
{
get { return mGlyphs.Count; }
}
bool ICollection<KeyValuePair<char, GlyphMetrics>>.IsReadOnly
{
get { return false; }
}
bool ICollection<KeyValuePair<char, GlyphMetrics>>.Remove(KeyValuePair<char, GlyphMetrics> item)
{
return ((ICollection<KeyValuePair<char, GlyphMetrics>>)mGlyphs).Remove(item);
}
#endregion
#region IEnumerable<KeyValuePair<char,GlyphMetrics>> Members
/// <summary>
/// Creates an enumerator.
/// </summary>
/// <returns></returns>
public IEnumerator<KeyValuePair<char, GlyphMetrics>> GetEnumerator()
{
return mGlyphs.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
private void ReadGlyphs030(XmlNode rootNode)
{
foreach (XmlNode node in rootNode.ChildNodes)
{
GlyphMetrics glyph = new GlyphMetrics();
char key = (char)int.Parse(node.Attributes["Char"].Value);
glyph.SourceRect = Rectangle.Parse(node.Attributes["Source"].Value);
glyph.LeftOverhang = GetAttributeInt32(node, "LeftOverhang");
glyph.RightOverhang = GetAttributeInt32(node, "RightOverhang");
mGlyphs.Add(key, glyph);
}
}
private int GetAttributeInt32(XmlNode node, string p)
{
if (node[p] == null)
return 0;
return int.Parse(node[p].Value);
}
private static void AddAttribute(XmlDocument doc, XmlNode current, string name, int value)
{
XmlAttribute att = doc.CreateAttribute(name);
att.Value = value.ToString();
current.Attributes.Append(att);
}
private static void AddAttribute(XmlDocument doc, XmlNode current, string name, Rectangle value)
{
XmlAttribute att = doc.CreateAttribute(name);
att.Value = value.ToString();
current.Attributes.Append(att);
}
private static void AddAttribute(XmlDocument doc, XmlNode current, string name, char value)
{
XmlAttribute att = doc.CreateAttribute(name);
att.Value = ((int)value).ToString();
current.Attributes.Append(att);
}
#region ICloneable Members
object ICloneable.Clone()
{
return Clone();
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace BackEnd
{
/// <summary>
/// University
/// </summary>
public class University
{
/// <summary>
/// Fields
/// </summary>
public SortedSet<Student<Int64>> Students { get; private set; }
public SortedSet<Paper<Int64>> Papers { get; private set; }
public SortedSet<Enrollment<Int64>> Enrollments { get; private set; }
/// <summary>
/// Ctor
/// </summary>
public University()
{
this.Students = new SortedSet<Student<Int64>>();
this.Papers = new SortedSet<Paper<Int64>>();
this.Enrollments = new SortedSet<Enrollment<Int64>>();
}
/// <summary>
/// Add
/// </summary>
/// <param name="student"></param>
/// <returns></returns>
public bool Add(Student<Int64> student)
{
return this.Students.Add(student);
}
/// <summary>
/// Add
/// </summary>
/// <param name="paper"></param>
/// <returns></returns>
public bool Add(Paper<Int64> paper)
{
return this.Papers.Add(paper);
}
/// <summary>
/// AddRange
/// </summary>
/// <param name="collection"></param>
public void AddRange(IEnumerable<Student<Int64>> collection)
{
foreach (var elem in collection)
this.Students.Add(elem);
}
/// <summary>
/// AddRange
/// </summary>
/// <param name="collection"></param>
public void AddRange(IEnumerable<Paper<Int64>> collection)
{
foreach (var elem in collection)
this.Papers.Add(elem);
}
/// <summary>
/// Import students
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long ImportStudents(string filename)
{
Func<string[], Student<Int64>> makeStudent = (line) =>
{
var id = Convert.ToInt64(line[0]);
string name = line[1];
DateTime birth = DateTime.Parse(line[2]);
string address = line[3];
return new Student<Int64>(id, name, birth, address);
};
try
{
long count = 0;
foreach (var line in Utilities.ReadFrom(filename))
count += this.Add(makeStudent(line.Split(','))) ? 1 : 0;
return count;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// import papers
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long ImportPapers(string filename)
{
Func<string[], Paper<Int64>> makePaper = (line) =>
{
Int64 code = Convert.ToInt64(line[0]);
string name = line[1];
string coordinator = line[2];
return new Paper<Int64>(code, name, coordinator);
};
try
{
long count = 0;
foreach(var line in Utilities.ReadFrom(filename))
count += this.Add(makePaper(line.Split(','))) ? 1 : 0;
return count;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// import enrollments info
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public long ImportEnrollments(string path)
{
try
{
long count = 0;
foreach(var line in Utilities.ReadFrom(path))
count += this.Enrol(line) ? 1 : 0;
return count;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// map student id to student
/// </summary>
/// <param name="studentId"></param>
/// <returns></returns>
public Student<Int64> FindStudent(Int64 studentId)
{
try
{
return Students.First(s => s.Id == studentId);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// map paper code to paper
/// </summary>
/// <param name="paperCode"></param>
/// <returns></returns>
public Paper<Int64> FindPaper(Int64 paperCode)
{
try
{
return this.Papers.First(p => p.Code == paperCode);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// find enrolled with paper code
/// </summary>
/// <param name="paperCode"></param>
/// <returns></returns>
public List<Student<Int64>> FindEnrolledByPaper(Int64 paperCode)
{
return
this.Enrollments
.Where(e => e.PaperCode == paperCode)
.Select(e => this.FindStudent(e.StudentId))
.ToList();
}
/// <summary>
/// find enrolled with a student id
/// </summary>
/// <param name="studentId"></param>
/// <returns></returns>
public List<Paper<Int64>> FindEnrolledByStudent(Int64 studentId)
{
var data = from e in this.Enrollments
where e.StudentId == studentId
select this.FindPaper(e.PaperCode);
return data.ToList();
}
/// <summary>
/// enrol
/// </summary>
/// <param name="paperCode"></param>
/// <param name="studentId"></param>
/// <returns></returns>
public bool Enrol(Int64 paperCode, Int64 studentId)
{
if(this.Papers.Contains(this.FindPaper(paperCode))
&& this.Students.Contains(this.FindStudent(studentId)))
return this.Enrollments.Add(new Enrollment<long>(paperCode, studentId));
else
return false;
}
/// <summary>
/// enrol
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
public bool Enrol(string line)
{
string[] buff = line.Split(',');
long paperCode = 0, studentId = 0;
if (! long.TryParse(buff[0], out paperCode))
throw new Exception(buff[0] + " is not a valid paper code");
if (! long.TryParse(buff[1], out studentId))
throw new Exception(buff[1] + " is not a valid student id");
return this.Enrol(paperCode, studentId);
}
/// <summary>
/// generic export function
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="set"></param>
/// <param name="folder"></param>
/// <param name="filename"></param>
/// <param name="fileExtention"></param>
/// <returns></returns>
public bool Export<T>(SortedSet<T> set, string folder, string filename, string fileExtention)
{
try
{
string path = @folder + "\\" + filename + "." + fileExtention;
using (var sw = new StreamWriter(path))
foreach (var element in set)
sw.WriteLine(element.ToString());
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// export all data to a specified folder
/// </summary>
/// <param name="folder"></param>
/// <returns></returns>
public bool ExportAllData(string folder)
{
string now = DateTime.Now.ToFileTime().ToString();
var ret = true;
ret = ret && this.Export<Student<long>>(this.Students, folder, "Students" + now, "csv");
ret = ret && this.Export<Paper<long>>(this.Papers, folder, "Papers" + now, "csv");
ret = ret && this.Export<Enrollment<long>>(this.Enrollments, folder, "Enrollments" + now, "csv");
return ret;
}
}
}
|
using UnityEngine;
namespace BIG.LayeredFSMs
{
/// <summary>
/// When picked up, sets actor's Health.currentHealth to max.
/// </summary>
public class HealthPickup : Pickup
{
private void OnTriggerEnter2D(Collider2D collision)
{
var health = collision.GetComponent<Health>();
if (health != null)
{
health.currentHealth = Health.MaxHealth;
Regenerate();
}
}
}
}
|
using Moonbyte.UniversalServer.Core.Client;
using static Moonbyte.UniversalServer.Core.Model.Utility;
namespace Moonbyte.UniversalServer.Core.Server.Events
{
public class OnBeforeClientRequestEventArgs
{
public MoonbyteCancelRequest CancelRequest = MoonbyteCancelRequest.Continue;
public string ErrorMessage = "USER_PLUGINAUTH";
public string RawData;
public ClientWorkObject Client;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace DXInfo.Principal
{
/// <summary>
/// 自定义用户信息
/// </summary>
[Serializable]
public class MyIdentity : System.Security.Principal.IIdentity//, ICloneable
{
private DXInfo.Models.aspnet_CustomProfile _oper;
private DXInfo.Models.aspnet_Users _user;
private DXInfo.Models.Depts _dept;
private string _AuthenticationType;
//private int _iDiscount;
public MyIdentity(DXInfo.Models.aspnet_CustomProfile oper,
DXInfo.Models.aspnet_Users user, DXInfo.Models.Depts dept, string authenticationType)
{
this._oper = oper;
this._AuthenticationType = authenticationType;
//this._iDiscount = discount;
this._dept = dept;
this._user = user;
}
public MyIdentity()
{
this._oper = new Models.aspnet_CustomProfile();
this._AuthenticationType = "MyIdentity";
this._dept = new Models.Depts();
}
public DXInfo.Models.aspnet_CustomProfile oper
{
get { return _oper; }
}
//public int iDiscount
//{
// get
// {
// if (_dept.cnnDeptID == 0) return 0;
// else return _dept.cnnDiscount;
// }
//}
public DXInfo.Models.Depts dept
{
get { return _dept; }
}
public DXInfo.Models.aspnet_Users user
{
get { return _user; }
}
#region IIdentity 成员
public string AuthenticationType
{
get { return _AuthenticationType; }
}
public bool IsAuthenticated
{
get { return true; }
}
public string Name
{
get { return _user.UserName; }
}
#endregion
//public object Clone()
//{
// //throw new NotImplementedException();
// MemoryStream ms = new MemoryStream();
// object obj;
// try
// {
// BinaryFormatter bf = new BinaryFormatter();
// bf.Serialize(ms, this);
// ms.Seek(0, SeekOrigin.Begin);
// obj = bf.Deserialize(ms);
// }
// catch (Exception ex)
// {
// throw ex;
// }
// finally
// {
// ms.Close();
// }
// return obj;
//}
}
}
|
using System.Text.RegularExpressions;
namespace Phunk.Luan
{
internal static class StringMatch
{
public static Match Match(this string str, string regex)
{
var m = new Regex(regex).Match(str);
return m.Length != 0 ? m : null;
}
}
} |
using Improbable.Gdk.Core;
using Improbable.Gdk.Core.SceneAuthoring;
using UnityEngine;
namespace Improbable.Gdk.TransformSynchronization
{
[AddComponentMenu("SpatialOS/Authoring Components/Transform From GameObject Authoring Component")]
public class TransformFromGameObjectAuthoringComponent : MonoBehaviour, ISpatialOsAuthoringComponent
{
#pragma warning disable 649
[SerializeField] private string writeAccess;
#pragma warning restore 649
public void WriteTo(EntityTemplate template)
{
var transformSnapshot = TransformUtils.CreateTransformSnapshot(transform.position, transform.rotation);
template.AddComponent(transformSnapshot, writeAccess);
}
}
}
|
// Copyright 2016 Jon Skeet. All Rights Reserved.
// Licensed under the Apache License Version 2.0.
using System;
public sealed class Popsicle
{
public bool Frozen { get; private set; }
private int value;
public int Value
{
get { return value; }
set
{
if (Frozen)
{
throw new InvalidOperationException("Couldn't keep it in, heaven knows I tried!");
}
this.value = value;
}
}
public void Freeze()
{
Frozen = true;
}
}
public class UsageOfPopsicle
{
public static void Main()
{
var popsicle = new Popsicle();
popsicle.Value = 10;
popsicle.Value = 15;
popsicle.Freeze();
Console.WriteLine(popsicle.Value); // 15? Memory model madness
popsicle.Value = 20; // Bang!
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ShoppingCore.Application;
using ShoppingCore.Application.ApplicationModels;
using ShoppingCore.Presentation.Models.Users;
namespace ShoppingCore.Presentation.Models.PresentationModelMapper
{
public static class ModelMapper
{
public static UserViewModel MapToUserViewModel(this UserModel user)
{
return
new UserViewModel
{
UserID = user.UserID,
UserName = user.UserName,
Password = user.Password,
AutheticationType = user.AutheticationType,
UserRole = user.UserRole,
IsAutheticated = user.IsAutheticated
};
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Drive.ScsArchive.Tests {
[TestClass]
public class HashFsFileNameTests {
[TestMethod]
public void TestCtor () {
HashFsFileName fileName;
fileName = new HashFsFileName("file");
Assert.IsFalse(fileName.IsDirectory);
Assert.AreEqual("file", fileName.Name);
fileName = new HashFsFileName("*dir");
Assert.IsTrue(fileName.IsDirectory);
Assert.AreEqual("dir", fileName.Name);
fileName = new HashFsFileName("file", "/def");
Assert.IsFalse(fileName.IsDirectory);
Assert.AreEqual("def/file", fileName.Name);
fileName = new HashFsFileName("*dir", "/def/");
Assert.IsTrue(fileName.IsDirectory);
Assert.AreEqual("def/dir", fileName.Name);
}
[TestMethod]
public void TestHashGeneration () {
string rootFolder = "";
string defFolder = "def";
ulong rootHash = 0x9AE16A3B2F90404F;
ulong defHash = 0x2C6F469EFB31C45A;
Assert.AreEqual(rootHash, HashFsFileName.GetHashForFullPath(rootFolder));
Assert.AreEqual(defHash, HashFsFileName.GetHashForFullPath(defFolder));
}
}
}
|
using JssSnippet.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Sitecore.DependencyInjection;
using Sitecore.LayoutService.ItemRendering;
namespace JssSnippet.Configurators
{
public class RegisterDependencies : IServicesConfigurator
{
public void Configure(IServiceCollection serviceCollection)
{
serviceCollection.Replace(ServiceDescriptor.Singleton<ILayoutService, CustomLayoutService>());
}
}
} |
@using serverhouse_web.Models.PropertyValue
@model PropertyValue
@{
var gallery = (ImagePropertyValue) Model;
}
<div class="v_valuerep v_valuerep_gallery">
<div class="v_valuerep_gallery_image">
@foreach (var url in gallery.urls) {
<img src="@url"/>
}
</div>
<div class="v_valuerep_gallery_thumbs">
@foreach (var url in gallery.urls) {
<div class="v_valuerep_gallery_thumb">
<img src="@url"/>
</div>
}
</div>
</div> |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Krtalic.Common.Extensions
{
public static class StopwatchExtensions
{
public static long ElapsedNanoseconds(this Stopwatch Self)
{
double ticks = Self.ElapsedTicks;
return (long)((ticks / Stopwatch.Frequency) * 1000000000);
}
public static long ElapsedMicroseconds(this Stopwatch Self)
{
double ticks = Self.ElapsedTicks;
return (long)((ticks / Stopwatch.Frequency) * 1000000);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Autofac.Features.Indexed;
using Lykke.Service.BlockchainApi.Client;
using Lykke.Service.BlockchainCashoutPreconditionsCheck.Core.Domain.Health;
using Lykke.Service.BlockchainCashoutPreconditionsCheck.Core.Domain.Validation;
using Lykke.Service.BlockchainCashoutPreconditionsCheck.Core.Domain.Validations;
using Lykke.Service.BlockchainCashoutPreconditionsCheck.Core.Services;
using Lykke.Service.BlockchainCashoutPreconditionsCheck.Core.Settings.ServiceSettings;
namespace Lykke.Service.BlockchainCashoutPreconditionsCheck.Services
{
public class BlockchainSettingsProvider : IBlockchainSettingsProvider
{
private readonly IImmutableDictionary<string, BlockchainSettings> _settings;
public BlockchainSettingsProvider(BlockchainsIntegrationSettings settings)
{
_settings = settings?.Blockchains.ToImmutableDictionary(x => x.Type, x=> x);
}
public BlockchainSettings Get(string blockchainType)
{
if (!_settings.TryGetValue(blockchainType, out var result))
{
throw new InvalidOperationException($"Blockchain Settings [{blockchainType}] is not found");
}
return result;
}
}
}
|
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.AsymmetricAlgorithm))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CipherMode))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicException))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptoStream))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptoStreamMode))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HashAlgorithm))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HashAlgorithmName))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HMAC))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.ICryptoTransform))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.KeyedHashAlgorithm))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.KeySizes))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.PaddingMode))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.SymmetricAlgorithm))]
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GitLabApiClient.Internal.Http;
using GitLabApiClient.Internal.Paths;
using GitLabApiClient.Internal.Queries;
using GitLabApiClient.Models.Branches.Requests;
using GitLabApiClient.Models.Branches.Responses;
using GitLabApiClient.Models.Projects.Responses;
namespace GitLabApiClient
{
public sealed class BranchClient
{
private readonly GitLabHttpFacade _httpFacade;
private readonly BranchQueryBuilder _branchQueryBuilder;
internal BranchClient(
GitLabHttpFacade httpFacade,
BranchQueryBuilder branchQueryBuilder)
{
_httpFacade = httpFacade;
_branchQueryBuilder = branchQueryBuilder;
}
/// <summary>
/// Retrieves a single branch
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <param name="branchName">The branch name.</param>
/// <returns></returns>
public async Task<Branch> GetAsync(ProjectId projectId, string branchName) =>
await _httpFacade.Get<Branch>($"projects/{projectId}/repository/branches/{branchName}");
/// <summary>
///
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <param name="options">Query options <see cref="BranchQueryOptions"/></param>
/// <returns></returns>
public async Task<IList<Branch>> GetAsync(ProjectId projectId, Action<BranchQueryOptions> options)
{
var queryOptions = new BranchQueryOptions();
options?.Invoke(queryOptions);
string url = _branchQueryBuilder.Build($"projects/{projectId}/repository/branches", queryOptions);
return await _httpFacade.GetPagedList<Branch>(url);
}
/// <summary>
/// Creates a branch
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <param name="request">Create branch request</param>
/// <returns></returns>
public async Task<Branch> CreateAsync(ProjectId projectId, CreateBranchRequest request) =>
await _httpFacade.Post<Branch>($"projects/{projectId}/repository/branches", request);
/// <summary>
/// Deletes a branch
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <param name="branchName">The branch, you want deleted.</param>
public async Task DeleteBranch(ProjectId projectId, string branchName) =>
await _httpFacade.Delete($"projects/{projectId}/repository/branches/{branchName}");
/// <summary>
/// Deletes the merged branches
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
public async Task DeleteMergedBranches(ProjectId projectId) =>
await _httpFacade.Delete($"projects/{projectId}/repository/merged_branches");
/// <summary>
/// Retrieve a single protected branch information.
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <param name="branchName">The protected branch</param>
/// <returns>A protected branch</returns>
public async Task<ProtectedBranch> GetProtectedBranchesAsync(ProjectId projectId, string branchName) =>
await _httpFacade.Get<ProtectedBranch>($"projects/{projectId}/protected_branches/{branchName}");
/// <summary>
/// Retrieves a list of Protected Branches from a project.
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <returns>List of protected branches.</returns>
public async Task<IList<ProtectedBranch>> GetProtectedBranchesAsync(ProjectId projectId) =>
await _httpFacade.GetPagedList<ProtectedBranch>($"projects/{projectId}/protected_branches");
/// <summary>
/// Protect a branch
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <param name="request">Protect branch request <see cref="ProtectBranchRequest"/>.</param>
/// <returns>The newly protected branch.</returns>
public async Task<ProtectedBranch> ProtectBranchAsync(ProjectId projectId, ProtectBranchRequest request) =>
await _httpFacade.Post<ProtectedBranch>($"projects/{projectId}/protected_branches", request);
/// <summary>
/// Unprotect a branch
/// </summary>
/// <param name="projectId">The ID, path or <see cref="Project"/> of the project.</param>
/// <param name="branchName">The Branch, you want to unprotect.</param>
public async Task UnprotectBranchAsync(ProjectId projectId, string branchName) =>
await _httpFacade.Delete($"projects/{projectId}/protected_branches/{branchName}");
}
}
|
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Xfrogcn.AspNetCore.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
public static class HttpClientBuilderExtensions
{
public static string DisableEnsureSuccessStatusCode_Key = "DisableEnsureSuccessStatusCode";
/// <summary>
/// 添加一个Mock Http消息处理层,用于单元测试
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static MockHttpMessageHandlerOptions AddMockHttpMessageHandler(this IHttpClientBuilder builder)
{
MockHttpMessageHandlerOptions options = new MockHttpMessageHandlerOptions();
builder.ConfigurePrimaryHttpMessageHandler(() =>
{
return new MockHttpMessageHandler(options);
});
return options;
}
/// <summary>
/// 添加一个消息处理器,通过此消息处理器会在请求过程中,自动从认证服务获取令牌并添加到请求头中
/// 该处理器通过<seealso cref="IClientCertificateProvider"/>获取对应客户端的认证令牌
/// </summary>
/// <param name="builder">HttpClient构建器</param>
/// <param name="clientId">认证客户端Id</param>
/// <returns></returns>
public static IHttpClientBuilder AddTokenMessageHandler(this IHttpClientBuilder builder, string clientId)
{
builder.AddHttpMessageHandler((sp) =>
{
IClientCertificateProvider provider = sp.GetRequiredService<IClientCertificateProvider>();
ClientCertificateManager cm = provider.GetClientCertificateManager(clientId);
return new GetClientTokenMessageHandler(cm);
});
return builder;
}
/// <summary>
/// 禁止HttpClient Extensions 方法自动调用EnsureSuccessStatusCode
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IHttpClientBuilder DisableEnsureSuccessStatusCode(this IHttpClientBuilder builder)
{
builder.AddHttpMessageHandler((sp) =>
{
return new DisableEnsureSuccessStatusCodeMessageHandler();
});
return builder;
}
public static void DisableEnsureSuccessStatusCode(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(DisableEnsureSuccessStatusCode_Key))
{
request.Properties[DisableEnsureSuccessStatusCode_Key] = true;
}
else
{
request.Properties.TryAdd(DisableEnsureSuccessStatusCode_Key, true);
}
}
public static bool IsDisableEnsureSuccessStatusCode(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(DisableEnsureSuccessStatusCode_Key))
{
return (bool)request.Properties[DisableEnsureSuccessStatusCode_Key];
}
return false;
}
public static void IgnoreRequestToken(this HttpRequestMessage request)
{
if (!request.Properties.ContainsKey(GetClientTokenMessageHandler.IGNORE_TOKEN_PROPERTY))
{
request.Properties.Add(GetClientTokenMessageHandler.IGNORE_TOKEN_PROPERTY, true);
}
}
}
}
|
namespace TeamTaskboard.Web.ViewModels.Project
{
using System.Collections.Generic;
using AutoMapper;
using TeamTaskboard.Models;
using TeamTaskboard.Web.Infrastructure.Mappings;
using TeamTaskboard.Web.ViewModels.Task;
public class ProjectViewModel : IMapFrom<Project>, ICustomMappings
{
public ProjectViewModel()
{
this.Tasks = new List<TaskViewModel>();
}
public int ProjectId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<TaskViewModel> Tasks { get; set; }
public void CreateMappings(IConfiguration configuration)
{
//configuration.CreateMap<Project, TeamProjectViewModel>()
// .ForMember(dest => dest.Tasks, opt => opt.MapFrom(src => src.Tasks))
}
}
}
|
using ConfigurationModel.Interfaces;
using ConfigurationModel.Models;
namespace WebApiApp.Middlewares
{
public class ConfigurationService : IConfigurationService
{
private readonly string _environmentName;
private readonly string? _currentDirectory;
private readonly IConfiguration _configuration;
public ConfigurationService()
{
_currentDirectory = AppContext.BaseDirectory;
_environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
_configuration = new ConfigurationBuilder()
.SetBasePath(_currentDirectory)
.AddJsonFile($"appsettings.json", optional: true)
.AddJsonFile($"appsettings.{_environmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
}
public IAppSettings GetAppSettings()
{
var appsettings = new AppSettings
{
Environment = _configuration.GetSection("AppSettings:Environment").Get<string>(),
AWS = new AwsSetting
{
S3 = new S3Setting
{
BucketName = GetConfigurationValue<string>("AWS:S3:BucketName"),
Path = new S3PathSetting
{
Root = GetConfigurationValue<string>("AWS:S3:Path:Root"),
Images = GetConfigurationValue<string>("AWS:S3:Path:Images"),
Thumbnails = GetConfigurationValue<string>("AWS:S3:Path:Thumbnails"),
Videos = GetConfigurationValue<string>("AWS:S3:Path:Videos"),
Sounds = GetConfigurationValue<string>("AWS:S3:Path:Sounds"),
Boards = GetConfigurationValue<string>("AWS:S3:Path:Boards"),
Profiles = GetConfigurationValue<string>("AWS:S3:Path:Profiles"),
ListThumbnail = GetConfigurationValue<string>("AWS:S3:Path:ListThumbnail"),
ViewThumbnail = GetConfigurationValue<string>("AWS:S3:Path:ViewThumbnail"),
}
},
Rds = new RdsSetting
{
ConnectionString = GetConfigurationValue<string>("AWS:Rds:ConnectionString"),
DbVersion = GetConfigurationValue<string>("AWS:Rds:DbVersion"),
},
Cognito = new CognitoSetting
{
RegionId = GetConfigurationValue<string>("AWS:Cognito:RegionId"),
UserPoolName = GetConfigurationValue<string>("AWS:Cognito:UserPoolName"),
UserPoolId = GetConfigurationValue<string>("AWS:Cognito:UserPoolId"),
AppClientId = GetConfigurationValue<string>("AWS:Cognito:AppClientId"),
TokenValidIssuer = GetConfigurationValue<string>("AWS:Cognito:TokenValidIssuer"),
HostingUiUri = GetConfigurationValue<string>("AWS:Cognito:HostingUiUri"),
},
AdminCognito = new CognitoSetting
{
RegionId = GetConfigurationValue<string>("AWS:AdminCognito:RegionId"),
UserPoolName = GetConfigurationValue<string>("AWS:AdminCognito:UserPoolName"),
UserPoolId = GetConfigurationValue<string>("AWS:AdminCognito:UserPoolId"),
AppClientId = GetConfigurationValue<string>("AWS:AdminCognito:AppClientId"),
TokenValidIssuer = GetConfigurationValue<string>("AWS:AdminCognito:TokenValidIssuer"),
HostingUiUri = GetConfigurationValue<string>("AWS:AdminCognito:HostingUiUri"),
},
},
CorsOrigins = _configuration.GetSection("AppSettings:CorsOrigins").Get<IEnumerable<string>>(),
Swagger = new SwaggerSetting
{
Title = GetConfigurationValue<string>("Swagger:Title"),
Version = GetConfigurationValue<string>("Swagger:Version"),
Description = GetConfigurationValue<string>("Swagger:Description"),
Link = GetConfigurationValue<string>("Swagger:Link"),
},
};
return appsettings;
}
private T GetConfigurationValue<T>(string key, bool isAppSettings = true)
{
if (isAppSettings)
{
return _configuration.GetSection($"AppSettings:{key}").Get<T>();
}
return _configuration.GetSection($"Serilog:{key}").Get<T>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DisBot {
public class CircularBuffer<T> {
protected T[] _buffer;
private int _position;
public virtual int Position {
get {
return _position;
}
set {
_position = value;
}
}
public virtual int Size {
get {
return _buffer.Length;
}
set {
Array.Resize(ref _buffer, value);
}
}
public int CurrentSize {
get {
return Math.Min(Position, Size);
}
}
public virtual T this[int i] {
get {
return _buffer[(_position - CurrentSize + i) % _buffer.Length];
}
set {
_buffer[_position % _buffer.Length] = value;
}
}
public CircularBuffer()
: this(32) {
}
public CircularBuffer(int size) {
_buffer = new T[size];
}
public virtual void Add(T item) {
_buffer[_position % _buffer.Length] = item;
_position++;
}
}
}
|
using System;
namespace iSukces.Binding
{
internal sealed class DisposableAction : IDisposable
{
public DisposableAction(Action action) { _action = action; }
~DisposableAction() { DisposeInternal(); }
public void Dispose()
{
DisposeInternal();
GC.SuppressFinalize(this);
}
private void DisposeInternal()
{
if (_action is null)
return;
_action();
_action = null;
}
private Action _action;
}
}
|
using Cake.Core.IO;
using Cake.Testing;
using System;
using Xunit;
namespace Cake.MonoApiTools.Tests
{
public class MonoApiInfoAliasesTest
{
[Theory]
[InlineData("/bin/tools/mono-api-info.exe", "/bin/tools/mono-api-info.exe")]
[InlineData("./tools/mono-api-info.exe", "/Working/tools/mono-api-info.exe")]
public void Should_Use_Executable_From_Tool_Path_If_Provided(string toolPath, string expected)
{
// Given
var fixture = new MonoApiInfoFixture();
fixture.Settings.ToolPath = toolPath;
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
[Fact]
public void Should_Throw_If_Input_File_Is_Null()
{
// Given
var fixture = new MonoApiInfoFixture();
fixture.AssemblyPaths = null;
// When + Then
var result = Assert.Throws<ArgumentNullException>("assemblies", () => fixture.Run());
}
[Fact]
public void Should_Throw_If_Input_Files_Are_Empty()
{
// Given
var fixture = new MonoApiInfoFixture();
fixture.AssemblyPaths = new FilePath[0];
// When + Then
var result = Assert.Throws<ArgumentException>("assemblies", () => fixture.Run());
}
[Fact]
public void Should_Find_Executable_If_Tool_Path_Was_Not_Provided()
{
// Given
var fixture = new MonoApiInfoFixture();
// When
var result = fixture.Run();
// Then
Assert.Equal("/Working/tools/mono-api-info.exe", result.Path.FullPath);
}
[Fact]
public void Should_Throw_When_Only_Assembly_Path()
{
// Given
var fixture = new MonoApiInfoFixture();
fixture.OutputPath = null;
// When + Then
var result = Assert.Throws<ArgumentNullException>("outputPath", () => fixture.Run());
}
[Fact]
public void Should_Create_Correct_Command_Line_Arguments_For_Assembly_And_Output()
{
// Given
var fixture = new MonoApiInfoFixture();
// When
var result = fixture.Run();
// Then
var args =
"-o=\"/Working/input.info.xml\" " +
"\"/Working/input.dll\"";
Assert.Equal(args, result.Args);
}
[Fact]
public void Should_Create_Correct_Command_Line_Arguments_For_Abi()
{
// Given
var fixture = new MonoApiInfoFixture();
fixture.Settings.GenerateAbi = true;
// When
var result = fixture.Run();
// Then
var args =
"--abi " +
"-o=\"/Working/input.info.xml\" " +
"\"/Working/input.dll\"";
Assert.Equal(args, result.Args);
}
[Fact]
public void Should_Create_Correct_Command_Line_Arguments_For_Everything()
{
// Given
var fixture = new MonoApiInfoFixture();
fixture.Settings.GenerateAbi = true;
fixture.Settings.FollowForwarders = true;
fixture.Settings.GenerateContractApi = true;
fixture.Settings.SearchPaths = new[]
{
new DirectoryPath("/search/path/a"),
new DirectoryPath("/search/path/b")
};
fixture.Settings.ResolvePaths = new[]
{
new FilePath("/resolve/assembly/a.dll"),
new FilePath("/resolve/assembly/b.dll"),
};
// When
var result = fixture.Run();
// Then
var args =
"--abi " +
"--follow-forwarders " +
"--search-directory=\"/search/path/a\" " +
"--search-directory=\"/search/path/b\" " +
"-r=\"/resolve/assembly/a.dll\" " +
"-r=\"/resolve/assembly/b.dll\" " +
"-o=\"/Working/input.info.xml\" " +
"--contract-api " +
"\"/Working/input.dll\"";
Assert.Equal(args, result.Args);
}
}
}
|
using System;
namespace Forms9Patch
{
static class ElementShapeExtensions
{
public static ExtendedElementShape ToExtendedElementShape(this ElementShape buttonShape)
{
switch(buttonShape)
{
case ElementShape.Square: return ExtendedElementShape.Square;
case ElementShape.Rectangle: return ExtendedElementShape.Rectangle;
case ElementShape.Circle: return ExtendedElementShape.Circle;
case ElementShape.Elliptical: return ExtendedElementShape.Elliptical;
case ElementShape.Obround: return ExtendedElementShape.Obround;
}
throw new NotSupportedException("ElementShape ["+buttonShape+"] cannot be converted to ExtendedElementShape");
}
public static bool IsSegment(this ExtendedElementShape shape)
{
return shape == ExtendedElementShape.SegmentEnd || shape == ExtendedElementShape.SegmentMid || shape == ExtendedElementShape.SegmentStart;
}
}
}
|
using CodyDocs.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodyDocs.Services
{
public static class DocumentationFileHandler
{
public static void AddDocumentationFragment(DocumentationFragment fragment, string filepath)
{
var content = DocumentationFileSerializer.Deserialize(filepath);
var newFragments = content.Fragments
.Where(f => !f.Selection.StartPosition.Equals(fragment.Selection.StartPosition)
|| !f.Selection.EndPosition.Equals(fragment.Selection.EndPosition));
newFragments = newFragments.Concat(new List<DocumentationFragment>() { fragment });
content.Fragments = newFragments.ToList();
DocumentationFileSerializer.Serialize(filepath, content);
}
}
}
|
using System;
namespace DeltaEngine.Graphics.OpenGL
{
internal abstract class BaseGraphicsContext : IDisposable
{
protected IntPtr GraphicsContext;
public MethodLoader Loader { get; private set; }
public static BaseGraphicsContext Current { get; protected set; }
public abstract bool VSync { set; }
public abstract bool IsCurrent { get; }
public IntPtr GLHandle { get; protected set; }
protected BaseGraphicsContext()
{
Loader = new MethodLoader(this);
}
public abstract IntPtr GetGLProcAddress(string functionName);
public abstract IntPtr GetProcAddress(IntPtr library, string functionName);
public abstract void SwapBuffers();
public abstract bool MakeCurrent();
internal abstract void UpdateDeviceParameters(byte colorBits, byte depth, byte stencil);
public abstract void Dispose();
}
} |
using Coslen.RogueTiler.Domain.Engine.Common;
namespace Coslen.RogueTiler.Domain.Engine.Actions
{
/// Base class for an [Action] that applies (or extends/intensifies) a
/// [Condition]. It handles cases where the condition is already in effect with
/// possibly a different intensity.
public abstract class ConditionAction : Action
{
/// The [Condition] on the actor that should be affected.
public abstract Condition condition { get; }
/// The intensity of the condition to apply.
public virtual int getIntensity()
{
return 1;
}
/// The number of turns the condition should last.
public virtual int getDuration()
{
return 0;
}
/// Override this to log the message when the condition is first applied.
public virtual void logApply()
{
}
/// Override this to log the message when the condition is already in effect
/// and its duration is extended.
public virtual void logExtend()
{
}
/// Override this to log the message when the condition is already in effect
/// at a weaker intensity and the intensity increases.
public virtual void logIntensify()
{
}
public override ActionResult OnPerform()
{
var intensity = getIntensity();
var duration = getDuration();
// TODO: Apply resistance to duration and bail if zero duration.
// TODO: Don't lower intensity by resistance here (we want to handle that
// each turn in case it changes), but do see if resistance will lower the
// intensity to zero. If so, bail.
if (!condition.IsActive)
{
condition.Activate(duration, intensity);
logApply();
return ActionResult.Success;
}
if (condition.Intensity >= intensity)
{
// Scale down the new duration by how much weaker the new intensity is.
duration = (duration*intensity)/condition.Intensity;
// Compounding doesn't add as much as the first one.
duration /= 2;
if (duration == 0)
{
return Succeed();
}
condition.Extend(duration);
logExtend();
return ActionResult.Success;
}
// Scale down the existing duration by how much stronger the new intensity
// is.
var oldDuration = (condition.Duration*condition.Intensity)/intensity;
condition.Activate(oldDuration + duration/2, intensity);
logIntensify();
return ActionResult.Success;
}
}
public class HasteAction : ConditionAction
{
private readonly int _duration;
private readonly int _speed;
public HasteAction(int duration, int speed)
{
_duration = duration;
_speed = speed;
}
public override Condition condition
{
get { return Actor.Haste; }
}
public override int getIntensity()
{
return _speed;
}
public override int getDuration()
{
return _duration;
}
public override void logApply()
{
Log("{1} start[s] moving faster.", Actor);
}
public override void logExtend()
{
Log("{1} [feel]s the haste lasting longer.", Actor);
}
public override void logIntensify()
{
Log("{1} move[s] even faster.", Actor);
}
}
public class FreezeAction : ConditionAction
{
private readonly int _damage;
public FreezeAction(int damage)
{
_damage = damage;
}
public override Condition condition
{
get { return Actor.Cold; }
}
// TODO: Should also break items in inventory.
public override int getIntensity()
{
return 1 + _damage/40;
}
public override int getDuration()
{
return 3 + Rng.Instance.triangleInt(_damage*2, _damage/2);
}
public override void logApply()
{
Log("{1} [are|is] frozen!", Actor);
}
public override void logExtend()
{
Log("{1} feel[s] the cold linger!", Actor);
}
public override void logIntensify()
{
Log("{1} feel[s] the cold intensify!", Actor);
}
}
public class PoisonAction : ConditionAction
{
private readonly int _damage;
public PoisonAction(int damage)
{
_damage = damage;
}
public override Condition condition
{
get { return Actor.Poison; }
}
public override int getIntensity()
{
return 1 + _damage/20;
}
public override int getDuration()
{
return 1 + Rng.Instance.triangleInt(_damage*2, _damage/2);
}
public override void logApply()
{
Log("{1} [are|is] poisoned!", Actor);
}
public override void logExtend()
{
Log("{1} feel[s] the poison linger!", Actor);
}
public override void logIntensify()
{
Log("{1} feel[s] the poison intensify!", Actor);
}
}
internal class DazzleAction : ConditionAction
{
private readonly int _damage;
public DazzleAction(int damage)
{
_damage = damage;
}
public override Condition condition
{
get { return Actor.Dazzle; }
}
public override int getDuration()
{
return 3 + Rng.Instance.triangleInt(_damage*2, _damage/2);
}
public override void logApply()
{
Log("{1} [are|is] dazzled by the light!", Actor);
}
public override void logExtend()
{
Log("{1} [are|is] dazzled by the light!", Actor);
}
}
public class ResistAction : ConditionAction
{
private readonly int _duration;
private readonly Element _element;
public ResistAction(int duration, Element element)
{
_duration = duration;
_element = element;
}
public override Condition condition
{
get { return Actor.Resistances[_element]; }
}
public override int getDuration()
{
return _duration;
}
// TODO: Resistances of different intensity.
public override void logApply()
{
Log("{1} [are|is] resistant to " + _element + ".", Actor);
}
public override void logExtend()
{
Log("{1} feel[s] the resistance extend.", Actor);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CompBind
{
public class Path
{
public bool IsGlobal = false;
public LinkedList<PathElement> PathElements = new LinkedList<PathElement>();
public Path() { }
public Path(string path)
{
ParsePath(path);
}
public Path(Path otherPath)
{
IsGlobal = otherPath.IsGlobal;
PathElements = new LinkedList<PathElement>(otherPath.PathElements);
}
public int Length
{
get
{
return PathElements.Count;
}
}
/// <summary>
/// Clears current elements and parses given string.
/// </summary>
/// <param name="path"></param>
public void ParsePath(string path)
{
PathElements.Clear();
List<string> splits = path.Split(new char[] { '.' }).ToList();
// Always resolve this path from the tree root
if (splits[0] == "#")
{
splits.RemoveAt(0);
IsGlobal = true;
} //TODO: SOME FAIL CHECKS!
foreach (string s in splits)
{
if(s == "-" || string.IsNullOrEmpty(s))
{
// Ignore - empty path
continue;
}
else if (Regex.IsMatch(s, @"^\[\d+\]"))
{
// Its an index
Match match = Regex.Match(s, @"^\[(\d+)\]");
int index = int.Parse(match.Groups[1].Value);
PathElements.AddLast(new PathElement(index));
}
else
{
// Its a field
PathElements.AddLast(new PathElement(s));
}
}
}
public override string ToString()
{
string s = "";
if (IsGlobal)
{
s += "#.";
}
int index = 0;
foreach(PathElement pe in PathElements)
{
if (index != 0) s += ".";
if(pe.Type == PathElement.PathElementType.Index)
{
s += "[" + pe.Index + "]";
}
else
{
s += pe.FieldName;
}
index++;
}
return s;
}
/// <summary>
/// Checks if the path is a subpath (not equal) of the given path.
/// </summary>
/// <param name="otherPath"></param>
/// <returns></returns>
public bool IsSubpathOf(Path otherPath)
{
// Same length or shorter -> not a subpath!
if (PathElements.Count <= otherPath.PathElements.Count) return false;
// Walk both lists of path elements and compare
var otherEnumerator = otherPath.PathElements.GetEnumerator();
var thisEnumerator = PathElements.GetEnumerator();
while (otherEnumerator.MoveNext())
{
thisEnumerator.MoveNext();
if (otherEnumerator.Current != thisEnumerator.Current) return false;
}
return true;
}
public bool IsSamePath(Path otherPath)
{
if (PathElements.Count != otherPath.PathElements.Count) return false;
// Walk both lists of path elements and compare
var otherEnumerator = otherPath.PathElements.GetEnumerator();
var thisEnumerator = PathElements.GetEnumerator();
while (otherEnumerator.MoveNext())
{
thisEnumerator.MoveNext();
if (otherEnumerator.Current != thisEnumerator.Current) return false;
}
return true;
}
/// <summary>
/// Returns pathelements in range [from, to[ .
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public Path GetSlice(int from, int to = -1)
{
if (to == -1) to = PathElements.Count;
Path newPath = new Path();
var enumerator = PathElements.GetEnumerator();
enumerator.MoveNext();
// Go to start position
for (int i = 0; i < from; i++)
{
enumerator.MoveNext();
}
int currentIndex = from;
while(currentIndex < to)
{
newPath.PathElements.AddLast(enumerator.Current);
enumerator.MoveNext();
currentIndex++;
}
return newPath;
}
/// <summary>
/// Retrieves index of last index typed path element.
/// </summary>
/// <returns>Index, or -1, if no index typed element was found.</returns>
public int GetLastIndex()
{
if (Length == 0) return -1;
Path workingCopy = new Path(this);
PathElement pe = workingCopy.PathElements.Last.Value;
// Walk backwards until index pathelement is found
while (pe.Type != PathElement.PathElementType.Index)
{
workingCopy.PathElements.RemoveLast();
// Is list now empty?
if (workingCopy.PathElements.Last == null) return -1;
pe = workingCopy.PathElements.Last.Value;
}
if (pe.Type == PathElement.PathElementType.Index) return pe.Index;
else return -1;
}
public override bool Equals(object obj)
{
Path other = (Path)obj;
if (IsGlobal != other.IsGlobal) return false;
return IsSamePath(other);
}
public override int GetHashCode()
{
string pathString = ToString();
if (IsGlobal) pathString = "#" + pathString;
return pathString.GetHashCode();
}
public static Path Concatenate(Path pathA, Path pathB)
{
Path concatenatedPath = new Path();
foreach(PathElement pe in pathA.PathElements)
{
concatenatedPath.PathElements.AddLast(pe);
}
foreach (PathElement pe in pathB.PathElements)
{
concatenatedPath.PathElements.AddLast(pe);
}
return concatenatedPath;
}
public static implicit operator Path(string pathString)
{
return new Path(pathString);
}
}
}
|
using System;
namespace HotChocolate.PreProcessingExtensions.Pagination
{
public interface IHavePreProcessedPagingInfo
{
public int? TotalCount { get; }
public bool HasNextPage { get; }
public bool HasPreviousPage { get; }
}
}
|
// TC Data ADO.NET Bridge
// Copyright © 2009-2015 Tommy Carlier
// https://github.com/tommy-carlier/tc-libs/
// License: MIT License (MIT): https://github.com/tommy-carlier/tc-libs/blob/master/LICENSE
using System.Data;
namespace TC.Data.Internal.ValueGetters
{
internal abstract class StructValueGetter<TValue> :
ObjectValueGetter,
IValueGetter<TValue>,
IValueGetter<TValue?>
where TValue : struct
{
#region IValueGetter<TValue> Members
public abstract TValue GetValue(IDataRecord dataRecord, int ordinal);
#endregion
#region IValueGetter<TValue?> Members
TValue? IValueGetter<TValue?>.GetValue(IDataRecord dataRecord, int ordinal)
{
return dataRecord.IsDBNull(ordinal)
? null
: new TValue?(GetValue(dataRecord, ordinal));
}
#endregion
}
} |
using System.Collections;
using UnityEngine;
public class ColorChanger : MonoBehaviour
{
private void Awake()
{
Renderer = GetComponent<Renderer>();
OriginalColor = Renderer.material.color;
Light = GetComponentInChildren<Light>();
Outline = GetComponent<Outline>();
StartColor = Color.red;
EndColor = Color.blue;
}
void Start()
{
enabled = false;
}
private void OnEnable()
{
StartTime = Time.time;
Renderer.material.color = OriginalColor;
Light.enabled = true;
}
private void OnDisable()
{
Outline.OutlineColor = Color.clear;
Renderer.material.color = OriginalColor;
Light.enabled = false;
enabled = false;
}
void Update()
{
if (Index == GameManager.Instance.CurrentIndex)
{
Outline.OutlineColor = Color.green;
}
float t = (Time.time - StartTime) * SettingsManager.Instance.Settings.Speed;
Renderer.material.color = Color.Lerp(StartColor, EndColor, t);
if (Renderer.material.color == Color.blue)
{
GameEvents.HitMiss(gameObject);
enabled = false;
}
}
float StartTime;
public Renderer Renderer;
Color OriginalColor;
Color StartColor;
Color EndColor;
[SerializeField] Light Light;
public int Index;
Outline Outline;
}
|
using System.Linq;
using CMS.DocumentEngine;
using CMS.Ecommerce;
using CMS.SiteProvider;
using DancingGoat.Infrastructure;
namespace DancingGoat.Repositories.Implementation
{
/// <summary>
/// Represents a collection of products.
/// </summary>
public class KenticoProductRepository : IProductRepository
{
private readonly string mCultureName;
private readonly bool mLatestVersionEnabled;
/// <summary>
/// Initializes a new instance of the <see cref="KenticoProductRepository"/> class that returns products in the specified language.
/// If the requested product doesn't exist in specified language then its default culture version is returned.
/// </summary>
/// <param name="cultureName">The name of a culture.</param>
/// <param name="latestVersionEnabled">Indicates whether the repository will provide the most recent version of pages.</param>
public KenticoProductRepository(string cultureName, bool latestVersionEnabled)
{
mCultureName = cultureName;
mLatestVersionEnabled = latestVersionEnabled;
}
/// <summary>
/// Returns the product with the specified identifier.
/// </summary>
/// <param name="nodeID">The product node identifier.</param>
/// <returns>The product with the specified node identifier, if found; otherwise, null.</returns>
[CacheDependency("ecommerce.sku|all")]
[CacheDependency("nodeid|{0}")]
public SKUTreeNode GetProduct(int nodeID)
{
var node = DocumentHelper.GetDocuments()
.LatestVersion(mLatestVersionEnabled)
.Published(!mLatestVersionEnabled)
.OnSite(SiteContext.CurrentSiteName)
.Culture(mCultureName)
.CombineWithDefaultCulture()
.WhereEquals("NodeID", nodeID)
.FirstOrDefault();
if ((node == null) || !node.IsProduct())
{
return null;
}
// Load product type specific fields from the database
node.MakeComplete(true);
return node as SKUTreeNode;
}
/// <summary>
/// Returns the product with the specified SKU identifier.
/// </summary>
/// <param name="skuID">The product or variant SKU identifier.</param>
/// <returns>The product with the specified SKU identifier, if found; otherwise, null.</returns>
[CacheDependency("ecommerce.sku|all")]
[CacheDependency("nodeid|{0}")]
public SKUTreeNode GetProductForSKU(int skuID)
{
var sku = SKUInfoProvider.GetSKUInfo(skuID);
if ((sku == null) || sku.IsProductOption)
{
return null;
}
if (sku.IsProductVariant)
{
skuID = sku.SKUParentSKUID;
}
var node = DocumentHelper.GetDocuments()
.LatestVersion(mLatestVersionEnabled)
.Published(!mLatestVersionEnabled)
.OnSite(SiteContext.CurrentSiteName)
.Culture(mCultureName)
.CombineWithDefaultCulture()
.WhereEquals("NodeSKUID", skuID)
.FirstOrDefault();
return node as SKUTreeNode;
}
}
} |
namespace Senko.Discord.Exceptions
{
public class DiscordRestException : DiscordException
{
public DiscordRestException(string message, int code)
: base(message)
{
Code = code;
}
public int Code { get; }
}
}
|
namespace Eolina;
public class OutputToken : IToken
{
public string TokenRepresentation()
=> "<OutputToken>";
} |
#region Using
using System;
using System.Windows;
using System.Windows.Controls;
using System.Reflection;
using NLib;
using NLib.Services;
using DMT.Models;
//using DMT.Windows;
#endregion
namespace DMT.TOD.Pages.Menu
{
/// <summary>
/// Interaction logic for ReportMenu.xaml
/// </summary>
public partial class ReportMenu : UserControl
{
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public ReportMenu()
{
InitializeComponent();
}
#endregion
#region Interna Variables
private User _user = null;
#endregion
#region Button Handlers
// TEST - PASSED.
private void cmdRevenueSlipReport_Click(object sender, RoutedEventArgs e)
{
MethodBase med = MethodBase.GetCurrentMethod();
med.Info("==> MENU - Revenue Slip Report");
var win = TODApp.Windows.RevenueSlipSearch;
win.Setup(_user);
if (win.ShowDialog() == false) return;
if (win.SelectedEntry == null)
{
// write log
med.Info("ไม่พบรายการ ในวันที่เลือก.");
// No Selected Entry.
var msg = TODApp.Windows.MessageBox;
msg.Setup("ไม่พบรายการ ในวันที่เลือก", "DMT - Tour of Duty");
msg.ShowDialog();
return;
}
var page = TODApp.Pages.RevenueSlipPreview;
page.Setup(_user, win.SelectedEntry);
PageContentManager.Instance.Current = page;
}
// TEST - PASSED.
private void cmdRevenueSummaryReport_Click(object sender, RoutedEventArgs e)
{
MethodBase med = MethodBase.GetCurrentMethod();
med.Info("==> MENU - Revenue Daily Summary Report");
var win = TODApp.Windows.RevenueSummarySearch;
win.Setup(_user);
if (win.ShowDialog() == false) return;
if (win.Revenues == null)
{
// write log
med.Info(" - ไม่พบรายการ ในวันที่เลือก.");
// No Result found.
var msg = TODApp.Windows.MessageBox;
msg.Setup("ไม่พบรายการ ในวันที่เลือก", "DMT - Tour of Duty");
msg.ShowDialog();
return;
}
var page = TODApp.Pages.DailyRevenueSummaryPreview;
page.Setup(_user, win.Revenues);
PageContentManager.Instance.Current = page;
}
// TEST - PASSED.
private void cmdEmptySlipReport_Click(object sender, RoutedEventArgs e)
{
MethodBase med = MethodBase.GetCurrentMethod();
med.Info("==> MENU - Empty Revenue Slip Report");
// Revenue Slip (Empty).
var page = TODApp.Pages.EmptyRevenueSlip;
page.Setup(_user);
PageContentManager.Instance.Current = page;
}
private void cmdBack_Click(object sender, RoutedEventArgs e)
{
GotoMainMenu();
}
#endregion
#region Private Methods
private void GotoMainMenu()
{
MethodBase med = MethodBase.GetCurrentMethod();
med.Info("==> MENU - MAIN MENU");
// Main Menu Page
var page = TODApp.Pages.MainMenu;
PageContentManager.Instance.Current = page;
}
#endregion
#region Public Methods
/// <summary>
/// Setup.
/// </summary>
/// <param name="user">The User Instance.</param>
public void Setup(User user)
{
_user = user;
}
#endregion
}
}
|
using UnityEngine;
using UnityEngine.Playables;
namespace CharacterAnimationEssentials.Hand
{
[System.Serializable]
public class HandBehaviour : PlayableBehaviour
{
public HandPosePreset handPreset;
[Range(0f, 1f)] public float strengthMultiplier = 1f;
public HandPose HandPose => handPreset.ToHandPose();
public override void OnPlayableCreate(Playable playable)
{
}
}
} |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Newtonsoft.Json.Linq;
using PuppeteerSharp.Tests.Attributes;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace PuppeteerSharp.Tests.NetworkTests
{
[Collection(TestConstants.TestFixtureCollectionName)]
public class NetworkEventTests : PuppeteerPageBaseTest
{
public NetworkEventTests(ITestOutputHelper output) : base(output)
{
}
[SkipBrowserFact(skipFirefox: true)]
public async Task PageEventsRequest()
{
var requests = new List<Request>();
Page.Request += (_, e) => requests.Add(e.Request);
await Page.GoToAsync(TestConstants.EmptyPage);
Assert.Single(requests);
Assert.Equal(TestConstants.EmptyPage, requests[0].Url);
Assert.Equal(ResourceType.Document, requests[0].ResourceType);
Assert.Equal(HttpMethod.Get, requests[0].Method);
Assert.NotNull(requests[0].Response);
Assert.Equal(Page.MainFrame, requests[0].Frame);
Assert.Equal(TestConstants.EmptyPage, requests[0].Frame.Url);
}
[SkipBrowserFact(skipFirefox: true)]
public async Task PageEventsResponse()
{
var responses = new List<Response>();
Page.Response += (_, e) => responses.Add(e.Response);
await Page.GoToAsync(TestConstants.EmptyPage);
Assert.Single(responses);
Assert.Equal(TestConstants.EmptyPage, responses[0].Url);
Assert.Equal(HttpStatusCode.OK, responses[0].Status);
Assert.False(responses[0].FromCache);
Assert.False(responses[0].FromServiceWorker);
Assert.NotNull(responses[0].Request);
var remoteAddress = responses[0].RemoteAddress;
// Either IPv6 or IPv4, depending on environment.
Assert.True(remoteAddress.IP == "[::1]" || remoteAddress.IP == "127.0.0.1");
Assert.Equal(TestConstants.Port, remoteAddress.Port);
}
[SkipBrowserFact(skipFirefox: true)]
public async Task PageEventsRequestFailed()
{
await Page.SetRequestInterceptionAsync(true);
Page.Request += async (_, e) =>
{
if (e.Request.Url.EndsWith("css"))
{
await e.Request.AbortAsync();
}
else
{
await e.Request.ContinueAsync();
}
};
var failedRequests = new List<Request>();
Page.RequestFailed += (_, e) => failedRequests.Add(e.Request);
await Page.GoToAsync(TestConstants.ServerUrl + "/one-style.html");
Assert.Single(failedRequests);
Assert.Contains("one-style.css", failedRequests[0].Url);
Assert.Null(failedRequests[0].Response);
Assert.Equal(ResourceType.StyleSheet, failedRequests[0].ResourceType);
if (TestConstants.IsChrome)
{
Assert.Equal("net::ERR_FAILED", failedRequests[0].Failure);
}
else
{
Assert.Equal("NS_ERROR_FAILURE", failedRequests[0].Failure);
}
Assert.NotNull(failedRequests[0].Frame);
}
[SkipBrowserFact(skipFirefox: true)]
public async Task PageEventsRequestFinished()
{
var requests = new List<Request>();
Page.RequestFinished += (_, e) => requests.Add(e.Request);
await Page.GoToAsync(TestConstants.EmptyPage);
Assert.Single(requests);
Assert.Equal(TestConstants.EmptyPage, requests[0].Url);
Assert.NotNull(requests[0].Response);
Assert.Equal(HttpMethod.Get, requests[0].Method);
Assert.Equal(Page.MainFrame, requests[0].Frame);
Assert.Equal(TestConstants.EmptyPage, requests[0].Frame.Url);
}
[SkipBrowserFact(skipFirefox: true)]
public async Task ShouldFireEventsInProperOrder()
{
var events = new List<string>();
Page.Request += (_, _) => events.Add("request");
Page.Response += (_, _) => events.Add("response");
Page.RequestFinished += (_, _) => events.Add("requestfinished");
await Page.GoToAsync(TestConstants.EmptyPage);
Assert.Equal(new[] { "request", "response", "requestfinished" }, events);
}
[SkipBrowserFact(skipFirefox: true)]
public async Task ShouldSupportRedirects()
{
var events = new List<string>();
Page.Request += (_, e) => events.Add($"{e.Request.Method} {e.Request.Url}");
Page.Response += (_, e) => events.Add($"{(int)e.Response.Status} {e.Response.Url}");
Page.RequestFinished += (_, e) => events.Add($"DONE {e.Request.Url}");
Page.RequestFailed += (_, e) => events.Add($"FAIL {e.Request.Url}");
Server.SetRedirect("/foo.html", "/empty.html");
const string FOO_URL = TestConstants.ServerUrl + "/foo.html";
var response = await Page.GoToAsync(FOO_URL);
Assert.Equal(new[] {
$"GET {FOO_URL}",
$"302 {FOO_URL}",
$"DONE {FOO_URL}",
$"GET {TestConstants.EmptyPage}",
$"200 {TestConstants.EmptyPage}",
$"DONE {TestConstants.EmptyPage}"
}, events);
// Check redirect chain
var redirectChain = response.Request.RedirectChain;
Assert.Single(redirectChain);
Assert.Contains("/foo.html", redirectChain[0].Url);
Assert.Equal(TestConstants.Port, redirectChain[0].Response.RemoteAddress.Port);
}
}
}
|
using Valley.Net.Protocols.MeterBus.EN13757_2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Valley.Net.Protocols.MeterBus.EN13757_3
{
public abstract class DataPacket : Packet
{
public UInt16 Manufr { get; set; }
public UInt32 IdentificationNo { get; set; }
public byte TransmissionCounter { get; set; }
public DeviceType DeviceType { get; set; }
public DataPacket(byte address)
{
Address = address;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
namespace InfiniteMunitions
{
internal class AmmoRotate : WeaponUIExtension.Rotation
{
private static int GetAmmoType(Item weapon) => weapon.useAmmo;
private static List<int> GetAmmoSlots(Player player, int ammoType) =>
WeaponUIExtension.AmmoOrder.Where(i => player.inventory[i].ammo == ammoType).ToList();
public override bool CanRotate(Player player, Item weapon) => GetAmmoType(weapon) > 0;
public override Item GetUI(Player player, Item weapon) {
int ammoType = GetAmmoType(weapon);
if (ammoType <= 0)
return null;
var slots = GetAmmoSlots(player, ammoType);
return slots.Count > 0 ? player.inventory[slots[0]] : null;
}
public override void Rotate(Player player, Item weapon, int offset, bool scroll) {
int ammoType = GetAmmoType(weapon);
if (ammoType <= 0)
return;
var slots = GetAmmoSlots(player, ammoType);
if (slots.Count <= 1)
return;
while (offset >= slots.Count)
offset -= slots.Count;
while (offset < 0)
offset += slots.Count;
if (offset == 0)
return;
var items = slots.Skip(offset).Concat(slots.Take(offset))
.Select(i => player.inventory[i].Clone()).ToList();
for (int i = 0; i < slots.Count; i++)
player.inventory[slots[i]] = items[i];
SoundEngine.PlaySound(SoundID.MenuTick);
}
}
}
|
using System.Threading.Tasks;
using OCC.Passports.Common.Infrastructure;
namespace OCC.Passports.Common.Sample.Console.Contracts
{
public interface IController
{
Task<StandardResponse<int>> Calculate(string session, int lhs, string @operator, int rhs);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace VAdvantage.DataBase
{
/// <summary>
/// * Interface for Vienna Databases
/// </summary>
public interface ViennaDatabase
{
///// <summary>
///// Get Database Name
///// </summary>
///// <returns>database short name</returns>
//public String GetName();
///// <summary>
///// Get Database Description
///// </summary>
///// <returns>database long name and version</returns>
//public String GetDescription();
string GetName();
/// <summary>
/// Get Standard JDBC Port
/// </summary>
/// <returns>standard port</returns>
int GetStandardPort();
///// <summary>
///// Get Catalog
///// </summary>
///// <returns></returns>
//public String GetCatalog();
///// <summary>
/////Get JDBC Schema
///// </summary>
///// <returns>Schema</returns>
//public String GetSchema();
/// <summary>
/// Supports BLOB
/// </summary>
/// <returns>true if BLOB is supported</returns>
bool SupportsBLOB();
///// <summary>
///// String Representation
///// </summary>
///// <returns>info</returns>
//String ToString();
/// <summary>
/// Convert an individual Oracle Style statements to target database statement syntax
/// </summary>
/// <param name="oraStatement">oracle statement</param>
/// <returns>converted Statement</returns>
String ConvertStatement(String oraStatement);
///// <summary>
///// Check if DBMS support the sql statement
///// </summary>
///// <param name="sql">SQL statement</param>
///// <returns>true: yes</returns>
//public bool Isupported(String sql);
///// <summary>
///// Get constraint type associated with the index
///// </summary>
///// <param name="conn">connection</param>
///// <param name="tableName"> table name</param>
///// <param name="IXName">Index name</param>
///// <returns>String[0] = 0: do not know, 1: Primary Key 2: Foreign Key
//// String[1] - String[n] = Constraint Name</returns>
//public String GetConstraintType(System.Data.IDbConnection conn, String tableName, String IXName);
///// <summary>
///// Check and generate an alternative SQL
///// </summary>
///// <param name="reExNo">number of re-execution</param>
///// <param name="msg">previous execution error message</param>
///// <param name="sql">previous executed SQL</param>
///// <returns>the alternative SQL, null if no alternative</returns>
//public String GetAlternativeSQL(int reExNo, String msg, String sql);
///// <summary>
///// Get Name of System User
///// </summary>
///// <returns>e.g. sa, system</returns>
//public String GetSystemUser();
///// <summary>
///// Get Name of System Database
///// </summary>
///// <param name="databaseName">database Name</param>
///// <returns>master or database Name</returns>
//public String GetSystemDatabase(String databaseName);
/// <summary>
/// Create SQL TO Date String from Timestamp
/// </summary>
/// <param name="time">time Date to be converted</param>
/// <param name="dayOnly">dayOnly true if time set to 00:00:00</param>
/// <returns>date function</returns>
String TO_DATE(DateTime? time, bool dayOnly);
/// <summary>
/// Create SQL for formatted Date, Number
/// </summary>
/// <param name="columnName">columnName the column name in the SQL</param>
/// <param name="displayType">displayType Display Type</param>
/// <param name="AD_Language">AD_Language 6 character language setting (from Env.LANG_*)</param>
/// <returns>TRIM(TO_CHAR(columnName,'999G999G999G990D00','NLS_NUMERIC_CHARACTERS='',.'''))
/// or TRIM(TO_CHAR(columnName,'TM9')) depending on DisplayType and Language</returns>
String TO_CHAR(String columnName, int displayType, String AD_Language);
/// <summary>
/// Return number as string for INSERT statements with correct precision
/// </summary>
/// <param name="number">number</param>
/// <param name="displayType">display Type</param>
/// <returns>number as string</returns>
String TO_NUMBER(Decimal? number, int displayType);
/// <summary>
/// Return next sequence this Sequence
/// </summary>
/// <param name="Name">Sequence Name</param>
/// <returns></returns>
//int GetNextID(String Name);
/// <summary>
/// Create Native Sequence
/// </summary>
/// <param name="name"></param>
/// <param name="increment"></param>
/// <param name="minvalue"></param>
/// <param name="maxvalue"></param>
/// <param name="start"></param>
/// <param name="trxName"></param>
/// <returns></returns>
bool CreateSequence(String name, int increment, int minvalue, int maxvalue, int start, Trx trxName);
/// <summary>
/// Get Database Connection
/// </summary>
/// <param name="connection"></param>
/// <param name="autoCommit"></param>
/// <param name="transactionIsolation"></param>
/// <returns></returns>
System.Data.IDbConnection GetCachedConnection(
bool autoCommit, int transactionIsolation);
/// <summary>
/// Connection String
/// </summary>
void SetConnectionString(string conString);
DataSet ExecuteDatasetPaging(string sql, int page, int pageSize, int increment);
///** Create User commands */
// static int CMD_CREATE_USER = 0;
///** Create Database/Schema Commands */
// static int CMD_CREATE_DATABASE = 1;
///** Drop Database/Schema Commands */
//static int CMD_DROP_DATABASE = 2;
/// <summary>
/// Get SQL Commands.
///The following variables are resolved:
/// @SystemPassword@, @SystemUser@, @SystemPassword@
/// @SystemPassword@, @DatabaseName@, @DatabaseDevice@
/// </code>
/// @param cmdType CMD_*
/// </summary>
/// <param name="cmdType"></param>
///// <returns>array of commands to be executed</returns>
// String[] GetCommands(int cmdType);
///// <summary>
///// Close
///// </summary>
// void Close();
/// <summary>
///
/// </summary>
/// <returns></returns>
//public ConvertSql GetConvert();
///**
// * @return true if support statement timeout
// */
//public bool IsQueryTimeoutSupported();
/// <summary>
///Default sql use to test whether a connection is still valid
/// </summary>
// static String DEFAULT_CONN_TEST_SQL = "SELECT Version FROM AD_System";
/// <summary>
///// Is the database have sql extension that return a subset of the query result
///// </summary>
///// <returns></returns>
//public bool IsPagingSupported();
///// <summary>
///// modify sql to return a subset of the query result
///// </summary>
///// <param name="sql"></param>
///// <param name="start"></param>
///// <param name="end"></param>
///// <returns></returns>
//public String AddPagingSQL(String sql, int start, int end);
} // AdempiereDatabase
} |
using UnityEngine;
using System;
[CreateAssetMenu(menuName ="Rendering/Custom Post FX Settings")]
public class PostFXSettings : ScriptableObject
{
[SerializeField]
Shader shader = default;
#region 测试Shader功能
[SerializeField]
Shader skinBlitShader = default;
[SerializeField]
Texture skinTexture = null;
[SerializeField]
Texture baseSkinTexture = null;
#endregion
[System.NonSerialized]
Material material;
[System.NonSerialized]
Material skinBlitMaterial;
public Material Material
{
get
{
if (material == null && shader != null)
{
material = new Material(shader);
material.hideFlags = HideFlags.HideAndDontSave;
}
return material;
}
}
public Material SkinBlitMaterial
{
get
{
if(skinBlitMaterial == null && skinBlitShader!=null)
{
skinBlitMaterial = new Material(skinBlitShader);
skinBlitMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return skinBlitMaterial;
}
}
public Texture BaseSkinTexture
{
get
{
if (baseSkinTexture != null)
return baseSkinTexture;
return null;
}
}
public Texture SkinTexture
{
get
{
if(skinTexture != null)
{
return skinTexture;
}
return null;
}
}
[System.Serializable]
public struct BloomSettings
{
[Range(0f,16f)]
public int maxIterations;
[Min(1f)]
public int downscaleLimit;
/// <summary>
/// 三线性过滤
/// </summary>
public bool bicubicUpsampling;
/// <summary>
/// 阈值
/// </summary>
[Min(0f)]
public float threshold;
[Range(0f,1f)]
public float thresholdKnee;
[Min(0f)]
public float intensity;
/// <summary>
/// 解决摄像机移动闪闪发光
/// </summary>
public bool fadeFireflies;
public enum Mode { Additive, Scattering }
public Mode mode;
[Range(0.05f,0.95f)]
public float scatter;
}
[Serializable]
public struct ColorAdjustmentsSetting
{
/// <summary>
/// 曝光值
/// </summary>
public float postExposure;
[Range(-100f,100f)]
public float contrast;
[ColorUsage(false,true)]
public Color colorFilter;
[Range(-180f,180f)]
public float hueShift;
[Range(-100f,100f)]
public float saturation;
}
[Serializable]
public struct WhiteBalanceSettings
{
/// <summary>
/// 温度和色彩
/// </summary>
public float temperature, tint;
}
[Serializable]
public struct SplitToningSettings
{
[ColorUsage(false)]
public Color shadows, highlights;
[Range(-100f,100f)]
public float balance;
}
[Serializable]
public struct ChannelMixerSettings
{
public Vector3 red, green, blue;
}
[Serializable]
public struct ShadowMidtonesHighlightsSettngs
{
[ColorUsage(false,true)]
public Color shadows, midtones, highlights;
[Range(0f, 2f)]
public float shadowsStart, shadowsEnd, highlightsStart, highLightsEnd;
}
[Serializable]
public struct ToneMappingSettings
{
public enum Mode { None,ACES,Neutral,Reinhard }
public Mode mode;
}
[SerializeField]
BloomSettings bloom = new BloomSettings { scatter=0.7f};
public BloomSettings Bloom => bloom;
[SerializeField]
ColorAdjustmentsSetting colorAdjustments = new ColorAdjustmentsSetting { colorFilter=Color.white};
[SerializeField]
WhiteBalanceSettings whiteBalance = default;
[SerializeField]
SplitToningSettings splitToning = new SplitToningSettings { shadows = Color.gray, highlights = Color.gray };
[SerializeField]
ChannelMixerSettings channelMixer = new ChannelMixerSettings
{
red=Vector3.right,
green=Vector3.up,
blue=Vector3.forward
};
[SerializeField]
ShadowMidtonesHighlightsSettngs shadowsMidtonesHighlights = new ShadowMidtonesHighlightsSettngs
{
shadows=Color.white,
midtones=Color.white,
highlights=Color.white,
shadowsEnd=0.3f,
highlightsStart=0.55f,
highLightsEnd=1f
};
public WhiteBalanceSettings WhiteBalance => whiteBalance;
public SplitToningSettings SplitToning => splitToning;
public ChannelMixerSettings ChannelMixer => channelMixer;
public ShadowMidtonesHighlightsSettngs ShadowsMidtonesHighlights => shadowsMidtonesHighlights;
[SerializeField]
ToneMappingSettings toneMapping = default;
public ColorAdjustmentsSetting ColorAdjustments => colorAdjustments;
public ToneMappingSettings ToneMapping => toneMapping;
}
|
using System;
using System.Collections.Generic;
using Sifon.Forms.Profiles.UserControls.Base;
namespace Sifon.Forms.Profiles.UserControls.Parameters
{
internal interface IParametersView : IBaseView
{
event EventHandler<EventArgs> DownloadSampleScriptClicked;
void SetValues(Dictionary<string, string> parameters);
bool ValidateValues();
void SaveSampleScript(string script);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using UniversityCourseAndResultManagementSystemApp.Models;
namespace UniversityCourseAndResultManagementSystemApp.DAL
{
public class SemesterGetway
{
public List<Semester> GetAllSemester()
{
List<Semester> listOfSemester = new List<Semester>();
DBPlayer db = new DBPlayer();
try
{
db.cmdText = "SELECT * FROM Semesters";
db.Open();
SqlDataReader reader = db.command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Semester semester = new Semester();
semester.Id = int.Parse(reader["Id"].ToString());
semester.Name = reader["Name"].ToString();
listOfSemester.Add(semester);
}
}
reader.Close();
}
catch (Exception)
{
throw;
}
finally
{
db.Close();
}
return listOfSemester;
}
}
} |
using schedule.api.core.Base;
namespace schedule.api.core.Models
{
public class ModuleProfessor : BaseEntity
{
public Module Module { get; set; }
public Professor Professor { get; set; }
public long ModuleId { get; set; }
public long ProfessorId { get; set; }
}
}
|
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Viticulture.Logic.Pieces.Structures;
using Viticulture.Logic.State;
using Viticulture.Services;
namespace Viticulture.Screens.Game.Actions.Summer.BuildStructure
{
[Export(typeof(IBuildStructureViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class BuildStructureViewModel : DialogViewModel<Structure>, IBuildStructureViewModel
{
private readonly IGameState _gameState;
private readonly List<Structure> _structures;
[ImportingConstructor]
public BuildStructureViewModel(IGameState gameState)
{
_gameState = gameState;
_structures = new List<Structure>();
foreach (var structure in _gameState.Structures)
{
if (structure is LargeCellar && !_gameState.MediumCellar.IsBought) continue;
_structures.Add(structure);
}
}
public IEnumerable<Structure> Structures => _structures;
public int BuildingBonus { get; set; }
public void Buy(Structure structure)
{
Close(structure);
}
public bool CanBuy(Structure structure)
{
return structure.Cost <= _gameState.Money + BuildingBonus;
}
public void Cancel()
{
Close(null);
}
}
} |
using UnityEngine;
using UnityEngine.UI;
public class HealthText : MonoBehaviour
{
public Text text;
public CharacterHealth health;
private void OnEnable()
{
health.OnHealthChange += SetText;
}
private void OnDisable()
{
health.OnHealthChange -= SetText;
}
private void Start()
{
SetText(health.Health);
}
private void SetText(float health)
{
text.text = string.Format("Health: {0:0}", health);
}
}
|
using System;
using NUnit.Framework;
namespace TorSteroids.Common.UnitTests
{
[Flags]
enum ExX
{
None = 0, A = 1, B = 2, C = 4, D = 8, All = A | B | C | D
}
[TestFixture]
public class BitExTests
{
[Test]
public void TestSetFlagWithEnum()
{
ExX x = ExX.A | ExX.D;
ExX newX = x.SetFlag(ExX.B);
Assert.IsTrue((newX & ExX.A) == ExX.A, "A not set in ExX");
Assert.IsTrue((newX & ExX.B) == ExX.B, "B not set in ExX");
Assert.IsFalse((newX & ExX.C) == ExX.C, "C set in ExX is unexpected");
Assert.IsTrue((newX & ExX.D) == ExX.D, "D not set in ExX");
newX = x.SetFlag(ExX.None);
Assert.IsTrue(newX == x);
x = ExX.None;
newX = x.SetFlag(ExX.B);
Assert.IsFalse((newX & ExX.A) == ExX.A, "A set in ExX is unexpected");
Assert.IsTrue((newX & ExX.B) == ExX.B, "B not set in ExX");
Assert.IsFalse((newX & ExX.C) == ExX.C, "C set in ExX is unexpected");
Assert.IsFalse((newX & ExX.D) == ExX.D, "D set in ExX is unexpected");
}
[Test, ExpectedException(typeof(ArgumentException))]
public void TestSetFlagWithEnumExpectException()
{
ExX x = ExX.A | ExX.D;
x.SetFlag(X.B);
}
[Test]
public void TestHasFlagWithEnum()
{
ExX x = ExX.A | ExX.D;
Assert.IsTrue(x.HasFlag(ExX.A), "Expected: true, because A is set in x");
Assert.IsFalse(x.HasFlag(ExX.B), "Expected: false, because B is not set in x");
Assert.IsTrue(x.HasFlag(ExX.D), "Expected: true, because D is set in x");
}
[Test, ExpectedException(typeof(ArgumentException))]
public void TestHasFlagWithEnumExpectException()
{
ExX x = ExX.A | ExX.D;
x.HasFlag(X.B);
}
[Test]
public void TestClearFlagWithEnum()
{
ExX x = ExX.All.ClearFlag(ExX.C);
Assert.IsTrue((x & ExX.A) == ExX.A, "Expected: true, because A is set in x");
Assert.IsFalse((x & ExX.C) == ExX.C, "Expected: false, because C should be cleared from x");
Assert.IsTrue((x & ExX.D) == ExX.D, "Expected: true, because D is set in x");
x = ExX.All.ClearFlag(ExX.None);
Assert.IsTrue((x & ExX.A) == ExX.A, "Expected: true, because A is set in x");
Assert.IsTrue((x & ExX.B) == ExX.B, "Expected: true, because B is set in x");
Assert.IsTrue((x & ExX.C) == ExX.C, "Expected: true, because C is set in x");
Assert.IsTrue((x & ExX.D) == ExX.D, "Expected: true, because D is set in x");
x = ExX.None.ClearFlag(ExX.A);
Assert.IsFalse((x & ExX.A) == ExX.A, "Expected: false, because x was None");
Assert.IsFalse((x & ExX.B) == ExX.B, "Expected: false, because x was None");
Assert.IsFalse((x & ExX.C) == ExX.C, "Expected: false, because x was None");
Assert.IsFalse((x & ExX.D) == ExX.D, "Expected: false, because x was None");
}
[Test]
public void TestClearFlagWithParamsEnum()
{
ExX x = ExX.All.ClearFlag(ExX.B, ExX.C);
Assert.IsTrue((x & ExX.A) == ExX.A, "Expected: true, because A is set in x");
Assert.IsFalse((x & ExX.B) == ExX.B, "Expected: false, because B should be cleared from x");
Assert.IsFalse((x & ExX.C) == ExX.C, "Expected: false, because C should be cleared from x");
Assert.IsTrue((x & ExX.D) == ExX.D, "Expected: true, because D is set in x");
}
[Test, ExpectedException(typeof(ArgumentException))]
public void TestClearFlagWithEnumExpectException()
{
ExX x = ExX.A | ExX.D;
x.ClearFlag(X.B);
}
[Test]
public void TestToggleFlagWithEnum()
{
ExX realX = ExX.A | ExX.C | ExX.D;
ExX x = realX.ToggleFlag(false, ExX.C);
Assert.IsTrue((x & ExX.A) == ExX.A, "Expected: true, because A is set in x");
Assert.IsFalse((x & ExX.C) == ExX.C, "Expected: false, because C should be cleared from x");
Assert.IsTrue((x & ExX.D) == ExX.D, "Expected: true, because D is set in x");
Assert.IsFalse((x & ExX.B) == ExX.B, "Expected: false, because B was not set at x");
x = realX.ToggleFlag(true, ExX.B);
Assert.IsTrue((x & ExX.B) == ExX.B, "Expected: true, because B was now set at x");
x = realX.ToggleFlag(true, ExX.None);
Assert.IsTrue(x == realX);
x = realX.ToggleFlag(false, ExX.None);
Assert.IsTrue(x == realX);
}
[Test, ExpectedException(typeof(ArgumentException))]
public void TestToggleFlagWithEnumExpectException()
{
ExX realX = ExX.A | ExX.C | ExX.D;
realX.ToggleFlag(false, X.C);
}
}
}
|
using FluentAssertions;
using Voidwell.Microservice.Tracing;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Voidwell.Microservice.Logging.Enrichers;
namespace Voidwell.Microservice.Test.Tracing
{
public class TracingExtensionsTest
{
[Fact]
public void AddTracing_TracingContextFactoryFromServiceProvider_NotNull()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(a => a.AddTracing())
.Configure(appBuilder => { });
using (var server = new TestServer(webHostBuilder))
{
var result = server.Host.Services.GetService<Func<TraceContext>>();
result.Should().NotBeNull();
}
}
[Fact]
public void AddTracing_TraceContextAccesssorContextFromServiceProvider_NotNull()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(a => a.AddTracing())
.Configure(appBuilder => { });
using (var server = new TestServer(webHostBuilder))
{
var result = server.Host.Services.GetService<ITraceContextAccessor>();
result.Should().NotBeNull()
.And.BeOfType<TraceContextAccessor>();
}
}
[Fact]
public void AddTracing_TracingHttpMessageHandlerFromServiceProvider_CorrectType()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(a => a.AddTracing())
.Configure(appBuilder => { });
using (var server = new TestServer(webHostBuilder))
{
var result = server.Host.Services.GetService<TracingHttpMessageHandler>();
result.Should().NotBeNull()
.And.BeOfType<TracingHttpMessageHandler>();
}
}
[Fact]
public void AddTracing_TracingEnricherFromServiceProvider_CorrectType()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(a => a.AddTracing())
.Configure(appBuilder => { });
using (var server = new TestServer(webHostBuilder))
{
var result = server.Host.Services.GetService<TracingEnricher>();
result.Should().NotBeNull()
.And.BeOfType<TracingEnricher>();
}
}
}
}
|
[RequiredByNativeCodeAttribute] // RVA: 0xC6570 Offset: 0xC6671 VA: 0xC6570
public class ResourceRequest : AsyncOperation // TypeDefIndex: 2988
{
// Fields
internal string m_Path; // 0x20
internal Type m_Type; // 0x28
// Properties
public Object asset { get; }
// Methods
// RVA: 0x2A240A0 Offset: 0x2A241A1 VA: 0x2A240A0
public Object get_asset() { }
// RVA: 0x2A24140 Offset: 0x2A24241 VA: 0x2A24140
public void .ctor() { }
}
|
using System;
using FluentAssertions;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Xunit;
namespace Extensions.Caching.Extras.Tests
{
public class MemoryCachePartitionTests
{
private readonly IMemoryCache _underlyingCache;
public MemoryCachePartitionTests()
{
var cacheOptions = Options.Create(new MemoryCacheOptions());
_underlyingCache = new MemoryCache(cacheOptions);
}
[Fact]
public void Can_set_and_get_value()
{
var cache = CreatePartition("test");
var key = 42;
var originalValue = new object();
cache.Set(key, originalValue);
var actualValue = cache.Get(key);
actualValue.Should().BeSameAs(originalValue);
}
[Fact]
public void Can_set_and_remove_value()
{
var cache = CreatePartition("test");
var key = 42;
cache.Set(key, new object());
cache.Remove(key);
cache.TryGetValue(key, out _).Should().BeFalse();
}
[Fact]
public void Entry_is_not_in_underlying_cache()
{
var cache = CreatePartition("test");
var key = 42;
cache.Set(key, new object());
_underlyingCache.TryGetValue(key, out _).Should().BeFalse();
}
[Fact]
public void Entry_is_not_shared_with_other_partition_with_different_key()
{
var cache1 = CreatePartition("test1");
var cache2 = CreatePartition("test2");
var key = 42;
cache1.Set(key, new object());
cache2.TryGetValue(key, out _).Should().BeFalse();
}
[Fact]
public void Entry_is_shared_with_other_partition_with_same_key()
{
var cache1 = CreatePartition("test");
var cache2 = CreatePartition("test");
var key = 42;
var originalValue = new object();
cache1.Set(key, originalValue);
var actualValue = cache2.Get(key);
actualValue.Should().Be(originalValue);
}
private IMemoryCache CreatePartition(object partitionKey) => _underlyingCache.Partition(partitionKey);
}
}
|
namespace AnyJob
{
/// <summary>
/// 表示状态跟踪服务
/// </summary>
public interface ITraceService
{
/// <summary>
/// 跟踪执行状态
/// </summary>
/// <param name="context">执行上下文</param>
/// <param name="state">执行状态</param>
/// <param name="result">执行结果</param>
//void TraceState(IExecuteContext context, ExecuteState state, ExecuteResult result);
/// <summary>
/// 跟踪执行状态
/// </summary>
/// <param name="traceInfo">提供跟踪的一些信息</param>
void TraceState(ITraceInfo traceInfo);
}
}
|
using BotSharp.Core;
using BotSharp.Platform.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace BotSharp.Platform.Dialogflow
{
public class PlatformSettings : PlatformSettingsBase
{
}
}
|
namespace ESFA.DC.ReferenceData.Stateless.Config
{
public class ReferenceDataConfiguration
{
public string ServiceBusConnectionString { get; set; }
public string JobsQueueName { get; set; }
public string JobStatusQueueName { get; set; }
public string AuditQueueName { get; set; }
public string LoggerConnectionString { get; set; }
}
}
|
@page
@model CustomerModel
<div class="text-center">
<h1 class="display-4">Welcome Customer!</h1>
@if (User.IsInRole("Admin"))
{
<h3>As Admin, you have access to all authorized areas.</h3>
}
</div> |
using System;
using System.Threading.Tasks;
namespace Conference.Clients.Portable
{
public interface IWiFiConfig
{
bool ConfigureWiFi(string ssid, string password);
bool IsConfigured(string ssid);
bool IsWiFiOn();
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ngpvanapi.Models
{
public class SignupList
{
[JsonProperty("items")]
public List<Signup> Items;
[JsonProperty("count")]
public int Count;
[JsonProperty("nextPageLink")]
public string NextPageLink;
[JsonProperty("top")]
public int? Top;
[JsonProperty("skip")]
public int? Skip;
[JsonProperty("vanId")]
public int? VanId;
[JsonProperty("eventId")]
public int? EventId;
}
public class Signup
{
[JsonProperty("person")]
public People Person;
[JsonProperty("event")]
public Event Event;
[JsonProperty("status")]
public Status Status;
[JsonProperty("role")]
public Role Role;
[JsonProperty("shift")]
public Shift Shift;
[JsonProperty("location")]
public Location Location;
}
public class SignupView
{
public int VanId;
public int EventId;
public int? StatusId;
public Event Event;
public List<Status> Statuses;
}
public class Status
{
[JsonProperty("statusId")]
public int StatusId;
[JsonProperty("name")]
public string Name;
}
} |
namespace AwsAspNetCoreLabs.Models.Logging
{
public class LogExceptionModel
{
public string Source { get; set; }
public string Message { get; set; }
public string[] StackTrace { get; set; }
public LogExceptionModel InnerException { get; set; }
}
}
|
namespace OpenClosedDrawingShapesAfter
{
using OpenClosedDrawingShapesAfter.Contracts;
public class Circle : IShape
{
public void DrawOnSurface(ISurface surface)
{
//do something on that surface
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shoot : MonoBehaviour {
public static string sphereObject = "Sphere";
public int speed = 40;
GameObject prefab;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
prefab = Resources.Load(sphereObject) as GameObject;
if (Input.GetMouseButtonDown(0))
{
GameObject ball = Instantiate(prefab) as GameObject;
ball.transform.position = transform.position + Camera.main.transform.forward * 1.3f;
Rigidbody rb = ball.GetComponent<Rigidbody>();
rb.velocity = Camera.main.transform.forward * speed;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Windows.UI.Xaml.Media.Animation
{
public enum ClockState
{
Active = 0,
Filling = 1,
Stopped = 2
}
}
|
using Assets.Scripts.Character;
using UnityEngine;
namespace Assets.Scripts.Attic.Interaction
{
public class InteractionToggler : MonoBehaviour
{
public InteractionObject TargetInteraction;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == CharacterPerspController.CHARACTER_TAG)
{
TargetInteraction.ActivateObject();
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == CharacterPerspController.CHARACTER_TAG)
{
TargetInteraction.DeactivateObject();
}
}
}
}
|
using System;
namespace NDO.Configuration
{
/// <summary>
/// Creates one instance of a type during the lifetime of a controller
/// </summary>
public class ContainerControlledLifetimeManager : ILifetimeManager
{
///<inheritdoc/>
public IResolver CreateResolver(Type tFrom, Type tTo)
{
return new ContainerControlledTypeMappingResolver( tFrom, tTo );
}
}
}
|
using EventWebHooks.PushEventsToElasticSearch.Events;
namespace EventWebHooks.PushEventsToElasticSearch.SubjectHandlers
{
public class EmployeeCreatedHandler : BaseHandler<EmployeeCreated>, ISubjectHandler
{
public override string Subject => "EmployeeCreated";
}
} |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Net;
using Multiverse.Config;
#endregion
namespace Multiverse.Network.Rdp
{
public enum ConnectionState
{
/// <summary>
/// The CLOSED state exists when no connection exists and there
/// is no connection record allocated.
/// </summary>
Closed,
/// <summary>
/// The LISTEN state is entered after a passive Open request is
/// processed. A connection record is allocated and RDP waits
/// for an active request to establish a connection from a
/// remote site.
/// </summary>
Listen,
/// <summary>
/// The SYN-SENT state is entered after processing an active
/// Open request. A connection record is allocated, an initial
/// sequence number is generated, and a SYN segment is sent to
/// the remote site. RDP then waits in the SYN-SENT state for
/// acknowledgement of its Open request.
/// </summary>
SynSent,
/// <summary>
/// The SYN-RCVD state may be reached from either the LISTEN
/// state or from the SYN-SENT state. SYN-RCVD is reached from
/// the LISTEN state when a SYN segment requesting a connection
/// is received from a remote host. In reply, the local RDP
/// generates an initial sequence number for its side of the
/// connection, and then sends the sequence number and an
/// acknowledgement of the SYN segment to the remote site. It
/// then waits for an acknowledgement.
///
/// The SYN-RCVD state is reached from the SYN-SENT state when a
/// SYN segment is received from the remote host without an
/// accompanying acknowledgement of the SYN segment sent to that
/// remote host by the local RDP. This situation is caused by
/// simultaneous attempts to open a connection, with the SYN
/// segments passing each other in transit. The action is to
/// repeat the SYN segment with the same sequence number, but
/// now including an ACK of the remote host's SYN segment to
/// indicate acceptance of the Open request.
/// </summary>
SynRcvd,
/// <summary>
/// The OPEN state exists when a connection has been established
/// by the successful exchange of state information between the
/// two sides of the connection. Each side has exchanged and
/// received such data as initial sequence number, maximum
/// segment size, and maximum number of unacknowledged segments
/// that may be outstanding. In the Open state data may be sent
/// between the two parties of the connection.
/// </summary>
Open,
/// <summary>
/// The CLOSE-WAIT state is entered from either a Close request
/// or from the receipt of an RST segment from the remote site.
/// RDP has sent an RST segment and is waiting a delay period
/// for activity on the connection to complete.
/// </summary>
CloseWait
}
public class RdpPacket {
// +-+-+-+-+-+-+---+---------------+
// |S|A|E|R|N| |Ver| Header |
// 0 |Y|C|A|S|U|0|No.| Length |
// |N|K|K|T|L| | | |
// +-+-+-+-+-+-+---+---------------+
// 1 | Source Port | Dest. Port |
// +---------------+---------------+
// 2 | Data Length |
// +---------------+---------------+
// 3 | |
// +--- Sequence Number ---+
// 4 | |
// +---------------+---------------+
// 5 | |
// +--- Acknowledgement Number ---+
// 6 | |
// +---------------+---------------+
// 7 | |
// +--- Checksum ---+
// 8 | |
// +---------------+---------------+
// 9 | Variable Header Area |
// . .
// . .
// | |
// | |
// +---------------+---------------+
const byte SynMask = 1 << 7;
const byte AckMask = 1 << 6;
const byte EakMask = 1 << 5;
const byte RstMask = 1 << 4;
const byte NulMask = 1 << 3;
const byte VerMask = 3;
byte[] data;
static private byte[] Convert(int val) {
return BitConverter.GetBytes(IPAddress.HostToNetworkOrder(val));
}
static private int Convert(byte[] val, int offset) {
return IPAddress.HostToNetworkOrder(BitConverter.ToInt32(val, offset));
}
public RdpPacket(byte[] data) {
this.data = data;
}
public RdpPacket(int dataLength) : this(dataLength, 0) {
}
public RdpPacket(int dataLength, int optionLength) {
data = new byte[dataLength + optionLength + 18];
HeaderLength = 18 + optionLength;
DataLength = dataLength;
}
#region Properties
public bool Syn {
get {
return (data[0] & SynMask) != 0;
}
set {
if (value)
data[0] |= SynMask;
else if (Syn)
data[0] -= SynMask;
}
}
public bool Ack {
get {
return (data[0] & AckMask) != 0;
}
set {
if (value)
data[0] |= AckMask;
else if (Ack)
data[0] -= AckMask;
}
}
public bool Eak {
get {
return (data[0] & EakMask) != 0;
}
set {
if (value)
data[0] |= EakMask;
else if (Eak)
data[0] -= EakMask;
}
}
public bool Rst {
get {
return (data[0] & RstMask) != 0;
}
set {
if (value)
data[0] |= RstMask;
else if (Rst)
data[0] -= RstMask;
}
}
public bool Nul {
get {
return (data[0] & NulMask) != 0;
}
set {
if (value)
data[0] |= NulMask;
else if (Nul)
data[0] -= NulMask;
}
}
public bool HasData {
get {
return DataLength != 0;
}
}
public int DataLength {
get {
return 256 * data[4] + data[5];
}
set {
data[4] = (byte)(value / 256);
data[5] = (byte)(value % 256);
}
}
public int HeaderLength {
get {
return (int)data[1];
}
set {
data[1] = (byte)value;
}
}
public int SourcePort {
get {
return (int)data[2];
}
set {
data[2] = (byte)value;
}
}
public int DestPort {
get {
return (int)data[3];
}
set {
data[3] = (byte)value;
}
}
public int SeqNumber {
get {
return Convert(data, 6);
}
set {
byte[] val = Convert(value);
Array.Copy(val, 0, data, 6, 4);
}
}
public int AckNumber {
get {
return Convert(data, 10);
}
set {
byte[] val = Convert(value);
Array.Copy(val, 0, data, 10, 4);
}
}
public int Checksum {
get {
return Convert(data, 14);
}
set {
byte[] val = Convert(value);
Array.Copy(val, 0, data, 14, 4);
}
}
#endregion
}
public class RdpConnection
{
ConnectionState state;
/// <summary>
/// The sequence number of the next segment that is to be sent.
/// </summary>
int sndNxt;
/// <summary>
/// The sequence number of the oldest unacknowledged segment.
/// </summary>
int sndUna;
/// <summary>
/// The maximum number of outstanding (unacknowledged) segments
/// that can be sent. The sender should not send more than this
/// number of segments without getting an acknowledgement.
/// </summary>
int sndMax;
/// <summary>
/// The initial send sequence number. This is the sequence
/// number that was sent in the SYN segment.
/// </summary>
int sndIss;
/// <summary>
/// The sequence number of the last segment received correctly
/// and in sequence.
/// </summary>
int rcvCur;
/// <summary>
/// The maximum number of segments that can be buffered for this
/// connection.
/// </summary>
int rcvMax;
/// <summary>
/// The initial receive sequence number. This is the sequence
/// number of the SYN segment that established this connection.
/// </summary>
int rcvIrs;
/// <summary>
/// The array of sequence numbers of segments that have been
/// received and acknowledged out of sequence.
/// </summary>
List<int> rcvdSeqNos = new List<int>();
/// <summary>
/// A timer used to time out the CLOSE-WAIT state.
/// </summary>
int closeWait;
/// <summary>
/// The largest possible segment (in octets) that can legally be
/// sent. This variable is specified by the foreign host in the
/// SYN segment during connection establishment.
/// </summary>
int sbufMax;
/// <summary>
/// The largest possible segment (in octets) that can be
/// received. This variable is specified by the user when the
/// connection is opened. The variable is sent to the foreign
/// host in the SYN segment.
/// </summary>
int rbufMax;
/// <summary>
/// The sequence number of the segment currently being
/// processed.
/// </summary>
int segSeq;
/// <summary>
/// The acknowledgement sequence number in the segment currently
/// being processed.
/// </summary>
int segAck;
/// <summary>
/// The maximum number of outstanding segments the receiver is
/// willing to hold, as specified in the SYN segment that
/// established the connection.
/// </summary>
int segMax;
/// <summary>
/// The maximum segment size (in octets) accepted by the foreign
/// host on a connection, as specified in the SYN segment that
/// established the connection.
/// </summary>
int segBmax;
int localPort;
int remotePort;
bool passiveOpen;
bool outOfOrderAllowed;
List<RdpPacket> unacknowledgedPackets = new List<RdpPacket>();
public RdpConnection() {
state = ConnectionState.Closed;
outOfOrderAllowed = true;
}
public void Open(bool passiveOpen, int localPort, int remotePort,
int sndMax, int rmaxBuf)
{
if (state != ConnectionState.Closed)
throw new Exception("Error - connection already open");
this.passiveOpen = passiveOpen;
// Create a connection record
if (passiveOpen) {
if (localPort <= 0)
throw new Exception("Error - local port not specified");
sndIss = 0;
sndNxt = sndIss + 1;
sndUna = sndIss;
this.sndMax = sndMax;
this.rbufMax = rmaxBuf;
state = ConnectionState.Listen;
} else {
if (remotePort <= 0)
throw new Exception("Error - remote port not specified");
sndIss = 0;
sndNxt = sndIss + 1;
sndUna = sndIss;
this.sndMax = sndMax;
this.rbufMax = rmaxBuf;
state = ConnectionState.Listen;
// TODO: Change this so that they can pass in 0 or something,
// and automatically pick a local port.
this.localPort = localPort;
/// Send <SEQ=SND.ISS><MAX=SND.MAX><MAXBUF=RMAX.BUF><SYN>
state = ConnectionState.SynSent;
}
}
public void Send(RdpPacket packet) {
switch (state) {
case ConnectionState.Open:
if (sndNxt >= sndUna + sndMax)
throw new Exception("Error - insufficient resources to send data");
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK><Data>
sndNxt = sndNxt + 1;
break;
case ConnectionState.Listen:
case ConnectionState.SynRcvd:
case ConnectionState.SynSent:
case ConnectionState.Closed:
case ConnectionState.CloseWait:
throw new Exception("Error - connection not open");
break;
}
}
public byte[] Receive() {
switch (state) {
case ConnectionState.Open:
// TODO: Add code to get data if pending or return no data
// if (data pending)
// return data;
return null;
case ConnectionState.Listen:
case ConnectionState.SynRcvd:
case ConnectionState.SynSent:
return null;
case ConnectionState.Closed:
case ConnectionState.CloseWait:
throw new Exception("Error - connection not open");
}
return null;
}
public void Close() {
switch (state) {
case ConnectionState.Open:
/// Send <SEQ=SND.NXT><RST>;
state = ConnectionState.CloseWait;
// TODO: Start TIMWAIT Timer
break;
case ConnectionState.Listen:
state = ConnectionState.Closed;
break;
case ConnectionState.SynRcvd:
case ConnectionState.SynSent:
/// Send <SEQ=SND.NXT><RST>
state = ConnectionState.Closed;
break;
case ConnectionState.CloseWait:
throw new Exception("Error - Connection closing");
break;
case ConnectionState.Closed:
throw new Exception("Error - Connection not open");
break;
}
}
// TODO: Should I pass in remote endpoint?
public void OnSegmentArrival(RdpPacket packet) {
switch (state) {
case ConnectionState.Closed:
if (packet.Rst)
return;
else if (packet.Ack || packet.Nul) {
/// Send <SEQ=SEG.ACK + 1><RST>
;
} else {
/// Send <SEQ=0><RST><ACK=SEG.SEQ><ACK>
;
}
break;
case ConnectionState.CloseWait:
break;
case ConnectionState.Listen:
if (packet.Rst)
return;
if (packet.Ack || packet.Nul) {
/// Send <SEQ=SEG.ACK + 1><RST>
return;
}
if (packet.Syn) {
rcvCur = segSeq;
rcvIrs = segSeq;
sndMax = segMax;
sbufMax = segBmax;
/// Send <SEQ=SND.ISS><ACK=RCV.CUR><MAX=RCV.MAX><BUFMAX=RBUF.MAX>
/// <ACK><SYN>
state = ConnectionState.SynRcvd;
return;
}
Trace.TraceWarning("Shouldn't have gotten here");
break;
case ConnectionState.SynSent:
if (packet.Rst) {
if (packet.Ack) {
state = ConnectionState.Closed;
throw new Exception("Connection Refused");
// TODO: deallocate connection
}
return;
}
if (packet.Syn) {
rcvCur = segSeq;
rcvIrs = segSeq;
sndMax = segMax;
rbufMax = segBmax;
if (packet.Ack) {
sndUna = segAck + 1; // per rfc 1151
state = ConnectionState.Open;
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK>
} else {
state = ConnectionState.SynRcvd;
/// Send <SEQ=SND.ISS><ACK=RCV.CUR><MAX=RCV.MAX><BUFMAX=RBUF.MAX>
// <SYN><ACK>
}
return;
}
if (packet.Ack) {
if (!packet.Rst && segAck != sndIss) {
/// Send <SEQ=SEG.ACK + 1><RST>
state = ConnectionState.Closed;
throw new Exception("Connection Reset");
// TODO: deallocate connection
return;
}
}
Trace.TraceWarning("Shouldn't have gotten here");
break;
case ConnectionState.SynRcvd:
if (rcvIrs >= segSeq || segSeq > (rcvCur + rcvMax * 2))
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK>
return;
if (packet.Rst) {
if (passiveOpen)
state = ConnectionState.Listen;
else {
state = ConnectionState.Closed;
throw new Exception("Connection Refused");
// TODO: deallocate connection
}
return;
}
if (packet.Syn) {
/// Send <SEQ=SEG.ACK + 1><RST>
state = ConnectionState.Closed;
throw new Exception("Connection Reset");
// TODO: deallocate connection
return;
}
if (packet.Eak) {
/// Send <SEQ=SEG.ACK + 1><RST>
return;
}
if (packet.Ack) {
if (segAck == sndIss)
state = ConnectionState.Open;
else
/// Send <SEQ=SEG.ACK + 1><RST>
return;
} else
return;
if (packet.HasData || packet.Nul) {
bool inSequence = true;
// If the received segment is in sequence
if (inSequence) {
/// TODO: Copy the data (if any) to user buffers
rcvCur = segSeq;
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK>
} else {
if (outOfOrderAllowed)
// TODO: Copy the data (if any) to user buffers
;
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK><EACK><RCVDSEQNO1>
/// ...<RCVDSEQNOn>
}
}
break;
case ConnectionState.Open:
if (rcvCur >= segSeq || segSeq > (rcvCur + rcvMax * 2)) {
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK>
return;
}
if (packet.Rst) {
state = ConnectionState.CloseWait;
throw new Exception("Connection Reset");
return;
}
if (packet.Nul) {
rcvCur = segSeq;
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK>
return;
}
if (packet.Syn) {
/// Send <SEQ=SEG.ACK + 1><RST>
state = ConnectionState.Closed;
throw new Exception("Connection Reset");
// TODO: deallocate connection
return;
}
if (packet.Ack) {
if (sndUna <= segAck && segAck < sndNxt) {
sndUna = segAck + 1; // per rfc 1151
// TODO: Flush acknowledged segments
}
}
if (packet.Eak) {
// TODO: Flush acknowledged segments
}
if (packet.HasData) {
bool inSequence = true;
// If the received segment is in sequence
if (inSequence) {
/// TODO: Copy the data (if any) to user buffers
rcvCur = segSeq;
// This can have EACKS too, if you want
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK>
} else {
if (outOfOrderAllowed)
// TODO: Copy the data (if any) to user buffers
;
/// Send <SEQ=SND.NXT><ACK=RCV.CUR><ACK><EACK><RCVDSEQNO1>
/// ...<RCVDSEQNOn>
}
}
break;
}
}
public void OnRetransmissionTimeout() {
// Re-send
}
public void OnCloseWaitTimeout() {
state = ConnectionState.Closed;
// this should be in some higher level guy that pulls me
}
public ConnectionState State {
get {
return state;
}
}
// TODO: Methods to get:
// Number of segments unacknowledged
// Number of segments received not given to user
public int MaxReceiveSegment {
get {
return rbufMax;
}
}
public int MaxSendSegment {
get {
return segBmax;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BizHawk.Common;
using BizHawk.Emulation.Common;
namespace BizHawk.Client.Common
{
/// <summary>
/// Represents an aggregated savestate file that includes core, movie, and other related data
/// </summary>
public class SavestateFile
{
private readonly IEmulator _emulator;
private readonly IStatable _statable;
private readonly IVideoProvider _videoProvider;
private readonly IMovieSession _movieSession;
private readonly IQuickBmpFile _quickBmpFile;
private readonly IDictionary<string, object> _userBag;
public SavestateFile(
IEmulator emulator,
IMovieSession movieSession,
IQuickBmpFile quickBmpFile,
IDictionary<string, object> userBag)
{
if (!emulator.HasSavestates())
{
throw new InvalidOperationException("The provided core must have savestates");
}
_emulator = emulator;
_statable = emulator.AsStatable();
if (emulator.HasVideoProvider())
{
_videoProvider = emulator.AsVideoProvider();
}
_movieSession = movieSession;
_quickBmpFile = quickBmpFile;
_userBag = userBag;
}
public void Create(string filename, SaveStateConfig config)
{
// the old method of text savestate save is now gone.
// a text savestate is just like a binary savestate, but with a different core lump
using var bs = new ZipStateSaver(filename, config.CompressionLevelNormal);
bs.PutVersionLumps();
using (new SimpleTime("Save Core"))
{
if (config.Type == SaveStateType.Text)
{
bs.PutLump(BinaryStateLump.CorestateText, tw => _statable.SaveStateText(tw));
}
else
{
bs.PutLump(BinaryStateLump.Corestate, bw => _statable.SaveStateBinary(bw));
}
}
if (config.SaveScreenshot && _videoProvider != null)
{
var buff = _videoProvider.GetVideoBuffer();
if (buff.Length == 1)
{
// is a hacky opengl texture ID. can't handle this now!
// need to discuss options
// 1. cores must be able to provide a pixels VideoProvider in addition to a texture ID, on command (not very hard overall but interface changing and work per core)
// 2. SavestateManager must be setup with a mechanism for resolving texture IDs (even less work, but sloppy)
// There are additional problems with AVWriting. They depend on VideoProvider providing pixels.
}
else
{
int outWidth = _videoProvider.BufferWidth;
int outHeight = _videoProvider.BufferHeight;
// if buffer is too big, scale down screenshot
if (!config.NoLowResLargeScreenshots && buff.Length >= config.BigScreenshotSize)
{
outWidth /= 2;
outHeight /= 2;
}
using (new SimpleTime("Save Framebuffer"))
{
bs.PutLump(BinaryStateLump.Framebuffer, s => _quickBmpFile.Save(_videoProvider, s, outWidth, outHeight));
}
}
}
if (_movieSession.Movie.IsActive())
{
bs.PutLump(BinaryStateLump.Input,
delegate(TextWriter tw)
{
// this never should have been a core's responsibility
tw.WriteLine("Frame {0}", _emulator.Frame);
_movieSession.HandleSaveState(tw);
});
}
if (_userBag.Any())
{
bs.PutLump(BinaryStateLump.UserData,
delegate(TextWriter tw)
{
var data = ConfigService.SaveWithType(_userBag);
tw.WriteLine(data);
});
}
if (_movieSession.Movie.IsActive() && _movieSession.Movie is ITasMovie)
{
bs.PutLump(BinaryStateLump.LagLog,
delegate(TextWriter tw)
{
((ITasMovie)_movieSession.Movie).LagLog.Save(tw);
});
}
}
public bool Load(string path)
{
// try to detect binary first
var bl = ZipStateLoader.LoadAndDetect(path);
if (bl != null)
{
try
{
var succeed = false;
// Movie timeline check must happen before the core state is loaded
if (_movieSession.Movie.IsActive())
{
bl.GetLump(BinaryStateLump.Input, true, tr => succeed = _movieSession.CheckSavestateTimeline(tr));
if (!succeed)
{
return false;
}
}
using (new SimpleTime("Load Core"))
{
bl.GetCoreState(br => _statable.LoadStateBinary(br), tr => _statable.LoadStateText(tr));
}
// We must handle movie input AFTER the core is loaded to properly handle mode changes, and input latching
if (_movieSession.Movie.IsActive())
{
bl.GetLump(BinaryStateLump.Input, true, tr => succeed = _movieSession.HandleLoadState(tr));
if (!succeed)
{
return false;
}
}
if (_videoProvider != null)
{
bl.GetLump(BinaryStateLump.Framebuffer, false, br => PopulateFramebuffer(br, _videoProvider, _quickBmpFile));
}
string userData = "";
bl.GetLump(BinaryStateLump.UserData, false, delegate(TextReader tr)
{
string line;
while ((line = tr.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line))
{
userData = line;
}
}
});
if (!string.IsNullOrWhiteSpace(userData))
{
var bag = (Dictionary<string, object>)ConfigService.LoadWithType(userData);
_userBag.Clear();
foreach (var (k, v) in bag) _userBag.Add(k, v);
}
if (_movieSession.Movie.IsActive() && _movieSession.Movie is ITasMovie)
{
bl.GetLump(BinaryStateLump.LagLog, false, delegate(TextReader tr)
{
((ITasMovie)_movieSession.Movie).LagLog.Load(tr);
});
}
}
finally
{
bl.Dispose();
}
return true;
}
return false;
}
private static void PopulateFramebuffer(BinaryReader br, IVideoProvider videoProvider, IQuickBmpFile quickBmpFile)
{
try
{
using (new SimpleTime("Load Framebuffer"))
{
quickBmpFile.Load(videoProvider, br.BaseStream);
}
}
catch
{
var buff = videoProvider.GetVideoBuffer();
try
{
for (int i = 0; i < buff.Length; i++)
{
int j = br.ReadInt32();
buff[i] = j;
}
}
catch (EndOfStreamException)
{
}
}
}
}
}
|
using System;
using UnityEngine;
// Token: 0x02000403 RID: 1027
public static class CounselorGlobals
{
// Token: 0x17000458 RID: 1112
// (get) Token: 0x06001C18 RID: 7192 RVA: 0x000FBF81 File Offset: 0x000FA381
// (set) Token: 0x06001C19 RID: 7193 RVA: 0x000FBFA1 File Offset: 0x000FA3A1
public static int DelinquentPunishments
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_DelinquentPunishments");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_DelinquentPunishments", value);
}
}
// Token: 0x17000459 RID: 1113
// (get) Token: 0x06001C1A RID: 7194 RVA: 0x000FBFC2 File Offset: 0x000FA3C2
// (set) Token: 0x06001C1B RID: 7195 RVA: 0x000FBFE2 File Offset: 0x000FA3E2
public static int CounselorPunishments
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_CounselorPunishments");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_CounselorPunishments", value);
}
}
// Token: 0x1700045A RID: 1114
// (get) Token: 0x06001C1C RID: 7196 RVA: 0x000FC003 File Offset: 0x000FA403
// (set) Token: 0x06001C1D RID: 7197 RVA: 0x000FC023 File Offset: 0x000FA423
public static int CounselorVisits
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_CounselorVisits");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_CounselorVisits", value);
}
}
// Token: 0x1700045B RID: 1115
// (get) Token: 0x06001C1E RID: 7198 RVA: 0x000FC044 File Offset: 0x000FA444
// (set) Token: 0x06001C1F RID: 7199 RVA: 0x000FC064 File Offset: 0x000FA464
public static int CounselorTape
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_CounselorTape");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_CounselorTape", value);
}
}
// Token: 0x1700045C RID: 1116
// (get) Token: 0x06001C20 RID: 7200 RVA: 0x000FC085 File Offset: 0x000FA485
// (set) Token: 0x06001C21 RID: 7201 RVA: 0x000FC0A5 File Offset: 0x000FA4A5
public static int ApologiesUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_ApologiesUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_ApologiesUsed", value);
}
}
// Token: 0x1700045D RID: 1117
// (get) Token: 0x06001C22 RID: 7202 RVA: 0x000FC0C6 File Offset: 0x000FA4C6
// (set) Token: 0x06001C23 RID: 7203 RVA: 0x000FC0E6 File Offset: 0x000FA4E6
public static int WeaponsBanned
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_WeaponsBanned");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_WeaponsBanned", value);
}
}
// Token: 0x1700045E RID: 1118
// (get) Token: 0x06001C24 RID: 7204 RVA: 0x000FC107 File Offset: 0x000FA507
// (set) Token: 0x06001C25 RID: 7205 RVA: 0x000FC127 File Offset: 0x000FA527
public static int BloodVisits
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_BloodVisits");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_BloodVisits", value);
}
}
// Token: 0x1700045F RID: 1119
// (get) Token: 0x06001C26 RID: 7206 RVA: 0x000FC148 File Offset: 0x000FA548
// (set) Token: 0x06001C27 RID: 7207 RVA: 0x000FC168 File Offset: 0x000FA568
public static int InsanityVisits
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_InsanityVisits");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_InsanityVisits", value);
}
}
// Token: 0x17000460 RID: 1120
// (get) Token: 0x06001C28 RID: 7208 RVA: 0x000FC189 File Offset: 0x000FA589
// (set) Token: 0x06001C29 RID: 7209 RVA: 0x000FC1A9 File Offset: 0x000FA5A9
public static int LewdVisits
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_LewdVisits");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_LewdVisits", value);
}
}
// Token: 0x17000461 RID: 1121
// (get) Token: 0x06001C2A RID: 7210 RVA: 0x000FC1CA File Offset: 0x000FA5CA
// (set) Token: 0x06001C2B RID: 7211 RVA: 0x000FC1EA File Offset: 0x000FA5EA
public static int TheftVisits
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_TheftVisits");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_TheftVisits", value);
}
}
// Token: 0x17000462 RID: 1122
// (get) Token: 0x06001C2C RID: 7212 RVA: 0x000FC20B File Offset: 0x000FA60B
// (set) Token: 0x06001C2D RID: 7213 RVA: 0x000FC22B File Offset: 0x000FA62B
public static int TrespassVisits
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_TrespassVisits");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_TrespassVisits", value);
}
}
// Token: 0x17000463 RID: 1123
// (get) Token: 0x06001C2E RID: 7214 RVA: 0x000FC24C File Offset: 0x000FA64C
// (set) Token: 0x06001C2F RID: 7215 RVA: 0x000FC26C File Offset: 0x000FA66C
public static int WeaponVisits
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_WeaponVisits");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_WeaponVisits", value);
}
}
// Token: 0x17000464 RID: 1124
// (get) Token: 0x06001C30 RID: 7216 RVA: 0x000FC28D File Offset: 0x000FA68D
// (set) Token: 0x06001C31 RID: 7217 RVA: 0x000FC2AD File Offset: 0x000FA6AD
public static int BloodExcuseUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_BloodExcuseUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_BloodExcuseUsed", value);
}
}
// Token: 0x17000465 RID: 1125
// (get) Token: 0x06001C32 RID: 7218 RVA: 0x000FC2CE File Offset: 0x000FA6CE
// (set) Token: 0x06001C33 RID: 7219 RVA: 0x000FC2EE File Offset: 0x000FA6EE
public static int InsanityExcuseUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_InsanityExcuseUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_InsanityExcuseUsed", value);
}
}
// Token: 0x17000466 RID: 1126
// (get) Token: 0x06001C34 RID: 7220 RVA: 0x000FC30F File Offset: 0x000FA70F
// (set) Token: 0x06001C35 RID: 7221 RVA: 0x000FC32F File Offset: 0x000FA72F
public static int LewdExcuseUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_LewdExcuseUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_LewdExcuseUsed", value);
}
}
// Token: 0x17000467 RID: 1127
// (get) Token: 0x06001C36 RID: 7222 RVA: 0x000FC350 File Offset: 0x000FA750
// (set) Token: 0x06001C37 RID: 7223 RVA: 0x000FC370 File Offset: 0x000FA770
public static int TheftExcuseUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_TheftExcuseUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_TheftExcuseUsed", value);
}
}
// Token: 0x17000468 RID: 1128
// (get) Token: 0x06001C38 RID: 7224 RVA: 0x000FC391 File Offset: 0x000FA791
// (set) Token: 0x06001C39 RID: 7225 RVA: 0x000FC3B1 File Offset: 0x000FA7B1
public static int TrespassExcuseUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_TrespassExcuseUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_TrespassExcuseUsed", value);
}
}
// Token: 0x17000469 RID: 1129
// (get) Token: 0x06001C3A RID: 7226 RVA: 0x000FC3D2 File Offset: 0x000FA7D2
// (set) Token: 0x06001C3B RID: 7227 RVA: 0x000FC3F2 File Offset: 0x000FA7F2
public static int WeaponExcuseUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_WeaponExcuseUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_WeaponExcuseUsed", value);
}
}
// Token: 0x1700046A RID: 1130
// (get) Token: 0x06001C3C RID: 7228 RVA: 0x000FC413 File Offset: 0x000FA813
// (set) Token: 0x06001C3D RID: 7229 RVA: 0x000FC433 File Offset: 0x000FA833
public static int BloodBlameUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_BloodBlameUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_BloodBlameUsed", value);
}
}
// Token: 0x1700046B RID: 1131
// (get) Token: 0x06001C3E RID: 7230 RVA: 0x000FC454 File Offset: 0x000FA854
// (set) Token: 0x06001C3F RID: 7231 RVA: 0x000FC474 File Offset: 0x000FA874
public static int InsanityBlameUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_InsanityBlameUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_InsanityBlameUsed", value);
}
}
// Token: 0x1700046C RID: 1132
// (get) Token: 0x06001C40 RID: 7232 RVA: 0x000FC495 File Offset: 0x000FA895
// (set) Token: 0x06001C41 RID: 7233 RVA: 0x000FC4B5 File Offset: 0x000FA8B5
public static int LewdBlameUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_LewdBlameUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_LewdBlameUsed", value);
}
}
// Token: 0x1700046D RID: 1133
// (get) Token: 0x06001C42 RID: 7234 RVA: 0x000FC4D6 File Offset: 0x000FA8D6
// (set) Token: 0x06001C43 RID: 7235 RVA: 0x000FC4F6 File Offset: 0x000FA8F6
public static int TheftBlameUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_TheftBlameUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_TheftBlameUsed", value);
}
}
// Token: 0x1700046E RID: 1134
// (get) Token: 0x06001C44 RID: 7236 RVA: 0x000FC517 File Offset: 0x000FA917
// (set) Token: 0x06001C45 RID: 7237 RVA: 0x000FC537 File Offset: 0x000FA937
public static int TrespassBlameUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_TrespassBlameUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_TrespassBlameUsed", value);
}
}
// Token: 0x1700046F RID: 1135
// (get) Token: 0x06001C46 RID: 7238 RVA: 0x000FC558 File Offset: 0x000FA958
// (set) Token: 0x06001C47 RID: 7239 RVA: 0x000FC578 File Offset: 0x000FA978
public static int WeaponBlameUsed
{
get
{
return PlayerPrefs.GetInt("Profile_" + GameGlobals.Profile + "_WeaponBlameUsed");
}
set
{
PlayerPrefs.SetInt("Profile_" + GameGlobals.Profile + "_WeaponBlameUsed", value);
}
}
// Token: 0x06001C48 RID: 7240 RVA: 0x000FC59C File Offset: 0x000FA99C
public static void DeleteAll()
{
Globals.Delete("Profile_" + GameGlobals.Profile + "_DelinquentPunishments");
Globals.Delete("Profile_" + GameGlobals.Profile + "_CounselorPunishments");
Globals.Delete("Profile_" + GameGlobals.Profile + "_CounselorVisits");
Globals.Delete("Profile_" + GameGlobals.Profile + "_CounselorTape");
Globals.Delete("Profile_" + GameGlobals.Profile + "_ApologiesUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_WeaponsBanned");
Globals.Delete("Profile_" + GameGlobals.Profile + "_BloodVisits");
Globals.Delete("Profile_" + GameGlobals.Profile + "_InsanityVisits");
Globals.Delete("Profile_" + GameGlobals.Profile + "_LewdVisits");
Globals.Delete("Profile_" + GameGlobals.Profile + "_TheftVisits");
Globals.Delete("Profile_" + GameGlobals.Profile + "_TrespassVisits");
Globals.Delete("Profile_" + GameGlobals.Profile + "_WeaponVisits");
Globals.Delete("Profile_" + GameGlobals.Profile + "_BloodExcuseUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_InsanityExcuseUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_LewdExcuseUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_TheftExcuseUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_TrespassExcuseUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_WeaponExcuseUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_BloodBlameUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_InsanityBlameUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_LewdBlameUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_TheftBlameUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_TrespassBlameUsed");
Globals.Delete("Profile_" + GameGlobals.Profile + "_WeaponBlameUsed");
}
// Token: 0x0400204B RID: 8267
private const string Str_DelinquentPunishments = "DelinquentPunishments";
// Token: 0x0400204C RID: 8268
private const string Str_CounselorPunishments = "CounselorPunishments";
// Token: 0x0400204D RID: 8269
private const string Str_CounselorVisits = "CounselorVisits";
// Token: 0x0400204E RID: 8270
private const string Str_CounselorTape = "CounselorTape";
// Token: 0x0400204F RID: 8271
private const string Str_ApologiesUsed = "ApologiesUsed";
// Token: 0x04002050 RID: 8272
private const string Str_WeaponsBanned = "WeaponsBanned";
// Token: 0x04002051 RID: 8273
private const string Str_BloodVisits = "BloodVisits";
// Token: 0x04002052 RID: 8274
private const string Str_InsanityVisits = "InsanityVisits";
// Token: 0x04002053 RID: 8275
private const string Str_LewdVisits = "LewdVisits";
// Token: 0x04002054 RID: 8276
private const string Str_TheftVisits = "TheftVisits";
// Token: 0x04002055 RID: 8277
private const string Str_TrespassVisits = "TrespassVisits";
// Token: 0x04002056 RID: 8278
private const string Str_WeaponVisits = "WeaponVisits";
// Token: 0x04002057 RID: 8279
private const string Str_BloodExcuseUsed = "BloodExcuseUsed";
// Token: 0x04002058 RID: 8280
private const string Str_InsanityExcuseUsed = "InsanityExcuseUsed";
// Token: 0x04002059 RID: 8281
private const string Str_LewdExcuseUsed = "LewdExcuseUsed";
// Token: 0x0400205A RID: 8282
private const string Str_TheftExcuseUsed = "TheftExcuseUsed";
// Token: 0x0400205B RID: 8283
private const string Str_TrespassExcuseUsed = "TrespassExcuseUsed";
// Token: 0x0400205C RID: 8284
private const string Str_WeaponExcuseUsed = "WeaponExcuseUsed";
// Token: 0x0400205D RID: 8285
private const string Str_BloodBlameUsed = "BloodBlameUsed";
// Token: 0x0400205E RID: 8286
private const string Str_InsanityBlameUsed = "InsanityBlameUsed";
// Token: 0x0400205F RID: 8287
private const string Str_LewdBlameUsed = "LewdBlameUsed";
// Token: 0x04002060 RID: 8288
private const string Str_TheftBlameUsed = "TheftBlameUsed";
// Token: 0x04002061 RID: 8289
private const string Str_TrespassBlameUsed = "TrespassBlameUsed";
// Token: 0x04002062 RID: 8290
private const string Str_WeaponBlameUsed = "WeaponBlameUsed";
}
|
using FastSLQL.Format;
using FastSLQL.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace FastSLQL
{
public static class FSLQL
{
public static string DBDirectory { get; private set; } = "";
public static readonly List<SLDB> SLDBases = new List<SLDB>();
public static void Load(string dbDirectory = "")
{
DBDirectory = dbDirectory;
if (Directory.Exists(dbDirectory) == false)
Directory.CreateDirectory(dbDirectory);
else
LoadDBases(dbDirectory);
}
private static void LoadDBases(string dbDirectory)
{
foreach (FileInfo file in new DirectoryInfo(dbDirectory).GetFiles())
{
if (file.Extension == ".sldb")
AddDBase(file);
}
}
public static void Link(string dbDirectory)
{
DBDirectory = dbDirectory;
}
public static string[] SendCommand(string command)
{
List<string> commandContent = command.SplitCommand().ToList();
string baseCommand = commandContent[0];
commandContent.RemoveAt(0);
string[] arguments = commandContent.ToArray();
string[] result;
try
{
switch (baseCommand)
{
case "CREATE":
result = TIL.Create(arguments);
break;
case "EDIT":
result = TIL.Edit(arguments);
break;
case "DELETE":
result = TIL.Delete(arguments);
break;
case "GET":
return EVL.Get(arguments);
case "INSERT":
result = EVL.Insert(arguments);
break;
case "CHANGE":
result = EVL.Change(arguments);
break;
case "REMOVE":
result = EVL.Remove(arguments);
break;
default:
result = CommandStatus.UnknownCommand(baseCommand);
break;
}
}
catch(Exception ex)
{
result = CommandStatus.UnknownException(ex);
}
return FSLQLSettings.Logging ? result : new string[] { "" };
}
internal static string FormatDirectory(string databaseName)
{
RemoveExtraPathSigns();
string subDirectory = DBDirectory != "" ? $"{DBDirectory}/" : "";
return $"{subDirectory}{databaseName}.sldb";
}
public static SLDB AddDBase(FileInfo file)
{
SLDB db = new SLDB(file);
SLDBases.Add(db);
return db;
}
public static SLDB GetDB(string name)
{
if (SLDBases.Count == 0)
return null;
foreach (SLDB database in SLDBases)
{
if (database.AssemblyName == name.ToLower())
return database;
}
return null;
}
public static void RemoveDBase(SLDB database)
{
SLDBases.Remove(database);
}
private static void RemoveExtraPathSigns()
{
if (DBDirectory.Length > 0)
{
int lastChar = DBDirectory.Length - 1;
if (DBDirectory[lastChar] == '/')
DBDirectory.Remove(lastChar);
}
}
}
}
|
using System;
using System.IO;
using System.Threading;
using CommandLineSwitchParser;
namespace Toolbelt.Diagnostics.Test
{
class Program
{
private static TextWriter CurrentWriter { get; set; } = Console.Out;
private static CommandLineOptions Options { get; set; } = new CommandLineOptions();
private static void WriteLine(string text)
{
CurrentWriter.WriteLine(text);
CurrentWriter.Flush();
if (Options.OutputMode == OutputMode.MixBoth)
{
CurrentWriter = CurrentWriter == Console.Out ? Console.Error : Console.Out;
}
}
static int Main(string[] args)
{
Options = CommandLineSwitch.Parse<CommandLineOptions>(ref args);
CurrentWriter = Options.OutputMode == OutputMode.StdErr ? Console.Error : Console.Out;
if (Options.InfiniteCounter)
{
InfiniteCounter();
}
else
{
HelloWorld();
}
return Options.ExitCode;
}
private static void HelloWorld()
{
WriteLine("Hello,");
Thread.Sleep(10);
WriteLine("everyone.");
Thread.Sleep(10);
WriteLine("Nice to");
Thread.Sleep(10);
WriteLine("meet you.");
Thread.Sleep(10);
}
private static void InfiniteCounter()
{
for (var c = 0; c < 10000; c++)
{
WriteLine(c.ToString());
Thread.Sleep(10);
}
}
}
}
|
using System;
namespace Glimpse.Server.Resources
{
public class ExceptionProblem : Problem
{
private readonly Exception _exception;
public ExceptionProblem(Exception exception)
{
_exception = exception;
Extensions["StackTrace"] = _exception.StackTrace;
}
public override Uri Type => new Uri("http://getglimpse.com/Docs/Troubleshooting/Exception");
public override string Title => "Server Exception";
public override string Details => _exception.Message;
public override int StatusCode => 500;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.