content stringlengths 23 1.05M |
|---|
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bore_hole1
{
public class Class1
{
[CommandMethod("BlockModel")]
public void BHL()
{
var BHL = new ClassLibrary2.Form1();
BHL.Show();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using Bhaptics.Tact.Unity;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(SimpleHapticClip), true)]
public class SimpleHapticClipEditor : FileHapticClipEditor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
FeedbackTypeUi();
PositionUi();
var feedbackTypeProperty = serializedObject.FindProperty("Mode");
switch (feedbackTypeProperty.enumNames[feedbackTypeProperty.enumValueIndex])
{
case "DotMode":
DotPointUi();
break;
case "PathMode":
PathPointUi();
break;
}
TimeMillisUi();
ResetUi();
GUILayout.Space(20);
PlayUi();
GUILayout.Space(3);
SaveAsUi();
serializedObject.ApplyModifiedProperties();
}
private void FeedbackTypeUi()
{
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(serializedObject.FindProperty("Mode"));
GUILayout.EndHorizontal();
}
private void TimeMillisUi()
{
GUILayout.BeginHorizontal();
EditorGUIUtility.labelWidth = 100f;
EditorGUILayout.PropertyField(serializedObject.FindProperty("TimeMillis"), new GUIContent("Time (ms)"));
GUILayout.EndHorizontal();
}
private void PositionUi()
{
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(serializedObject.FindProperty("Position"));
GUILayout.EndHorizontal();
}
private void PathPointUi()
{
GUILayout.BeginHorizontal();
var points = serializedObject.FindProperty("Points");
EditorGUILayout.LabelField(points.name, EditorStyles.boldLabel);
if (GUILayout.Button(" + ", GUILayout.Width(50)))
{
int inserted = points.arraySize;
points.InsertArrayElementAtIndex(inserted);
points.GetArrayElementAtIndex(inserted).FindPropertyRelative("X").floatValue = 0.5f;
points.GetArrayElementAtIndex(inserted).FindPropertyRelative("Y").floatValue = 0.5f;
points.GetArrayElementAtIndex(inserted).FindPropertyRelative("Intensity").intValue = 100;
}
GUILayout.EndHorizontal();
for (var index = 0; index < points.arraySize; index++)
{
GUILayout.BeginHorizontal();
EditorGUIUtility.labelWidth = 15f;
SerializedProperty property = points.GetArrayElementAtIndex(index);
SerializedProperty x = property.FindPropertyRelative("X");
SerializedProperty y = property.FindPropertyRelative("Y");
SerializedProperty intensity = property.FindPropertyRelative("Intensity");
x.floatValue = Mathf.Min(1, Mathf.Max(0, x.floatValue));
y.floatValue = Mathf.Min(1, Mathf.Max(0, y.floatValue));
intensity.intValue = Mathf.Min(100, Mathf.Max(0, intensity.intValue));
EditorGUILayout.PropertyField(x, new GUIContent(x.name));
EditorGUILayout.PropertyField(y, new GUIContent(y.name));
GUILayout.Label(intensity.name, GUILayout.Width(55));
EditorGUILayout.PropertyField(intensity, GUIContent.none);
if (GUILayout.Button(new GUIContent("-", "delete"), GUILayout.Width(50)))
{
points.DeleteArrayElementAtIndex(index);
}
GUILayout.EndHorizontal();
}
}
private void DotPointUi()
{
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Dot Points", EditorStyles.boldLabel);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
var dotPoints = serializedObject.FindProperty("DotPoints");
for (var index = 0; index < dotPoints.arraySize; index++)
{
if (index % 5 == 0)
{
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
}
EditorGUIUtility.labelWidth = 20f;
SerializedProperty property = dotPoints.GetArrayElementAtIndex(index);
property.intValue = Mathf.Min(100, Mathf.Max(0, property.intValue));
EditorGUILayout.PropertyField(property, new GUIContent("" + (index + 1)));
}
GUILayout.EndHorizontal();
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RtspClientSharp.Rtsp;
namespace RtspClientSharp.UnitTests.Rtsp
{
[TestClass]
public class RtspRequestMessageFactoryTests
{
private static readonly Uri FakeUri = new Uri("rtsp://127.0.0.1");
private const string UserAgent = "TestAgent";
[TestMethod]
public void EnsureCSeqIncreasesAfterEveryCreatedRequest()
{
var factory = new RtspRequestMessageFactory(FakeUri, null);
RtspRequestMessage request1 = factory.CreateOptionsRequest();
RtspRequestMessage request2 = factory.CreateDescribeRequest();
Assert.AreEqual(1u, request1.CSeq);
Assert.AreEqual(2u, request2.CSeq);
}
[TestMethod]
public void CreateOptionsRequest_ValidProperties()
{
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent);
RtspRequestMessage request = factory.CreateOptionsRequest();
Assert.AreEqual(RtspMethod.OPTIONS, request.Method);
Assert.AreEqual(FakeUri, request.ConnectionUri);
Assert.AreEqual(UserAgent, request.UserAgent);
}
[TestMethod]
public void CreateDescribeRequest_ValidProperties()
{
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent);
RtspRequestMessage request = factory.CreateDescribeRequest();
Assert.AreEqual(RtspMethod.DESCRIBE, request.Method);
Assert.AreEqual(FakeUri, request.ConnectionUri);
Assert.AreEqual(UserAgent, request.UserAgent);
}
[TestMethod]
public void CreateSetupTcpInterleavedRequest_ValidProperties()
{
const string testTrackName = "testTrack";
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent);
RtspRequestMessage request = factory.CreateSetupTcpInterleavedRequest(testTrackName, 1, 2);
Assert.AreEqual(RtspMethod.SETUP, request.Method);
Assert.AreEqual(FakeUri + "testTrack", request.ConnectionUri.ToString());
Assert.AreEqual(UserAgent, request.UserAgent);
string transportHeaderValue = request.Headers.Get("Transport");
Assert.IsTrue(transportHeaderValue.Contains("TCP"));
Assert.IsTrue(transportHeaderValue.Contains($"{1}-{2}"));
}
[TestMethod]
public void CreateSetupUdpUnicastRequest_ValidProperties()
{
const string testTrackName = "testTrack";
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent);
RtspRequestMessage request = factory.CreateSetupUdpUnicastRequest(testTrackName, 1, 2);
Assert.AreEqual(RtspMethod.SETUP, request.Method);
Assert.AreEqual(FakeUri + "testTrack", request.ConnectionUri.ToString());
Assert.AreEqual(UserAgent, request.UserAgent);
string transportHeaderValue = request.Headers.Get("Transport");
Assert.IsTrue(transportHeaderValue.Contains("unicast"));
Assert.IsTrue(transportHeaderValue.Contains($"{1}-{2}"));
}
[TestMethod]
public void CreateGetParameterRequest_ValidProperties()
{
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent);
RtspRequestMessage request = factory.CreateGetParameterRequest();
Assert.AreEqual(RtspMethod.GET_PARAMETER, request.Method);
Assert.AreEqual(FakeUri, request.ConnectionUri);
Assert.AreEqual(UserAgent, request.UserAgent);
}
[TestMethod]
public void CreatePlayRequest_ValidProperties()
{
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent);
RtspRequestMessage request = factory.CreatePlayRequest();
Assert.AreEqual(RtspMethod.PLAY, request.Method);
Assert.AreEqual(FakeUri, request.ConnectionUri);
Assert.AreEqual(UserAgent, request.UserAgent);
}
[TestMethod]
public void CreatePlayRequest_ContentBaseAndSessionAreSet_ValidProperties()
{
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent)
{
SessionId = "testSessionId",
ContentBase = new Uri("http://127.0.0.1/base")
};
RtspRequestMessage request = factory.CreatePlayRequest();
Assert.AreEqual(factory.SessionId, request.Headers.Get("Session"));
Assert.AreEqual(factory.ContentBase, request.ConnectionUri);
}
[TestMethod]
public void CreateTeardownRequest_ValidProperties()
{
var factory = new RtspRequestMessageFactory(FakeUri, UserAgent);
RtspRequestMessage request = factory.CreateTeardownRequest();
Assert.AreEqual(RtspMethod.TEARDOWN, request.Method);
Assert.AreEqual(FakeUri, request.ConnectionUri);
Assert.AreEqual(UserAgent, request.UserAgent);
}
}
} |
using OrderServiceProject.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OrderServiceProject.Views
{
public partial class EditProductView : Form
{
public EditProductView()
{
InitializeComponent();
}
private int id;
public Product ChangeData
{
get
{
return new Product
{
Id = id,
NameProduct = nameBox.Text,
Price = int.Parse(priceBox.Text),
IsDeleted = false
};
}
}
public DialogResult ShowDialog(Product product)
{
if (product == null)
product = new Product();
id = product.Id;
nameBox.Text = product.NameProduct;
priceBox.Text = product.Price.ToString();
return ShowDialog();
}
private void applyButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void cancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}
|
using System.IO;
namespace ObsWeather
{
public static class General
{
public static string StartupPath => ObsController.Core.General.StartupPath;
public static string SettingPath => ObsController.Core.General.SettingPath;
public static string WeatherIconsPath => Path.Combine(StartupPath, "weathericons.xml");
}
}
|
namespace Facepunch.Minigolf.Entities;
/// <summary>
/// Bounds of a hole.
/// </summary>
[Library( "minigolf_hole_bounds" )]
[HammerEntity, Solid, AutoApplyMaterial( "materials/editor/minigolf_wall/minigolf_hole_bounds.vmat" )]
[VisGroup( VisGroup.Trigger )]
[Title( "Hole Bounds" )]
public partial class HoleBounds : BaseTrigger
{
/// <summary>
/// Which hole this hole is on.
/// </summary>
[Property]
public int HoleNumber { get; set; }
public override void StartTouch(Entity other)
{
if ( Game.Current.Course.CurrentHole.Number != HoleNumber )
return;
if ( other is not Ball ball )
return;
Game.Current.UpdateBallInBounds( ball, true );
}
public override void EndTouch(Entity other)
{
if ( Game.Current.Course.CurrentHole.Number != HoleNumber )
return;
if ( other is not Ball ball )
return;
Game.Current.UpdateBallInBounds( ball, false );
}
}
|
using Newtonsoft.Json;
namespace Binance_Spot_API.Model.Market
{
[JsonConverter(typeof(Utils.Converter.Candlestick))]
public class Candlestick
{
public long OpenTime { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double Close { get; set; }
public double Volume { get; set; }
public long CloseTime { get; set; }
public double QuoteAssetVolume { get; set; }
public int NumberOfTrade { get; set; }
public double TakerBuyBaseAssetVolume { get; set; }
public double TakerBuyQuoteAssetVolume { get; set; }
}
}
|
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using Correspondence.Mementos;
namespace Correspondence.IsolatedStorage
{
public class MessageStore
{
private const string MessageTableFileName = "MessageTable.bin";
private List<MessageRecord> _messageTable = new List<MessageRecord>();
private MessageStore()
{
}
public IEnumerable<MessageMemento> LoadRecentMessagesForServer(int peerId, TimestampID timestamp)
{
return _messageTable
.Where(message =>
message.MessageMemento.FactId.key > timestamp.Key &&
message.SourcePeerId != peerId)
.Select(message => message.MessageMemento)
.ToList();
}
public IEnumerable<FactID> LoadRecentMessagesForClient(FactID pivotId, TimestampID timestamp)
{
return _messageTable
.Where(message =>
message.MessageMemento.PivotId.Equals(pivotId) &&
message.MessageMemento.FactId.key > timestamp.Key)
.Select(message => message.MessageMemento.FactId);
}
public List<FactID> GetPivotsOfFacts(List<FactID> factIds)
{
return _messageTable
.Where(message => factIds.Contains(message.MessageMemento.FactId))
.Select(message => message.MessageMemento.PivotId)
.Distinct()
.ToList();
}
public void AddMessages(IsolatedStorageFile store, List<MessageMemento> messages, int peerId)
{
_messageTable.AddRange(messages.Select(message => new MessageRecord
{
MessageMemento = message,
SourcePeerId = peerId
}));
using (BinaryWriter factWriter = new BinaryWriter(
store.OpenFile(MessageTableFileName,
FileMode.Append,
FileAccess.Write)))
{
foreach (MessageMemento message in messages)
{
long pivotId = message.PivotId.key;
long factId = message.FactId.key;
factWriter.Write(pivotId);
factWriter.Write(factId);
factWriter.Write(peerId);
}
}
}
public static MessageStore Load(IsolatedStorageFile store)
{
MessageStore result = new MessageStore();
if (store.FileExists(MessageTableFileName))
{
using (BinaryReader messageReader = new BinaryReader(
store.OpenFile(MessageTableFileName,
FileMode.Open,
FileAccess.Read)))
{
long length = messageReader.BaseStream.Length;
while (messageReader.BaseStream.Position < length)
{
result.ReadMessageFromStorage(messageReader);
}
}
}
return result;
}
private void ReadMessageFromStorage(BinaryReader messageReader)
{
long pivotId = messageReader.ReadInt64();
long factId = messageReader.ReadInt64();
int sourcePeerId = messageReader.ReadInt32();
MessageMemento messageMemento = new MessageMemento(
new FactID() { key = pivotId },
new FactID() { key = factId });
_messageTable.Add(new MessageRecord
{
MessageMemento = messageMemento,
SourcePeerId = sourcePeerId
});
}
public static void DeleteAll(IsolatedStorageFile store)
{
if (store.FileExists(MessageTableFileName))
{
store.DeleteFile(MessageTableFileName);
}
}
}
}
|
using System;
using System.Globalization;
using System.IO;
using NUnit.Framework;
using ValveResourceFormat;
namespace Tests
{
public class ShaderTest
{
[Test]
public void ParseShaders()
{
var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files", "Shaders");
var files = Directory.GetFiles(path, "*.vcs");
foreach (var file in files)
{
var shader = new CompiledShader();
using var sw = new StringWriter(CultureInfo.InvariantCulture);
var originalOutput = Console.Out;
Console.SetOut(sw);
shader.Read(file);
Console.SetOut(originalOutput);
}
}
}
}
|
namespace GoNorth.Data.Karta.Marker
{
/// <summary>
/// Marker Geometry Type
/// </summary>
public enum MarkerGeometryType
{
/// <summary>
/// Polygon Geometry
/// </summary>
Polygon,
/// <summary>
/// Circle Geometry
/// </summary>
Circle,
/// <summary>
/// Line String Geometry
/// </summary>
LineString,
/// <summary>
/// Rectangle Geometry
/// </summary>
Rectangle
};
} |
using System.Linq;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
#endif
// Apply the default category of "Issues" to all of the tests in this assembly
// We use this as a catch-all for tests which haven't been individually categorized
#if UITEST
[assembly: NUnit.Framework.Category("Issues")]
#endif
namespace Xamarin.Forms.Controls.Issues
{
public class Bugzilla41054NumericValidationBehavior : Behavior<Entry>
{
public static readonly BindableProperty AttachBehaviorProperty =
BindableProperty.CreateAttached("AttachBehavior", typeof(bool), typeof(Bugzilla41054NumericValidationBehavior), false, propertyChanged: OnAttachBehaviorChanged);
public static bool GetAttachBehavior(BindableObject view)
{
return (bool)view.GetValue(AttachBehaviorProperty);
}
public static void SetAttachBehavior(BindableObject view, bool value)
{
view.SetValue(AttachBehaviorProperty, value);
}
static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
{
var entry = view as Entry;
if (entry == null)
{
return;
}
bool attachBehavior = (bool)newValue;
if (attachBehavior)
{
entry.Behaviors.Add(new Bugzilla41054NumericValidationBehavior());
}
else
{
var toRemove = entry.Behaviors.FirstOrDefault(b => b is Bugzilla41054NumericValidationBehavior);
if (toRemove != null)
{
entry.Behaviors.Remove(toRemove);
}
}
}
protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += OnEntryTextChanged;
base.OnAttachedTo(entry);
}
protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= OnEntryTextChanged;
base.OnDetachingFrom(entry);
}
void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
double result;
bool isValid = double.TryParse(args.NewTextValue, out result);
((Entry)sender).TextColor = isValid ? Color.Default : Color.Red;
}
}
#if UITEST
[NUnit.Framework.Category(Core.UITests.UITestCategories.Bugzilla)]
#endif
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 41054, "Cannot update Entry.Text from attached Behavior on UWP", PlatformAffected.Default)]
public class Bugzilla41054 : TestContentPage
{
protected override void Init()
{
var entry = new Entry
{
Placeholder = "Enter a System.Double; text will be red when invalid",
PlaceholderColor = Color.Green,
};
var entry2 = new Entry
{
Placeholder = "This entry starts with blue text when typing",
TextColor = Color.Blue
};
Bugzilla41054NumericValidationBehavior.SetAttachBehavior(entry, true);
Content = new StackLayout
{
Children = {
entry,
entry2,
new Entry
{
Text = "This is an entry with some default colored text"
},
new Button
{
Text = "Change first entry placeholder color to purple",
Command = new Command(() => entry.PlaceholderColor = Color.Purple)
},
new Button
{
Text = "Change second entry text color to orange",
Command = new Command(() => entry2.TextColor = Color.Orange)
}
}
};
}
}
}
|
namespace ShadyNagy.Blazor.JavaScriptUtilities.Services
{
public interface ISyncBlazorFile
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StarLinker : MonoBehaviour
{
[SerializeField]
private GameObject _linkPrefab;
private Tracer _tracer;
private GameObject _activeLink;
void Awake()
{
_tracer = GetComponent<Tracer>();
}
void Update()
{
if(_activeLink != null)
{
Vector3 diff = _activeLink.transform.position - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
_activeLink.transform.rotation = Quaternion.Euler(0f, 0f, rot_z + 180);
ScaleToPoint(transform.position);
}
}
public void CreateActiveLink()
{
if(_activeLink != null) { return; }
_activeLink = Instantiate(_linkPrefab, _tracer.CurrentStar);
}
public void EndActiveLink()
{
ScaleToPoint(_tracer.CurrentStar.position);
_activeLink = null;
}
private void ScaleToPoint(Vector3 point)
{
if(_activeLink != null)
{
Vector3 tempScale = _activeLink.transform.localScale;
tempScale.x = (_activeLink.transform.position - point).magnitude/* * 1.5f*/;
_activeLink.transform.localScale = tempScale;
}
}
}
|
using System;
#if WISEJ
using Wisej.Web;
#else
using System.Windows.Forms;
#endif
using MasterDetailWithModel.ViewModels;
using MvvmFx.CaliburnMicro;
namespace MasterDetailWithModel.Views
{
public partial class StudentEditView : UserControl, IHaveDataContext
{
public StudentEditView()
{
InitializeComponent();
model_FirstName.Focus();
}
#region IHaveDataContext implementation
public event EventHandler<DataContextChangedEventArgs> DataContextChanged = delegate { };
private StudentEditViewModel _viewModel;
public object DataContext
{
get { return _viewModel; }
set
{
if (value != _viewModel)
{
var viewModel = value as StudentEditViewModel;
if (viewModel != null)
{
_viewModel = viewModel;
DataContextChanged(this, new DataContextChangedEventArgs());
}
}
}
}
#endregion
}
} |
// Copyright (c) 2009-2010 Frank Laub
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using OpenSSL;
using NUnit.Framework;
using OpenSSL.Core;
using OpenSSL.Crypto;
using OpenSSL.X509;
using System.Resources;
using System.Reflection;
using System.Collections.Generic;
namespace UnitTests
{
[TestFixture]
public class TestX509Certificate : TestBase
{
[Test]
public void CanCreateAndDispose()
{
using (var cert = new X509Certificate())
{
Assert.AreNotEqual(IntPtr.Zero, cert.Handle);
}
}
[Test]
public void CanLoadFromPEM()
{
using (var bio = new BIO(Util.LoadString(Resources.CaCrt)))
{
using (var cert = new X509Certificate(bio))
{
TestCert(cert, "CN=Root", "CN=Root", 1234);
}
}
}
[Test]
public void CanLoadFromDER()
{
using (var bio = new BIO(Util.LoadBytes(Resources.CaDer)))
{
using (var cert = X509Certificate.FromDER(bio))
{
TestCert(cert, "CN=Root", "CN=Root", 1234);
}
}
}
[Test]
public void CanLoadFromPKCS7_PEM()
{
using (var bio = new BIO(Util.LoadString(Resources.CaChainP7cPem)))
{
using (var cert = X509Certificate.FromPKCS7_PEM(bio))
{
TestCert(cert, "CN=Root", "CN=Root", 1234);
}
}
}
[Test]
public void CanLoadFromPKCS7_DER()
{
using (var bio = new BIO(Util.LoadBytes(Resources.CaChainP7c)))
{
using (var cert = X509Certificate.FromPKCS7_DER(bio))
{
TestCert(cert, "CN=Root", "CN=Root", 1234);
}
}
}
[Test]
public void CanLoadFromPCKS12()
{
using (var cert = Util.LoadPKCS12Certificate(Resources.ServerPfx, Resources.Password))
{
TestCert(cert, "CN=localhost", "CN=Root", 1235);
}
}
[Test]
public void CanCreatePKCS12()
{
using (var bio = new BIO(Util.LoadBytes(Resources.ServerPfx)))
using (var pfx = new PKCS12(bio, Resources.Password))
using (var new_pfx = new PKCS12(Resources.Password,
pfx.Certificate.PrivateKey,
pfx.Certificate,
pfx.CACertificates))
{
TestCert(new_pfx.Certificate, "CN=localhost", "CN=Root", 1235);
}
}
[Test]
public void CanCreateWithArgs()
{
var serial = 101;
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var subject = new X509Name("CN=localhost"))
using (var issuer = new X509Name("CN=Root"))
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(serial, subject, issuer, key, start, end))
{
Assert.AreEqual(subject, cert.Subject);
Assert.AreEqual(issuer, cert.Issuer);
Assert.AreEqual(serial, cert.SerialNumber);
// We compare short date/time strings here because the wrapper can't handle milliseconds
Assert.AreEqual(start.ToShortDateString(), cert.NotBefore.ToShortDateString());
Assert.AreEqual(start.ToShortTimeString(), cert.NotBefore.ToShortTimeString());
}
}
[Test]
public void CanGetAndSetProperties()
{
var serial = 101;
var subject = new X509Name("CN=localhost");
var issuer = new X509Name("CN=Root");
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
var key = new CryptoKey(new DSA(true));
var bits = key.Bits;
X509Name saveIssuer = null;
X509Name saveSubject = null;
CryptoKey savePublicKey = null;
CryptoKey savePrivateKey = null;
using (var cert = new X509Certificate())
{
cert.Subject = subject;
cert.Issuer = issuer;
cert.SerialNumber = serial;
cert.NotBefore = start;
cert.NotAfter = end;
cert.PublicKey = key;
cert.PrivateKey = key;
Assert.AreEqual(subject, cert.Subject);
Assert.AreEqual(issuer, cert.Issuer);
Assert.AreEqual(serial, cert.SerialNumber);
Assert.AreEqual(key, cert.PublicKey);
Assert.AreEqual(key, cert.PrivateKey);
// If the original key gets disposed before the internal private key,
// make sure that memory is correctly managed
key.Dispose();
// If the internal private key has already been disposed, this will blowup
Assert.AreEqual(bits, cert.PublicKey.Bits);
Assert.AreEqual(bits, cert.PrivateKey.Bits);
// We compare short date/time strings here because the wrapper can't handle milliseconds
Assert.AreEqual(start.ToShortDateString(), cert.NotBefore.ToShortDateString());
Assert.AreEqual(start.ToShortTimeString(), cert.NotBefore.ToShortTimeString());
saveSubject = cert.Subject;
saveIssuer = cert.Issuer;
savePublicKey = cert.PublicKey;
savePrivateKey = cert.PrivateKey;
}
// make sure that a property torn-off from the cert is still valid
using (subject)
using (saveSubject)
{
Assert.AreEqual(subject, saveSubject);
}
using (issuer)
using (saveIssuer)
{
Assert.AreEqual(issuer, saveIssuer);
}
using (savePublicKey)
{
Assert.AreEqual(bits, savePublicKey.Bits);
}
using (savePrivateKey)
{
Assert.AreEqual(bits, savePrivateKey.Bits);
}
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CannotSetUnmatchedPrivateKey()
{
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end))
{
var other = new CryptoKey(new DSA(true));
cert.PrivateKey = other;
}
}
[Test]
public void CanCompare()
{
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end))
{
Assert.AreEqual(cert, cert);
using (var cert2 = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end))
{
Assert.AreEqual(cert, cert2);
}
using (var cert2 = new X509Certificate(101, "CN=other", "CN=Root", key, start, end))
{
Assert.AreNotEqual(cert, cert2);
}
using (var cert2 = new X509Certificate(101, "CN=localhost", "CN=other", key, start, end))
{
Assert.AreNotEqual(cert, cert2);
}
using (var otherKey = new CryptoKey(new DSA(true)))
using (var cert2 = new X509Certificate(101, "CN=localhost", "CN=Root", otherKey, start, end))
{
Assert.AreNotEqual(cert, cert2);
}
}
}
[Test]
public void CanGetAsPEM()
{
var data = Util.LoadString(Resources.CaCrt);
var expected = data.Replace("\r\n", "\n");
using (var bio = new BIO(data))
using (var cert = new X509Certificate(bio))
{
var pem = cert.PEM;
var text = cert.ToString();
Assert.AreEqual(expected, text + pem);
}
}
[Test]
public void CanSaveAsDER()
{
var data = Util.LoadBytes(Resources.CaDer);
using (var bio = new BIO(data))
using (var cert = X509Certificate.FromDER(bio))
{
var der = cert.DER;
Assert.AreEqual(data.Length, der.Length);
for (var i = 0; i < data.Length; i++)
{
Assert.AreEqual(data[i], der[i]);
}
}
}
[Test]
public void CanSign()
{
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end))
{
cert.Sign(key, MessageDigest.SHA256);
}
}
[Test]
public void CanCheckPrivateKey()
{
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end))
{
Assert.AreEqual(true, cert.CheckPrivateKey(key));
using (var other = new CryptoKey(new DSA(true)))
{
Assert.AreEqual(false, cert.CheckPrivateKey(other));
}
}
}
[Test]
[Ignore("Not implemented yet")]
public void CanCheckTrust()
{
}
[Test]
public void CanVerify()
{
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end))
{
cert.Sign(key, MessageDigest.SHA256);
Assert.AreEqual(true, cert.Verify(key));
using (var other = new CryptoKey(new DSA(true)))
{
Assert.AreEqual(false, cert.Verify(other));
}
}
}
[Test]
[Ignore("Not implemented yet")]
public void CanDigest()
{
}
[Test]
[Ignore("Not implemented yet")]
public void CanDigestPublicKey()
{
}
[Test]
public void CanCreateRequest()
{
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(101, "CN=localhost", "CN=Root", key, start, end))
using (var request = cert.CreateRequest(key, MessageDigest.SHA256))
{
Assert.IsTrue(request.Verify(key));
}
}
[Test]
public void CanAddExtensions()
{
var extList = new List<X509V3ExtensionValue> {
new X509V3ExtensionValue("subjectKeyIdentifier", false, "hash"),
new X509V3ExtensionValue("authorityKeyIdentifier", false, "keyid:always,issuer:always"),
new X509V3ExtensionValue("basicConstraints", true, "critical,CA:true"),
new X509V3ExtensionValue("keyUsage", false, "cRLSign,keyCertSign"),
};
var start = DateTime.Now;
var end = start + TimeSpan.FromMinutes(10);
using (var key = new CryptoKey(new DSA(true)))
using (var cert = new X509Certificate(101, "CN=Root", "CN=Root", key, start, end))
{
foreach (var extValue in extList)
{
using (var ext = new X509Extension(cert, cert, extValue.Name, extValue.IsCritical, extValue.Value))
{
cert.AddExtension(ext);
}
}
foreach (var ext in cert.Extensions)
{
Console.WriteLine(ext);
}
Assert.AreEqual(extList.Count, cert.Extensions.Count);
}
}
private void TestCert(X509Certificate cert, string subject, string issuer, int serial)
{
Assert.AreEqual(subject, cert.Subject.ToString());
Assert.AreEqual(issuer, cert.Issuer.ToString());
Assert.AreEqual(serial, cert.SerialNumber);
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using PNS4OneS.KeyStorage;
namespace PNS4OneS
{
public static class AuthHandler
{
public static async Task Auth(HttpRequest request, HttpResponse response)
{
string serverKey = request.Query["server_key"].ToString();
if (string.IsNullOrEmpty(serverKey))
{
response.StatusCode = 401;
return;
}
ClientApplication clientApp = GetClientAppByServerKey(serverKey);
if (clientApp == null)
{
response.StatusCode = 400;
return;
}
clientApp.UpdateAccessToken();
if (!Program.ClientAppsStorage.SaveApp(clientApp))
{
response.StatusCode = 500;
return;
}
response.Headers.Add("Content-Type", "application/json");
string body = string.Format("{{\"access_token\": \"{0}\", \"expires_in\": {1:0}}}",
clientApp.AccessToken.Token,
new System.TimeSpan(clientApp.AccessToken.ExpiresIn.Ticks).TotalSeconds);
await response.Body.WriteAsync(System.Text.Encoding.UTF8.GetBytes(body));
}
private static ClientApplication GetClientAppByServerKey(string serverKey)
{
var apps = Program.ClientAppsStorage.GetApps();
return apps.FirstOrDefault(x => x.ServerKey == serverKey);
}
}
}
|
using UnityEngine;
using etf.santorini.km150096d.utils;
namespace etf.santorini.km150096d.model.gameobject
{
public class Roof : MonoBehaviour
{
public static void GenerateRoof(int x, int y, Board board, int height)
{
GameObject gameObject = Instantiate(board.roofPrefab) as GameObject;
gameObject.transform.SetParent(board.transform);
Roof roof = gameObject.GetComponent<Roof>();
Util.MoveRoof(roof, x, y, height);
}
}
}
|
namespace ErlSharp.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ErlSharp.Language;
public class MultiFunExpression : IExpression
{
private IList<FunExpression> expressions;
public MultiFunExpression(IList<FunExpression> expressions)
{
this.expressions = expressions;
}
public IList<FunExpression> Expressions { get { return this.expressions; } }
public object Evaluate(Context context, bool withvars = false)
{
int arity = this.expressions[0].ParameterExpressions.Count;
if (!this.expressions.Skip(1).All(f => f.ParameterExpressions.Count == arity))
throw new Exception("head mismatch");
IList<Function> functions = new List<Function>();
foreach (var form in this.Expressions)
functions.Add((Function)form.Evaluate(context, true));
var func = new MultiFunction(functions);
return func;
}
public bool HasVariable()
{
return false;
}
}
}
|
using Gravity.Abstraction.Contracts;
using Gravity.Abstraction.Tests.Base;
using Gravity.Abstraction.WebDriver;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OpenQA.Selenium.Remote;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Gravity.Abstraction.Tests.Integration
{
[TestClass]
public class CreateSessionTests : TestSuite
{
public TestContext TestContext { get; set; }
[TestCleanup]
public void Cleanup()
{
UpdateBrowserStack(onContext: TestContext);
}
[TestMethod]
public void CreateRemoteChrome()
{
// execute
var actual = CreateRemoteDriver(
onDriver: "ChromeDriver",
onTest: MethodBase.GetCurrentMethod().Name,
onContext: TestContext);
// assertion
Assert.IsTrue(condition: actual);
}
[TestMethod]
public void CreateRemoteFirefox()
{
// execute
var actual = CreateRemoteDriver(
onDriver: "FirefoxDriver",
onTest: MethodBase.GetCurrentMethod().Name,
onContext: TestContext);
// assertion
Assert.IsTrue(condition: actual);
}
[TestMethod]
public void CreateRemoteInternetExplorer()
{
// execute
var actual = CreateRemoteDriver(
onDriver: "IEDriverServer",
onTest: MethodBase.GetCurrentMethod().Name,
onContext: TestContext);
// assertion
Assert.IsTrue(condition: actual);
}
[TestMethod]
public void CreateRemoteEdge()
{
// execute
var actual = CreateRemoteDriver(
onDriver: "MicrosoftWebDriver",
onTest: MethodBase.GetCurrentMethod().Name,
onContext: TestContext);
// assertion
Assert.IsTrue(condition: actual);
}
}
} |
using System.Web.Compilation;
using System.Web;
namespace Texxtoor.BaseLibrary.Globalization.Provider
{
/// <summary>
/// Provider factory that instantiates the individual provider. The provider
/// passes a 'classname' which is the ResourceSet id or how a resource is identified.
/// For global resources it's the name of hte resource file, for local resources
/// it's the full Web relative virtual path
/// </summary>
public class DbSimpleResourceProviderFactory : ResourceProviderFactory
{
/// <summary>
/// ASP.NET sets up provides the global resource name which is the
/// resource ResX file (without any extensions). This will become
/// our ResourceSet id. ie. Resource.resx becomes "Resources"
/// </summary>
/// <param name="classname"></param>
/// <returns></returns>
public override IResourceProvider CreateGlobalResourceProvider(string classname)
{
return new DbSimpleResourceProvider(null, classname);
}
/// <summary>
/// ASP.NET passes the full page virtual path (/MyApp/subdir/test.aspx) wich is
/// the effective ResourceSet id. We'll store only an application relative path
/// (subdir/test.aspx) by stripping off the base path.
/// </summary>
/// <param name="virtualPath"></param>
/// <returns></returns>
public override IResourceProvider CreateLocalResourceProvider(string virtualPath)
{
// DEPENDENCY HERE: use Configuration class to strip off Virtual path leaving
// just a page/control relative path for ResourceSet Ids
// ASP.NET passes full virtual path: Strip out the virtual path
// leaving us just with app relative page/control path
var resourceSetName = VirtualPathUtility.ToAppRelative(virtualPath);
return new DbSimpleResourceProvider(null, resourceSetName.ToLower());
}
}
}
|
// ----------------------------------------------------------------------------
// The MIT License
// LeopotamGroupLibrary https://github.com/Leopotam/LeopotamGroupLibraryUnity
// Copyright (c) 2012-2019 Leopotam <leopotam@gmail.com>
// ----------------------------------------------------------------------------
using Leopotam.Group.Common;
using Leopotam.Group.Events;
using UnityEngine;
namespace Leopotam.Group.SystemUi.Actions {
/// <summary>
/// Base class for ui action.
/// </summary>
public abstract class UiActionBase : MonoBehaviour {
[SerializeField]
string _group;
protected int GroupId { get; private set; }
protected virtual void Awake () {
SetGroup (_group);
}
protected virtual void Start () {
// Force create eventbus object.
Service<UnityEventBus>.Get ();
}
protected void SendActionData<T> (T data) {
if (Service<UnityEventBus>.IsRegistered) {
Service<UnityEventBus>.Get ().Publish<T> (data);
}
}
public void SetGroup (string group) {
_group = group;
GroupId = _group.GetUiActionGroupId ();
}
}
} |
using System.Collections.Generic;
namespace UdpKit {
public class UdpStreamPool {
readonly UdpSocket socket;
readonly Stack<UdpStream> pool = new Stack<UdpStream>();
internal UdpStreamPool (UdpSocket s) {
socket = s;
}
internal void Release (UdpStream stream) {
UdpAssert.Assert(stream.IsPooled == false);
lock (pool) {
stream.Size = 0;
stream.Position = 0;
stream.IsPooled = true;
pool.Push(stream);
}
}
public UdpStream Acquire () {
UdpStream stream = null;
lock (pool) {
if (pool.Count > 0) {
stream = pool.Pop();
}
}
if (stream == null) {
stream = new UdpStream(new byte[socket.Config.PacketSize * 2]);
stream.Pool = this;
}
UdpAssert.Assert(stream.IsPooled);
stream.IsPooled = false;
stream.Position = 0;
stream.Size = (socket.Config.PacketSize - UdpMath.BytesRequired(UdpSocket.HeaderBitSize)) << 3;
return stream;
}
public void Free () {
lock (pool) {
while (pool.Count > 0) {
pool.Pop();
}
}
}
}
} |
using ABP.WebApi.Dtos;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.ComponentModel.DataAnnotations;
namespace ASF.Application.DTO
{
/// <summary>
/// 批量删除日志请求
/// </summary>
public class LoggerDeleteRequestDto : IDto
{
/// <summary>
/// 开始时间
/// </summary>
[Required]
public DateTime BeginTime { get; set; }
/// <summary>
/// 结束时间
/// </summary>
[Required]
public DateTime EndTime { get; set; }
/// <summary>
/// 转换Json字符串
/// </summary>
/// <returns></returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
|
using Foundation.Cms.ViewModels;
using Foundation.Commerce.Models.Blocks;
using System.Collections.Generic;
namespace Foundation.Commerce.ViewModels
{
public class CategoryBlockViewModel : BlockViewModel<CategoryBlock>
{
public CategoryBlockViewModel(CategoryBlock currentBlock) : base(currentBlock)
{
}
public string Heading { get; set; }
public List<CategoryItemViewModel> CategoryItems { get; set; }
}
public class CategoryItemViewModel
{
public string Name { get; set; }
public string Uri { get; set; }
public string ImageUrl { get; set; }
public List<CategoryChildLinkViewModel> ChildLinks { get; set; }
}
public class CategoryChildLinkViewModel
{
public string Text { get; set; }
public string Uri { get; set; }
}
}
|
// Copyright (c) Mahmoud Shaheen, 2021. All rights reserved.
// Licensed under the Apache 2.0 license.
// See the LICENSE.txt file in the project root for full license information.
using System.Diagnostics.Contracts;
using X.Paymob.CashIn.Models.Callback;
using X.Paymob.CashIn.Models.Orders;
using X.Paymob.CashIn.Models.Payment;
using X.Paymob.CashIn.Models.Transactions;
namespace X.Paymob.CashIn;
public interface IPaymobCashInBroker {
/// <summary>Create order. Order is a logical container for a transaction(s).</summary>
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInCreateOrderResponse> CreateOrderAsync(CashInCreateOrderRequest request);
/// <summary>
/// Get payment key which is used to authenticate payment request and verifying transaction
/// request metadata.
/// </summary>
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInPaymentKeyResponse> RequestPaymentKeyAsync(CashInPaymentKeyRequest request);
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInWalletPayResponse> CreateWalletPayAsync(string paymentKey, string phoneNumber);
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInKioskPayResponse> CreateKioskPayAsync(string paymentKey);
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInCashCollectionPayResponse> CreateCashCollectionPayAsync(string paymentKey);
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInSavedTokenPayResponse> CreateSavedTokenPayAsync(string paymentKey, string savedToken);
/// <summary>Get transactions page.</summary>
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInTransactionsPage?> GetTransactionsPageAsync(CashInTransactionsPageRequest? request = null);
/// <summary>Get transaction by id.</summary>
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInTransaction?> GetTransactionAsync(string transactionId);
/// <summary>Get order by id.</summary>
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInOrder?> GetOrderAsync(string orderId);
/// <summary>Get orders page.</summary>
/// <exception cref="PaymobRequestException"></exception>
[Pure] Task<CashInOrdersPage?> GetOrdersPageAsync(CashInOrdersPageRequest? request = null);
/// <summary>Validate the identity and integrity for "Paymob Accept"'s callback submission.</summary>
/// <param name="concatenatedString">Object concatenated string.</param>
/// <param name="hmac">Received HMAC.</param>
/// <returns>True if is valid, otherwise return false.</returns>
[Pure] bool Validate(string concatenatedString, string hmac);
/// <summary>Validate the identity and integrity for "Paymob Accept"'s callback submission.</summary>
/// <param name="transaction">Received transaction.</param>
/// <param name="hmac">Received HMAC.</param>
/// <returns>True if is valid, otherwise return false.</returns>
[Pure] bool Validate(CashInCallbackTransaction transaction, string hmac);
/// <summary>Validate the identity and integrity for "Paymob Accept"'s callback submission.</summary>
/// <param name="token">Received token.</param>
/// <param name="hmac">Received HMAC.</param>
/// <returns>True if is valid, otherwise return false.</returns>
[Pure] bool Validate(CashInCallbackToken token, string hmac);
/// <summary>Create iframe src url.</summary>
/// <param name="iframeId">Iframe Id.</param>
/// <param name="token">Payment token.</param>
[Pure] string CreateIframeSrc(string iframeId, string token);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
static Program()
{
TestList = new Dictionary<string, Action>()
{
["And.Vector128.Double"] = And_Vector128_Double,
["And.Vector128.Int16"] = And_Vector128_Int16,
["And.Vector128.Int32"] = And_Vector128_Int32,
["And.Vector128.Int64"] = And_Vector128_Int64,
["And.Vector128.SByte"] = And_Vector128_SByte,
["And.Vector128.Single"] = And_Vector128_Single,
["And.Vector128.UInt16"] = And_Vector128_UInt16,
["And.Vector128.UInt32"] = And_Vector128_UInt32,
["And.Vector128.UInt64"] = And_Vector128_UInt64,
["BitwiseClear.Vector64.Byte"] = BitwiseClear_Vector64_Byte,
["BitwiseClear.Vector64.Double"] = BitwiseClear_Vector64_Double,
["BitwiseClear.Vector64.Int16"] = BitwiseClear_Vector64_Int16,
["BitwiseClear.Vector64.Int32"] = BitwiseClear_Vector64_Int32,
["BitwiseClear.Vector64.Int64"] = BitwiseClear_Vector64_Int64,
["BitwiseClear.Vector64.SByte"] = BitwiseClear_Vector64_SByte,
["BitwiseClear.Vector64.Single"] = BitwiseClear_Vector64_Single,
["BitwiseClear.Vector64.UInt16"] = BitwiseClear_Vector64_UInt16,
["BitwiseClear.Vector64.UInt32"] = BitwiseClear_Vector64_UInt32,
["BitwiseClear.Vector64.UInt64"] = BitwiseClear_Vector64_UInt64,
["BitwiseClear.Vector128.Byte"] = BitwiseClear_Vector128_Byte,
["BitwiseClear.Vector128.Double"] = BitwiseClear_Vector128_Double,
["BitwiseClear.Vector128.Int16"] = BitwiseClear_Vector128_Int16,
["BitwiseClear.Vector128.Int32"] = BitwiseClear_Vector128_Int32,
["BitwiseClear.Vector128.Int64"] = BitwiseClear_Vector128_Int64,
["BitwiseClear.Vector128.SByte"] = BitwiseClear_Vector128_SByte,
["BitwiseClear.Vector128.Single"] = BitwiseClear_Vector128_Single,
["BitwiseClear.Vector128.UInt16"] = BitwiseClear_Vector128_UInt16,
["BitwiseClear.Vector128.UInt32"] = BitwiseClear_Vector128_UInt32,
["BitwiseClear.Vector128.UInt64"] = BitwiseClear_Vector128_UInt64,
["BitwiseSelect.Vector64.Byte"] = BitwiseSelect_Vector64_Byte,
["BitwiseSelect.Vector64.Double"] = BitwiseSelect_Vector64_Double,
["BitwiseSelect.Vector64.Int16"] = BitwiseSelect_Vector64_Int16,
["BitwiseSelect.Vector64.Int32"] = BitwiseSelect_Vector64_Int32,
["BitwiseSelect.Vector64.Int64"] = BitwiseSelect_Vector64_Int64,
["BitwiseSelect.Vector64.SByte"] = BitwiseSelect_Vector64_SByte,
["BitwiseSelect.Vector64.Single"] = BitwiseSelect_Vector64_Single,
["BitwiseSelect.Vector64.UInt16"] = BitwiseSelect_Vector64_UInt16,
["BitwiseSelect.Vector64.UInt32"] = BitwiseSelect_Vector64_UInt32,
["BitwiseSelect.Vector64.UInt64"] = BitwiseSelect_Vector64_UInt64,
["BitwiseSelect.Vector128.Byte"] = BitwiseSelect_Vector128_Byte,
["BitwiseSelect.Vector128.Double"] = BitwiseSelect_Vector128_Double,
["BitwiseSelect.Vector128.Int16"] = BitwiseSelect_Vector128_Int16,
["BitwiseSelect.Vector128.Int32"] = BitwiseSelect_Vector128_Int32,
["BitwiseSelect.Vector128.Int64"] = BitwiseSelect_Vector128_Int64,
["BitwiseSelect.Vector128.SByte"] = BitwiseSelect_Vector128_SByte,
["BitwiseSelect.Vector128.Single"] = BitwiseSelect_Vector128_Single,
["BitwiseSelect.Vector128.UInt16"] = BitwiseSelect_Vector128_UInt16,
["BitwiseSelect.Vector128.UInt32"] = BitwiseSelect_Vector128_UInt32,
["BitwiseSelect.Vector128.UInt64"] = BitwiseSelect_Vector128_UInt64,
["Ceiling.Vector64.Single"] = Ceiling_Vector64_Single,
["Ceiling.Vector128.Single"] = Ceiling_Vector128_Single,
["CeilingScalar.Vector64.Double"] = CeilingScalar_Vector64_Double,
["CeilingScalar.Vector64.Single"] = CeilingScalar_Vector64_Single,
["CompareEqual.Vector64.Byte"] = CompareEqual_Vector64_Byte,
["CompareEqual.Vector64.Int16"] = CompareEqual_Vector64_Int16,
["CompareEqual.Vector64.Int32"] = CompareEqual_Vector64_Int32,
["CompareEqual.Vector64.SByte"] = CompareEqual_Vector64_SByte,
["CompareEqual.Vector64.Single"] = CompareEqual_Vector64_Single,
["CompareEqual.Vector64.UInt16"] = CompareEqual_Vector64_UInt16,
["CompareEqual.Vector64.UInt32"] = CompareEqual_Vector64_UInt32,
["CompareEqual.Vector128.Byte"] = CompareEqual_Vector128_Byte,
["CompareEqual.Vector128.Int16"] = CompareEqual_Vector128_Int16,
["CompareEqual.Vector128.Int32"] = CompareEqual_Vector128_Int32,
["CompareEqual.Vector128.SByte"] = CompareEqual_Vector128_SByte,
["CompareEqual.Vector128.Single"] = CompareEqual_Vector128_Single,
["CompareEqual.Vector128.UInt16"] = CompareEqual_Vector128_UInt16,
["CompareEqual.Vector128.UInt32"] = CompareEqual_Vector128_UInt32,
["CompareGreaterThan.Vector64.Byte"] = CompareGreaterThan_Vector64_Byte,
["CompareGreaterThan.Vector64.Int16"] = CompareGreaterThan_Vector64_Int16,
["CompareGreaterThan.Vector64.Int32"] = CompareGreaterThan_Vector64_Int32,
["CompareGreaterThan.Vector64.SByte"] = CompareGreaterThan_Vector64_SByte,
["CompareGreaterThan.Vector64.Single"] = CompareGreaterThan_Vector64_Single,
["CompareGreaterThan.Vector64.UInt16"] = CompareGreaterThan_Vector64_UInt16,
["CompareGreaterThan.Vector64.UInt32"] = CompareGreaterThan_Vector64_UInt32,
["CompareGreaterThan.Vector128.Byte"] = CompareGreaterThan_Vector128_Byte,
["CompareGreaterThan.Vector128.Int16"] = CompareGreaterThan_Vector128_Int16,
["CompareGreaterThan.Vector128.Int32"] = CompareGreaterThan_Vector128_Int32,
["CompareGreaterThan.Vector128.SByte"] = CompareGreaterThan_Vector128_SByte,
["CompareGreaterThan.Vector128.Single"] = CompareGreaterThan_Vector128_Single,
["CompareGreaterThan.Vector128.UInt16"] = CompareGreaterThan_Vector128_UInt16,
["CompareGreaterThan.Vector128.UInt32"] = CompareGreaterThan_Vector128_UInt32,
["CompareGreaterThanOrEqual.Vector64.Byte"] =
CompareGreaterThanOrEqual_Vector64_Byte,
["CompareGreaterThanOrEqual.Vector64.Int16"] =
CompareGreaterThanOrEqual_Vector64_Int16,
["CompareGreaterThanOrEqual.Vector64.Int32"] =
CompareGreaterThanOrEqual_Vector64_Int32,
["CompareGreaterThanOrEqual.Vector64.SByte"] =
CompareGreaterThanOrEqual_Vector64_SByte,
["CompareGreaterThanOrEqual.Vector64.Single"] =
CompareGreaterThanOrEqual_Vector64_Single,
["CompareGreaterThanOrEqual.Vector64.UInt16"] =
CompareGreaterThanOrEqual_Vector64_UInt16,
["CompareGreaterThanOrEqual.Vector64.UInt32"] =
CompareGreaterThanOrEqual_Vector64_UInt32,
["CompareGreaterThanOrEqual.Vector128.Byte"] =
CompareGreaterThanOrEqual_Vector128_Byte,
["CompareGreaterThanOrEqual.Vector128.Int16"] =
CompareGreaterThanOrEqual_Vector128_Int16,
["CompareGreaterThanOrEqual.Vector128.Int32"] =
CompareGreaterThanOrEqual_Vector128_Int32,
["CompareGreaterThanOrEqual.Vector128.SByte"] =
CompareGreaterThanOrEqual_Vector128_SByte,
["CompareGreaterThanOrEqual.Vector128.Single"] =
CompareGreaterThanOrEqual_Vector128_Single,
["CompareGreaterThanOrEqual.Vector128.UInt16"] =
CompareGreaterThanOrEqual_Vector128_UInt16,
["CompareGreaterThanOrEqual.Vector128.UInt32"] =
CompareGreaterThanOrEqual_Vector128_UInt32,
["CompareLessThan.Vector64.Byte"] = CompareLessThan_Vector64_Byte,
["CompareLessThan.Vector64.Int16"] = CompareLessThan_Vector64_Int16,
["CompareLessThan.Vector64.Int32"] = CompareLessThan_Vector64_Int32,
["CompareLessThan.Vector64.SByte"] = CompareLessThan_Vector64_SByte,
["CompareLessThan.Vector64.Single"] = CompareLessThan_Vector64_Single,
};
}
}
}
|
using System;
using System.Linq;
using Android.Content;
using Android.Views;
using AndroidX.Core.Content;
using AndroidX.RecyclerView.Widget;
namespace AuthenticatorPro.IconList
{
internal sealed class IconAdapter : RecyclerView.Adapter
{
private readonly Context _context;
private readonly IconSource _iconSource;
public IconAdapter(Context context, IconSource iconSource)
{
_context = context;
_iconSource = iconSource;
}
public override int ItemCount => _iconSource.List.Count;
public event EventHandler<int> ItemClick;
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var icon = _iconSource.List.ElementAt(position);
var holder = (IconHolder) viewHolder;
var drawable = ContextCompat.GetDrawable(_context, icon.Value);
holder.Icon.SetImageDrawable(drawable);
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
var itemView = LayoutInflater.From(parent.Context).Inflate(
Resource.Layout.iconListItem, parent, false);
var holder = new IconHolder(itemView, OnItemClick);
return holder;
}
private void OnItemClick(int position)
{
ItemClick?.Invoke(this, position);
}
public override long GetItemId(int position)
{
return Icons.Service.ElementAt(position).GetHashCode();
}
}
} |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using NuGet;
namespace ICSharpCode.PackageManagement
{
public class ManagePackagesUserPrompts
{
ILicenseAcceptanceService licenseAcceptanceService;
ISelectProjectsService selectProjectsService;
IPackageManagementEvents packageManagementEvents;
IFileConflictResolver fileConflictResolver;
FileConflictResolution lastFileConflictResolution;
public ManagePackagesUserPrompts(IPackageManagementEvents packageManagementEvents)
: this(
packageManagementEvents,
new LicenseAcceptanceService(),
new SelectProjectsService(),
new FileConflictResolver())
{
}
public ManagePackagesUserPrompts(
IPackageManagementEvents packageManagementEvents,
ILicenseAcceptanceService licenseAcceptanceService,
ISelectProjectsService selectProjectsService,
IFileConflictResolver fileConflictResolver)
{
this.packageManagementEvents = packageManagementEvents;
this.licenseAcceptanceService = licenseAcceptanceService;
this.selectProjectsService = selectProjectsService;
this.fileConflictResolver = fileConflictResolver;
ResetFileConflictResolution();
SubscribeToEvents();
}
void ResetFileConflictResolution()
{
lastFileConflictResolution = FileConflictResolution.Overwrite;
}
void SubscribeToEvents()
{
packageManagementEvents.AcceptLicenses += AcceptLicenses;
packageManagementEvents.SelectProjects += SelectProjects;
packageManagementEvents.ResolveFileConflict += ResolveFileConflict;
packageManagementEvents.PackageOperationsStarting += PackageOperationsStarting;
}
void AcceptLicenses(object sender, AcceptLicensesEventArgs e)
{
e.IsAccepted = licenseAcceptanceService.AcceptLicenses(e.Packages);
}
void SelectProjects(object sender, SelectProjectsEventArgs e)
{
e.IsAccepted = selectProjectsService.SelectProjects(e.SelectedProjects);
}
void ResolveFileConflict(object sender, ResolveFileConflictEventArgs e)
{
if (UserPreviouslySelectedOverwriteAllOrIgnoreAll()) {
e.Resolution = lastFileConflictResolution;
} else {
e.Resolution = fileConflictResolver.ResolveFileConflict(e.Message);
lastFileConflictResolution = e.Resolution;
}
}
bool UserPreviouslySelectedOverwriteAllOrIgnoreAll()
{
return
(lastFileConflictResolution == FileConflictResolution.IgnoreAll) ||
(lastFileConflictResolution == FileConflictResolution.OverwriteAll);
}
void PackageOperationsStarting(object sender, EventArgs e)
{
ResetFileConflictResolution();
}
public void Dispose()
{
UnsubscribeFromEvents();
}
public void UnsubscribeFromEvents()
{
packageManagementEvents.SelectProjects -= SelectProjects;
packageManagementEvents.AcceptLicenses -= AcceptLicenses;
packageManagementEvents.ResolveFileConflict -= ResolveFileConflict;
packageManagementEvents.PackageOperationsStarting -= PackageOperationsStarting;
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
namespace LogicMonitor.Api.Netscans
{
/// <summary>
/// A Netscan Policy Schedule Type
/// </summary>
[DataContract(Name = "type")]
[JsonConverter(typeof(StringEnumConverter))]
public enum NetscanScheduleType
{
/// <summary>
/// Unknown
/// </summary>
[EnumMember(Value = "unknown")]
Unknown = 0,
/// <summary>
/// Manual
/// </summary>
[EnumMember(Value = "manual")]
Manual,
/// <summary>
/// Daily
/// </summary>
[EnumMember(Value = "daily")]
Daily,
/// <summary>
/// Weekly
/// </summary>
[EnumMember(Value = "weekly")]
Weekly,
/// <summary>
/// Weekly
/// </summary>
[EnumMember(Value = "monthly")]
Monthly,
/// <summary>
/// Hourly
/// </summary>
[EnumMember(Value = "hourly")]
Hourly
}
} |
using System.Collections.Generic;
namespace ESFA.DC.ILR.FundingService.FM35.FundingOutput.Model.Output
{
public class FM35Global
{
public int UKPRN { get; set; }
public string CurFundYr { get; set; }
public string LARSVersion { get; set; }
public string OrgVersion { get; set; }
public string PostcodeDisadvantageVersion { get; set; }
public string RulebaseVersion { get; set; }
public List<FM35Learner> Learners { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
namespace la_rive_admin.Models
{
public class UserContext
{
public DbSet<User> Users { get; set; }
}
}
|
using System;
using UnityEngine;
using UnityEngine.Networking;
using Assets.Scripts.Utils;
namespace Assets.Scripts.Networking {
class SyncPosition : NetworkBehaviour {
[SerializeField]
Transform _transform;
[SerializeField]
float lerpRate = 15f;
[SyncVar]
Vector3 syncPosition;
private bool isLocal;
void Start() {
isLocal = NetworkUtils.RatinhosTest(gameObject);
}
void FixedUpdate() {
LerpPosition();
TransmitPosition();
}
void LerpPosition() {
if (!isLocal) {
_transform.position = Vector3.Lerp(_transform.position, syncPosition, Time.deltaTime * lerpRate);
}
}
[Command]
void CmdProvidePositionToServer(Vector3 value) {
syncPosition = value;
}
[Client]
void TransmitPosition() {
if (isLocal) {
CmdProvidePositionToServer(_transform.position);
}
}
}
}
|
namespace DotNetCommons.CheckDigits
{
/// <summary>
/// Check digit calculations.
/// </summary>
public interface ICheckDigits
{
/// <summary>
/// Calculate a new check digit from a given input string.
/// </summary>
char Calculate(string input);
/// <summary>
/// Append a new check digit to a given input string.
/// </summary>
string Append(string input) => input + Calculate(input);
/// <summary>
/// Validate whether the input string has a correct check digit or not.
/// </summary>
bool Validate(string input) => input == Append(input[0..^1]);
}
}
|
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GenHTTP.Testing.Acceptance.Engine
{
[TestClass]
public sealed class RoutingTests
{
/// <summary>
/// As a client, I expect the server to return 404 for non-existing files.
/// </summary>
[TestMethod]
public void NotFoundForUnknownRoute()
{
using var runner = TestRunner.Run();
using var response = runner.GetResponse();
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
}
}
}
|
using System;
namespace Gridsum.DataflowEx.Databases
{
/// <summary>
/// Represents a mapping from C# property to a DB column
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class DBColumnMapping : Attribute
{
/// <summary>
/// Constructs a mapping from the tagged property to a db column name by property name
/// </summary>
/// <param name="destLabel">The label to help categorize all column mappings</param>
public DBColumnMapping(string destLabel)
: this(destLabel, -1, null, null, ColumnMappingOption.Mandatory)
{
}
/// <summary>
/// Constructs a mapping from the tagged property to a db column by column offset in the db table
/// </summary>
/// <param name="destLabel">The label to help categorize all column mappings</param>
/// <param name="destColumnOffset">the column offset in the db table</param>
/// <param name="defaultValue">default value for the property if the propety is null</param>
/// <param name="option">The option, or priority of this mapping</param>
public DBColumnMapping(string destLabel, int destColumnOffset, object defaultValue = null, ColumnMappingOption option = ColumnMappingOption.Mandatory)
: this(destLabel, destColumnOffset, null, defaultValue, option) { }
/// <summary>
/// Constructs a mapping from the tagged property to a db column by column name in the db table
/// </summary>
/// <param name="destLabel">The label to help categorize all column mappings</param>
/// <param name="destColumnName">the column name in the db table</param>
/// <param name="defaultValue">default value for the property if the propety is null</param>
/// <param name="option">The option, or priority of this mapping</param>
public DBColumnMapping(string destLabel, string destColumnName, object defaultValue = null, ColumnMappingOption option = ColumnMappingOption.Mandatory)
: this(destLabel, -1, destColumnName, defaultValue, option)
{
}
protected DBColumnMapping(string destLabel, int destColumnOffset, string destColumnName, object defaultValue, ColumnMappingOption option)
{
DestLabel = destLabel;
DestColumnOffset = destColumnOffset;
DestColumnName = destColumnName;
DefaultValue = defaultValue;
this.Option = option;
}
/// <summary>
/// The label to help categorize all column mappings
/// </summary>
public string DestLabel { get; private set; }
/// <summary>
/// Column offset in the db table
/// </summary>
public int DestColumnOffset { get; set; }
/// <summary>
/// Column name in the db table
/// </summary>
public string DestColumnName { get; set; }
/// <summary>
/// Default value for the property if the propety is null
/// </summary>
public object DefaultValue { get; internal set; }
/// <summary>
/// The option, or priority of this mapping
/// </summary>
public ColumnMappingOption Option { get; set; }
internal PropertyTreeNode Host { get; set; }
internal bool IsDestColumnOffsetOk()
{
return DestColumnOffset >= 0;
}
internal bool IsDestColumnNameOk()
{
return string.IsNullOrWhiteSpace(DestColumnName) == false;
}
public override string ToString()
{
return string.Format(
"[ColName:{0}, ColOffset:{1}, DefaultValue:{2}, Option: {3}]",
this.DestColumnName,
this.DestColumnOffset,
this.DefaultValue,
this.Option);
}
}
/// <summary>
/// The option of a db column mapping
/// </summary>
public enum ColumnMappingOption
{
/// <summary>
/// Used typically by external mappings to overwrite Mandatory option on tagged attribute. The column must exist in the destination table.
/// </summary>
Overwrite = short.MinValue,
/// <summary>
/// The column must exist in the destination table
/// </summary>
Mandatory = 1,
/// <summary>
/// The column mapping can be ignored if the column is not found in the destination table
/// This option is useful when you have one dest label for multiple different tables
/// </summary>
Optional = 2
}
}
|
using System.Collections.Immutable;
using UnicornHack.Primitives;
namespace UnicornHack.Systems.Abilities
{
public class SubAttackStats
{
public AbilitySuccessCondition SuccessCondition { get; set; }
public int HitProbability { get; set; }
public int Accuracy { get; set; }
public ImmutableList<GameEntity> Effects { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Core;
namespace RPG.Characters
{
public abstract class AbilityConfig : ScriptableObject
{
//safer than public, only children who inherit from specialAbility can acces this
protected AbilityBehaviour behaviour;
[Header("Special Ability General")]
[SerializeField]
private int energyCost = 10;
[SerializeField]
private int abilityCooldownThreshold = 10;
[SerializeField]
private AnimationClip abilityAnimation;
[SerializeField]
private GameObject abilityParticleEffectPrefab;
[SerializeField]
private AudioClip[] abilitySoundClips;
public bool isSelfAbility = false;
public abstract AbilityBehaviour GetBehaviourComponent(GameObject objectToAttachTo);
public void AttachAbilityTo(GameObject objectToAttachTo)
{
AbilityBehaviour behaviourComponent = GetBehaviourComponent(objectToAttachTo);
behaviourComponent.SetConfig(this);
behaviour = behaviourComponent;
}
public void Use(GameObject target, float baseWeaponDamage)
{
behaviour.Use(target, baseWeaponDamage);
}
public int GetEnergyCost()
{
return energyCost;
}
public AnimationClip GetAbilityAnimationClip()
{
return abilityAnimation;
}
public GameObject GetAbilityParticleEffect()
{
return abilityParticleEffectPrefab;
}
public AudioClip GetRandomAudioClips()
{
return abilitySoundClips[Random.Range(0, abilitySoundClips.Length)];
}
public int GetAbilityCooldownThreshold()
{
return abilityCooldownThreshold;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace mvc_webapp.Models
{
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdProduct { get; set; }
[Display(Name = "Escreva o codigo do produto")]
[StringLength(20)]
[Required(ErrorMessage = "{0} é necessário.")]
public string ProductCode { get; set; }
[Display(Name = "Escreva o tipo do produto")]
[StringLength(50)]
[Required(ErrorMessage = "{0} é necessário.")]
public string ProductType { get; set; }
[Display(Name = "Apresente a descrição do produto")]
[StringLength(150)]
public string Description { get; set; }
[Display(Name = "Preço unitário")]
[DisplayFormat(DataFormatString = "{0:C}")]
[Required(ErrorMessage = "{0} é necessário.")]
public decimal UniPrice { get; set; }
[Display(Name = "Quantidade no estoque")]
[Required(ErrorMessage = "{0} é necessário.")]
public int QtyInStock { get; set; }
}
} |
using System.Runtime.InteropServices;
using Vanara.InteropServices;
namespace Vanara.PInvoke
{
public static partial class IpHlpApi
{
/// <summary>
/// <para>
/// The <c>TCP_TABLE_CLASS</c> enumeration defines the set of values used to indicate the type of table returned by calls to GetExtendedTcpTable.
/// </para>
/// </summary>
/// <remarks>
/// <para>
/// On the Microsoft Windows Software Development Kit (SDK) released for Windows Vista and later, the organization of header files
/// has changed and the <c>TCP_TABLE_CLASS</c> enumeration is defined in the Iprtrmib.h header file, not in the Iphlpapi.h header
/// file. Note that the Iprtrmib.h header file is automatically included in Iphlpapi.h header file. The Iprtrmib.h header files
/// should never be used directly.
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/desktop/api/iprtrmib/ne-iprtrmib-_tcp_table_class typedef enum _TCP_TABLE_CLASS {
// TCP_TABLE_BASIC_LISTENER , TCP_TABLE_BASIC_CONNECTIONS , TCP_TABLE_BASIC_ALL , TCP_TABLE_OWNER_PID_LISTENER ,
// TCP_TABLE_OWNER_PID_CONNECTIONS , TCP_TABLE_OWNER_PID_ALL , TCP_TABLE_OWNER_MODULE_LISTENER , TCP_TABLE_OWNER_MODULE_CONNECTIONS ,
// TCP_TABLE_OWNER_MODULE_ALL } TCP_TABLE_CLASS, *PTCP_TABLE_CLASS;
[PInvokeData("iprtrmib.h", MSDNShortId = "abfaf7e5-7739-4f23-bfb4-09206111599f")]
public enum TCP_TABLE_CLASS
{
/// <summary>
/// A MIB_TCPTABLE table that contains all listening (receiving only) TCP endpoints on the local computer is returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_TCPTABLE), CorrespondingAction.Get)]
TCP_TABLE_BASIC_LISTENER,
/// <summary>A MIB_TCPTABLE table that contains all connected TCP endpoints on the local computer is returned to the caller.</summary>
[CorrespondingType(typeof(MIB_TCPTABLE), CorrespondingAction.Get)]
TCP_TABLE_BASIC_CONNECTIONS,
/// <summary>A MIB_TCPTABLE table that contains all TCP endpoints on the local computer is returned to the caller.</summary>
[CorrespondingType(typeof(MIB_TCPTABLE), CorrespondingAction.Get)]
TCP_TABLE_BASIC_ALL,
/// <summary>
/// A MIB_TCPTABLE_OWNER_PID or MIB_TCP6TABLE_OWNER_PID that contains all listening (receiving only) TCP endpoints on the local
/// computer is returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_TCPTABLE_OWNER_PID), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_TCP6TABLE_OWNER_PID), CorrespondingAction.Get)]
TCP_TABLE_OWNER_PID_LISTENER,
/// <summary>
/// A MIB_TCPTABLE_OWNER_PID or MIB_TCP6TABLE_OWNER_PID that structure that contains all connected TCP endpoints on the local
/// computer is returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_TCPTABLE_OWNER_PID), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_TCP6TABLE_OWNER_PID), CorrespondingAction.Get)]
TCP_TABLE_OWNER_PID_CONNECTIONS,
/// <summary>
/// A MIB_TCPTABLE_OWNER_PID or MIB_TCP6TABLE_OWNER_PID structure that contains all TCP endpoints on the local computer is
/// returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_TCPTABLE_OWNER_PID), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_TCP6TABLE_OWNER_PID), CorrespondingAction.Get)]
TCP_TABLE_OWNER_PID_ALL,
/// <summary>
/// A MIB_TCPTABLE_OWNER_MODULE or MIB_TCP6TABLE_OWNER_MODULE structure that contains all listening (receiving only) TCP
/// endpoints on the local computer is returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_TCPTABLE_OWNER_MODULE), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_TCP6TABLE_OWNER_MODULE), CorrespondingAction.Get)]
TCP_TABLE_OWNER_MODULE_LISTENER,
/// <summary>
/// A MIB_TCPTABLE_OWNER_MODULE or MIB_TCP6TABLE_OWNER_MODULE structure that contains all connected TCP endpoints on the local
/// computer is returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_TCPTABLE_OWNER_MODULE), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_TCP6TABLE_OWNER_MODULE), CorrespondingAction.Get)]
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
/// <summary>
/// A MIB_TCPTABLE_OWNER_MODULE or MIB_TCP6TABLE_OWNER_MODULE structure that contains all TCP endpoints on the local computer is
/// returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_TCPTABLE_OWNER_MODULE), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_TCP6TABLE_OWNER_MODULE), CorrespondingAction.Get)]
TCP_TABLE_OWNER_MODULE_ALL
}
/// <summary>
/// The <c>TCPIP_OWNER_MODULE_INFO_CLASS</c> enumeration defines the type of module information structure passed to calls of the
/// <c>GetOwnerModuleFromXXXEntry</c> family.
/// </summary>
// https://docs.microsoft.com/en-us/windows/desktop/api/iprtrmib/ne-iprtrmib-_tcpip_owner_module_info_class typedef enum
// _TCPIP_OWNER_MODULE_INFO_CLASS { TCPIP_OWNER_MODULE_INFO_BASIC } TCPIP_OWNER_MODULE_INFO_CLASS, *PTCPIP_OWNER_MODULE_INFO_CLASS;
[PInvokeData("iprtrmib.h", MSDNShortId = "8529dd62-8516-47d0-8118-95e6d33fc799")]
public enum TCPIP_OWNER_MODULE_INFO_CLASS
{
/// <summary>A <see cref="TCPIP_OWNER_MODULE_BASIC_INFO"/> structure is passed to the GetOwnerModuleFromXXXEntry function.</summary>
[CorrespondingType(typeof(TCPIP_OWNER_MODULE_BASIC_INFO))]
TCPIP_OWNER_MODULE_INFO_BASIC,
}
/// <summary>
/// <para>
/// The <c>UDP_TABLE_CLASS</c> enumeration defines the set of values used to indicate the type of table returned by calls to GetExtendedUdpTable.
/// </para>
/// </summary>
/// <remarks>
/// <para>
/// On the Microsoft Windows Software Development Kit (SDK) released for Windows Vista and later, the organization of header files
/// has changed and the <c>UDP_TABLE_CLASS</c> enumeration is defined in the Iprtrmib.h header file, not in the Iphlpapi.h header
/// file. Note that the Iprtrmib.h header file is automatically included in Iphlpapi.h header file. The Iprtrmib.h header files
/// should never be used directly.
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/desktop/api/iprtrmib/ne-iprtrmib-_udp_table_class typedef enum _UDP_TABLE_CLASS {
// UDP_TABLE_BASIC , UDP_TABLE_OWNER_PID , UDP_TABLE_OWNER_MODULE } UDP_TABLE_CLASS, *PUDP_TABLE_CLASS;
[PInvokeData("iprtrmib.h", MSDNShortId = "2e7304d1-b89c-46d4-9121-936a1c38cc51")]
public enum UDP_TABLE_CLASS
{
/// <summary>A MIB_UDPTABLE structure that contains all UDP endpoints on the local computer is returned to the caller.</summary>
[CorrespondingType(typeof(MIB_UDPTABLE), CorrespondingAction.Get)]
UDP_TABLE_BASIC,
/// <summary>
/// A MIB_UDPTABLE_OWNER_PID or MIB_UDP6TABLE_OWNER_PID structure that contains all UDP endpoints on the local computer is
/// returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_UDPTABLE_OWNER_PID), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_UDP6TABLE_OWNER_PID), CorrespondingAction.Get)]
UDP_TABLE_OWNER_PID,
/// <summary>
/// A MIB_UDPTABLE_OWNER_MODULE or MIB_UDP6TABLE_OWNER_MODULE structure that contains all UDP endpoints on the local computer is
/// returned to the caller.
/// </summary>
[CorrespondingType(typeof(MIB_UDPTABLE_OWNER_MODULE), CorrespondingAction.Get)]
[CorrespondingType(typeof(MIB_UDP6TABLE_OWNER_MODULE), CorrespondingAction.Get)]
UDP_TABLE_OWNER_MODULE,
}
/// <summary>
/// The <c>TCPIP_OWNER_MODULE_BASIC_INFO</c> structure contains pointers to the module name and module path values associated with a
/// TCP connection. The <c>TCPIP_OWNER_MODULE_BASIC_INFO</c> structure is returned by the GetOwnerModuleFromTcpEntry and
/// GetOwnerModuleFromTcp6Entry functions.
/// </summary>
/// <remarks>
/// <para>
/// If the module owner is the system kernel, the <c>lpModuleName</c> and <c>lpModulePath</c> members point to a wide character
/// string that contains "System".
/// </para>
/// <para>
/// On Windows Vista and later as well as on the Microsoft Windows Software Development Kit (SDK), the organization of header files
/// has changed and the <c>TCPIP_OWNER_MODULE_BASIC_INFO</c> structure is defined in the Iprtrmib.h header file.
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/desktop/api/iprtrmib/ns-iprtrmib-tcpip_owner_module_basic_info typedef struct
// _TCPIP_OWNER_MODULE_BASIC_INFO { PWCHAR pModuleName; PWCHAR pModulePath; } TCPIP_OWNER_MODULE_BASIC_INFO, *PTCPIP_OWNER_MODULE_BASIC_INFO;
[PInvokeData("iprtrmib.h", MSDNShortId = "cce3e0ff-31f2-454b-8aae-3b35f72f47ed")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TCPIP_OWNER_MODULE_BASIC_INFO
{
/// <summary>
/// A pointer to the name of the module. This field should be a <c>NULL</c> pointer when passed to GetOwnerModuleFromTcpEntry or
/// GetOwnerModuleFromTcp6Entry function.
/// </summary>
public string pModuleName;
/// <summary>
/// A pointer to the full path of the module, including the module name. This field should be a <c>NULL</c> pointer when passed
/// to GetOwnerModuleFromTcpEntry or GetOwnerModuleFromTcp6Entry function.
/// </summary>
public string pModulePath;
}
/// <summary>
/// The <c>TCPIP_OWNER_MODULE_BASIC_INFO</c> structure contains pointers to the module name and module path values associated with a
/// TCP connection. The <c>TCPIP_OWNER_MODULE_BASIC_INFO</c> structure is returned by the GetOwnerModuleFromTcpEntry and
/// GetOwnerModuleFromTcp6Entry functions.
/// </summary>
/// <remarks>
/// <para>
/// If the module owner is the system kernel, the <c>lpModuleName</c> and <c>lpModulePath</c> members point to a wide character
/// string that contains "System".
/// </para>
/// <para>
/// On Windows Vista and later as well as on the Microsoft Windows Software Development Kit (SDK), the organization of header files
/// has changed and the <c>TCPIP_OWNER_MODULE_BASIC_INFO</c> structure is defined in the Iprtrmib.h header file.
/// </para>
/// </remarks>
// https://docs.microsoft.com/en-us/windows/desktop/api/iprtrmib/ns-iprtrmib-tcpip_owner_module_basic_info typedef struct
// _TCPIP_OWNER_MODULE_BASIC_INFO { PWCHAR pModuleName; PWCHAR pModulePath; } TCPIP_OWNER_MODULE_BASIC_INFO, *PTCPIP_OWNER_MODULE_BASIC_INFO;
[PInvokeData("iprtrmib.h", MSDNShortId = "cce3e0ff-31f2-454b-8aae-3b35f72f47ed")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TCPIP_OWNER_MODULE_BASIC_INFO_UNMGD
{
/// <summary>
/// A pointer to the name of the module. This field should be a <c>NULL</c> pointer when passed to GetOwnerModuleFromTcpEntry or
/// GetOwnerModuleFromTcp6Entry function.
/// </summary>
public StrPtrUni pModuleName;
/// <summary>
/// A pointer to the full path of the module, including the module name. This field should be a <c>NULL</c> pointer when passed
/// to GetOwnerModuleFromTcpEntry or GetOwnerModuleFromTcp6Entry function.
/// </summary>
public StrPtrUni pModulePath;
/// <summary>Performs an implicit conversion from <see cref="TCPIP_OWNER_MODULE_BASIC_INFO_UNMGD"/> to <see cref="TCPIP_OWNER_MODULE_BASIC_INFO"/>.</summary>
/// <param name="unmgd">The unmanaged structure.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator TCPIP_OWNER_MODULE_BASIC_INFO(TCPIP_OWNER_MODULE_BASIC_INFO_UNMGD unmgd) => new TCPIP_OWNER_MODULE_BASIC_INFO { pModuleName = unmgd.pModuleName, pModulePath = unmgd.pModulePath };
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zaggoware.BugTracker.Common;
namespace Zaggoware.BugTracker.Services
{
using Zaggoware.BugTracker.Data;
using Zaggoware.BugTracker.Services.DataMappers;
public class OrganizationService : IOrganizationService
{
private readonly IDbContext context;
public OrganizationService(IDbContext context)
{
this.context = context;
}
public Organization CreateOrganization(string name, bool copyUserGroupTemplates)
{
var organization = this.context.Organizations.Create();
organization.Name = name;
organization.CreationDate = DateTime.Now;
organization.ModificationDate = DateTime.Now;
if (copyUserGroupTemplates)
{
// TODO: Copy user groups when copyUserGroupTemplates == true
}
this.context.Organizations.Add(organization);
this.context.SaveChanges();
return organization.Map();
}
public Organization GetOrganizationById(string id)
{
return this.context.Organizations.Find(id).Map();
}
public Organization GetOrganizationByName(string name)
{
return
this.context.Organizations.FirstOrDefault(
o => o.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).Map();
}
public Organization GetOrganizationByUrl(string url)
{
return
this.context.Organizations.FirstOrDefault(
o => o.Url.Equals(url, StringComparison.InvariantCultureIgnoreCase)).Map();
}
public IEnumerable<Organization> GetOrganizations()
{
return this.context.Organizations.ToList().Select(o => o.Map());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Laba4_ApproximateCalculationOfIntegrals
{
public class AntiderivativeFunction : IFunction
{
public string Print()
{
return "f(x) = sin(x) * cos(x) + e^x";
}
public double Value(double x)
{
return Math.Sin(x) * Math.Cos(x) + Math.Exp(x);
// return x;
// return x * x;
// return x * x * x;
// return x * x * x * x;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using IL2CPU.API.Attribs;
namespace Cosmos.CPU.x86 {
static public class Boot {
// OLD CODE pasted.. .still cleaning/porting
// See note in Global - these are a "hack" for now so
// we dont force static init of Global, and it "pulls" these later till
// we eventually eliminate them
static public PIC PIC;
// Has to be static for now, ZeroFill gets called before the Init.
static public readonly Processor Processor = new Processor();
// Bootstrap is a class designed only to get the essentials done.
// ie the stuff needed to "pre boot". Do only the very minimal here.
// IDT, PIC, and Float
// Note: This is changing a bit GDT (already) and IDT are moving to a real preboot area.
[BootEntry(10)]
static private void Init() {
PIC = new PIC();
Processor.UpdateIDT(true);
/* TODO check using CPUID that SSE2 is supported */
Processor.InitSSE();
/*
* We liked to use SSE for all floating point operation and end to mix SSE / x87 in Cosmos code
* but sadly in x86 this resulte impossible as Intel not implemented some needed instruction (for example conversion
* for long to double) so - in some rare cases - x87 continue to be used. I hope passing to the x32 or x64 IA will solve
* definively this problem.
*/
Processor.InitFloat();
// Managed_Memory_System.ManagedMemory.Initialize();
// Managed_Memory_System.ManagedMemory.SetUpMemoryArea();
}
}
}
|
using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Net.Http;
using System.Windows;
using Thinktecture.Samples;
namespace WpfClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
LoginWebView _login;
AuthorizeResponse _response;
public MainWindow()
{
InitializeComponent();
_login = new LoginWebView();
_login.Done += _login_Done;
Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
_login.Owner = this;
}
void _login_Done(object sender, AuthorizeResponse e)
{
_response = e;
Textbox1.Text = e.Raw;
}
private void LoginWithProfileButton_Click(object sender, RoutedEventArgs e)
{
RequestToken("openid profile", "code id_token");
}
private void LoginWithProfileAndAccessTokenButton_Click(object sender, RoutedEventArgs e)
{
RequestToken("openid profile offline_access WebApi1", "code id_token token");
}
private void RequestToken(string scope, string responseType)
{
var request = new AuthorizeRequest(Constants.AuthorizeEndpoint);
var startUrl = request.CreateAuthorizeUrl(
clientId: "hybridclient",
responseType: responseType,
scope: scope,
redirectUri: "oob://localhost/wpfclient",
state: "random_state",
nonce: "random_nonce");
_login.Show();
_login.Start(new Uri(startUrl), new Uri("oob://localhost/wpfclient"));
}
private async void UseCodeButton_Click(object sender, RoutedEventArgs e)
{
if (_response != null && _response.Values.ContainsKey("code"))
{
var client = new TokenClient(
Constants.TokenEndpoint,
"hybridclient",
"secret");
var response = await client.RequestAuthorizationCodeAsync(
_response.Code,
"oob://localhost/wpfclient");
Textbox1.Text = response.Json.ToString();
}
}
private async void CallUserInfo_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient
{
BaseAddress = new Uri(Constants.UserInfoEndpoint)
};
if (_response != null && _response.Values.ContainsKey("access_token"))
{
client.SetBearerToken(_response.AccessToken);
}
var response = await client.GetAsync("");
if (response.StatusCode == HttpStatusCode.OK)
{
var json = await response.Content.ReadAsStringAsync();
Textbox1.Text = JObject.Parse(json).ToString();
}
else
{
MessageBox.Show(response.StatusCode.ToString());
}
}
private void ShowIdTokenButton_Click(object sender, RoutedEventArgs e)
{
if (_response.Values.ContainsKey("id_token"))
{
var viewer = new IdentityTokenViewer();
viewer.IdToken = _response.Values["id_token"];
viewer.Show();
}
}
private void ShowAccessTokenButton_Click(object sender, RoutedEventArgs e)
{
if (_response.Values.ContainsKey("access_token"))
{
var viewer = new IdentityTokenViewer();
viewer.IdToken = _response.Values["access_token"];
viewer.Show();
}
}
private async void CallServiceButton_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient
{
BaseAddress = new Uri("http://localhost:44334/")
};
if (_response != null && _response.Values.ContainsKey("access_token"))
{
client.SetBearerToken(_response.AccessToken);
}
var response = await client.GetAsync("test");
if (response.StatusCode == HttpStatusCode.OK)
{
var json = await response.Content.ReadAsStringAsync();
Textbox1.Text = json;
}
else
{
MessageBox.Show(response.StatusCode.ToString());
}
}
private async void ValidateIdTokenButton_Click(object sender, RoutedEventArgs e)
{
if (_response != null && _response.Values.ContainsKey("id_token"))
{
var client = new HttpClient();
var response = await client.GetAsync(Constants.IdentityTokenValidationEndpoint + "?token=" + _response.Values["id_token"] + "&client_id=hybridclient");
if (response.StatusCode == HttpStatusCode.OK)
{
var json = await response.Content.ReadAsStringAsync();
Textbox1.Text = JObject.Parse(json).ToString();
}
else
{
MessageBox.Show(response.StatusCode.ToString());
}
}
}
}
} |
using SharpReact.Core.MockUI.Routing.Test.Navigation;
using SharpReact.Core.MockUI.Test.Props;
using SharpReact.Core.Properties;
namespace SharpReact.Core.MockUI.Routing.Test.Components
{
public class Header : SharpComponent<Props.Header, object>
{
public override ISharpProp Render()
{
return new StackPanel
{
Children =
{
new TextBlock { Text = Props.PageTitle },
new Button {
Content = new TextBlock { Text = "First page"},
Click = (s, e) => ReactServices.Navigation.NavigateTo(new FirstPageNavigationArgs())
},
new Button {
Content = new TextBlock { Text = "Second page"},
Click = (s, e) => ReactServices.Navigation.NavigateTo(new SecondPageNavigationArgs())
}
},
};
}
}
}
|
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture.NUnit3;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerDemand.Application.CourseDemand.Queries.GetAggregatedCourseDemandList;
using SFA.DAS.EmployerDemand.Domain.Interfaces;
using SFA.DAS.EmployerDemand.Domain.Models;
using SFA.DAS.Testing.AutoFixture;
namespace SFA.DAS.EmployerDemand.Application.UnitTests.CourseDemand.Queries
{
public class WhenHandlingGetAggregatedCourseDemandListQuery
{
[Test, MoqAutoData]
public async Task Then_Returns_List_From_Service(
int totalResultCount,
GetAggregatedCourseDemandListQuery query,
List<AggregatedCourseDemandSummary> listFromService,
[Frozen] Mock<ICourseDemandService> mockDemandService,
GetAggregatedCourseDemandListQueryHandler handler)
{
mockDemandService
.Setup(service => service.GetAggregatedCourseDemandList(
query.Ukprn, query.CourseId, query.Lat, query.Lon, query.Radius))
.ReturnsAsync(listFromService);
mockDemandService
.Setup(service => service.GetAggregatedDemandTotal(query.Ukprn)).ReturnsAsync(totalResultCount);
var result = await handler.Handle(query, CancellationToken.None);
result.AggregatedCourseDemandList.Should().BeEquivalentTo(listFromService);
result.Total.Should().Be(totalResultCount);
}
}
} |
using UnityEngine;
using System.Collections;
using System.IO.Ports; // for RS-232C
using NS_MyRs232cUtil;
public class rs232cSendCS : MonoBehaviour {
void Test_rs232c() {
SerialPort sp;
bool res = MyRs232cUtil.Open ("COM3", out sp);
if (res == false) {
return; // fail
}
string msg = "hello";
sp.Write (msg);
MyRs232cUtil.Close (ref sp);
}
void Start () {
Test_rs232c ();
}
void Update () {
}
}
|
namespace Disqus.NET.Requests
{
public enum DisqusExportFormat
{
Xml
}
}
|
using UnityEngine;
using System.Collections;
public class CollectableBehaviour : Timeoutable
{
[SerializeField]
private float _rotationSpeed = 0.5f;
[SerializeField]
ReceivedCollectable _receivableType = ReceivedCollectable.Random;
[SerializeField]
private Transform _model;
private Collectable _collectable;
//naming just sucks..
public enum ReceivedCollectable
{
Random,
Bonus
}
public ReceivedCollectable ReceivableType
{
set
{
_receivableType = value;
}
}
private void Update ()
{
_model.Rotate (Vector3.up, _rotationSpeed);
}
private void Start ()
{
//TODO change sprite based on the type?
if (_receivableType == ReceivedCollectable.Random)
{
_collectable = Collectable.newRandomCollectable();
}
else
{
_collectable = Collectable.newBonusCollectable();
}
}
public override float GetTimeout ()
{
return GameConstants.COLLECTABLE_TIMEOUT;
}
private void OnTriggerEnter (Collider other)
{
if (other.CompareTag ("spaceship"))
{
//This code could also be in PlayerController.. refactor if needed
SpaceShipController spaceShip = other.GetComponent<SpaceShipController> ();
PlayerController playerController = spaceShip.Player;
playerController.AddCollectable (_collectable);
Destroy (this.gameObject);
PlaySoundFX ();
}
else if (other.CompareTag ("planet"))
{
//destroy just so that it doesn't stay within the planet looking stupid.
//spawning these should however check that this doesn't happen, but leave this just in case
Destroy (this.gameObject);
}
}
private void PlaySoundFX ()
{
switch (_collectable.Type)
{
case Collectable.CollectableType.SpeedUp: AudioManager.Instance.playClip(AudioManager.AppAudioClip.AcquireSpeedup);
break;
case Collectable.CollectableType.Weapon: AudioManager.Instance.playClip(AudioManager.AppAudioClip.AcquireWeapon);
break;
case Collectable.CollectableType.Enlarge: AudioManager.Instance.playClip (AudioManager.AppAudioClip.AcquireEnlarge);
break;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyCustomAction.Model;
namespace MyCustomAction.Service
{
/// <summary>
/// 客户行为服务.
/// </summary>
public interface ICustomActionService
{
/// <summary>
/// 新的行为
/// </summary>
/// <param name="customID">客户代码</param>
/// <param name="moduleCode">模块代码</param>
/// <param name="expData">附加数据</param>
/// <returns></returns>
long NewAction(long customID, string moduleCode, string expData);
/// <summary>
/// 后续的行为.
/// </summary>
/// <param name="actionID">行为ID.</param>
/// <param name="customID">客户代码(数据检查时使用)</param>
/// <param name="moduleCode">模块代码(数据检查时使用)</param>
bool ContinueAction(long actionID, long customID, string moduleCode);
/// <summary>
/// 查询指定客户, 在指定的时间, 都做了哪些操作.
/// </summary>
/// <param name="customID"></param>
/// <param name="fromTime"></param>
/// <param name="toTime"></param>
/// <returns></returns>
List<CustomAction> QueryCustomAction(long? customID, DateTime? fromTime, DateTime? toTime);
}
}
|
using PipServices3.Commons.Data;
using System;
using System.Runtime.Serialization;
namespace PipServices.Blobs.Client.Version1
{
[DataContract]
public class BlobInfoV1 : IStringIdentifiable
{
/* Identification */
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "group")]
public string Group { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
/* Content */
[DataMember(Name = "size")]
public long Size { get; set; }
[DataMember(Name = "content_type")]
public string ContentType { get; set; }
[DataMember(Name = "create_time")]
public DateTime CreateTime { get; set; }
[DataMember(Name = "expire_time")]
public DateTime? ExpireTime { get; set; }
[DataMember(Name = "completed")]
public bool Completed { get; set; }
}
}
|
using Data.Models;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.QueryHelper;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SharedLibraryCore.Interfaces
{
public interface IMetaService
{
/// <summary>
/// adds or updates meta key and value to the database
/// </summary>
/// <param name="metaKey">key of meta data</param>
/// <param name="metaValue">value of the meta data</param>
/// <param name="client">client to save the meta for</param>
/// <returns></returns>
Task AddPersistentMeta(string metaKey, string metaValue, EFClient client, EFMeta linkedMeta = null);
/// <summary>
/// adds or updates meta key and value to the database
/// </summary>
/// <param name="metaKey">key of meta data</param>
/// <param name="metaValue">value of the meta data</param>
/// <returns></returns>
Task AddPersistentMeta(string metaKey, string metaValue);
/// <summary>
/// removes meta key with given value
/// </summary>
/// <param name="metaKey">key of meta data</param>
/// <param name="client">client to delete the meta for</param>
/// <returns></returns>
Task RemovePersistentMeta(string metaKey, EFClient client);
/// <summary>
/// removes meta key with given value
/// </summary>
/// <param name="metaKey">key of the meta data</param>
/// <param name="metaValue">value of the meta data</param>
/// <returns></returns>
Task RemovePersistentMeta(string metaKey, string metaValue = null);
/// <summary>
/// retrieves meta data for given client and key
/// </summary>
/// <param name="metaKey">key to retrieve value for</param>
/// <param name="client">client to retrieve meta for</param>
/// <returns></returns>
Task<EFMeta> GetPersistentMeta(string metaKey, EFClient client);
/// <summary>
/// retrieves collection of meta for given key
/// </summary>
/// <param name="metaKey">key to retrieve values for</param>
/// <returns></returns>
Task<IEnumerable<EFMeta>> GetPersistentMeta(string metaKey);
/// <summary>
/// adds a meta task to the runtime meta list
/// </summary>
/// <param name="metaKey">type of meta</param>
/// <param name="metaAction">action to perform</param>
void AddRuntimeMeta<T,V>(MetaType metaKey, Func<T, Task<IEnumerable<V>>> metaAction) where V : IClientMeta where T: PaginationRequest;
/// <summary>
/// retrieves all the runtime meta information for given client idea
/// </summary>
/// <param name="request">request information</param>
/// <returns></returns>
Task<IEnumerable<IClientMeta>> GetRuntimeMeta(ClientPaginationRequest request);
/// <summary>
/// retreives all the runtime of provided type
/// </summary>
/// <param name="request">>request information</param>
/// <param name="metaType">type of meta to retreive</param>
/// <returns></returns>
Task<IEnumerable<T>> GetRuntimeMeta<T>(ClientPaginationRequest request, MetaType metaType) where T : IClientMeta;
}
}
|
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace ShowSelection
{
[Export(typeof(IWpfTextViewCreationListener))]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal sealed class AdornmentFactory : IWpfTextViewCreationListener
{
[Export(typeof(AdornmentLayerDefinition))]
[Name("SelectionAdornment")]
[Order(After = PredefinedAdornmentLayers.Caret)]
[TextViewRole(PredefinedTextViewRoles.Document)]
public AdornmentLayerDefinition EditorAdornmentLayer = null;
public void TextViewCreated(IWpfTextView textView)
{
textView.Properties.GetOrCreateSingletonProperty(() => new SelectionAdornment(textView));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WallpaperTool.Server.Models;
using WallpaperTool.Wallpapers;
namespace WallpaperTool.ViewModels
{
public static class WallpaperManger
{
static ExeWallpaper exeWallPaper = new ExeWallpaper();
static VideoWallpaper videoWallpaper = new VideoWallpaper();
static HTMLWallpaper htmlWallpaper = new HTMLWallpaper();
public static IWallpaper LastWallpaper { get; private set; }
public static async Task ApplyWallpaper(WallpaperType type, WallpapaerParameter info)
{
if (LastWallpaper != null)
LastWallpaper.Clean();
LastWallpaper = GetWallper(type);
await LastWallpaper.Show(info);
}
private static IWallpaper GetWallper(WallpaperType type)
{
switch (type)
{
case WallpaperType.Exe:
return exeWallPaper;
case WallpaperType.HTML:
return htmlWallpaper;
case WallpaperType.Video:
return videoWallpaper;
}
return null;
}
internal static void Clean()
{
if (LastWallpaper != null)
LastWallpaper.Clean();
}
}
}
|
using System;
using System.Collections.Generic;
using R5T.T0113;
using Instances = R5T.T0113.X001.Instances;
namespace System
{
public static class ISolutionOperatorExtensions
{
public static IEnumerable<string> DetermineMissingProjectReferences(this ISolutionOperator _,
IEnumerable<string> existingProjectReferences,
IEnumerable<string> requiredProjectReferences)
{
var output = Instances.ProjectOperator.DetermineMissingProjectReferences(
existingProjectReferences,
requiredProjectReferences);
return output;
}
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Threading;
using SciChart.Examples.Demo.Common;
using SciChart.Examples.Demo.ViewModels;
namespace SciChart.Examples.Demo.Behaviors
{
public class TilesHarmonistBehavior : Behavior<WrapPanelCompatible>
{
private DispatcherTimer _timer;
private int _counter;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += OnLoaded;
AssociatedObject.Unloaded += OnUnloaded;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= OnLoaded;
AssociatedObject.Unloaded -= OnUnloaded;
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
_timer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(2),
};
_timer.Tick += (_, __) =>
{
_counter++;
foreach (ContentPresenter child in AssociatedObject.Children)
{
var tile = (TileViewModel)child.Content;
if (_counter % tile.TransitionSeed == 0)
{
tile.ChangeState();
}
}
};
_timer.Start();
}
private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs)
{
if (_timer != null)
{
_timer.Stop();
_timer = null;
}
}
}
} |
using AutoMapper;
using FintecDemo.API.Entities;
using FintecDemo.API.Models.Stock;
namespace FintecDemo.API.Configuration.Mappings
{
public class StockProfile : Profile
{
public StockProfile()
{
CreateMap<Stock, StockDetailsModel>();
CreateMap<Stock, StockListModel>();
}
}
} |
using System;
public class ValueType1
{
static int Main ()
{
Blah a = new Blah ("abc", 1);
Blah b = new Blah ("ab" + 'c', 1);
long start, end;
start = Environment.TickCount;
start = Environment.TickCount;
for (int i = 0; i < 1000000; i++)
a.GetHashCode ();
end = Environment.TickCount;
Console.WriteLine ("struct common GetHashCode(): {0}", end-start);
start = Environment.TickCount;
for (int i = 0; i < 1000000; i++)
a.Equals (b);
end = Environment.TickCount;
Console.WriteLine ("struct common Equals(): {0}", end-start);
Blah2 a2 = new Blah2 ("abc", 1);
Blah2 b2 = new Blah2 ("abc", 1);
start = Environment.TickCount;
for (int i = 0; i < 1000000; i++)
a2.GetHashCode ();
end = Environment.TickCount;
Console.WriteLine ("struct specific GetHashCode(): {0}", end-start);
start = Environment.TickCount;
for (int i = 0; i < 1000000; i++)
a2.Equals (b2);
end = Environment.TickCount;
Console.WriteLine ("struct specific Equals(): {0}", end-start);
return 0;
}
struct Blah
{
public string s;
public int i;
public Blah (string s, int k)
{
this.s = s;
i = k;
}
}
struct Blah2
{
public string s;
public int i;
public Blah2 (string s, int k)
{
this.s = s;
i = k;
}
public override int GetHashCode () {
return i ^ s.GetHashCode ();
}
public override bool Equals (object obj) {
if (obj == null || !(obj is Blah2))
return false;
Blah2 b = (Blah2)obj;
return b.s == this.s && b.i == this.i;
}
}
}
|
namespace Zergatul.Network.Http.Frames
{
public enum ErrorCode : uint
{
NO_ERROR = 0x00,
PROTOCOL_ERROR = 0x01,
INTERNAL_ERROR = 0x02,
FLOW_CONTROL_ERROR = 0x03,
SETTINGS_TIMEOUT = 0x04,
STREAM_CLOSED = 0x05,
FRAME_SIZE_ERROR = 0x06,
REFUSED_STREAM = 0x07,
CANCEL = 0x08,
COMPRESSION_ERROR = 0x09,
CONNECT_ERROR = 0x0A,
ENHANCE_YOUR_CALM = 0x0B,
INADEQUATE_SECURITY = 0x0C,
HTTP_1_1_REQUIRED = 0x0D
}
} |
using StudentForum.BL.Abstractions;
using StudentForum.BL.Helpers.Settings;
using StudentForum.BL.Models.Authorization;
using StudentForum.DAL.Abstractions;
using StudentForum.Data.Models;
using System;
using System.Threading.Tasks;
namespace StudentForum.BL.Services
{
public class UserService : BaseService, IUserService
{
public UserService(IUnitOfWork unitOfWork) : base(unitOfWork)
{ }
public async Task<User> Authenticate(AuthInfo authorizeInfo)
{
var user = await UnitOfWork.GetUser.GetByEmail(authorizeInfo.Email);
if (user == null)
{
throw new ArgumentNullException();
}
if (!BCrypt.Net.BCrypt.Verify(authorizeInfo.Password, user.Password))
{
throw new ArgumentNullException("Invalid Credentials");
}
return user;
}
public async Task<User> Create(RegisterInfo registerInfo)
{
if (registerInfo == null)
{
throw new ArgumentNullException();
}
var user = new User
{
FirstName = registerInfo.FirstName,
LastName = registerInfo.LastName,
Email = registerInfo.Email,
Password = BCrypt.Net.BCrypt.HashPassword(registerInfo.Password),
Role = Role.User
};
UnitOfWork.GetUser.Insert(user);
await UnitOfWork.SaveAsync();
return user;
}
public async Task<User> GetById(int id)
{
if (id < 1)
{
throw new ArgumentOutOfRangeException();
}
return await UnitOfWork.GetUser.GetById(id);
}
}
}
|
namespace UIC.Framework.Interfaces.Project
{
public interface DatapointTaskMetadata
{
double ExpectedMaximum { get; }
double ExpectedMinimum { get; }
double WarningThreshold { get; }
double ErrorThreshold { get; }
bool IslnverseThresholdEvaluation { get; }
string Tags { get; }
}
} |
using System;
using NUnit.Framework;
using Roadkill.Core.Configuration;
using Roadkill.Core.Converters;
using Roadkill.Core.Database;
using Roadkill.Tests.Unit.StubsAndMocks;
namespace Roadkill.Tests.Unit.Text
{
[TestFixture]
[Category("Unit")]
public class MarkdownParserTests
{
private PluginFactoryMock _pluginFactory;
[SetUp]
public void Setup()
{
_pluginFactory = new PluginFactoryMock();
}
[Test]
public void internal_links_should_resolve_with_id()
{
// Bug #87
// Arrange
Page page = new Page() { Id = 1, Title = "My first page" };
var settingsRepository = new SettingsRepositoryMock();
settingsRepository.SiteSettings = new SiteSettings() { MarkupType = "Markdown" };
PageRepositoryMock pageRepositoryStub = new PageRepositoryMock();
pageRepositoryStub.AddNewPage(page, "My first page", "admin", DateTime.UtcNow);
ApplicationSettings settings = new ApplicationSettings();
settings.Installed = true;
UrlResolverMock resolver = new UrlResolverMock();
resolver.InternalUrl = "blah";
MarkupConverter converter = new MarkupConverter(settings, settingsRepository, pageRepositoryStub, _pluginFactory);
converter.UrlResolver = resolver;
string markdownText = "[Link](My-first-page)";
string invalidMarkdownText = "[Link](My first page)";
// Act
string expectedHtml = "<p><a href=\"blah\">Link</a></p>\n";
string expectedInvalidLinkHtml = "<p>[Link](My first page)</p>\n";
string actualHtml = converter.ToHtml(markdownText);
string actualHtmlInvalidLink = converter.ToHtml(invalidMarkdownText);
// Assert
Assert.That(actualHtml, Is.EqualTo(expectedHtml));
Assert.That(actualHtmlInvalidLink, Is.EqualTo(expectedInvalidLinkHtml));
}
[Test]
public void code_blocks_should_allow_quotes()
{
// Issue #82
// Arrange
Page page = new Page() { Id = 1, Title = "My first page" };
PageRepositoryMock pageRepositoryStub = new PageRepositoryMock();
pageRepositoryStub.AddNewPage(page, "My first page", "admin", DateTime.UtcNow);
var settingsRepository = new SettingsRepositoryMock();
settingsRepository.SiteSettings = new SiteSettings() { MarkupType = "Markdown" };
ApplicationSettings settings = new ApplicationSettings();
settings.Installed = true;
MarkupConverter converter = new MarkupConverter(settings, settingsRepository, pageRepositoryStub, _pluginFactory);
string markdownText = "Here is some `// code with a 'quote' in it and another \"quote\"`\n\n" +
" var x = \"some tabbed code\";\n\n"; // 2 line breaks followed by 4 spaces (tab stop) at the start indicates a code block
string expectedHtml = "<p>Here is some <code>// code with a 'quote' in it and another \"quote\"</code></p>\n\n" +
"<pre><code>var x = \"some tabbed code\";\n" +
"</code></pre>\n";
// Act
string actualHtml = converter.ToHtml(markdownText);
// Assert
Assert.That(actualHtml, Is.EqualTo(expectedHtml));
}
[Test]
public void images_should_support_dimensions()
{
// Arrange
Page page = new Page() { Id = 1, Title = "My first page" };
PageRepositoryMock pageRepositoryStub = new PageRepositoryMock();
pageRepositoryStub.AddNewPage(page, "My first page", "admin", DateTime.UtcNow);
var settingsRepository = new SettingsRepositoryMock();
settingsRepository.SiteSettings = new SiteSettings() { MarkupType = "Markdown" };
ApplicationSettings settings = new ApplicationSettings();
settings.Installed = true;
MarkupConverter converter = new MarkupConverter(settings, settingsRepository, pageRepositoryStub, _pluginFactory);
string markdownText = "Here is an image: \n\n" +
"And another with equal dimensions  \n\n" +
"And this one is a rectangle ";
string expectedHtml = "<p>Here is an image:<img src=\"/Attachments/Image1.png\" class=\"img-responsive\" border=\"0\" alt=\"Image\" width=\"\" height=\"\" /> </p>\n\n" +
"<p>And another with equal dimensions <img src=\"/Attachments/Image1.png\" class=\"img-responsive\" border=\"0\" alt=\"Square\" width=\"250px\" height=\"\" /> </p>\n\n" +
"<p>And this one is a rectangle <img src=\"/Attachments/Image1.png\" class=\"img-responsive\" border=\"0\" alt=\"Rectangle\" width=\"250px\" height=\"350px\" /></p>\n";
// Act
string actualHtml = converter.ToHtml(markdownText);
// Assert
Assert.That(actualHtml, Is.EqualTo(expectedHtml));
}
[Test]
public void images_should_support_dimensions_and_titles()
{
// Arrange
Page page = new Page() { Id = 1, Title = "My first page" };
PageRepositoryMock pageRepositoryStub = new PageRepositoryMock();
pageRepositoryStub.AddNewPage(page, "My first page", "admin", DateTime.UtcNow);
var settingsRepository = new SettingsRepositoryMock();
settingsRepository.SiteSettings = new SiteSettings() { MarkupType = "Markdown" };
ApplicationSettings settings = new ApplicationSettings();
settings.Installed = true;
MarkupConverter converter = new MarkupConverter(settings, settingsRepository, pageRepositoryStub, _pluginFactory);
string markdownText = "Here is an image with a title: \n\n" +
"And another with equal dimensions  \n\n" +
"And this one is a rectangle ";
string expectedHtml = "<p>Here is an image with a title:<img src=\"/Attachments/Image1.png\" class=\"img-responsive\" border=\"0\" alt=\"Image\" width=\"\" height=\"\" title=\"Image\" /> </p>\n\n" +
"<p>And another with equal dimensions <img src=\"/Attachments/Image1.png\" class=\"img-responsive\" border=\"0\" alt=\"Square\" width=\"250px\" height=\"\" title=\"Square\" /> </p>\n\n" +
"<p>And this one is a rectangle <img src=\"/Attachments/Image1.png\" class=\"img-responsive\" border=\"0\" alt=\"Rectangle\" width=\"250px\" height=\"350px\" title=\"Rectangle\" /></p>\n";
// Act
string actualHtml = converter.ToHtml(markdownText);
// Assert
Assert.That(actualHtml, Is.EqualTo(expectedHtml));
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Iviz.Msgs
{
public struct RentEnumerator<T> : IEnumerator<T>
{
readonly T[] a;
readonly int length;
int currentIndex;
public RentEnumerator(T[] a, int length)
{
this.a = a;
this.length = length;
currentIndex = -1;
}
public bool MoveNext()
{
if (currentIndex == length - 1)
{
return false;
}
currentIndex++;
return true;
}
public void Reset() => throw new NotImplementedException();
object? IEnumerator.Current => Current;
public T Current => a[currentIndex];
public void Dispose()
{
}
}
} |
using Homework4.Enums;
using Homework4.Interfaces;
using System;
namespace Homework4.Models
{
class Animal{
private readonly Guid _id = Guid.NewGuid();
public string Name { get; set; }
public Taxonomic TaxonomikClass { get; set; }
public string Variety { get; set; }
public Animal()
{
Variety = "nonvariety";
Name = "noname";
TaxonomikClass = Taxonomic.None;
_id.ToString();
}
public Animal(string variety)
{
Variety = variety;
}
public Animal(string variety, string name)
{
Name = name;
Variety = variety;
}
public Animal(string variety, string name, Taxonomic taxonomikClass)
{
Name = name;
TaxonomikClass = taxonomikClass;
Variety=variety;
}
public Guid Getid() {
return _id;
}
};
}
|
//#define DISABLE_CACHE
using OpenTK.Graphics.OpenGL;
namespace example.Renderer
{
public class StencilStateComponent
{
public StencilOp StencilFailOp = StencilOp.Keep;
public StencilOp ZFailOp = StencilOp.Keep;
public StencilOp ZPassOp = StencilOp.Keep;
public StencilFunction Function = StencilFunction.Always;
public int Reference = 0;
public int TestMask = 0xffff;
public int WriteMask = 0xffff;
public void Apply(StencilFace face, StencilStateComponent cache)
{
#if !DISABLE_CACHE
if(
(cache.StencilFailOp != StencilFailOp) ||
(cache.ZFailOp != ZFailOp) ||
(cache.ZPassOp != ZPassOp)
)
#endif
{
GL.StencilOpSeparate(face, StencilFailOp, ZFailOp, ZPassOp);
cache.StencilFailOp = StencilFailOp;
cache.ZFailOp = ZFailOp;
cache.ZPassOp = ZPassOp;
}
#if !DISABLE_CACHE
if(cache.WriteMask != WriteMask)
#endif
{
GL.StencilMaskSeparate(face, WriteMask);
cache.WriteMask = WriteMask;
}
#if !DISABLE_CACHE
if(
(cache.Function != Function) ||
(cache.Reference != Reference) ||
(cache.TestMask != TestMask)
)
#endif
{
GL.StencilFuncSeparate((Version20)face, Function, Reference, TestMask);
cache.Function = Function;
cache.Reference = Reference;
cache.TestMask = TestMask;
}
}
public void ApplyShared(StencilState cache)
{
#if !DISABLE_CACHE
if(
(cache.Front.StencilFailOp != StencilFailOp) ||
(cache.Front.ZFailOp != ZFailOp) ||
(cache.Front.ZPassOp != ZPassOp) ||
(cache.Back.StencilFailOp != StencilFailOp) ||
(cache.Back.ZFailOp != ZFailOp) ||
(cache.Back.ZPassOp != ZPassOp)
)
#endif
{
GL.StencilOp(StencilFailOp, ZFailOp, ZPassOp);
cache.Front.StencilFailOp = cache.Back.StencilFailOp = StencilFailOp;
cache.Front.ZFailOp = cache.Back.ZFailOp = ZFailOp;
cache.Front.ZPassOp = cache.Back.ZPassOp = ZPassOp;
}
#if !DISABLE_CACHE
if(
(cache.Front.WriteMask != WriteMask) ||
(cache.Back.WriteMask != WriteMask)
)
#endif
{
GL.StencilMask(WriteMask);
cache.Front.WriteMask = cache.Back.WriteMask = WriteMask;
}
#if !DISABLE_CACHE
if(
(cache.Front.Function != Function) ||
(cache.Front.Reference != Reference) ||
(cache.Front.TestMask != TestMask) ||
(cache.Back.Function != Function) ||
(cache.Back.Reference != Reference) ||
(cache.Back.TestMask != TestMask)
)
#endif
{
GL.StencilFunc(Function, Reference, TestMask);
cache.Front.Function = cache.Back.Function = Function;
cache.Front.Reference = cache.Back.Reference = Reference;
cache.Front.TestMask = cache.Back.TestMask = TestMask;
}
}
}
public class StencilState : RenderState
{
public bool Enabled = false;
public bool Separate = false;
public StencilStateComponent Front = new StencilStateComponent();
public StencilStateComponent Back = new StencilStateComponent();
private static StencilState last = null;
private static StencilState @default = new StencilState();
private static readonly StencilState stateCache = new StencilState();
public static StencilState Default { get { return @default; } }
public static void ResetState()
{
GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Keep);
stateCache.Front.StencilFailOp = stateCache.Back.StencilFailOp = StencilOp.Keep;
stateCache.Front.ZFailOp = stateCache.Back.ZFailOp = StencilOp.Keep;
stateCache.Front.ZPassOp = stateCache.Back.ZPassOp = StencilOp.Keep;
GL.StencilMask(0xffff);
stateCache.Front.WriteMask = stateCache.Back.WriteMask = 0xffff;
GL.StencilFunc(StencilFunction.Always, 0, 0xffff);
stateCache.Front.Function = stateCache.Back.Function = StencilFunction.Always;
stateCache.Front.Reference = stateCache.Back.Reference = 0;
stateCache.Front.TestMask = stateCache.Back.TestMask = 0xffff;
last = null;
}
public override void Reset()
{
Separate = false;
Enabled = false;
Front.StencilFailOp = Back.StencilFailOp = StencilOp.Keep;
Front.ZFailOp = Back.ZFailOp = StencilOp.Keep;
Front.ZPassOp = Back.ZPassOp = StencilOp.Keep;
Front.WriteMask = Back.WriteMask = 0xffff;
Front.Function = Back.Function = StencilFunction.Always;
Front.Reference = Back.Reference = 0;
Front.TestMask = Back.TestMask = 0xffff;
}
public override void Execute()
{
#if !DISABLE_CACHE
if(last == this)
{
return;
}
#endif
if(Enabled)
{
#if !DISABLE_CACHE
if(stateCache.Enabled == false)
#endif
{
GL.Enable(EnableCap.StencilTest);
stateCache.Enabled = true;
}
if(Separate)
{
Front.Apply(StencilFace.Front, stateCache.Front);
Back.Apply(StencilFace.Back, stateCache.Back);
stateCache.Separate = true;
}
else
{
#if !DISABLE_CACHE
if(stateCache.Separate == false)
{
// Cache already in shared state
Front.Apply(StencilFace.FrontAndBack, stateCache.Front);
}
else
#endif
{
// Cache not yet in shared state - make it shared
Front.ApplyShared(stateCache);
stateCache.Separate = false;
}
}
}
else
{
#if !DISABLE_CACHE
if(stateCache.Enabled == true)
#endif
{
GL.Disable(EnableCap.StencilTest);
stateCache.Enabled = false;
}
}
last = this;
}
}
}
|
using System;
using System.Threading.Tasks;
using kiwiho.EFcore.MultiTenant.Core.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace kiwiho.EFcore.MultiTenant.Core
{
public class TenantInfoMiddleware
{
private readonly RequestDelegate _next;
public TenantInfoMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, ITenantInfoGenerator tenantInfoGenerator)
{
tenantInfoGenerator.GenerateTenant(this, context);
// Call the next delegate/middleware in the pipeline
await _next(context);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cardville.Dungeon;
namespace Cardville.Engine
{
public abstract class GameObject
{
public readonly GameObjectType Type = GameObjectType.Empty;
public Guid UUID { get; }
public string Name { get; protected set; }
public readonly Game Game;
private Action Update;
public event Action OnUpdate
{
add { Update += value; }
remove { Update -= value; }
}
public readonly List<GameObject> Chlidren;
public GameObject Parent { get; private set; }
public virtual void UpdateSelf()
{
Update?.Invoke();
}
private GameObject(Game game, string name)
{
UUID = Guid.NewGuid();
Game = game;
Name = name;
Chlidren = new List<GameObject>();
UpdateSelf();
}
public GameObject (Game game, string name, GameObjectType type) : this (game, name)
{
Type = type;
}
}
}
|
// Presentation Karaoke Player
// File: Clock.cs
//
// Copyright 2014, Arlo Belshee. All rights reserved. See LICENSE.txt for usage.
using System;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Player.Model
{
public abstract class Clock
{
[NotNull]
public RecurringEvent Schedule(TimeSpan frequency, [NotNull] Func<Task> action)
{
var whatAndWhen = new RecurringEvent(frequency, action);
_Schedule(whatAndWhen);
return whatAndWhen;
}
[NotNull]
protected abstract void _Schedule([NotNull] RecurringEvent whatAndWhen);
}
} |
<form asp-controller="Home" asp-action="LoginPage">
用户名:<input type="text" name="userName"/>
<br/>
密码:<input type="password" name="pwd"/>
<input type="submit" value="登陆"/>
</form>
@User.Claims.Where(g => g.Type.Equals("FamilyName")).FirstOrDefault().Value; |
using System.Collections.ObjectModel;
using QSF.Examples.ListPickerControl.Models;
using QSF.Services.Toast;
using QSF.ViewModels;
using Xamarin.Forms;
namespace QSF.Examples.ListPickerControl.CustomizationExample
{
public class CustomizationViewModel : ExampleViewModel
{
private const int defaultColorIndex = 0;
private const int defaultSizeIndex = 7;
private ProductViewModel product;
private ColorViewModel color;
private double size;
private double quantity;
private double price;
public CustomizationViewModel()
{
this.Product = new ProductViewModel
{
Name = "Kuako Womens Trainers",
Description = "Comfort running shoes using air cushion design.",
Image = "Picker_Demo1_Header.png",
Price = 230
};
this.Colors = new ObservableCollection<ColorViewModel>
{
new ColorViewModel("Purple", "#AE3C63"),
new ColorViewModel("Black", "#000000"),
new ColorViewModel("Azure Blue", "#316FC8"),
new ColorViewModel("Grey", "#CCCCCC"),
new ColorViewModel("Light Blue", "#6FA2DC"),
new ColorViewModel("Light Green", "#9CCC65"),
new ColorViewModel("Blue", "#42A5F5"),
new ColorViewModel("Yellow", "#FFEE58"),
new ColorViewModel("Red", "#EE534F"),
new ColorViewModel("Orange", "#FFA726"),
new ColorViewModel("Brown", "#8D6E63"),
};
this.Sizes = new ObservableCollection<double>
{
5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10
};
this.AddToCartCommand = new Command(this.ExecuteAddToCartCommand, this.CanExecuteAddToCartCommand);
this.Color = this.Colors[defaultColorIndex];
this.Size = this.Sizes[defaultSizeIndex];
this.Quantity = 1;
}
public ProductViewModel Product
{
get
{
return this.product;
}
set
{
if (this.product != value)
{
this.product = value;
this.OnPropertyChanged();
}
}
}
public ColorViewModel Color
{
get
{
return this.color;
}
set
{
if (this.color != value)
{
this.color = value;
this.OnPropertyChanged();
}
}
}
public double Size
{
get
{
return this.size;
}
set
{
if (this.size != value)
{
this.size = value;
this.OnPropertyChanged();
}
}
}
public double Quantity
{
get
{
return this.quantity;
}
set
{
if (this.quantity != value)
{
this.quantity = value;
this.OnPropertyChanged();
this.OnQuantityChanged();
}
}
}
public double Price
{
get
{
return this.price;
}
set
{
if (this.price != value)
{
this.price = value;
this.OnPropertyChanged();
}
}
}
public ObservableCollection<ColorViewModel> Colors { get; }
public ObservableCollection<double> Sizes { get; }
public Command AddToCartCommand { get; }
private void OnQuantityChanged()
{
this.Price = this.Quantity * this.Product.Price;
this.AddToCartCommand.ChangeCanExecute();
}
private bool CanExecuteAddToCartCommand()
{
return this.Quantity > 0;
}
private void ExecuteAddToCartCommand()
{
this.Color = this.Colors[defaultColorIndex];
this.Size = this.Sizes[defaultSizeIndex];
this.Quantity = 0;
var toastService = DependencyService.Get<IToastMessageService>();
var toastMessage = $"The product '{this.Product.Name}' added to cart.";
toastService.ShortAlert(toastMessage);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CineTeatro.Common.Entities
{
public class Venta : ICloneable
{
public int VentaId { get; set; }
public DateTime FechaDeVenta { get; set; }
public FormaDeVenta FormaDeVenta { get; set; }
public int FormaDeVentaId { get; set; }
public FormaDePago FormaDePago { get; set; }
public int FormaDePagoId { get; set; }
public int Cantidad { get; set; }
public decimal Total { get; set; }
public List<ItemVenta> DetalleDeVenta { get; set; } = new List<ItemVenta>();
public object Clone()
{
return this.MemberwiseClone();
}
}
}
|
using System;
using System.Collections.Generic;
namespace Weikio.ApiFramework.Plugins.Harvest
{
public class HarvestOptions
{
public string HarvestCompany { get; set; } = "";
public string HarvestUser { get; set; } = "";
public string HarvestUserPassword { get; set; } = "";
public decimal WorkDayHours { get; set; }
public DateTime BalancePeriodStartDate { get; set; }
public List<DateTime> Holidays { get; set; }
public List<long> NonBalanceTasks { get; set; }
public List<long> BalanceModeratingTasks { get; set; }
}
}
|
namespace Witter.Data.Models.Enums
{
public enum NotificationType
{
Like = 0,
Follow = 1,
}
}
|
namespace TheDmi.CouchDesignDocuments
{
using System;
using Newtonsoft.Json;
public class IndexSpec
{
private readonly Lazy<string> _indexFunction;
internal IndexSpec(Lazy<string> indexFunction)
{
_indexFunction = indexFunction;
}
[JsonProperty(PropertyName = "index")]
public string Map => _indexFunction.Value;
}
} |
// ---------------------------------------------------------------------------
// <copyright file="MockCloudProvider.cs" company="Microsoft">
// Copyright(c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// </copyright>
// ---------------------------------------------------------------------------
namespace CloudProviders
{
using System;
/// <summary>
/// Mock cloud provider
/// </summary>
public class MockCloudProvider : ICloudProvider
{
/// <summary>
/// flag to tell if the child providers will succeed.
/// </summary>
private bool shouldSuccceed;
/// <summary>
/// Queue provider
/// </summary>
private IQueueProvider queueProvider;
/// <summary>
/// Storage provider
/// </summary>
private IStorageProvider storageProvider;
/// <summary>
/// Auth middleware
/// </summary>
private IAuthMiddleware authMiddleware;
/// <summary>
/// Initializes a new instance of the <see cref="MockCloudProvider"/> class.
/// </summary>
/// <param name="shouldSuccceed">Whether upload should succeed.</param>
public MockCloudProvider(bool shouldSuccceed)
{
this.shouldSuccceed = shouldSuccceed;
this.queueProvider = new MockQueueProvider(this.shouldSuccceed);
this.storageProvider = new MockStorageProvider(this.shouldSuccceed);
this.authMiddleware = new MockAuthMiddleware();
Console.WriteLine("Using MockCloudProvider");
}
/// <summary>
/// Gets the cloud storage provider
/// </summary>
/// <returns>cloud storage provider</returns>
public IQueueProvider QueueProvider()
{
return this.queueProvider;
}
/// <summary>
/// Gets the cloud storage provider
/// </summary>
/// <returns>cloud storage provider</returns>
public IStorageProvider StorageProvider()
{
return this.storageProvider;
}
/// <summary>
/// Gets the cloud auth middleware
/// </summary>
/// <returns>cloud storage provider</returns>
public IAuthMiddleware AuthMiddleware()
{
return this.authMiddleware;
}
}
} |
namespace MessageMedia.Messages.Models
{
public enum MessageStatus
{
enroute,
submitted,
delivered,
expired,
rejected,
undeliverable,
queued,
processed,
cancelled,
scheduled,
failed
}
} |
using System;
// Problem 4. Multiplication Sign
// • Write a program that shows the sign (+, - or 0) of the product of three real numbers, without calculating it.
// ◦ Use a sequence of if operators.
public class MultiplicationSign
{
public static void Main()
{
while (true)
{
Console.WriteLine("Please enter three real numbers.");
Console.Write("A = ");
double numberA = double.Parse(Console.ReadLine());
Console.Write("B = ");
double numberB = double.Parse(Console.ReadLine());
Console.Write("C = ");
double numberC = double.Parse(Console.ReadLine());
if ((numberA == 0) || (numberB == 0) || (numberC == 0))
{
Console.WriteLine("The result of the product of the numbers you have entered is 0.");
}
else if ((numberA < 0) && (numberB < 0) && (numberC < 0))
{
Console.WriteLine("The sign of the product of these three numbers is -");
}
else if ((numberA < 0) && (numberB < 0) && (numberC > 0))
{
Console.WriteLine("The sign of the product of these three numbers is +");
}
else if ((numberA < 0) && (numberB > 0) && (numberC < 0))
{
Console.WriteLine("The sign of the product of these three numbers is +");
}
else if ((numberA < 0) && (numberB > 0) && (numberC > 0))
{
Console.WriteLine("The sign of the product of these three numbers is -");
}
else if ((numberA > 0) && (numberB < 0) && (numberC < 0))
{
Console.WriteLine("The sign of the product of these three numbers is +");
}
else if ((numberA > 0) && (numberB > 0) && (numberC < 0))
{
Console.WriteLine("The sign of the product of these three numbers is +");
}
else if ((numberA > 0) && (numberB < 0) && (numberC > 0))
{
Console.WriteLine("The sign of the product of these three numbers is +");
}
else if ((numberA > 0) && (numberB > 0) && (numberC > 0))
{
Console.WriteLine("The sign of the product of these three numbers is +");
}
}
}
}
|
using System;
using Steamworks;
using UnityEngine;
public class SteamAchievementsController : MonoBehaviour
{
public void InitSteamAchievementStatus()
{
if (!SteamManager.Initialized)
{
Debug.Log("Steam连接失败!");
return;
}
SteamUserStats.GetStat("stat_JiShaGuaiWu", out this.m_JiShaGuaiWu);
SteamUserStats.GetStat("stat_ShiYongJiNeng", out this.m_ShiYongJiNeng);
SteamUserStats.GetStat("stat_CunQian", out this.m_CunQian);
SteamUserStats.GetStat("stat_MaiTuoTuo", out this.m_MaiTuoTuo);
Debug.Log(string.Concat(new string[]
{
"Steam成就初始数据: 击杀:",
this.m_JiShaGuaiWu.ToString(),
" 技能:",
this.m_ShiYongJiNeng.ToString(),
" 存钱:",
this.m_CunQian.ToString(),
" 坨坨:",
this.m_MaiTuoTuo.ToString()
}));
}
public void SetAchievementStatus(AchievementType type, int value)
{
if (!SteamManager.Initialized)
{
Debug.Log("Steam连接失败!");
return;
}
switch (type)
{
case AchievementType.NEW_ACHIEVEMENT_guaiwujiaorouji:
this.m_JiShaGuaiWu += value;
SteamUserStats.SetStat("stat_JiShaGuaiWu", this.m_JiShaGuaiWu);
break;
case AchievementType.NEW_ACHIEVEMENT_jiqiaodashi:
this.m_ShiYongJiNeng += value;
SteamUserStats.SetStat("stat_ShiYongJiNeng", this.m_ShiYongJiNeng);
break;
case AchievementType.NEW_ACHIEVEMENT_licaigaoshou:
this.m_CunQian += value;
SteamUserStats.SetStat("stat_CunQian", this.m_CunQian);
break;
case AchievementType.NEW_ACHIEVEMENT_qinlaofajia:
this.m_MaiTuoTuo += value;
SteamUserStats.SetStat("stat_MaiTuoTuo", this.m_MaiTuoTuo);
break;
}
SteamUserStats.StoreStats();
this.CheckIsCanUnlock(type, value);
}
private void CheckIsCanUnlock(AchievementType type, int currentStatus)
{
if (!SteamManager.Initialized)
{
Debug.Log("Steam连接失败!");
return;
}
switch (type)
{
case AchievementType.NEW_ACHIEVEMENT_guaiwujiaorouji:
if (currentStatus >= 1000)
{
this.UnlockAchievement(type);
return;
}
break;
case AchievementType.NEW_ACHIEVEMENT_jiqiaodashi:
if (currentStatus >= 100)
{
this.UnlockAchievement(type);
return;
}
break;
case AchievementType.NEW_ACHIEVEMENT_jinsechuanshuo:
case AchievementType.NEW_ACHIEVEMENT_zhuangxiudashi:
case AchievementType.NEW_ACHIEVEMENT_zhufu:
break;
case AchievementType.NEW_ACHIEVEMENT_licaigaoshou:
if (currentStatus >= 5000)
{
this.UnlockAchievement(type);
return;
}
break;
case AchievementType.NEW_ACHIEVEMENT_qinlaofajia:
if (currentStatus >= 1000)
{
this.UnlockAchievement(type);
}
break;
default:
return;
}
}
private bool GetAchievement(AchievementType type)
{
bool result;
SteamUserStats.GetAchievement(type.ToString(), out result);
return result;
}
public void UnlockAchievement(AchievementType type)
{
if (!SteamManager.Initialized)
{
Debug.Log("Steam连接失败!");
return;
}
bool flag;
SteamUserStats.GetAchievement(type.ToString(), out flag);
if (!flag)
{
if (!SteamUserStats.SetAchievement(type.ToString()))
{
Debug.LogError("成就解锁失败,未初始化Steam或未收到Steam响应回调!");
return;
}
SteamUserStats.StoreStats();
}
}
[NonSerialized]
public int m_JiShaGuaiWu;
[NonSerialized]
public int m_ShiYongJiNeng;
[NonSerialized]
public int m_CunQian;
[NonSerialized]
public int m_MaiTuoTuo;
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Rivers
{
public class UserDataComparer : IEqualityComparer<IDictionary<object, object>>
{
public bool Equals(IDictionary<object, object> x, IDictionary<object, object> y)
{
if (x.Count != y.Count)
return false;
foreach (var entry in x)
{
if (!y.TryGetValue(entry.Key, out var value))
return false;
if (entry.Value is IEnumerable collection1 && value is IEnumerable collection2)
{
if (!collection1.Cast<object>().SequenceEqual(collection2.Cast<object>()))
return false;
}
else if (!Equals(entry.Value, value))
{
return false;
}
}
return true;
}
public int GetHashCode(IDictionary<object, object> obj)
{
return obj.GetHashCode();
}
}
} |
namespace SFA.DAS.NotificationService.Application.DataEntities
{
public class MessageData
{
public string MessageType { get; set; }
public string MessageId { get; set; }
public MessageContent Content { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Line.Messaging
{
public static class BoxComponentExtensions
{
public static BoxComponent AddContents(this BoxComponent self, IFlexComponent component)
{
self.Contents.Add(component);
return self;
}
}
}
|
using Lidgren.Network;
using P = AkroNetworking.Packets;
using System;
using System.Linq;
using System.Reflection;
namespace AkroNetworking {
public static class MessageReceiverFactory {
public static NoOpMessageReceiver CreateNoOpMessageReceiver() {
return new NoOpMessageReceiver();
}
}
public class NoOpMessageReceiver : IMessageReceiver {
public virtual void DecodePacket(NetIncomingMessage msg) {
}
}
}
|
using DCSoft.Common;
using System;
using System.Runtime.InteropServices;
namespace DCSoft.Writer.Dom
{
/// <summary>
/// 访问文档对象模型时的标记
/// </summary>
[Flags]
[Guid("A41F518E-269C-4E18-B444-CFA723A00998")]
[ComVisible(true)]
[DCPublishAPI]
[DocumentComment]
public enum DomAccessFlags
{
/// <summary>
/// 没有任何标记
/// </summary>
None = 0x0,
/// <summary>
/// 检查控件是否只读
/// </summary>
CheckControlReadonly = 0x1,
/// <summary>
/// 是否检查用户可直接编辑设置
/// </summary>
CheckUserEditable = 0x2,
/// <summary>
/// 检查输入域是否只读
/// </summary>
CheckReadonly = 0x4,
/// <summary>
/// 检查用户权限限制
/// </summary>
CheckPermission = 0x8,
/// <summary>
/// 检查表单视图模式
/// </summary>
CheckFormView = 0x10,
/// <summary>
/// 检查文档锁定状态
/// </summary>
CheckLock = 0x20,
/// <summary>
/// 检查内容保护状态
/// </summary>
CheckContentProtect = 0x40,
/// <summary>
/// 检查容器元素是否只读状态
/// </summary>
CheckContainerReadonly = 0x80,
/// <summary>
/// 所有的标记
/// </summary>
Normal = 0xFF
}
}
|
//Original Scripts by IIColour (IIColour_Spectrum)
using UnityEngine;
using System.Collections;
public class InteractBed : MonoBehaviour
{
public static string[] english;
public static string[] spanish;
public string engDialog;
public string spanDialog;
private bool hasSwitched = false;
private DialogBoxHandler Dialog;
private NPCHandler thisNPC;
private DictionaryHandler dictHandler;
void Awake()
{
Dialog = GameObject.Find("GUI").GetComponent<DialogBoxHandler>();
if (transform.GetComponent<NPCHandler>() != null)
{
thisNPC = transform.GetComponent<NPCHandler>();
}
dictHandler = GameObject.Find("GUI").GetComponent<DictionaryHandler>();
if (transform.GetComponent<DictionaryHandler>() != null)
{
dictHandler = transform.GetComponent<DictionaryHandler>();
}
}
public IEnumerator interact()
{
if (PlayerMovement.player.setCheckBusyWith(this.gameObject))
{
if (thisNPC != null)
{
int direction;
//calculate player's position relative to this npc's and set direction accordingly.
float xDistance = thisNPC.transform.position.x - PlayerMovement.player.transform.position.x;
float zDistance = thisNPC.transform.position.z - PlayerMovement.player.transform.position.z;
if (xDistance >= Mathf.Abs(zDistance))
{
//Mathf.Abs() converts zDistance to a positive always.
direction = 3;
} //this allows for better accuracy when checking orientation.
else if (xDistance <= Mathf.Abs(zDistance) * -1)
{
direction = 1;
}
else if (zDistance >= Mathf.Abs(xDistance))
{
direction = 2;
}
else
{
direction = 0;
}
thisNPC.setDirection(direction);
}
//start of interaction
Dialog.drawDialogBox();
string thisEng = "";
string thisSpan = "";
foreach (string word in dictHandler.getEnglish())
{
if (engDialog.Contains(word))
{
thisEng = word;
}
}
foreach (string word in dictHandler.getSpanish())
{
if (spanDialog.Contains(word))
{
thisSpan = word;
}
}
Dialog.drawDialogBox();
if (dictHandler.getDict().ContainsKey(thisEng))
{
yield return StartCoroutine(Dialog.drawText(spanDialog));
while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
{
yield return null;
}
Dialog.undrawDialogBox();
}
else
{
yield return StartCoroutine(Dialog.drawText(engDialog));
while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
{
yield return null;
}
Dialog.undrawDialogBox();
Dialog.drawDialogBox();
yield return StartCoroutine(Dialog.drawText(spanDialog));
while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
{
yield return null;
}
Dialog.undrawDialogBox();
for (int i = 0; i < dictHandler.getEnglish().Length; i++)
{
if (!dictHandler.getDict().ContainsKey(thisEng))
{
dictHandler.addToDict(thisEng, thisSpan);
}
}
}
print("Dictionary size: ");
print(dictHandler.getDict().Count);
print("Dictionary:");
dictHandler.printDict();
PlayerMovement.player.unsetCheckBusyWith(this.gameObject);
/*if (dictHandler.getDict().ContainsKey(english))
{
yield return StartCoroutine(Dialog.drawText(spanDialog));
while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
{
yield return null;
}
Dialog.undrawDialogBox();
}
else
{
yield return StartCoroutine(Dialog.drawText(engDialog));
while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
{
yield return null;
}
Dialog.undrawDialogBox();
Dialog.drawDialogBox();
yield return StartCoroutine(Dialog.drawText(spanDialog));
while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back"))
{
yield return null;
}
Dialog.undrawDialogBox();
if (!dictHandler.getDict().ContainsKey(english))
{
dictHandler.addToDict(english, spanish);
}
print("Dictionary:");
dictHandler.printDict();
hasSwitched = true;
}
}*/
}
}
} |
namespace RolePlayingGame.Engine.Items
{
public abstract class ArmorPiece : IDistinguishable
{
protected ArmorPiece(string name, int armor)
{
Name = name;
Armor = armor;
}
public int Armor { get; }
public string Name { get; }
}
} |
using Microsoft.EntityFrameworkCore;
using WebApp;
namespace WithContextFactory
{
public class MyController
{
#region Construct
private readonly IDbContextFactory<ApplicationDbContext> _contextFactory;
public MyController(IDbContextFactory<ApplicationDbContext> contextFactory)
{
_contextFactory = contextFactory;
}
#endregion
#region DoSomething
public void DoSomething()
{
using (var context = _contextFactory.CreateDbContext())
{
// ...
}
}
#endregion
}
}
|
// 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.Collections.Generic;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Routing.Matching
{
public readonly struct PolicyNodeEdge
{
public PolicyNodeEdge(object state, IReadOnlyList<Endpoint> endpoints)
{
State = state ?? throw new System.ArgumentNullException(nameof(state));
Endpoints = endpoints ?? throw new System.ArgumentNullException(nameof(endpoints));
}
public IReadOnlyList<Endpoint> Endpoints { get; }
public object State { get; }
}
}
|
using System.Linq;
using SIL.Machine.DataStructures;
using SIL.ObjectModel;
namespace SIL.Machine.Annotations
{
internal class ShapeRangeFactory : RangeFactory<ShapeNode>
{
public ShapeRangeFactory()
: base(true, AnonymousComparer.Create<ShapeNode>(Compare), FreezableEqualityComparer<ShapeNode>.Default)
{
Null = new Range<ShapeNode>(null, null);
}
private static int Compare(ShapeNode x, ShapeNode y)
{
if (x == null)
return y == null ? 0 : -1;
if (y == null)
return 1;
return x.CompareTo(y);
}
public override bool IsEmptyRange(ShapeNode start, ShapeNode end)
{
return start == null || end == null;
}
public override int GetLength(ShapeNode start, ShapeNode end)
{
if (start == null || end == null)
return 0;
return start.GetNodes(end).Count();
}
public override Range<ShapeNode> Create(ShapeNode offset, Direction dir)
{
return Create(offset, offset, dir);
}
}
}
|
using System;
namespace Cysharp.Diagnostics
{
public class ProcessErrorException : Exception
{
public int ExitCode { get; }
public string[] ErrorOutput { get; }
public ProcessErrorException(int exitCode, string[] errorOutput)
: base("Process returns error, ExitCode:" + exitCode + Environment.NewLine + string.Join(Environment.NewLine, errorOutput))
{
this.ExitCode = exitCode;
this.ErrorOutput = errorOutput;
}
}
} |
using FluentNHibernate.Mapping;
using Shoko.Models.Server;
using Shoko.Server.Models;
namespace Shoko.Server.Mappings
{
public class AnimeEpisode_UserMap : ClassMap<SVR_AnimeEpisode_User>
{
public AnimeEpisode_UserMap()
{
Table("AnimeEpisode_User");
Not.LazyLoad();
Id(x => x.AnimeEpisode_UserID);
Map(x => x.AnimeEpisodeID).Not.Nullable();
Map(x => x.AnimeSeriesID).Not.Nullable();
Map(x => x.JMMUserID).Not.Nullable();
Map(x => x.PlayedCount).Not.Nullable();
Map(x => x.StoppedCount).Not.Nullable();
Map(x => x.WatchedCount).Not.Nullable();
Map(x => x.WatchedDate);
Map(x => x.ContractVersion).Not.Nullable();
Map(x => x.ContractBlob).Nullable().CustomType("BinaryBlob");
Map(x => x.ContractSize).Not.Nullable();
}
}
} |
using System;
using System.IO;
using XSLibrary.ThreadSafety.Executors;
namespace XSLibrary.Utility
{
public class FileLogger : Logger
{
string FilePath { get; set; }
SafeExecutor m_lock = new SingleThreadExecutor();
public FileLogger(string filePath)
{
FilePath = filePath;
CheckFile();
}
protected override void LogMessage(string text)
{
string withDate = string.Format("[{0}] {1}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), text);
DebugTools.CatchAll(() => m_lock.Execute(() => File.AppendAllLines(FilePath, new string[1] { withDate })));
}
private void CheckFile()
{
string directory = Path.GetDirectoryName(FilePath);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
if (!File.Exists(FilePath))
File.Create(FilePath).Close();
}
}
}
|
using System;
using Cirrus.Business;
namespace Cirrus.Module.CatchEmAll.StartUp
{
/// <summary>
/// Todo's
/// - Zusätzliche Filter auf Queries
/// - Triggers für zB Email Versand bei gewissem Preis (oder default?)
/// </summary>
public class Program
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Starting service.");
var service = new BusinessServices(args);
service.Start();
Console.WriteLine("The service is ready.");
Console.WriteLine();
Console.ReadLine();
Console.WriteLine("The service is stopped.");
service.Stop();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
}
}
|
using System;
using UnityEngine;
namespace UnityObjectSerializer.Patchers
{
/// <summary>
/// A PatcherFactory of dependent of Unity.
/// </summary>
public class UnityPatcherFactory : IPatcherFactory
{
public bool IsSerializableType(Type type)
{
if (Match<Vector2>(type)) return true;
if (Match<Vector3>(type)) return true;
if (Match<Vector4>(type)) return true;
if (Match<Quaternion>(type)) return true;
if (Match<Vector2Int>(type)) return true;
if (Match<Vector3Int>(type)) return true;
return SerializeHelper.MatchTypeForClass<ScriptableObject>(type);
}
public IPatcher CreatePatcher(Type type, IPatcherRegistry patcherRegistry)
{
if (type.IsArray || type.IsGenericType)
{
return new ListPatcher(type, NodeType.Complex, patcherRegistry);
}
if (typeof(Vector2) == type ||
typeof(Vector3) == type ||
typeof(Vector4) == type ||
typeof(Quaternion) == type)
{
return new ComplexPatcher(type, patcherRegistry);
}
if (typeof(Vector2Int) == type || typeof(Vector3Int) == type)
{
return new VectorIntPatcher(type, typeof(Vector2Int) == type ? 2 : 3);
}
return new ScriptableObjectPatcher(type, patcherRegistry);
}
public void UseContext(PatchContext context)
{
context.Use<UnityPatchContext>(new UnityPatchContext());
}
private static bool Match<T>(Type t)
=> SerializeHelper.MatchType<T>(t);
}
}
|
using Momentary.Common;
using Npgsql;
namespace Momentary.PostgreSql
{
/// <summary>
/// <inheritdoc cref="ISession"/>
/// </summary>
internal class Session : ISession
{
public void Execute(string connectionString, string command)
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (var npgsqlCommand = connection.CreateCommand())
{
npgsqlCommand.CommandText = command;
npgsqlCommand.ExecuteNonQuery();
}
connection.Close();
}
}
public void ExecuteReader(string connectionString, string command, out int rows)
{
rows = 0;
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (var npgsqlCommand = connection.CreateCommand())
{
npgsqlCommand.CommandText = command;
using (var npgsqlReader = npgsqlCommand.ExecuteReader())
{
if (npgsqlReader.HasRows)
{
while (npgsqlReader.Read())
{
rows++;
}
}
}
}
connection.Close();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aphysoft.Share
{
public enum DatabaseExceptionType2
{
None,
LoginFailed,
Timeout
}
public class DatabaseExceptionEventArgs2 : EventArgs
{
#region Fields
public string Sql { get; internal set; }
public string Message { get; internal set; }
public DatabaseExceptionType2 Type { get; internal set; }
public bool NoRetry { get; set; } = false;
#endregion
#region Constructor
public DatabaseExceptionEventArgs2()
{
}
#endregion
}
public delegate void DatabaseExceptionEventHandler2(object sender, DatabaseExceptionEventArgs2 eventArgs);
}
|
namespace BullOak.Repositories.EventStore.Metadata
{
using System;
using System.Collections.Generic;
using System.Linq;
internal class EventMetadata_V2 : IHoldMetadata
{
public string EventTypeFQN { get; set; }
public int MetadataVersion { get; set; }
public Dictionary<string, string> Properties { get; set; }
public EventMetadata_V2(string eventTypeFQN, Dictionary<string, string> properties)
{
EventTypeFQN = eventTypeFQN ?? throw new ArgumentNullException(nameof(EventTypeFQN));
MetadataVersion = 2;
Properties = properties;
}
internal static EventMetadata_V2 From(ItemWithType @event, params (string key, string value)[] properties)
=> new EventMetadata_V2(@event.type.FullName, properties.ToDictionary(x => x.key, x => x.value));
public static EventMetadata_V2 Upconvert(EventMetadata_V1 event_V1)
{
return new EventMetadata_V2(event_V1.EventTypeFQN, new Dictionary<string, string>());
}
}
}
|
using System;
namespace Document_Program_Practice
{
public class ExpertDocumentProgram : ProDocumentProgram
{
public override void Save()
{
Console.WriteLine("Document Saved in pdf format.");
}
public override void DoAllOperations()
{
Open();
Edit();
Save();
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using NUnit.Framework;
using TwitterClone.Application.Common.Exceptions;
using TwitterClone.Application.Conversations.Commands.CreateConversation;
using TwitterClone.Domain.Entities;
using static TwitterClone.Application.IntegrationTests.Testing;
namespace TwitterClone.Application.IntegrationTests.Conversations.Commands
{
public class CreateConversationTests : TestBase
{
[Test]
public void ShouldRequireAtLestOneOtherMember()
{
var command = new CreateConversationCommand();
FluentActions.Invoking(() =>
SendAsync(command)).Should().Throw<ValidationException>();
}
[Test]
public async Task ShouldRequireValidMemberIds()
{
await RunAsDefaultDomainUserAsync();
var command = new CreateConversationCommand
{
Members = new List<int> { 123, 42 }
};
FluentActions.Invoking(() =>
SendAsync(command)).Should().Throw<NotFoundException>();
}
[Test]
public async Task ShouldCreateConversation()
{
var userId = await RunAsDefaultDomainUserAsync();
var member1 = new User { FullName = "Member One", Username = "m_one" };
await AddAsync(member1);
var member2 = new User { FullName = "Member Two", Username = "m_two" };
await AddAsync(member2);
var command = new CreateConversationCommand
{
Members = new List<int> { member1.Id, member2.Id }
};
var createdId = await SendAsync(command);
var created = await FirstOrDefaultAsync<Conversation>(c => c.Id == createdId, include: c => c.Members);
created.Should().NotBeNull();
created.Members.Should().Contain(m => m.Id == member1.Id);
created.Members.Should().Contain(m => m.Id == member2.Id);
created.Members.Should().Contain(m => m.Id == userId);
}
}
} |
// ReSharper disable CheckNamespace
namespace GameLovers.Statechart
{
/// <summary>
/// The state factory is used to setup the <see cref="IStateMachine"/> representation of states and transitions
/// There is always a state factory being created per region in the <see cref="IStateMachine"/>.
/// A state factory is also the data container of the states and transitions of the <see cref="IStateMachine"/>
/// </summary>
public interface IStateFactory
{
/// <inheritdoc cref="IInitialState"/>
IInitialState Initial(string name);
/// <inheritdoc cref="IFinalState"/>
IFinalState Final(string name);
/// <inheritdoc cref="ISimpleState"/>
ISimpleState State(string name);
/// <inheritdoc cref="ITransition"/>
ITransitionState Transition(string name);
/// <inheritdoc cref="INestState"/>
INestState Nest(string name);
/// <inheritdoc cref="IChoiceState"/>
IChoiceState Choice(string name);
/// <inheritdoc cref="IWaitState"/>
IWaitState Wait(string name);
/// <inheritdoc cref="ITaskWaitState"/>
ITaskWaitState TaskWait(string name);
/// <inheritdoc cref="ISplitState"/>
ISplitState Split(string name);
/// <inheritdoc cref="ILeaveState"/>
ILeaveState Leave(string name);
}
} |
namespace ServiceBusDepot.ConsoleHost.Features.Application.Initialisation
{
using System;
using MediatR;
public class QueryHandler: PageRequestHandler<Request>
{
public QueryHandler(IMediator mediator) : base("Initialising....", mediator)
{
}
public override IPageRequest Handle(Request message)
{
System.Console.WriteLine("Checking for service bus connection strings...");
var connections = Mediator
.SendAsync(new Core.Features.ServiceBusConnection.Index.Query())
.ConfigureAwait(false).GetAwaiter().GetResult();
if (connections.Count == 0)
{
System.Console.WriteLine("There are no service bus connections.");
return new Features.ServiceBusConnections.Create.Request();
}
return new Features.Application.Main.Request();
}
}
}
|
using System;
using System.Threading;
namespace UserInterfaceTemplate.Infrastructure.Dialogs
{
public class ProgressHandling
{
public ProgressHandling()
{
ProgressReport = new Progress<double>();
CancellationTokenSource = new CancellationTokenSource();
}
public CancellationTokenSource CancellationTokenSource { get; }
public IProgress<double> ProgressReport { get; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.