content stringlengths 23 1.05M |
|---|
namespace SharpSharp.Benchmarks {
public abstract class PerfBase {
protected int Height { get; } = 588;
protected int Width { get; } = 720;
}
}
|
/*
Copyright 2017 Enkhbold Nyamsuren (http://www.bcogs.net , http://www.bcogs.info/)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SeriousRPG.Model.DrawingNS;
using SeriousRPG.Model.ImageObjectNS;
using SeriousRPG.Model.ActorNS;
using SeriousRPG.Model.GameNS;
using SeriousRPG.Model.RuleNS.ConditionNS;
namespace SeriousRPG.Model.MapNS
{
internal class Map
{
#region Constants
/// <summary>
/// Default height of a map.
/// </summary>
internal const int DEFAULT_ROW_NUM = 50;
/// <summary>
/// Default width of a map.
/// </summary>
internal const int DEFAULT_COL_NUM = 50;
/// <summary>
/// Maximum height of a map.
/// </summary>
internal const int MAX_ROW_NUM = 256;
/// <summary>
/// Maximum width of a map.
/// </summary>
internal const int MAX_COL_NUM = 256;
/// <summary>
/// Minimum height of a map.
/// </summary>
internal const int MIN_ROW_NUM = 1;
/// <summary>
/// Minimum width of a map.
/// </summary>
internal const int MIN_COL_NUM = 1;
#endregion Constants
#region Fields
/// <summary>
/// Map Id unique within a game.
/// </summary>
private int id;
/// <summary>
/// Map name.
/// </summary>
private string name;
/// <summary>
/// Map height in number of square cells
/// </summary>
private int rowNum = Map.DEFAULT_ROW_NUM;
/// <summary>
/// Map width in number of square cells
/// </summary>
private int colNum = Map.DEFAULT_COL_NUM;
private Background bg;
private BackgroundOverlay bgo;
private Foreground fg;
private ForegroundOverlay fgo;
private RouteMap rm;
private LogicLayer ll;
private Game game;
#endregion Fields
#region Properties
/// <summary>
/// ID getter/setter.
/// </summary>
internal int Id {
get { return this.id; }
private set { this.id = value; }
}
/// <summary>
/// Name getter/setter.
/// </summary>
internal string Name {
get { return this.name; }
set {
if (!String.IsNullOrEmpty(value)) {
this.name = value;
}
else {
// [TODO]
}
}
}
internal int RowNum {
get { return this.rowNum; }
private set {
if (!IsValidRowNum(value)) {
// [TODO] invalid value error msg
}
else {
this.rowNum = value;
}
}
}
internal int ColNum {
get { return this.colNum; }
private set {
if (!IsValidColNum(value)) {
// [TODO] invalid value error msg
}
else {
this.colNum = value;
}
}
}
internal int PixelWidth {
get { return this.ColNum * Tile.TILE_WIDTH; }
}
internal int PixelHeight {
get { return this.RowNum * Tile.TILE_HEIGHT; }
}
#endregion Properties
#region Constructors
private Map(int id, string name, int rowNum, int colNum, Game game) {
this.Id = id;
this.Name = name;
this.RowNum = rowNum;
this.ColNum = colNum;
this.game = game; // [TODO] what if game is null
this.bg = new Background(this.RowNum, this.ColNum);
this.bgo = new BackgroundOverlay(this.RowNum, this.ColNum);
this.rm = new RouteMap(this.RowNum, this.ColNum);
this.fg = new Foreground(this.RowNum, this.ColNum);
this.fgo = new ForegroundOverlay(this.RowNum, this.ColNum);
this.ll = new LogicLayer(this.RowNum, this.ColNum);
}
#endregion Constructors
#region Methods
// [TODO] rewrite
internal void Resize(int rowNum, int colNum) {
if (this.bg.CanResize(rowNum, colNum)
&& this.bgo.CanResize(rowNum, colNum)
&& this.fg.CanResize(rowNum, colNum)
&& this.fgo.CanResize(rowNum, colNum)
&& this.rm.CanResize(rowNum, colNum)
&& this.ll.CanResize(rowNum, colNum)
) {
this.RowNum = rowNum;
this.ColNum = colNum;
this.bg.Resize(rowNum, colNum);
this.bgo.Resize(rowNum, colNum);
this.fg.Resize(rowNum, colNum);
this.fgo.Resize(rowNum, colNum);
this.rm.Resize(rowNum, colNum);
this.ll.Resize(rowNum, colNum);
}
}
internal bool SetLayerRenderFlag(int layerType, bool flag) {
if (layerType == this.bg.LayerType) {
this.bg.IsRendered = flag;
return true;
}
else if (layerType == this.bgo.LayerType) {
this.bgo.IsRendered = flag;
return true;
}
else if (layerType == this.fg.LayerType) {
this.fg.IsRendered = flag;
return true;
}
else if (layerType == this.fgo.LayerType) {
this.fgo.IsRendered = flag;
return true;
}
else if (layerType == this.rm.LayerType) {
this.rm.IsRendered = flag;
return true;
}
else if (layerType == this.ll.LayerType) {
this.ll.IsRendered = flag;
return true;
}
// [TODO] error msg
return false;
}
internal bool GetLayerRenderFlag(int layerType) {
if (layerType == this.bg.LayerType) {
return this.bg.IsRendered;
}
else if (layerType == this.bgo.LayerType) {
return this.bgo.IsRendered;
}
else if (layerType == this.fg.LayerType) {
return this.fg.IsRendered;
}
else if (layerType == this.fgo.LayerType) {
return this.fgo.IsRendered;
}
else if (layerType == this.rm.LayerType) {
return this.rm.IsRendered;
}
else if (layerType == this.ll.LayerType) {
return this.ll.IsRendered;
}
// [TODO] error msg
return false;
}
internal void Act() {
this.bg.Act();
this.bgo.Act();
this.ll.Act();
this.fg.Act();
//this.fgo.Act(); // [TODO]
this.rm.Act();
}
internal void DrawMap(ICanvas canvas) {
this.bg.Draw(canvas);
this.bgo.Draw(canvas);
this.ll.Draw(canvas);
this.fg.Draw(canvas);
//this.fgo.Draw(canvas); // [TODO]
this.rm.Draw(canvas);
}
internal void Animate(long currentTime) {
this.fg.Animate(currentTime);
}
internal bool IsNoCollision(ICollidableObject clientObject) {
// [SC] collision detection with a route map
if (!this.rm.IsNoCollision(clientObject)) {
return false;
}
// [SC] collision detection with foreground actors
if (!this.fg.IsNoCollision(clientObject)) {
return false;
}
return true;
}
internal Map Clone(Game cloneGame) {
Map cloneMap = new Map(this.Id, this.Name, this.RowNum, this.ColNum, cloneGame);
// [SC] Cloning Background layer
Tile[,] cloneTiles = this.bg.CloneTiles();
for (int rowIndex = 0; rowIndex < this.RowNum; rowIndex++) {
for (int colIndex = 0; colIndex < this.ColNum; colIndex++) {
if (cloneTiles[rowIndex, colIndex] != null) {
Tile cloneTile = cloneTiles[rowIndex, colIndex];
cloneMap.AddTile(cloneTile.Image.Id, cloneTile.X, cloneTile.Y);
}
}
}
// [SC] Cloning Background Overlay layer
List<ImageObject> cloneBgImages = this.bgo.CloneImageObjects();
foreach(ImageObject cloneImage in cloneBgImages) {
cloneMap.AddBackgroundImage(cloneImage.Image.Id, cloneImage.X, cloneImage.Y);
}
// [TODO] Cloning Foreground is not complete
List<IActor> cloneActors = this.fg.CloneActors();
foreach(IActor cloneActor in cloneActors) {
cloneMap.AddActor(cloneActor.Id, cloneActor.X, cloneActor.Y);
}
// [TODO] cloning of other layers is not done
// [SC] Cloning the Route Map
bool[,] cloneRouteFlags = this.rm.CloneRouteFlags();
for (int rowIndex = 0; rowIndex < this.RowNum; rowIndex++) {
for (int colIndex = 0; colIndex < this.ColNum; colIndex++) {
cloneMap.SetRouteMapCellState(rowIndex, colIndex, cloneRouteFlags[rowIndex, colIndex]);
}
}
// [SC] Cloning the Logic Layer
foreach(IdNamePair rTriggerStub in this.ll.GetRegionTriggerList()) {
RegionTrigger regionTrigger = cloneGame.GetCondition<RegionTrigger>(rTriggerStub.Id);
cloneMap.AddRegionTrigger(regionTrigger, regionTrigger.X, regionTrigger.Y);
}
return cloneMap;
}
internal bool IsWithin(float x, float y) {
return x >= 0 && x < this.PixelWidth && y >= 0 && y < this.PixelHeight;
}
/// <summary>
/// Returns true if the specified rectangle fits within the map
/// </summary>
/// <param name="x"> </param>
/// <param name="y"> BOTTOM coordinate in pixels</param>
/// <param name="width"> </param>
/// <param name="height"> </param>
/// <returns></returns>
internal bool IsWithin(float x, float y, int width, int height) {
float maxX = x + width - 1;
float minY = y - height + 1;
return x >= 0 && minY >= 0 && maxX < this.PixelWidth && y < this.PixelHeight;
}
#endregion Methods
#region Background methods
internal bool AddTile(int genericImageId, float x, float y) {
return bg.AddTile(genericImageId, x, y);
}
#endregion Background methods
#region BackgroundOverlay methods
internal bool AddBackgroundImage(int genericImageId, float x, float y) {
return bgo.AddImageObject(genericImageId, x, y);
}
internal int GetBackgroundImageId(float x, float y) {
return bgo.GetImageObjectId(x, y);
}
internal bool RemoveBackgroundImage(float x, float y) {
return bgo.RemoveImageObject(x, y);
}
#endregion BackgroundOverlay methods
#region Foreground methods
internal bool AddActor(int actorId, float x, float y) {
return fg.AddActor(this.game.GetActor<IActor>(actorId), x, y);
}
#endregion Foreground methods
#region ForegroundOverlay methods
// [TODO]
#endregion ForegroundOverlay methods
#region RouteMap methods
internal bool SetRouteMapCellState(int rowIndex, int colIndex, bool cellState) {
return rm.SetCellState(rowIndex, colIndex, cellState);
}
internal bool ToggleRouteMapPointState(float x, float y) {
return rm.TogglePointState(x, y);
}
#endregion RouteMap methods
#region LogicLayer methods
internal bool AddRegionTrigger(RegionTrigger rTrigger, float x, float y) {
return this.ll.AddRegionTrigger(rTrigger, x, y);
}
#endregion LogicLayer methods
#region Static methods
internal static Map CreateInstance(int id, string name, int rowNum, int colNum, Game game) {
if (game == null) {
// [TODO] error msg
return null;
}
else if (String.IsNullOrEmpty(name)) {
// [TODO] warning msg
return null;
}
else if (!IsValidRowNum(rowNum) || !IsValidColNum(colNum)) {
// [TODO] warning msg
return null;
}
else {
return new Map(id, name, rowNum, colNum, game);
}
}
internal static bool IsValidRowNum(int rowNum) {
return rowNum >= Map.MIN_ROW_NUM && rowNum <= Map.MAX_ROW_NUM;
}
internal static bool IsValidColNum(int colNum) {
return colNum >= Map.MIN_COL_NUM && colNum <= Map.MAX_COL_NUM;
}
#endregion Static methods
}
}
|
using System;
using System.IO;
using System.Linq;
using FluentAssertions;
using PrivateWiki.DataModels.Pages;
using PrivateWiki.Services.AppSettingsService.BackendSettings;
using PrivateWiki.Services.Backends;
using PrivateWiki.Services.Backends.Sqlite;
using Xunit;
using Path = System.IO.Path;
namespace PrivateWiki.Test.Services.StorageBackendService.SQLite
{
public class LabelBackendTest : IDisposable
{
private readonly string _dbPath;
private readonly ILabelBackend _backend;
public LabelBackendTest()
{
IBackendSettingsService settings = new BackendSettingsTestService();
_dbPath = settings.GetSqliteBackendPath();
var conv1 = new DbReaderToLabelConverter();
_backend = new LabelSqliteBackend(settings, conv1, new DbReaderToLabelsConverter(conv1));
}
[Fact]
public async void InsertGetLabelsTest()
{
var label = new Label("testKey1", "Description 1", System.Drawing.Color.Red.ToColor());
await _backend.InsertLabelAsync(label);
var actualLabel = (await _backend.GetAllLabelsAsync()).First();
actualLabel.Should().BeEquivalentTo(label);
}
public void Dispose()
{
var path = Path.GetFullPath(_dbPath);
File.Delete(path);
}
}
} |
using System;
using Jint.Runtime;
namespace Jint.Native
{
/// <summary>
/// The _object value of a <see cref="JsSymbol"/> is the [[Description]] internal slot.
/// </summary>
public sealed class JsSymbol : JsValue, IEquatable<JsSymbol>
{
internal readonly string _value;
public JsSymbol(string value) : base(Types.Symbol)
{
_value = value;
}
public override object ToObject()
{
return _value;
}
public override bool Equals(JsValue obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (!(obj is JsBoolean number))
{
return false;
}
return Equals(number);
}
public bool Equals(JsSymbol other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return _value == other._value;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
}
} |
using System.IO;
using System.Threading.Tasks;
using LeanCode.CodeAnalysis.Analyzers;
using LeanCode.CodeAnalysis.Tests.Verifiers;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace LeanCode.CodeAnalysis.Tests.Analyzers
{
public class SuggestCommandsHaveValidatorsTests : DiagnosticVerifier
{
[Fact]
public async Task Ignores_commands_with_validators_reports_not_validated()
{
var source = await File.ReadAllTextAsync("TestSamples/Command_validation.cs");
var diag = new DiagnosticResult(DiagnosticsIds.CommandsShouldHaveValidators, 17, 17);
await VerifyDiagnostics(source, diag);
}
protected override DiagnosticAnalyzer GetDiagnosticAnalyzer()
{
return new SuggestCommandsHaveValidators();
}
}
}
|
using System;
using Xunit;
using BattleshipGame.Models;
namespace BattleshipGameTest
{
public class PlayerTest
{
[Fact]
public void CreatePlayer()
{
string name = "John";
Player player = new Player(name);
Assert.Equal(player.Name, name);
}
[Theory]
[InlineData("Michael", 5)]
[InlineData("JohnTrovolta", 5)]
public void ValidatePlayerFleet(string name, int shipCount)
{
Player player = new Player(name);
Assert.Equal(player.Name, name);
Assert.Equal(player.Fleet.Count, shipCount);
}
}
}
|
namespace Dependinator.ModelViewing
{
/// <summary>
/// Contains the model viewing of nodes, lines and links.
/// </summary>
public class NamespaceDoc
{
}
}
|
using System;
using System.Xml;
using System.Text;
namespace EnhancedPresence
{
public class RoamingData :
OutContentBase
{
private Categories categories;
protected RoamingData()
{
}
public static RoamingData Create(Categories categories)
{
RoamingData roamingData = new RoamingData();
roamingData.categories = categories;
return roamingData;
}
public override void Generate(XmlWriter writer)
{
writer.WriteStartElement(@"roamingData", @"http://schemas.microsoft.com/2006/09/sip/roaming-self");
this.categories.Generate(writer);
writer.WriteEndElement();
writer.Flush();
}
public override string OutContentType
{
get { return @"application"; }
}
public override string OutContentSubtype
{
get { return @"vnd-microsoft-roaming-self+xml"; }
}
}
}
|
using System;
using Hasty.Client.Api;
namespace Hasty.Client.Debug
{
public class OctetBufferDebug
{
private static readonly uint[] g_lookupTable = CreateLookupTable();
const int lookupTableSize = 256;
private static uint[] CreateLookupTable()
{
var result = new uint[lookupTableSize];
for (int i = 0; i < lookupTableSize; i++)
{
string s = i.ToString("X2");
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
return result;
}
public static string OctetsToHex(byte[] bytes)
{
var octetToHexLookup = g_lookupTable;
var result = new char[bytes.Length * 3];
var pos = 0;
for (int i = 0; i < bytes.Length; i++)
{
var val = octetToHexLookup[bytes[i]];
result[pos++] = (char)val;
result[pos++] = (char)(val >> 16);
result[pos++] = ' ';
}
return new string(result);
}
public static void DebugOctets(byte[] buffer, string description, ILog log)
{
var hex = OctetsToHex(buffer);
log.Debug("{0} {1}", description, hex);
}
}
}
|
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
/*Write a program to count how many numbers between 1 and 100 are
divisible by 3 with no remainder. Display the count on the console.*/
var count = 0;
for (var i = 1; i <= 100; i++)
{
if (i % 3 == 0)
{
count++;
}
}
System.Console.WriteLine($"There are {count} numbers that are divisible by 3 between 1 and 100");
/*Write a program and continuously ask the user to enter a number or "ok"
to exit. Calculate the sum of all the previously entered numbers and
display it on the console.*/
var sum = 0;
while (true)
{
System.Console.WriteLine("Please enter a number.");
var check = Console.ReadLine();
if (!String.IsNullOrWhiteSpace(check))
{
var temp = Convert.ToInt32(check);
sum += temp;
continue;
}
System.Console.WriteLine($"The sum of all entered values are {sum}");
break;
}
/*Write a program and ask the user to enter a number. Compute the factorial
of the number and print it on the console. For example, if the user enters 5,
the program should calculate 5 x 4 x 3 x 2 x 1 and display it as 5! = 120.*/
System.Console.WriteLine("Please enter a number for factorial calculation.");
var userNumber = Convert.ToInt32(Console.ReadLine());
var factorial = 1;
for (var i = 1; i <= userNumber; i++)
{
factorial *= i;
}
System.Console.WriteLine($"The factorial for {userNumber}! is {factorial}");
/*Write a program that picks a random number between 1 and 10. Give the user 4
chances to guess the number. If the user guesses the number, display “You won";
otherwise, display “You lost". (To make sure the program is behaving correctly,
you can display the secret number on the console first.)*/
var rand = new Random();
int randNumber = rand.Next(1, 10);
var chances = 4;
for (int i = 1; i <= chances; i++)
{
System.Console.WriteLine("Please guess a random number between one and ten. You have four attempts");
var guess = Convert.ToInt32(Console.ReadLine());
if (guess == randNumber)
{
System.Console.WriteLine("You won");
break;
}
else
System.Console.WriteLine("You lost");
}
/*Write a program and ask the user to enter a series of numbers separated by comma.
Find the maximum of the numbers and display it on the console. For example, if the
user enters “5, 3, 8, 1, 4", the program should display 8.*/
System.Console.WriteLine("Please enter a series of number separted by a comma.");
string[] stringOfNumbers = Console.ReadLine().Split(",");
int maxNumber = Convert.ToInt32(stringOfNumbers[0]);
foreach (var str in stringOfNumbers)
{
var number = Convert.ToInt32(str);
if (maxNumber < number)
{
maxNumber = number;
}
}
System.Console.WriteLine($"{maxNumber} is the maximun number in the array");
}
}
}
|
using NSubstitute.Core.Arguments;
namespace NSubstitute.Core
{
public class CallSpecificationFactoryFactoryYesThatsRight
{
public static ICallSpecificationFactory CreateCallSpecFactory()
{
return
new CallSpecificationFactory(
new ArgumentSpecificationsFactory(
new MixedArgumentSpecificationsFactory(
new ArgumentSpecificationFactory(
NewParamsArgumentSpecificationFactory(),
NewNonParamsArgumentSpecificationFactory()
),
new SuppliedArgumentSpecificationsFactory(NewDefaultChecker())
)
)
);
}
private static IDefaultChecker NewDefaultChecker()
{
return new DefaultChecker(new DefaultForType());
}
private static IParamsArgumentSpecificationFactory NewParamsArgumentSpecificationFactory()
{
return
new ParamsArgumentSpecificationFactory(
NewDefaultChecker(),
new ArgumentEqualsSpecificationFactory(),
new ArrayArgumentSpecificationsFactory(
new NonParamsArgumentSpecificationFactory(new ArgumentEqualsSpecificationFactory())
),
new ParameterInfosFromParamsArrayFactory(),
new SuppliedArgumentSpecificationsFactory(NewDefaultChecker()),
new ArrayContentsArgumentSpecificationFactory()
);
}
private static INonParamsArgumentSpecificationFactory NewNonParamsArgumentSpecificationFactory()
{
return
new NonParamsArgumentSpecificationFactory(new ArgumentEqualsSpecificationFactory()
);
}
}
} |
using AutoMapper;
using IdentityServer4.NCache.Entities;
namespace IdentityServer4.NCache.Mappers
{
public static class ClientMappers
{
static ClientMappers()
{
Mapper = new MapperConfiguration(cfg => cfg.AddProfile<ClientMapperProfile>())
.CreateMapper();
}
internal static IMapper Mapper { get; }
public static Models.Client ToModel(this Client entity)
{
return Mapper.Map<Models.Client>(entity);
}
public static Client ToEntity(this Models.Client model)
{
return Mapper.Map<Client>(model);
}
}
}
|
namespace FubuCsProjFile.Templating.Runtime
{
public interface ITemplateLogger
{
void Starting(int numberOfSteps);
void TraceStep(ITemplateStep step);
void Trace(string contents, params object[] parameters);
void StartProject(int numberOfAlterations);
void EndProject();
void TraceAlteration(string alteration);
void Finish();
void WriteSuccess(string message);
void WriteWarning(string message);
}
} |
using System.Collections.Generic;
using System.Linq;
using Xpand.Persistent.Base.Logic.Model;
namespace Xpand.ExpressApp.Logic.DomainLogic {
public class ModelActionExecutionContextDomainLogic {
public static List<string> Get_ExecutionContexts(IModelActionExecutionContext modelExecutionContext) {
return modelExecutionContext.Application.ActionDesign.Actions.Select(modelAction => modelAction.Id).ToList();
}
}
}
|
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Common.Concurrency
{
public class ConcurrentDictionaryOfCollections<TKey, TValue>
{
private ConcurrentDictionary<TKey, ConcurrentCollection<TValue>> Values { get; }
public ConcurrentDictionaryOfCollections()
{
Values = new ConcurrentDictionary<TKey, ConcurrentCollection<TValue>>();
}
public IEnumerable<TValue> Get(TKey key)
{
if (Values.TryGetValue(key, out ConcurrentCollection<TValue> values))
{
return values;
}
return new TValue[0];
}
public List<TValue> GetAll()
{
return Values.Values.SelectMany(c => c).ToList();
}
public void Add(TKey key, TValue value)
{
Values.AddOrUpdate(key,
new ConcurrentCollection<TValue>
{
value
},
(_, oldCollection) =>
{
oldCollection.Add(value);
return oldCollection;
});
}
public void Remove(TKey key, TValue value)
{
if (Values.TryGetValue(key, out ConcurrentCollection<TValue> values))
{
try
{
values._lock.EnterWriteLock();
values.RemoveNoLock(value);
if (values.CountNoLock == 0)
{
Values.TryRemove(key, out values);
}
}
finally
{
values._lock.ExitWriteLock();
}
}
}
}
}
|
namespace ShelterAPI.Models
{
public class Cat : Animal
{
public int CatId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using Com.Ericmas001.Windows.Demo.TabControlApp.ViewModels.FirstCategory;
using Com.Ericmas001.Windows.Demo.TabControlApp.Views.MainTabViews;
using Com.Ericmas001.Windows.Demo.TabControlApp.Views.MenuViews;
namespace Com.Ericmas001.Windows.Demo.TabControlApp
{
public class MyApp : ITabControlAppParms
{
public string AppTitle => "Demo TabControlApp";
public string MainIconName => "Demo";
public Dictionary<string, string> Images => new Dictionary<string, string>
{
{"Demo", "Resources/demo.png" },
{"First", "Resources/first.png" },
{"Hidden", "Resources/hidden.png" }
};
public IEnumerable<string> ResourceDictionaries => new string[]
{
};
public Dictionary<string,Type> Resources => new Dictionary<string, Type>
{
};
public int MenuSectionsWidth => 600;
public bool CacheNewTab => false;
public IEnumerable<AppCategory> Categories => new []
{
new AppCategory
{
Title = "First Category",
MenuColor = "DeepSkyBlue",
MenuViewModelType = typeof(FirstCategoryMenuViewModel),
MenuViewType = typeof(FirstCategoryMenuView),
}
};
public Dictionary<Type, Type> MainTabViews => new Dictionary<Type, Type>
{
{typeof(FirstCategoryMainTabViewModel), typeof(FirstCategoryMainTabView) }
};
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Windows.Storage.Streams;
namespace Ghostly
{
public static class StringExtensions
{
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Used after scope")]
public static async Task<IInputStream> ToInputStreamAsync(this string input)
{
var stream = new InMemoryRandomAccessStream();
using (var writer = new DataWriter(stream))
{
writer.WriteString(input);
await writer.StoreAsync();
writer.DetachStream();
}
return stream.GetInputStreamAt(0);
}
}
}
|
using Newtonsoft.Json;
namespace MoneroClient.Wallet.DataTransfer
{
public class TransferResultDto
{
[JsonProperty("amount")]
public ulong Amount { get; set; }
[JsonProperty("fee")]
public ulong Fee { get; set; }
[JsonProperty("multisig_txset")]
public string MultisigTxset { get; set; }
[JsonProperty("tx_blob")]
public string TxBlob { get; set; }
[JsonProperty("tx_hash")]
public string TxHash { get; set; }
[JsonProperty("tx_key")]
public string TxKey { get; set; }
[JsonProperty("tx_metadata")]
public string TxMetadata { get; set; }
[JsonProperty("unsigned_txset")]
public string UnsignedTxset { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DragonFly.Permissions
{
public class AssetPermissions
{
public const string Asset = "Asset";
public const string AssetRead = "AssetRead";
public const string AssetQuery = "AssetQuery";
public const string AssetCreate = "AssetCreate";
public const string AssetUpdate = "AssetUpdate";
public const string AssetDelete = "AssetDelete";
public const string AssetPublish = "AssetPublish";
public const string AssetUnpublish = "AssetUnpublish";
public const string AssetUpload = "AssetUpload";
public const string AssetDownload = "AssetDownload";
}
}
|
using System;
namespace Shamisen.Codecs.Native.Flac.LibFLAC
{
public partial struct FLAC__FrameFooter
{
[NativeTypeName("FLAC__uint16")]
public ushort crc;
}
}
|
using System.ServiceModel;
using Microsoft.Practices.Unity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ProxyHelper.Tests.Support;
using ProxyHelper.Wcf;
namespace ProxyHelper.Tests.UnitTests
{
[TestClass]
public class WcfProxyHelperTest
{
private ServiceHost _serviceHost;
private const string ENDPOINT = "net.tcp://localhost:32065/MyService";
private IProxyHelper<IMyService> _proxyHelper;
private IUnityContainer _container;
[TestInitialize]
public void Init()
{
_container = BuildContainer();
_proxyHelper = _container.Resolve<IProxyHelper<IMyService>>();
_serviceHost = new ServiceHost(typeof (MyService));
_serviceHost.AddServiceEndpoint(typeof(IMyService), NetTcpBindingFactory.GetBinding(), ENDPOINT);
_serviceHost.Open();
}
[TestMethod]
public void TestServiceWithVoidMethod()
{
_proxyHelper.CallService(proxy => proxy.DoWork());
Assert.IsTrue(true);
}
[TestMethod]
public void TestServiceWithMethodReturningAString()
{
string result = _proxyHelper.CallService(proxy => proxy.DoWorkAndReturnString());
Assert.IsNotNull(result);
Assert.AreEqual(result, MyService.ResultMessage);
}
[TestMethod]
public void TestSingleInstanceOfTheProxyHelperWithSynchronousCalls()
{
string result = null;
string result2 = null;
_proxyHelper.CallService(proxy =>
{
proxy.DoWork();
result = proxy.DoWorkAndReturnString();
result2 = proxy.DoWorkAndReturnString();
});
_serviceHost.Close();
Assert.IsNotNull(result);
Assert.AreEqual(result, MyService.ResultMessage);
Assert.AreEqual(result2, MyService.ResultMessage);
}
public static IUnityContainer BuildContainer()
{
var container = new UnityContainer();
container.RegisterType(typeof(IProxyHelper<IMyService>), typeof(WcfProxyHelper<IMyService>),
new InjectionConstructor(NetTcpBindingFactory.GetBinding(),ENDPOINT));
return container;
}
[TestCleanup]
public void CleanUp()
{
_serviceHost.Close();
_container.Dispose();
_serviceHost = null;
_proxyHelper = null;
_container = null;
}
}
}
|
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System.Threading.Tasks;
namespace Xenko.Core
{
/// <summary>
/// An interface allowing to dispose an object asynchronously.
/// </summary>
public interface IAsyncDisposable
{
/// <summary>
/// Disposes the given instance asynchronously.
/// </summary>
/// <returns>A task that completes when this instance has been disposed.</returns>
Task DisposeAsync();
}
}
|
using System;
using System.Collections.Generic;
namespace XamList.UnitTests
{
public class DependencyServiceStub : IDependencyService
{
#region Constant Fields
readonly Dictionary<Type, object> _registeredServices = new Dictionary<Type, object>();
#endregion
#region Methods
public void Register<T>(object impl) => _registeredServices[typeof(T)] = impl;
public T Get<T>() where T : class => (T)_registeredServices[typeof(T)];
#endregion
}
} |
using Microsoft.AspNetCore.Mvc;
using ServiceLayer.Logger;
namespace BookApp.Controllers
{
public class BaseTraceController: Controller
{
protected void SetupTraceInfo()
{
ViewData["TraceIdent"] = HttpContext.TraceIdentifier;
ViewData["NumLogs"] = HttpRequestLog.GetHttpRequestLog(HttpContext.TraceIdentifier).RequestLogs.Count;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
using UnityEngine.EventSystems;
public class MainMenu : MonoBehaviour, ISelectHandler, IDeselectHandler
{
public GameObject selectFrame;
public AudioSource selectSound;
private void Awake()
{
selectFrame.SetActive(false);
}
private void Start()
{
if (transform.name == "Continue")
{
TextMeshProUGUI continueText = transform.GetChild(0).GetComponent<TextMeshProUGUI>();
if (!SaveSystem.CheckSaveExist())
{
Color noSaveColor = continueText.color;
noSaveColor.a = 0.2f;
continueText.color = noSaveColor;
}
else
{
EventSystem.current.firstSelectedGameObject = this.gameObject;
}
}
}
public void NewGameButton()
{
//SaveSystem.DeleteExistingSave();
SceneManager.LoadScene("DirtCave0");
}
public void ContinueButton()
{
if (SaveSystem.CheckSaveExist())
{
SaveSystem.LoadPlayerData();
SceneManager.LoadScene(GameMaster.instance.playerData.respawnScene);
}
}
public void QuitButton()
{
Debug.Log("Quit");
Application.Quit();
}
public void OnSelect(BaseEventData eventData)
{
selectFrame.SetActive(true);
selectSound.Play();
}
public void OnDeselect(BaseEventData eventData)
{
selectFrame.SetActive(false);
}
}
|
using MongoDB.Bson;
using MongoDB.Driver;
namespace NRLS_APITest.TestModels
{
public class MockDUpdateResult : UpdateResult
{
public MockDUpdateResult() { }
public MockDUpdateResult(long updatedCount, bool isAcknowledged)
{
_modifiedCount = updatedCount;
_isAcknowledged = isAcknowledged;
}
public override long ModifiedCount => _modifiedCount;
public override bool IsAcknowledged => _isAcknowledged;
public override bool IsModifiedCountAvailable => throw new System.NotImplementedException();
public override long MatchedCount => throw new System.NotImplementedException();
public override BsonValue UpsertedId => throw new System.NotImplementedException();
private long _modifiedCount { get; set; }
private bool _isAcknowledged { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Mediachase.Ibn.Assignments
{
public enum AssignmentExecutionResult
{
Accepted = 1,
Declined = 2,
Canceled = 3,
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace sort.Infrastructure
{
public class FileSorter
{
public Task SortFile(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
throw new ArgumentNullException(nameof(fileName));
if (!File.Exists(fileName))
throw new FileNotFoundException($"File {fileName} was not found");
return Task.Run(() => ReadAndSort(fileName));
}
private void ReadAndSort(string file)
{
var stringList = new List<string>();
using (var reader = new StreamReader(file))
{
string line;
while ((line = reader.ReadLine()) != null)
{
stringList.Add(line);
}
}
// Старый добрый Array.Sort().
// В итоге все сводится к сортировке массива строк в памяти
// алгоритмом QuickSort.
stringList.Sort();
using (var writer = new StreamWriter(file))
{
foreach (string s in stringList)
{
writer.WriteLine(s);
}
}
}
}
} |
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Octokit.GraphQL.Model
{
/// <summary>
/// The possible states in which a deployment can be.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum DeploymentState
{
/// <summary>
/// The pending deployment was not updated after 30 minutes.
/// </summary>
[EnumMember(Value = "ABANDONED")]
Abandoned,
/// <summary>
/// The deployment is currently active.
/// </summary>
[EnumMember(Value = "ACTIVE")]
Active,
/// <summary>
/// An inactive transient deployment.
/// </summary>
[EnumMember(Value = "DESTROYED")]
Destroyed,
/// <summary>
/// The deployment experienced an error.
/// </summary>
[EnumMember(Value = "ERROR")]
Error,
/// <summary>
/// The deployment has failed.
/// </summary>
[EnumMember(Value = "FAILURE")]
Failure,
/// <summary>
/// The deployment is inactive.
/// </summary>
[EnumMember(Value = "INACTIVE")]
Inactive,
/// <summary>
/// The deployment is pending.
/// </summary>
[EnumMember(Value = "PENDING")]
Pending,
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Ceebeetle
{
[DataContract(Name="BagItem")]
[KnownType(typeof(CCBCountedBagItem))]
public class CCBBagItem : IEquatable<CCBBagItem>, IComparable<CCBBagItem>
{
[DataMember(Name="Item")]
private string m_item;
public string Item
{
get { return m_item; }
set { m_item = value; }
}
public virtual bool IsCountable
{
get { return false; }
}
public virtual int Count
{
get { return 0; }
set { }
}
public CCBBagItem()
{
m_item = "item";
}
public CCBBagItem(string item)
{
m_item = item;
}
public CCBBagItem(CCBBagItem item)
{
if (null == item)
m_item = "";
else
m_item = item.m_item;
}
#region Comparisons
public static bool operator ==(CCBBagItem lhs, CCBBagItem rhs)
{
if (ReferenceEquals(lhs, null) && ReferenceEquals(rhs, null)) return true;
if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null)) return false;
return 0 == string.Compare(lhs.m_item, rhs.m_item);
}
public static bool operator !=(CCBBagItem lhs, CCBBagItem rhs)
{
if (ReferenceEquals(lhs, null) && ReferenceEquals(rhs, null)) return false;
if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null)) return true;
return 0 == string.Compare(lhs.m_item, rhs.m_item);
}
public override bool Equals(object obj)
{
if (obj is CCBBagItem)
{
CCBBagItem item = (CCBBagItem)obj;
if (null != item)
return m_item.Equals(item.m_item);
}
if (obj is string)
{
string strItem = (string)obj;
if (null != strItem)
return 0 == m_item.CompareTo(strItem);
}
return m_item.Equals(obj);
}
public override int GetHashCode()
{
return m_item.GetHashCode();
}
//IEquatable
public bool Equals(CCBBagItem rhs)
{
return m_item.Equals(rhs.m_item);
}
//IComparable
public int CompareTo(CCBBagItem rhs)
{
return m_item.CompareTo(rhs.m_item);
}
#endregion
public override string ToString()
{
return m_item.ToString();
}
}
[DataContract(Name = "CountedBagItem")]
[KnownType(typeof(CCBStoreItem))]
public class CCBCountedBagItem : CCBBagItem
{
[DataMember(Name="Count")]
private int m_count;
public override int Count
{
get { return m_count; }
set { m_count = value; }
}
public override bool IsCountable
{
get { return true; }
}
public CCBCountedBagItem() : base()
{
m_count = 1;
}
public CCBCountedBagItem(int count) : base()
{
m_count = count;
}
public CCBCountedBagItem(string item, int count) : base(item)
{
m_count = count;
}
public CCBCountedBagItem(CCBBagItem item) : base(item)
{
m_count = item.Count;
}
public override string ToString()
{
if (-1 == m_count)
return base.ToString();
return string.Format("{0} ({1})", base.ToString(), m_count);
}
}
#region PredicateHelper
//Helper classes for Predicates
public class CompareBagItemToName
{
private readonly string m_name;
public CompareBagItemToName(string name)
{
m_name = name;
}
private CompareBagItemToName() { }
public Predicate<CCBBagItem> GetPredicate
{
get { return IsThisItem; }
}
private bool IsThisItem(CCBBagItem item)
{
if (null == item)
return false;
return 0 == string.Compare(m_name, item.Item);
}
}
public class CompareBagToName
{
private readonly string m_name;
public CompareBagToName(string name)
{
m_name = name;
}
private CompareBagToName() { }
public Predicate<CCBBag> GetPredicate
{
get { return IsThisBag; }
}
private bool IsThisBag(CCBBag bag)
{
if (null == bag)
return false;
return 0 == string.Compare(m_name, bag.Name);
}
}
#endregion
[DataContract(Name = "Bag")]
[KnownType(typeof(CCBLockedBag))]
[KnownType(typeof(CCBStore))]
public class CCBBag
{
[DataMember(Name = "BagName")]
private string m_name;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
[DataMember(Name = "BagItems")]
private List<CCBBagItem> m_items;
public List<CCBBagItem> Items
{
get
{
if (null == m_items) m_items = new List<CCBBagItem>();
return m_items;
}
}
public virtual bool IsLocked
{
get { return false; }
}
public CCBBag() : base()
{
m_name = "Items";
m_items = new List<CCBBagItem>();
}
public CCBBag(string name) : base()
{
m_name = name;
m_items = new List<CCBBagItem>();
}
public CCBBag(CCBBag bagFrom)
{
m_name = bagFrom.m_name;
m_items = new List<CCBBagItem>();
foreach (CCBBagItem item in bagFrom.m_items)
{
if (item.IsCountable)
m_items.Add(new CCBCountedBagItem(item));
else
m_items.Add(new CCBBagItem(item));
}
}
public override string ToString()
{
return m_name;
}
public virtual CCBBagItem AddItem(string item)
{
CCBBagItem bagItem = new CCBBagItem(item);
if (null == m_items)
m_items = new List<CCBBagItem>();
m_items.Add(bagItem);
return bagItem;
}
public CCBBagItem AddCountableItem(string item, int value)
{
CCBCountedBagItem bagItem = new CCBCountedBagItem(item, value);
if (null == m_items)
m_items = new List<CCBBagItem>();
m_items.Add(bagItem);
return bagItem;
}
public virtual CCBBagItem Add(CCBBagItem item)
{
if (null == m_items)
m_items = new List<CCBBagItem>();
m_items.Add(item);
return item;
}
public CCBBagItem Find(string name)
{
if (null != m_items)
{
CompareBagItemToName comparer = new CompareBagItemToName(name);
return m_items.Find(comparer.GetPredicate);
}
return null;
}
public bool RemoveItem(string item)
{
return RemoveItem(Find(item));
}
public bool RemoveItem(CCBBagItem item)
{
if (null == m_items)
return false;
if (!ReferenceEquals(null, item))
return m_items.Remove(item);
return false;
}
public string RenderString()
{
StringBuilder sb = new StringBuilder();
bool firstItem = true;
foreach (CCBBagItem item in m_items)
{
if (!firstItem)
sb.Append(", ");
sb.Append(item.ToString());
firstItem = false;
}
return sb.ToString();
}
}
//Bag with fixed name
[DataContract(Name = "FixedBag")]
class CCBLockedBag : CCBBag
{
public CCBLockedBag() : base()
{
}
public CCBLockedBag(string name) : base(name)
{
}
public override bool IsLocked
{
get { return true; }
}
}
class CCBOwnedBag : CCBBag
{
private readonly CCBCharacter m_character;
public CCBCharacter Character
{
get { return m_character; }
}
private CCBOwnedBag()
{
m_character = null;
}
public CCBOwnedBag(CCBCharacter character, CCBBag bag) : base(bag)
{
m_character = character;
}
public override string ToString()
{
if (null != m_character)
return string.Format("{0}:{1}", m_character.Name, this.Name);
return base.ToString();
}
}
[CollectionDataContract(Name = "Bags")]
public class CCBBags : List<CCBBag>
{
public bool Remove(string name)
{
CompareBagToName comparer = new CompareBagToName(name);
CCBBag bagToRemove = base.Find(comparer.GetPredicate);
if (null != bagToRemove)
return base.Remove(bagToRemove);
return false;
}
}
}
|
using System.Collections.Generic;
using UML = TSF.UmlToolingFramework.UML;
namespace TSF.UmlToolingFramework.UML.Interactions.BasicInteractions {
//This is an enumerated type that identifies the type of message.
public enum MessageKind : int {
//sendEvent and receiveEvent are present.
complete,
//sendEvent and receiveEvent are present.
lost,
//sendEvent absent and receiveEvent present.
found,
//sendEvent and receiveEvent absent (should not appear).
unknown
}
} |
namespace Skybrud.Social.Vimeo.Models.Users {
/// <summary>
/// Enum class indicating the gender of a Vimeo user.
/// </summary>
public enum VimeoGender {
/// <summary>
/// Indicates that the user hasn't yet specified their gender.
/// </summary>
Unspecified,
/// <summary>
/// Indicates that the user doesn't wish to specify their gender.
/// </summary>
RatherNotSay,
/// <summary>
/// Indicates that the user is a male (he/him).
/// </summary>
Male,
/// <summary>
/// Indicates that the user is a female (she/her).
/// </summary>
Female,
/// <summary>
/// Indicates that the user does not identify as either male or female (wishes to be entitled (they/them).
/// </summary>
Other
}
} |
using System.Threading.Tasks;
namespace AspNetCore.Mvc.Extensions.Notifications
{
public interface INotificationService
{
Task SendAsync(string message, string userId);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Mawor.Net.Interface
{
/// <summary>
/// Represents an identifiable object
/// </summary>
/// <typeparam name="T">Type of the identification, preferred Guid or Int</typeparam>
public interface IIdentifiable<T>:IEquatable<T>
{
/// <summary>
/// Unique value that represents an object among the collection of objects of all workflows
/// </summary>
T Id { get; set; }
/// <summary>
/// Descriptive value, the same as Name
/// </summary>
string Description { get; set; }
}
}
|
using System;
using System.Data;
using System.Collections.Generic;
using WCMS.Framework.Core;
namespace WCMS.Framework.Core
{
public interface IWebSiteProvider : IDataProvider<WSite>
{
IEnumerable<WSite> GetList(int parentId);
WSite Get(string identity);
int GetMaxRank();
}
}
|
namespace DotNet.ProgrammingPrinciples.LSP.New
{
public class Circle : IShape
{
public void Draw()
{
// Draws a circle
}
}
}
|
using Newtonsoft.Json;
namespace Dracoon.Sdk.SdkInternal.ApiModel.Requests {
internal class ApiGetS3Urls {
[JsonProperty("size", NullValueHandling = NullValueHandling.Ignore)]
public long Size {
get; set;
}
[JsonProperty("firstPartNumber", NullValueHandling = NullValueHandling.Ignore)]
public int FirstPartNumber {
get; set;
}
[JsonProperty("lastPartNumber", NullValueHandling = NullValueHandling.Ignore)]
public int LastPartNumber {
get; set;
}
}
}
|
namespace LisoTetris.Components.Tetris.Engine.Elements
{
public static class Presets
{
public static readonly bool[,] FigureO = new bool[2, 2] { { true, true }, { true, true } };
public static readonly bool[,] FigureI = new bool[1, 4] { { true, true, true, true } };
public static readonly bool[,] FigureS = new bool[3, 2] { { false, true }, { true, true }, { true, false} };
public static readonly bool[,] FigureZ = new bool[3, 2] { { true, false }, { true, true }, { false, true } };
public static readonly bool[,] FigureL = new bool[2, 3] { { true, true, true }, { false, false, true } };
public static readonly bool[,] FigureJ = new bool[2, 3] { { false, false, true }, { true, true, true } };
public static readonly bool[,] FigureT = new bool[3, 2] { { true, false }, { true, true }, { true, false } };
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pause : MonoBehaviour
{
private float currentTime;
private void OnEnable()
{
currentTime = Time.timeScale;
Time.timeScale = 0;
}
private void OnDisable()
{
Time.timeScale = currentTime;
}
}
|
using Moq;
using System.Threading.Tasks;
using Xunit;
namespace Domain0.Api.Client.Test
{
public class Domain0ContextAttachedClientTest
{
public interface ITestClient
{
Task MethodA();
void MethodB();
}
[Fact]
public async void AttachedClientLogin()
{
var testContext = TestContext.MockUp();
var domain0Context = new AuthenticationContext(
domain0ClientEnvironment: testContext.ClientScopeMock.Object,
externalStorage: testContext.LoginInfoStorageMock.Object);
var attachedClientMock = new Mock<ITestClient>();
var attachedClient = attachedClientMock.Object;
var attachedEnvironmentMock = new Mock<IClientScope<ITestClient>>();
attachedEnvironmentMock
.Setup(callTo => callTo.Client)
.Returns(() => attachedClient);
var proxy = domain0Context.AttachClientEnvironment(attachedEnvironmentMock.Object);
Assert.NotNull(proxy);
var profile = await domain0Context.LoginByPhone(123, "2");
Assert.NotNull(profile);
attachedEnvironmentMock
.VerifySet(env =>
env.Token = It.Is<string>(s => string.IsNullOrWhiteSpace(s)),
Times.Once);
}
[Fact]
public async void ClientShouldLoginWhenAttached()
{
var testContext = TestContext.MockUp();
var domain0Context = new AuthenticationContext(
domain0ClientEnvironment: testContext.ClientScopeMock.Object,
externalStorage: testContext.LoginInfoStorageMock.Object);
var attachedClientMock = new Mock<ITestClient>();
var attachedClient = attachedClientMock.Object;
var attachedEnvironmentMock = new Mock<IClientScope<ITestClient>>();
attachedEnvironmentMock
.Setup(callTo => callTo.Client)
.Returns(() => attachedClient);
var profile = await domain0Context.LoginByPhone(123, "2");
Assert.NotNull(profile);
var proxy = domain0Context.AttachClientEnvironment(attachedEnvironmentMock.Object);
Assert.NotNull(proxy);
attachedEnvironmentMock
.VerifySet(env => env.Token = It.IsAny<string>(), Times.Once);
}
[Fact]
public async void AttachedClientRefresh()
{
var testContext = TestContext.MockUp(accessValidTime: 0.1);
var domain0Context = new AuthenticationContext(
domain0ClientEnvironment: testContext.ClientScopeMock.Object,
externalStorage: testContext.LoginInfoStorageMock.Object);
var attachedClientMock = new Mock<ITestClient>();
var attachedClient = attachedClientMock.Object;
var attachedEnvironmentMock = new Mock<ClientLockScope<ITestClient>>();
attachedEnvironmentMock
.Setup(callTo => callTo.Client)
.Returns(() => attachedClient);
var proxy = domain0Context.AttachClientEnvironment(attachedEnvironmentMock.Object);
var profile = await domain0Context.LoginByPhone(123, "2");
Assert.NotNull(profile);
proxy.MethodB();
attachedEnvironmentMock
.VerifySet(env =>
env.Token = It.Is<string>(s => !string.IsNullOrWhiteSpace(s)),
Times.Exactly(2));
attachedClientMock
.Verify(c => c.MethodB(), Times.Once);
await proxy.MethodA();
attachedEnvironmentMock
.VerifySet(env =>
env.Token = It.Is<string>(s => !string.IsNullOrWhiteSpace(s)),
Times.Exactly(3));
attachedClientMock
.Verify(c => c.MethodA(), Times.Once);
}
[Fact]
public async void AttachedClientLogout()
{
var testContext = TestContext.MockUp(accessValidTime: 0.1);
var domain0Context = new AuthenticationContext(
domain0ClientEnvironment: testContext.ClientScopeMock.Object,
externalStorage: testContext.LoginInfoStorageMock.Object);
var attachedClientMock = new Mock<ITestClient>();
var attachedClient = attachedClientMock.Object;
var attachedEnvironmentMock = new Mock<IClientScope<ITestClient>>();
attachedEnvironmentMock
.Setup(callTo => callTo.Client)
.Returns(() => attachedClient);
var profile = await domain0Context.LoginByPhone(123, "2");
Assert.NotNull(profile);
var proxy = domain0Context.AttachClientEnvironment(attachedEnvironmentMock.Object);
Assert.NotNull(proxy);
domain0Context.Logout();
attachedEnvironmentMock
.VerifySet(env =>
env.Token = It.Is<string>(x => string.IsNullOrWhiteSpace(x)),
Times.Once);
}
[Fact]
public async void ClientDetach()
{
var testContext = TestContext.MockUp();
var domain0Context = new AuthenticationContext(
domain0ClientEnvironment: testContext.ClientScopeMock.Object,
externalStorage: testContext.LoginInfoStorageMock.Object);
var attachedClientMock = new Mock<ITestClient>();
var attachedClient = attachedClientMock.Object;
var attachedEnvironmentMock = new Mock<IClientScope<ITestClient>>();
attachedEnvironmentMock
.Setup(callTo => callTo.Client)
.Returns(() => attachedClient);
var proxy = domain0Context.AttachClientEnvironment(attachedEnvironmentMock.Object);
Assert.NotNull(proxy);
var profile = await domain0Context.LoginByPhone(123, "2");
Assert.NotNull(profile);
attachedEnvironmentMock
.VerifySet(env =>
env.Token = It.Is<string>(s => string.IsNullOrWhiteSpace(s)),
Times.Once);
domain0Context.DetachClientEnvironment(attachedEnvironmentMock.Object);
profile = await domain0Context.LoginByPhone(123, "2");
Assert.NotNull(profile);
attachedEnvironmentMock
.VerifySet(env =>
env.Token = It.Is<string>(s => string.IsNullOrWhiteSpace(s)),
Times.Once);
}
}
}
|
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Buffers;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using ImageProcessor.Quantizers;
namespace ImageProcessor.Formats
{
/// <summary>
/// Encodes multiple images as an animated gif to a stream.
/// <remarks>
/// Uses default .NET GIF encoding and adds animation headers.
/// Adapted from <see href="http://github.com/DataDink/Bumpkit/blob/master/BumpKit/BumpKit/GifEncoder.cs"/>.
/// </remarks>
/// </summary>
public class GifEncoder
{
/// <summary>
/// The application block size.
/// </summary>
private const byte ApplicationBlockSize = 0x0b;
/// <summary>
/// The application extension block identifier.
/// </summary>
private const int ApplicationExtensionBlockIdentifier = 0xFF21;
/// <summary>
/// The file trailer.
/// </summary>
private const byte FileTrailer = 0x3b;
/// <summary>
/// The graphic control extension block identifier.
/// </summary>
private const int GraphicControlExtensionBlockIdentifier = 0xF921;
/// <summary>
/// The graphic control extension block size.
/// </summary>
private const byte GraphicControlExtensionBlockSize = 0x04;
/// <summary>
/// The source color block length.
/// </summary>
private const int SourceColorBlockLength = 768;
/// <summary>
/// The source color block position.
/// </summary>
private const int SourceColorBlockPosition = 13;
/// <summary>
/// The source global color info position.
/// </summary>
private const int SourceGlobalColorInfoPosition = 10;
/// <summary>
/// The source graphic control extension length.
/// </summary>
private const int SourceGraphicControlExtensionLength = 8;
/// <summary>
/// The source graphic control extension position.
/// </summary>
private const int SourceGraphicControlExtensionPosition = 781;
/// <summary>
/// The source image block header length.
/// </summary>
private const int SourceImageBlockHeaderLength = 11;
/// <summary>
/// The source image block position.
/// </summary>
private const int SourceImageBlockPosition = 789;
/// <summary>
/// The application identification.
/// </summary>
private static readonly byte[] ApplicationIdentification = Encoding.ASCII.GetBytes("NETSCAPE2.0");
/// <summary>
/// The file type and version.
/// </summary>
private static readonly byte[] FileType = Encoding.ASCII.GetBytes("GIF89a");
/// <summary>
/// The stream.
/// </summary>
private readonly MemoryStream imageStream;
/// <summary>
/// The repeat count.
/// </summary>
private readonly int repeatCount;
/// <summary>
/// Whether the gif has has the last terminated byte written.
/// </summary>
private bool terminated;
/// <summary>
/// Whether this is first image frame.
/// </summary>
private bool isFirstImageFrame = true;
/// <summary>
/// The quantizer for reducing the palette.
/// </summary>
private readonly IQuantizer quantizer;
/// <summary>
/// Initializes a new instance of the <see cref="GifEncoder"/> class.
/// </summary>
/// <param name="quantizer">The quantizer used to reduce and index the images pixels.</param>
/// <param name="repeatCount">
/// The number of times to repeat the animation.
/// </param>
public GifEncoder(IQuantizer quantizer, int repeatCount)
{
this.quantizer = quantizer;
this.imageStream = new MemoryStream();
this.repeatCount = repeatCount;
}
/// <summary>
/// Encodes the image frame to the output gif.
/// </summary>
/// <param name="frame">The <see cref="GifFrame"/> containing the image.</param>
public void EncodeFrame(GifFrame frame)
{
// We need to quantize the image.
Image image = this.quantizer.Quantize(frame.Image);
using (var gifStream = new MemoryStream())
{
image.Save(gifStream, ImageFormat.Gif);
if (this.isFirstImageFrame)
{
// Steal the global color table info
this.WriteHeaderBlock(gifStream, image.Width, image.Height);
}
this.WriteGraphicControlBlock(gifStream, Convert.ToInt32(frame.Delay.TotalMilliseconds / 10F));
this.WriteImageBlock(gifStream, !this.isFirstImageFrame, frame.X, frame.Y, image.Width, image.Height);
}
this.isFirstImageFrame = false;
}
/// <summary>
/// Encodes the completed gif to an <see cref="Image"/>.
/// </summary>
/// <returns>The completed animated gif.</returns>
public Image Encode()
{
this.Terminate();
// Push the data
this.imageStream.Position = 0;
return Image.FromStream(this.imageStream);
}
/// <summary>
/// Encodes the completed gif to an <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The stream.</param>
public void EncodeToStream(Stream stream)
{
this.Terminate();
if (stream.CanSeek)
{
stream.Position = 0;
}
// Push the data
this.imageStream.Position = 0;
this.imageStream.CopyTo(stream);
}
/// <summary>
/// Writes the termination marker to the image stream.
/// </summary>
private void Terminate()
{
if (!this.terminated)
{
// Complete File
this.WriteByte(FileTrailer);
this.terminated = true;
}
}
/// <summary>
/// Writes the header block of the animated gif to the stream.
/// </summary>
/// <param name="sourceGif">The source gif.</param>
/// <param name="width">The width of the image.</param>
/// <param name="height">The height of the image.</param>
private void WriteHeaderBlock(Stream sourceGif, int width, int height)
{
// File Header signature and version.
this.imageStream.Write(FileType, 0, FileType.Length);
// Write the logical screen descriptor.
this.WriteShort(width); // Initial Logical Width
this.WriteShort(height); // Initial Logical Height
// Read the global color table info.
sourceGif.Position = SourceGlobalColorInfoPosition;
this.WriteByte(sourceGif.ReadByte());
this.WriteByte(255); // Background Color Index
this.WriteByte(0); // Pixel aspect ratio
this.WriteColorTable(sourceGif);
// Application Extension Header
int count = this.repeatCount;
if (count != 1)
{
// 0 means loop indefinitely. count is set as play n + 1 times.
count = Math.Max(0, count - 1);
this.WriteShort(ApplicationExtensionBlockIdentifier);
this.WriteByte(ApplicationBlockSize);
this.imageStream.Write(ApplicationIdentification, 0, ApplicationIdentification.Length);
this.WriteByte(3); // Application block length
this.WriteByte(1);
this.WriteShort(count); // Repeat count for images.
this.WriteByte(0); // Terminator
}
}
/// <summary>
/// Writes the given integer as a byte to the stream.
/// </summary>
/// <param name="value">The value.</param>
private void WriteByte(int value) => this.imageStream.WriteByte(Convert.ToByte(value));
/// <summary>
/// Writes the color table.
/// </summary>
/// <param name="sourceGif">The source gif.</param>
private void WriteColorTable(Stream sourceGif)
{
sourceGif.Position = SourceColorBlockPosition; // Locating the image color table
byte[] colorTable = ArrayPool<byte>.Shared.Rent(SourceColorBlockLength);
try
{
sourceGif.Read(colorTable, 0, SourceColorBlockLength);
this.imageStream.Write(colorTable, 0, SourceColorBlockLength);
}
finally
{
ArrayPool<byte>.Shared.Return(colorTable);
}
}
/// <summary>
/// Writes graphic control block.
/// </summary>
/// <param name="gifStream">The source gif.</param>
/// <param name="frameDelay">The frame delay.</param>
private void WriteGraphicControlBlock(Stream gifStream, int frameDelay)
{
gifStream.Position = SourceGraphicControlExtensionPosition; // Locating the source GCE
Span<byte> blockhead = stackalloc byte[SourceGraphicControlExtensionLength];
gifStream.Read(blockhead); // Reading source GCE
this.WriteShort(GraphicControlExtensionBlockIdentifier); // Identifier
this.WriteByte(GraphicControlExtensionBlockSize); // Block Size
this.WriteByte((blockhead[3] & 0xF7) | 0x08); // Setting disposal flag
this.WriteShort(frameDelay); // Setting frame delay
this.WriteByte(255); // Transparent color index
this.WriteByte(0); // Terminator
}
/// <summary>
/// Writes the image block data.
/// </summary>
/// <param name="gifStream">The source gif.</param>
/// <param name="includeColorTable">The include color table.</param>
/// <param name="x">The x position to write the image block.</param>
/// <param name="y">The y position to write the image block.</param>
/// <param name="h">The height of the image block.</param>
/// <param name="w">The width of the image block.</param>
private void WriteImageBlock(Stream gifStream, bool includeColorTable, int x, int y, int h, int w)
{
// Local Image Descriptor
gifStream.Position = SourceImageBlockPosition; // Locating the image block
Span<byte> header = stackalloc byte[SourceImageBlockHeaderLength];
gifStream.Read(header);
this.WriteByte(header[0]); // Separator
this.WriteShort(x); // Position X
this.WriteShort(y); // Position Y
this.WriteShort(h); // Height
this.WriteShort(w); // Width
if (includeColorTable)
{
// If first frame, use global color table - else use local
gifStream.Position = SourceGlobalColorInfoPosition;
this.WriteByte((gifStream.ReadByte() & 0x3F) | 0x80); // Enabling local color table
this.WriteColorTable(gifStream);
}
else
{
this.WriteByte((header[9] & 0x07) | 0x07); // Disabling local color table
}
this.WriteByte(header[10]); // LZW Min Code Size
// Read/Write image data
gifStream.Position = SourceImageBlockPosition + SourceImageBlockHeaderLength;
int dataLength = gifStream.ReadByte();
while (dataLength > 0)
{
byte[] imgData = ArrayPool<byte>.Shared.Rent(dataLength);
try
{
gifStream.Read(imgData, 0, dataLength);
this.imageStream.WriteByte(Convert.ToByte(dataLength));
this.imageStream.Write(imgData, 0, dataLength);
dataLength = gifStream.ReadByte();
}
finally
{
ArrayPool<byte>.Shared.Return(imgData);
}
}
this.imageStream.WriteByte(0); // Terminator
}
/// <summary>
/// Writes a short to the image stream.
/// </summary>
/// <param name="value">The value.</param>
private void WriteShort(int value)
{
// Leave only one significant byte.
this.imageStream.WriteByte(Convert.ToByte(value & 0xFF));
this.imageStream.WriteByte(Convert.ToByte((value >> 8) & 0xFF));
}
}
}
|
using PnP.Core.Services;
namespace PnP.Core.Admin.Model.SharePoint
{
internal sealed class SiteCollectionAppManager : AppManager<ISiteCollectionApp>, ISiteCollectionAppManager
{
protected override string Scope => "sitecollection";
internal SiteCollectionAppManager(PnPContext pnpContext) : base(pnpContext)
{
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cake.Testing.Xunit;
using Xunit;
namespace Cake.Core.Tests.Unit
{
public sealed class CakeRuntimeTests
{
public sealed class TheTargetFrameworkProperty
{
[RuntimeFact(TestRuntime.Clr)]
public void Should_Return_Correct_Result_For_Clr()
{
// Given
var runtime = new CakeRuntime();
// When
var framework = runtime.TargetFramework;
// Then
Assert.Equal(".NETFramework,Version=v4.6.1", framework.FullName);
}
[RuntimeFact(TestRuntime.CoreClr)]
public void Should_Return_Correct_Result_For_CoreClr()
{
// Given
var runtime = new CakeRuntime();
// When
var framework = runtime.TargetFramework;
// Then
Assert.Equal(".NETStandard,Version=v1.6", framework.FullName);
}
}
}
}
|
using System.Threading.Tasks;
namespace Knapcode.Delta.Common
{
public interface IAsyncEnumerator<T>
{
T Current { get; }
Task<bool> MoveNextAsync();
}
}
|
using DoctorHouse.Data;
namespace DoctorHouse.Business.Services
{
public interface IWebCacheService
{
User GetUserById(int id);
}
} |
using Stamps.DataAccess;
using System.Windows;
namespace Stamps.View
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
/// <summary>
/// This serves as the main function of the complete application. It creates initial state, consisting of the
/// initial model and view model, and ties together the view and the dispatching function through an
/// <see cref="ApplicationModel"/> object. All dependencies of the model, like our small data access layer,
/// are also initialized here and passed to the model. I like the term "composition root" for describing this
/// place in the system.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Application_Startup(object sender, StartupEventArgs e)
{
// Create the initial model and view model.
var stampService = new WorldStampKnowledgeBaseService();
var initialModel = Stamps.Model.Model.smallCollection(stampService);
var initialViewModel = Stamps.ViewModel.ViewModel.initialViewModel(initialModel);
var application = new ApplicationModel(initialModel, initialViewModel);
var mainWindow = new MainWindow(initialViewModel, application);
mainWindow.Show();
}
}
}
|
using System;
using PublicHolidays.Au.Internal.PublicHolidays;
using Shouldly;
using Xunit;
namespace PublicHolidays.Au.UnitTests.Internal.PublicHolidays
{
public class LabourDayTests
{
const int Year = 2017;
private readonly LabourDay _labourDay;
public LabourDayTests()
{
_labourDay = new LabourDay();
}
[Fact]
public void InWA_2017_ReturnsDateOfFirstMondayInMarch()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.WA).In(Year);
result.ShouldContain(new DateTime(Year, 3, 6));
}
[Fact]
public void InTAS_2017_ReturnsDateOfSecondMondayInMarch()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.TAS).In(Year);
result.ShouldContain(new DateTime(Year, 3, 13));
}
[Fact]
public void InVIC_2017_ReturnsDateOfSecondMondayInMarch()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.VIC).In(Year);
result.ShouldContain(new DateTime(Year, 3, 13));
}
[Fact]
public void InQLD_2017_ReturnsDateOfFirstMondayInMay()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.QLD).In(Year);
result.ShouldContain(new DateTime(Year, 5, 1));
}
[Fact]
public void InNT_2017_ReturnsDateOfFirstMondayInMay()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.NT).In(Year);
result.ShouldContain(new DateTime(Year, 5, 1));
}
[Fact]
public void InNSW_2017_ReturnsDateOfFirstMondayInOctober()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.NSW).In(Year);
result.ShouldContain(new DateTime(Year, 10, 2));
}
[Fact]
public void InACT_2017_ReturnsDateOfFirstMondayInOctober()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.ACT).In(Year);
result.ShouldContain(new DateTime(Year, 10, 2));
}
[Fact]
public void InSA_2017_ReturnsDateOfFirstMondayInOctober()
{
var result = _labourDay.GetPublicHolidayDatesFor(State.SA).In(Year);
result.ShouldContain(new DateTime(Year, 10, 2));
}
[Fact]
public void GetNameOfPublicHolidayIn_NT_ReturnsCorrectName()
{
var name = _labourDay.GetNameOfPublicHolidayIn(State.NT);
name.ShouldBe("May Day");
}
[Fact]
public void GetNameOfPublicHolidayIn_TAS_ReturnsCorrectName()
{
var name = _labourDay.GetNameOfPublicHolidayIn(State.TAS);
name.ShouldBe("Eight Hours Day");
}
[Fact]
public void GetNameOfPublicHolidayIn_NeitherNTNorTAS_ReturnsCorrectName()
{
var name = _labourDay.GetNameOfPublicHolidayIn(State.National);
name.ShouldBe("Labour Day");
}
}
} |
using Cafe.Domain.Entities;
using MediatR;
using Optional;
using System;
using System.Threading.Tasks;
namespace Cafe.Domain.Repositories
{
public interface IBaristaRepository
{
Task<Option<Barista>> Get(Guid id);
Task<Unit> Update(Barista barista);
Task<Unit> Add(Barista barista);
}
}
|
using NinMemApi.Data.Models;
using System.Collections.Generic;
namespace NinMemApi.Data
{
public class GraphInput
{
public List<NatureAreaDto> NatureAreas { get; set; }
public List<RedlistCategory> NatureAreaRedlistCategories { get; set; }
public List<RedlistTheme> NatureAreaRedlistThemes { get; set; }
public GeographicalAreaData NatureAreaGeographicalAreaData { get; set; }
public List<Taxon> Taxons { get; set; }
public CodeTreeNode CodeTree { get; set; }
public List<NatureAreaVariables> NatureAreaVariables { get; set; }
public List<TaxonTraits> TaxonTraits { get; set; }
}
} |
namespace SLStudio
{
public interface IStudioModule : IHaveName
{
string Author { get; }
int Priority { get; }
bool ShouldBeLoaded { get; }
bool IsLoaded { get; }
void Load(IModuleContainer container);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dodge
{
struct Area
{
public int startRow;
public int endRow;
public int startCol;
public int endCol;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenuAttribute(fileName = "New NPC Data", menuName = "Character Data/NPC")]
public class NPCData : CharacterData
{
}
|
using System;
class PrintNumbers
{
static void Main()
{
Console.WriteLine("{0}\n{1}\n{2}", 1, 101, 1001);
}
} |
using CommandLine;
using Newtonsoft.Json;
using Serilog;
using System.IO;
using System.Text;
using System.Xml;
namespace Xml2JsonConsole
{
internal static class Program
{
private static ILogger Logger { get; set; }
static void Main(string[] args)
{
Logger = new LoggerConfiguration()
.WriteTo.ColoredConsole()
.CreateLogger();
Parser.Default.ParseArguments<Options>(args)
.WithParsed<Options>(o =>
{
if (!string.IsNullOrEmpty(o.Filename))
{
if (File.Exists(o.Filename))
{
CreateJson(o.Filename, o.Verbose, o.JsonSuffix);
}
else
{
Logger.Warning("Inexisting file: {Filename}.", o.Filename);
}
}
if (!string.IsNullOrEmpty(o.Directory))
{
CreateJsonDirectory(o.Directory, o.Verbose, o.JsonSuffix);
}
});
}
private static void CreateJsonDirectory(string directory, bool verbose, string jsonSuffix)
{
if (Directory.Exists(directory))
{
foreach(var file in Directory.GetFiles(directory, "*.xml"))
{
CreateJson(file, verbose, jsonSuffix);
}
}
else
{
Logger.Warning("Inexisting directory: {Directory}", directory);
}
}
private static void CreateJson(string filename, bool verbose = true, string jsonSuffix = ".json")
{
var xml = File.ReadAllText(filename);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var builder = new StringBuilder();
JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder)), doc);
var serialized = builder.ToString();
var outputFile = filename + jsonSuffix;
if (verbose)
{
Logger.Information("{InputFile} -> {OutputFile}", filename, outputFile);
}
File.WriteAllText(outputFile, serialized, Encoding.UTF8);
}
}
}
|
using FluentValidation;
namespace Din.Domain.Commands.Accounts
{
public class ActivateAccountCommandValidator : AbstractValidator<ActivateAccountCommand>
{
public ActivateAccountCommandValidator()
{
RuleFor(cmd => cmd.Code)
.NotEmpty().WithMessage("The code cannot be empty")
.Length(30).WithMessage("The code is exactly thirty characters long");
}
}
}
|
//---------------------------------------------------------------------
// <copyright file="Simplifier.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace System.Data.Common.Utils.Boolean
{
// Simplifier visitor for Boolean expressions. Performs the following
// simplifications bottom-up:
// - Eliminate True and False (A Or False iff. A, A And True iff. A)
// - Resolve tautology (A Or !A iff. True, True Or A iff. True) and
// contradiction (A And !A iff. False, False And A iff. False)
// - Flatten nested negations (!!A iff. A)
// - Evaluate bound literals (!True iff. False, etc.)
// - Flatten unary/empty And/Or expressions
internal class Simplifier<T_Identifier> : BasicVisitor<T_Identifier>
{
internal static readonly Simplifier<T_Identifier> Instance = new Simplifier<T_Identifier>();
protected Simplifier()
{
}
internal override BoolExpr<T_Identifier> VisitNot(NotExpr<T_Identifier> expression)
{
BoolExpr<T_Identifier> child = expression.Child.Accept(this);
switch (child.ExprType)
{
case ExprType.Not:
return ((NotExpr<T_Identifier>)child).Child;
case ExprType.True: return FalseExpr<T_Identifier>.Value;
case ExprType.False: return TrueExpr<T_Identifier>.Value;
default: return base.VisitNot(expression);
}
}
internal override BoolExpr<T_Identifier> VisitAnd(AndExpr<T_Identifier> expression)
{
return SimplifyTree(expression);
}
internal override BoolExpr<T_Identifier> VisitOr(OrExpr<T_Identifier> expression)
{
return SimplifyTree(expression);
}
private BoolExpr<T_Identifier> SimplifyTree(TreeExpr<T_Identifier> tree)
{
bool isAnd = ExprType.And == tree.ExprType;
Debug.Assert(isAnd || ExprType.Or == tree.ExprType);
// Get list of simplified children, flattening nested And/Or expressions
List<BoolExpr<T_Identifier>> simplifiedChildren = new List<BoolExpr<T_Identifier>>(tree.Children.Count);
foreach (BoolExpr<T_Identifier> child in tree.Children)
{
BoolExpr<T_Identifier> simplifiedChild = child.Accept(this);
// And(And(A, B), C) iff. And(A, B, C)
// Or(Or(A, B), C) iff. Or(A, B, C)
if (simplifiedChild.ExprType == tree.ExprType)
{
simplifiedChildren.AddRange(((TreeExpr<T_Identifier>)simplifiedChild).Children);
}
else
{
simplifiedChildren.Add(simplifiedChild);
}
}
// Track negated children separately to identify tautologies and contradictions
Dictionary<BoolExpr<T_Identifier>, bool> negatedChildren = new Dictionary<BoolExpr<T_Identifier>, bool>(tree.Children.Count);
List<BoolExpr<T_Identifier>> otherChildren = new List<BoolExpr<T_Identifier>>(tree.Children.Count);
foreach (BoolExpr<T_Identifier> simplifiedChild in simplifiedChildren)
{
switch (simplifiedChild.ExprType)
{
case ExprType.Not:
negatedChildren[((NotExpr<T_Identifier>)simplifiedChild).Child] = true;
break;
case ExprType.False:
// False And A --> False
if (isAnd) { return FalseExpr<T_Identifier>.Value; }
// False || A --> A (omit False from child collections)
break;
case ExprType.True:
// True Or A --> True
if (!isAnd) { return TrueExpr<T_Identifier>.Value; }
// True And A --> A (omit True from child collections)
break;
default:
otherChildren.Add(simplifiedChild);
break;
}
}
List<BoolExpr<T_Identifier>> children = new List<BoolExpr<T_Identifier>>();
foreach (BoolExpr<T_Identifier> child in otherChildren)
{
if (negatedChildren.ContainsKey(child))
{
// A && !A --> False, A || !A --> True
if (isAnd) { return FalseExpr<T_Identifier>.Value; }
else { return TrueExpr<T_Identifier>.Value; }
}
children.Add(child);
}
foreach (BoolExpr<T_Identifier> child in negatedChildren.Keys)
{
children.Add(child.MakeNegated());
}
if (0 == children.Count)
{
// And() iff. True
if (isAnd) { return TrueExpr<T_Identifier>.Value; }
// Or() iff. False
else { return FalseExpr<T_Identifier>.Value; }
}
else if (1 == children.Count)
{
// Or(A) iff. A, And(A) iff. A
return children[0];
}
else
{
// Construct simplified And/Or expression
TreeExpr<T_Identifier> result;
if (isAnd) { result = new AndExpr<T_Identifier>(children); }
else { result = new OrExpr<T_Identifier>(children); }
return result;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchController : MonoBehaviour {
private Vector3 lastTouchPosition;
[SerializeField] private float dragThreshold;
[SerializeField] private float dragThresholdX;
[SerializeField] private float dragThresholdY;
void Start () {
lastTouchPosition = Vector3.zero;
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
lastTouchPosition = Input.mousePosition;
} else if (Input.GetMouseButton(0)) {
Vector3 newTouchPosition = Input.mousePosition;
Vector3 inputDiff = newTouchPosition - lastTouchPosition;
if(inputDiff.magnitude > dragThreshold) {
lastTouchPosition = newTouchPosition;
float x = Mathf.Abs(inputDiff.x) > dragThresholdX ? inputDiff.x : 0.0f;
float y = Mathf.Abs(inputDiff.y) > dragThresholdY ? inputDiff.y : 0.0f;
EventManager.Instance.OnDirectionInputChanged.Invoke(x, y);
}
}
}
}
|
using System;
namespace RThomasHyde.PluginFramework.Catalogs.Roslyn
{
public class InvalidCodeException : Exception
{
public InvalidCodeException(Exception exception) : this("", exception)
{
}
public InvalidCodeException(string message, Exception exception) : base(message, exception)
{
}
}
}
|
/****************************************************************************
Copyright 2016 sophieml1989@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
using System;
using Newtonsoft.Json.Linq;
namespace UBlockly
{
public sealed class FieldNumber : FieldTextInput
{
[FieldCreator(FieldType = "field_number")]
private static FieldNumber CreateFromJson(JObject json)
{
string fieldName = json["name"].IsString() ? json["name"].ToString() : "FIELDNAME_DEFAULT";
return new FieldNumber(fieldName,
json["value"].ToString(),
json["min"] == null ? null : json["min"].ToString(),
json["max"] == null ? null : json["max"].ToString(),
json["int"] != null && (bool) json["int"]);
}
private Number mNumber;
private Number mMin;
public Number Min { get { return mMin; } }
private Number mMax;
public Number Max { get { return mMax; } }
private bool mIntOnly;
public bool IntOnly { get { return mIntOnly; } }
/// <summary>
/// Class for an editable number field.
/// </summary>
public FieldNumber(string fieldName) : this(fieldName, "0") {}
/// <summary>
/// Class for an editable number field.
/// </summary>
public FieldNumber(string fieldName, string optValue, string optMin = null, string optMax = null, bool optIntOnly = false) : base(fieldName)
{
mNumber = new Number(!string.IsNullOrEmpty(optValue) ? optValue : "0");
if (mNumber.IsNaN) mNumber = new Number(0);
this.SetValue(mNumber.ToString());
mMin = !string.IsNullOrEmpty(optMin) ? new Number(optMin) : Number.MinValue;
mMax = !string.IsNullOrEmpty(optMax) ? new Number(optMax) : Number.MaxValue;
mIntOnly = optIntOnly;
SetValue(CallValidator(GetValue()));
}
/// <summary>
/// Class for an editable number field.
/// Please input a Number value instantiated of Number Type
/// </summary>
public FieldNumber(string fieldName, Number optValue, Number optMin, Number optMax, bool optIntOnly = false) : base(fieldName)
{
mNumber = optValue.IsNaN ? new Number(0) : optValue;
this.SetValue(mNumber.ToString());
mMin = optMin.IsNaN ? Number.MinValue : optMin;
mMax = optMax.IsNaN ? Number.MaxValue : optMax;
mIntOnly = optIntOnly;
SetValue(CallValidator(GetValue()));
}
protected override string ClassValidator(string text)
{
if (string.IsNullOrEmpty(text))
return null;
text = text.Replace(",", "");
mNumber = new Number(text);
if (mNumber.IsNaN)
{
// Invalid number.
return null;
}
mNumber.Clamp(mMin, mMax);
return mNumber.ToString();
}
}
}
|
using System;
namespace CreatureConstructor
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the ASCII Art Creature Constructor!");
Console.WriteLine("Construct a random creature? [y/n]");
string random = Console.ReadLine();
if (random == "y")
{
RandomMode();
}
else
{
Console.WriteLine("Choose any of the following:");
Console.WriteLine("head: [monster/ghost/bug]");
string head = Console.ReadLine();
Console.WriteLine("body: [monster/ghost/bug]");
string body = Console.ReadLine();
Console.WriteLine("feet: [monster/ghost/bug]");
string feet = Console.ReadLine();
BuildACreature(head, body, feet);
}
}
static void BuildACreature(string head, string body, string feet)
{
Console.WriteLine(head);
Random randomNumber = new Random();
int headNum;
int bodyNum;
int feetNum;
if (head == "")
{
headNum = randomNumber.Next(1,4);
}
else
{
headNum = TranslateToNumber(head);
}
if (body == "")
{
bodyNum = randomNumber.Next(1,4);
}
else
{
bodyNum = TranslateToNumber(body);
}
if (feet == "")
{
feetNum = randomNumber.Next(1,4);
}
else
{
feetNum = TranslateToNumber(feet);
}
SwitchCase(headNum, bodyNum, feetNum);
}
static void RandomMode()
{
Random randomNumber = new Random();
int head = randomNumber.Next(1, 4);
int body = randomNumber.Next(1, 4);
int feet = randomNumber.Next(1, 4);
SwitchCase(head, body, feet);
}
static void SwitchCase(int head, int body, int feet)
{
switch(head)
{
case 1:
MonsterHead();
break;
case 2:
GhostHead();
break;
case 3:
BugHead();
break;
}
switch(body)
{
case 1:
MonsterBody();
break;
case 2:
GhostBody();
break;
case 3:
BugBody();
break;
}
switch(feet)
{
case 1:
MonsterFeet();
break;
case 2:
GhostFeet();
break;
case 3:
BugFeet();
break;
}
}
static int TranslateToNumber(string creature)
{
switch (creature)
{
case "monster":
return 1;
break;
case "ghost":
return 2;
break;
case "bug":
return 3;
break;
default:
return 1;
break;
}
}
static void GhostHead()
{
Console.WriteLine(" ..-..");
Console.WriteLine(" ( o o )");
Console.WriteLine(" | O |");
}
static void GhostBody()
{
Console.WriteLine(" | |");
Console.WriteLine(" | |");
Console.WriteLine(" | |");
}
static void GhostFeet()
{
Console.WriteLine(" | |");
Console.WriteLine(" | |");
Console.WriteLine(" '~~~~~'");
}
static void BugHead()
{
Console.WriteLine(" / \\");
Console.WriteLine(" \\. ./");
Console.WriteLine(" (o + o)");
}
static void BugBody()
{
Console.WriteLine(" --| | |--");
Console.WriteLine(" --| | |--");
Console.WriteLine(" --| | |--");
}
static void BugFeet()
{
Console.WriteLine(" v v");
Console.WriteLine(" *****");
}
static void MonsterHead()
{
Console.WriteLine(" _____");
Console.WriteLine(" .-,;='';_),-.");
Console.WriteLine(" \\_\\(),()/_/");
Console.WriteLine(" (,___,)");
}
static void MonsterBody()
{
Console.WriteLine(" ,-/`~`\\-,___");
Console.WriteLine(" / /).:.('--._)");
Console.WriteLine(" {_[ (_,_)");
}
static void MonsterFeet()
{
Console.WriteLine(" | Y |");
Console.WriteLine(" / | \\");
Console.WriteLine(" \"\"\"\" \"\"\"\"");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Biz.Morsink.Identity
{
/// <summary>
/// This interface describes the underlying component value of the most identifying component (last component).
/// </summary>
/// <typeparam name="K">The type of the underlying component value.</typeparam>
public interface IIdentityComponentValue<K> : IIdentity
{
/// <summary>
/// Gets the underlying component value for this identity value.
/// </summary>
new K ComponentValue { get; }
}
}
|
// Copyright (c) Doug Swisher. All Rights Reserved.
// Licensed under the MIT License. See LICENSE.md in the project root for license information.
using System;
using System.ComponentModel;
using System.Globalization;
using SwishSvg.IO;
namespace SwishSvg.DataTypes
{
/// <summary>
/// A length is a distance measurement, given as a number along with a unit which may be optional.
/// </summary>
[TypeConverter(typeof(SvgLengthConverter))]
public class SvgLength
{
/// <summary>
/// Gets a length of none.
/// </summary>
public static readonly SvgLength None = new SvgLength(0, SvgUnit.None);
/// <summary>
/// Initializes a new instance of the <see cref="SvgLength"/> class.
/// </summary>
/// <param name="value">The value for the length.</param>
/// <param name="unit">The unit for the length.</param>
public SvgLength(float value, SvgUnit unit = SvgUnit.User)
{
Value = value;
Unit = unit;
}
/// <summary>
/// Gets the value of the length.
/// </summary>
public float Value { get; private set; }
/// <summary>
/// Gets the unit of the length.
/// </summary>
public SvgUnit Unit { get; private set; }
/// <inheritdoc />
public override bool Equals(object obj)
{
var other = obj as SvgLength;
if (other == null)
{
return false;
}
return Value == other.Value && Unit == other.Unit;
}
/// <inheritdoc />
public override int GetHashCode()
{
return Value.GetHashCode() ^ Unit.GetHashCode();
}
/// <inheritdoc />
public override string ToString()
{
string unit;
switch (Unit)
{
case SvgUnit.None:
return "none";
case SvgUnit.Pixel:
unit = "px";
break;
case SvgUnit.Em:
unit = "em";
break;
case SvgUnit.Percentage:
unit = "%";
break;
case SvgUnit.User:
unit = string.Empty;
break;
case SvgUnit.Inch:
unit = "in";
break;
case SvgUnit.Centimeter:
unit = "cm";
break;
case SvgUnit.Millimeter:
unit = "mm";
break;
default:
throw new Exception($"Unhandled length unit: {Unit}");
}
return string.Concat(Value.ToString(CultureInfo.InvariantCulture), unit);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Store.PartnerCenter.PowerShell.Utilities
{
using System;
using Identity.Client;
using Microsoft.Extensions.Caching.Memory;
using Rest;
/// <summary>
/// Provides an in-memory token cache for client applications.
/// </summary>
public class InMemoryTokenCache : PartnerTokenCache, IDisposable
{
/// <summary>
/// Identifier for the token cache.
/// </summary>
private const string cacheId = "CacheId";
/// <summary>
/// Provides a resource lock to ensure operations are performed in a thread-safe manner.
/// </summary>
private static readonly object resourceLock = new object();
/// <summary>
/// Provides a local in-memory cache for storing token information.
/// </summary>
private readonly IMemoryCache memoryCache;
/// <summary>
/// A flag indicating if the object has already been disposed.
/// </summary>
private bool disposed = false;
/// <summary>
/// Initializes a new instance of the <see cref="InMemoryTokenCache" /> class.
/// </summary>
public InMemoryTokenCache()
{
memoryCache = new MemoryCache(new MemoryCacheOptions());
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
memoryCache?.Dispose();
}
disposed = true;
}
/// <summary>
/// Gets the data from the cache.
/// </summary>
/// <param name="clientId">The client identifier used to request a token.</param>
/// <returns>The data from the token cache.</returns>
public override byte[] GetCacheData()
{
memoryCache.TryGetValue(cacheId, out byte[] value);
return value;
}
/// <summary>
/// Notification that is triggered after token acquisition.
/// </summary>
/// <param name="args">Arguments related to the cache item impacted</param>
public override void AfterAccessNotification(TokenCacheNotificationArgs args)
{
args.AssertNotNull(nameof(args));
lock (resourceLock)
{
memoryCache.Set(cacheId, args.TokenCache.SerializeMsalV3());
}
}
/// <summary>
/// Notification that is triggered before token acquisition.
/// </summary>
/// <param name="args">Arguments related to the cache item impacted</param>
public override void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
args.AssertNotNull(nameof(args));
lock (resourceLock)
{
if (memoryCache.TryGetValue(cacheId, out byte[] value))
{
args.TokenCache.DeserializeMsalV3(value);
}
}
}
/// <summary>
/// Registers the token cache with client application.
/// </summary>
/// <param name="client">The client application to be used when registering the token cache.</param>
public override void RegisterCache(IClientApplicationBase client)
{
ServiceClientTracing.Information("Registering the in-memory token cache.");
base.RegisterCache(client);
}
}
} |
using ChatBackend.Auth;
using ChatBackend.Dto;
using ChatBackend.Middleware.Auth;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace ChatBackend.Controllers
{
[ApiController]
[Route("auth")]
[EnableCors]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
private readonly ILoginOrchestrator _loginOrchestrator;
private readonly ILogoutOrchestrator _logoutOrchestrator;
private readonly ILoggedInUserProvider _loggedInUserProvider;
private readonly IUserNameSanitizer _userNameSanitizer;
private readonly IUserCreator _userCreator;
private readonly ICreatedUserResponseMapper _createdUserResponseMapper;
public AuthController(
ILogger<AuthController> logger,
IUserCreator userCreator,
ICreatedUserResponseMapper createdUserResponseMapper,
IUserNameSanitizer userNameSanitizer,
ILoginOrchestrator loginOrchestrator,
ILogoutOrchestrator logoutOrchestrator,
ILoggedInUserProvider loggedInUserProvider)
{
_logger = logger;
_userCreator = userCreator;
_createdUserResponseMapper = createdUserResponseMapper;
_userNameSanitizer = userNameSanitizer;
_loginOrchestrator = loginOrchestrator;
_logoutOrchestrator = logoutOrchestrator;
_loggedInUserProvider = loggedInUserProvider;
}
[HttpGet]
[Authorize]
[Route("data")]
public IActionResult DoCheck()
{
return Ok("here's some data");
}
[HttpPost]
[Route("authenticate")]
public async Task<LoginResponse> DoLogin([FromBody] UserCredentials rawUserCredentials)
{
var sanitizedUserName = _userNameSanitizer.Sanitize(rawUserCredentials.UserName);
var userCredentials = new UserCredentials(sanitizedUserName);
var loginResult = await _loginOrchestrator.DoLogin(userCredentials);
Response.Cookies.Append("Chat-Auth", loginResult.Token);
if (loginResult.UserLoginState != UserLoginState.JustAuthorized &&
loginResult.UserLoginState != UserLoginState.WasAlreadyAuthorized)
{
return new LoginResponse()
{
Success = false
};
}
var loginResponse = new LoginResponse()
{
Id = loginResult.UserId,
LoggedInUsername = sanitizedUserName,
LoggedInScreenName = loginResult.LoggedInScreenName,
Success = true,
Token = loginResult.Token
};
return loginResponse;
}
[HttpPost]
[Authorize]
[Route("logout")]
public IActionResult DoLogout()
{
var loggedInUser = _loggedInUserProvider.GetUserForCurrentRequest(this);
var loggedInUserName = loggedInUser.Username;
_logoutOrchestrator.DoLogout(loggedInUserName);
return Ok();
}
[HttpPost]
[Route("create-user")]
public async Task<CreatedUserResponse> CreateUser([FromBody] CreateUserInput user)
{
_logger.LogInformation($"User creation request for username {user.UserName} [{user.ScreenName}]");
var createUserResponse = await _userCreator.CreateUser(user);
if (!createUserResponse.UserCreated)
{
throw new ApplicationException(createUserResponse.UserNotCreatedReason);
}
var createdUserResponse = _createdUserResponseMapper.Map(createUserResponse);
return createdUserResponse;
}
}
}
|
using System.Text.RegularExpressions;
namespace Harbor.Tagd.Extensions
{
public static class StringExtensions
{
public static Regex ToCompiledRegex(this string input, RegexOptions options = RegexOptions.None) =>
string.IsNullOrEmpty(input) ? null : new Regex(input, options | RegexOptions.Compiled);
public static bool Matches(this string input, Regex regex) => regex.IsMatch(input);
}
}
|
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
internal static class TaskExtensions
{
private static readonly Action<Task> observeErrors = ObverveErrors;
private static void ObverveErrors(this Task task)
{
if (task != null) GC.KeepAlive(task.Exception);
}
public static Task ObserveErrors(this Task task)
{
task?.ContinueWith(observeErrors, TaskContinuationOptions.OnlyOnFaulted);
return task;
}
public static Task<T> ObserveErrors<T>(this Task<T> task)
{
task?.ContinueWith(observeErrors, TaskContinuationOptions.OnlyOnFaulted);
return task;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredTaskAwaitable ForAwait(this Task task) => task.ConfigureAwait(false);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredValueTaskAwaitable ForAwait(this in ValueTask task) => task.ConfigureAwait(false);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredTaskAwaitable<T> ForAwait<T>(this Task<T> task) => task.ConfigureAwait(false);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredValueTaskAwaitable<T> ForAwait<T>(this in ValueTask<T> task) => task.ConfigureAwait(false);
internal static void RedisFireAndForget(this Task task) => task?.ContinueWith(t => GC.KeepAlive(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
// Inspired from https://github.com/dotnet/corefx/blob/81a246f3adf1eece3d981f1d8bb8ae9de12de9c6/src/Common/tests/System/Threading/Tasks/TaskTimeoutExtensions.cs#L15-L43
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
public static async Task<bool> TimeoutAfter(this Task task, int timeoutMs)
{
var cts = new CancellationTokenSource();
if (task == await Task.WhenAny(task, Task.Delay(timeoutMs, cts.Token)).ForAwait())
{
cts.Cancel();
await task.ForAwait();
return true;
}
else
{
return false;
}
}
}
}
|
using ApplicationCore.Helpers;
using ApplicationCore.Interfaces.Repository;
using ApplicationCore.Models;
using ApplicationCore.Services;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Infrastructure.Data.Repositories
{
public class DeviceRepository : GenericRepository<Device>, IDeviceRepository
{
public DeviceRepository(ApplicationDbContext context) : base(context) { }
public async Task<IEnumerable<Device>> GetDevicesWithTypeAsync(PagingParams pagingParams)
{
var devices = _context.Devices.Include(x => x.DeviceType)
.ThenInclude(x => x.DeviceTypeProperties)
.ThenInclude(x => x.DevicePropertyValue).AsQueryable();
DeviceSearchService deviceSearchService = new DeviceSearchService();
var result = deviceSearchService.GetDevicesByParams(devices, pagingParams);
return await PagedList<Device>.CreateAsync(result, pagingParams.PageNumber, pagingParams.PageSize);
}
public async Task<Device> GetDeviceWithTypePropertyValueAsync(int id)
{
return await _context.Devices.Include(x => x.DeviceType.Parent)
.ThenInclude(x => x.DeviceTypeProperties)
.ThenInclude(x => x.DevicePropertyValue)
.Include(x => x.DeviceType)
.ThenInclude(x => x.DeviceTypeProperties)
.ThenInclude(x => x.DevicePropertyValue).FirstOrDefaultAsync(x => x.Id == id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Castle.Components.DictionaryAdapter.Xml;
namespace MIMWebClient.Core.Player.Skills
{
using MIMWebClient.Core.Events;
using MIMWebClient.Core.PlayerSetup;
using MIMWebClient.Core.Room;
public class Haste : Skill
{
private static bool _taskRunnning = false;
private static Player _target = new Player();
public static Skill HasteSkill { get; set; }
public static void StartHaste(Player player, Room room, string target = "")
{
//Check if player has spell
var hasSpell = Skill.CheckPlayerHasSkill(player, HasteAb().Name);
if (hasSpell == false)
{
HubContext.Instance.SendToClient("You don't know that spell.", player.HubGuid);
return;
}
var canDoSkill = Skill.CanDoSkill(player);
if (!canDoSkill)
{
return;
}
player.Status = Player.PlayerStatus.Busy;
_target = Skill.FindTarget(target, room);
//Fix issue if target has similar name to user and they use abbrivations to target them
if (_target == player)
{
_target = null;
}
if (!_taskRunnning && _target != null)
{
if (player.ManaPoints < HasteAb().ManaCost)
{
HubContext.Instance.SendToClient("You fail to concentrate due to lack of mana.", player.HubGuid);
return;
}
//TODO REfactor
player.ManaPoints -= HasteAb().ManaCost;
Score.UpdateUiPrompt(player);
HubContext.Instance.SendToClient("You utter citus multo festina.", player.HubGuid);
foreach (var character in room.players)
{
if (character != player)
{
var roomMessage = $"{ Helpers.ReturnName(player, character, string.Empty)} utters citus multo festina.";
HubContext.Instance.SendToClient(roomMessage, character.HubGuid);
}
}
Task.Run(() => DoHaste(player, room));
}
else
{
if (_target == null)
{
if (player.ManaPoints < HasteAb().ManaCost)
{
HubContext.Instance.SendToClient("You attempt to draw energy but fail", player.HubGuid);
return;
}
//TODO REfactor
player.ManaPoints -= HasteAb().ManaCost;
Score.UpdateUiPrompt(player);
HubContext.Instance.SendToClient("You utter citus multo festina.", player.HubGuid);
foreach (var character in room.players)
{
if (character != player)
{
var hisOrHer = Helpers.ReturnHisOrHers(player, character);
var roomMessage = $"{ Helpers.ReturnName(player, character, string.Empty)} utters citus multo festina.";
HubContext.Instance.SendToClient(roomMessage, character.HubGuid);
}
}
Task.Run(() => DoHaste(player, room));
}
}
}
private static async Task DoHaste(Player attacker, Room room)
{
_taskRunnning = true;
attacker.Status = Player.PlayerStatus.Busy;
var hasteAff = new Effect
{
Name = "Haste",
Duration = attacker.Level + 5,
AffectLossMessagePlayer = "Your body begins to slow down.",
AffectLossMessageRoom = $" begins to slow down."
};
await Task.Delay(500);
try
{
if (_target == null)
{
var castingTextAttacker = "You begin to move much faster.";
HubContext.Instance.SendToClient(castingTextAttacker, attacker.HubGuid);
foreach (var character in room.players.ToList())
{
if (character != attacker)
{
var roomMessage =
$"{Helpers.ReturnName(attacker, character, string.Empty)} starts to blur as they move faster.";
HubContext.Instance.SendToClient(roomMessage, character.HubGuid);
}
}
if (attacker.Effects == null)
{
attacker.Effects = new List<Effect> {hasteAff};
}
else
{
attacker.Effects.Add(hasteAff);
}
Score.ReturnScoreUI(attacker);
Score.UpdateUiAffects(attacker);
}
else
{
var castingTextAttacker = Helpers.ReturnName(_target, attacker, null) +
" starts to blur as they move faster.";
var castingTextDefender = "You begin to move much faster.";
HubContext.Instance.SendToClient(castingTextAttacker, attacker.HubGuid);
HubContext.Instance.SendToClient(castingTextDefender, _target.HubGuid);
foreach (var character in room.players.ToList())
{
if (character != attacker || character != _target)
{
var roomMessage =
$"{Helpers.ReturnName(_target, character, string.Empty)} starts to blur as they move faster.";
HubContext.Instance.SendToClient(roomMessage, character.HubGuid);
}
}
if (_target.Effects == null)
{
_target.Effects = new List<Effect> {hasteAff};
}
else
{
_target.Effects.Add(hasteAff);
}
Score.UpdateUiAffects(_target);
Score.ReturnScoreUI(_target);
}
Player.SetState(attacker);
}
catch (Exception ex)
{
var log = new Error.Error
{
Date = DateTime.Now,
ErrorMessage = ex.Message.ToString(),
MethodName = "haste"
};
Save.LogError(log);
}
_target = null;
_taskRunnning = false;
}
public static Skill HasteAb()
{
var skill = new Skill
{
Name = "Haste",
SpellGroup = SpellGroupType.Transmutation,
SkillType = Type.Spell,
CoolDown = 0,
Delay = 0,
LevelObtained = 2,
ManaCost = 10,
Passive = false,
Proficiency = 1,
MaxProficiency = 95,
UsableFromStatus = "Standing",
Syntax = "cast haste / cast haste <Target>"
};
var help = new Help
{
Syntax = skill.Syntax,
HelpText = "Increases your dexterity and speed in performing actions",
DateUpdated = "20/04/2017"
};
skill.HelpText = help;
return skill;
}
}
}
|
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// AlipayMerchantOrderRefundModel Data Structure.
/// </summary>
public class AlipayMerchantOrderRefundModel : AlipayObject
{
/// <summary>
/// 业务场景,某些场景下操作的不是用户本身的订单,而是用户所在群体的订单的情况下,必传
/// </summary>
[JsonPropertyName("biz_scene")]
public string BizScene { get; set; }
/// <summary>
/// 下单时候的买家id
/// </summary>
[JsonPropertyName("buyer")]
public UserIdentity Buyer { get; set; }
/// <summary>
/// 退款扩展信息
/// </summary>
[JsonPropertyName("ext_info")]
public List<OrderExtInfo> ExtInfo { get; set; }
/// <summary>
/// 下单并支付的时候返回的订单号,与外部请求号两者之间必须传一个
/// </summary>
[JsonPropertyName("order_id")]
public string OrderId { get; set; }
/// <summary>
/// 创建订单时传入的外部请求号
/// </summary>
[JsonPropertyName("out_biz_no")]
public string OutBizNo { get; set; }
/// <summary>
/// 退款原因描述,可能是用户发起退款、或者是系统异常发起的回补退款
/// </summary>
[JsonPropertyName("refund_reason")]
public string RefundReason { get; set; }
/// <summary>
/// 退款请求,比如下面的请求代表在这次退款中退2000家庭积分[{"request_no":"2019678438","amount":{"type":"FAMILY_POINT","amount":2000}}]。之所以是一个list是为了支持多笔退款,退款失败重试请不要更换request_no。单次全额退的request_no可以用out_biz_no
/// </summary>
[JsonPropertyName("refund_request")]
public List<PaymentInformation> RefundRequest { get; set; }
}
}
|
using CropsNDrops.Scripts.Enum;
using CropsNDrops.Scripts.Scriptables.Inventory.CropsNDrops.Scripts.Scriptables;
using CropsNDrops.Scripts.Tools;
using UnityEngine;
using UnityEngine.UI;
namespace CropsNDrops.Scripts.UI
{
public class Item : MonoBehaviour
{
[Header("Definitions")]
[SerializeField] private GameObject _selector = default;
[SerializeField] private Image _image = default;
[Header("Informations")]
[SerializeField] private ItemDisplay _display = default;
[SerializeField] private Transform _parent = default;
[SerializeField] private ItemType _type = default;
[SerializeField] private bool _isCaught = default;
//[SerializeField] private ActionArea _area = default;
private void Update()
{
if (!_isCaught)
{
transform.position = Utils.Centralize(_parent.position, transform.position);
}
}
public void Initialize(ItemDisplay display)
{
_display = display;
if (_display)
{
name = display.name;
_parent = transform.parent;
_image.sprite = _display.sprite;
_type = _display.type;
//_area = _display.area;
_isCaught = false;
transform.localPosition = Vector3.zero;
}
else
{
Destroy(gameObject);
}
}
public bool IsCaught
{
set { _isCaught = value; }
}
public ItemType Type
{
get { return _type; }
}
public ItemDisplay Display
{
get { return _display; }
}
public bool ActiveSelector
{
set { _selector.SetActive((value)); }
}
}
} |
using System.Windows.Media;
namespace MyPad.Views.Components
{
public class TextView : ICSharpCode.AvalonEdit.Rendering.TextView
{
public TextView()
{
// HACK: 依存関係プロパティ ColumnRulerPen の設定
// おそらく SearchPanel.MarkerBrush と似たような理由だと思われる。
this.ColumnRulerPen = new Pen(Brushes.DimGray, 2);
}
}
}
|
using System;
using System.Collections.Generic;
using Akka;
using Akka.Actor;
using Akka.Cluster;
using Akka.Persistence;
using Cik.Magazine.Shared.Messages;
namespace Cik.Magazine.Shared.Domain
{
public class AggregateRootCreationParameters
{
public AggregateRootCreationParameters(Guid id, IActorRef projections, ISet<IActorRef> processManagers,
int snapshotThreshold = 250)
{
Id = id;
Projections = projections;
ProcessManagers = processManagers;
SnapshotThreshold = snapshotThreshold;
}
public Guid Id { get; }
public IActorRef Projections { get; }
public ISet<IActorRef> ProcessManagers { get; }
public int SnapshotThreshold { get; }
}
public abstract class AggregateRootActor : PersistentActor, IEventSink
{
protected Cluster Cluster = Cluster.Get(Context.System);
private readonly Guid _id;
private readonly IActorRef _projections;
private readonly int _snapshotThreshold;
protected readonly ISet<IActorRef> ProcessManagers;
protected AggregateRootActor(AggregateRootCreationParameters parameters)
{
_id = parameters.Id;
_projections = parameters.Projections;
_snapshotThreshold = parameters.SnapshotThreshold;
ProcessManagers = parameters.ProcessManagers;
}
public override string PersistenceId => $"{GetType().Name}-agg-{_id:n}".ToLowerInvariant();
private long LastSnapshottedVersion { get; set; }
void IEventSink.Publish(IEvent @event)
{
Persist(@event, e =>
{
Apply(e);
_projections.Tell(@event);
Self.Tell(SaveAggregate.Message); // save the snapshot if it is possible
});
}
protected override bool ReceiveRecover(object message)
{
return message.Match()
.With<RecoveryCompleted>(x => { Log.Debug("Recovered state to version {0}", LastSequenceNr); })
.With<SnapshotOffer>(offer =>
{
Log.Debug("State loaded from snapshot");
LastSnapshottedVersion = offer.Metadata.SequenceNr;
RecoverState(offer.Snapshot);
})
.With<IEvent>(x => Apply(x))
.WasHandled;
}
protected override bool ReceiveCommand(object message)
{
return message.Match()
.With<SaveAggregate>(x => Save())
.With<SaveSnapshotSuccess>(success =>
{
Log.Debug("Saved snapshot");
DeleteMessages(success.Metadata.SequenceNr);
})
.With<SaveSnapshotFailure>(failure =>
{
// handle snapshot save failure...
})
.With<ICommand>(command =>
{
try
{
var handled = Handle(command);
Sender.Tell(new CommandResponse(handled));
}
catch (DomainException e)
{
Sender.Tell(e);
}
}).WasHandled;
}
protected override void PreStart()
{
Cluster.Subscribe(Self, typeof(ClusterEvent.MemberUp));
Log.Info("PM [{0}]: Send from {1}", Cluster.SelfAddress, Sender);
base.PreStart();
}
protected override void PostStop()
{
Cluster.Unsubscribe(Self);
base.PostStop();
}
private bool Save()
{
if (LastSequenceNr - LastSnapshottedVersion >= _snapshotThreshold)
SaveSnapshot(GetState());
return true;
}
protected abstract bool Handle(ICommand command);
protected abstract bool Apply(IEvent @event);
protected abstract void RecoverState(object state);
protected abstract object GetState();
}
} |
#region Using directives
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Blazorise.RichTextEdit
{
/// <summary>
/// Base <see cref="Blazorise.RichTextEdit"/> component
/// </summary>
public class BaseRichTextEditComponent : BaseComponent
{
#region Constructors
/// <summary>
/// Creates a new <see cref="BaseRichTextEditComponent"/>
/// </summary>
protected BaseRichTextEditComponent() { }
#endregion
#region Methods
/// <summary>
/// Executes given action after the rendering is done.
/// </summary>
/// <remarks>Don't await this on the UI thread, because that will cause a deadlock.</remarks>
protected async Task<T> ExecuteAfterRender<T>( Func<Task<T>> action, CancellationToken token = default )
{
var source = new TaskCompletionSource<T>();
token.Register( () => source.TrySetCanceled() );
ExecuteAfterRender( async () =>
{
try
{
var result = await action();
source.TrySetResult( result );
}
catch ( TaskCanceledException )
{
source.TrySetCanceled();
}
catch ( Exception e )
{
source.TrySetException( e );
}
} );
return await source.Task.ConfigureAwait( false );
}
#endregion
}
}
|
using System;
using System.Linq;
using System.Text.Json;
using Forms.Infrastructure.CloudFoundry.Models;
using StackExchange.Redis;
namespace Forms.Infrastructure.CloudFoundry
{
public static class CloudFoundryConnectionHelpers
{
public static ConnectionMultiplexer CreateRedisConnection()
{
// Grab the Environment Variable from Cloud Foundry and parse the services
var paasServices = Environment.GetEnvironmentVariable("VCAP_SERVICES");
var paasServicesAsJson = JsonSerializer.Deserialize<PaasServices>(paasServices);
var credentials = paasServicesAsJson.Redis.First().Credentials;
var configOptions = new ConfigurationOptions
{
EndPoints = {{credentials.Host, credentials.Port}},
Password = credentials.Password,
Ssl = credentials.TlsEnabled
};
return ConnectionMultiplexer.Connect(configOptions);
}
}
} |
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
namespace Financier.DataAccess.Data
{
[DebuggerDisplay("{Title}")]
[Table(Backup.ATTRIBUTES_TABLE)]
public class AttributeDefinition : Entity, IIdentity
{
public const int TYPE_TEXT = 1;
public const int TYPE_NUMBER = 2;
public const int TYPE_LIST = 3;
public const int TYPE_CHECKBOX = 4;
[Column(IdColumn)]
public int Id { get; set; } = -1;
[Column("type")]
public int Type { get; set; }
[Column(IsActiveColumn)]
public bool IsActive { get; set; } = true;
[Column(TitleColumn)]
public string Title { get; set; }
[Column("list_values")]
public string ListValues { get; set; }
[Column("default_value")]
public string DefaultValue { get; set; }
[NotMapped]
public long UpdatedOn { get; set; }
}
}
|
public static class XmlExtensions
{
public static void AppendChild(this System.Xml.XmlNode node, string name, string value)
{
System.Xml.XmlElement child = node.OwnerDocument.CreateElement(name);
child.AppendChild(node.OwnerDocument.CreateTextNode(value));
node.AppendChild(child);
}
public static void AppendChild(this System.Xml.XmlNode node, string name, int value)
{
node.AppendChild(name, value.ToString());
}
public static void AppendChild(this System.Xml.XmlNode node, string name, uint value)
{
node.AppendChild(name, value.ToString());
}
public static void AppendChild(this System.Xml.XmlNode node, string name, bool value)
{
node.AppendChild(name, value.ToString());
}
public static void ToInt(this System.Xml.XmlNode root, string name, ref int value)
{
if (root[name] == null) return;
value = root[name].InnerText.SoftParse(value);
}
public static void ToString(this System.Xml.XmlNode root, string name, ref string value)
{
if (root[name] == null) return;
value = root[name].InnerText;
}
public static void ToBool(this System.Xml.XmlNode root, string name, ref bool value)
{
if (root[name] == null) return;
value = root[name].InnerText.SoftParse(value);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenKh.Engine.Parsers.Kddf2
{
public class Kkdf2MdlxBuiltModel
{
public SortedDictionary<int, Model> textureIndexBasedModelDict;
public Kkdf2MdlxParser parser;
}
}
|
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace JJerkBot.Modules
{
public class HelloCommand : ICommand
{
public string Name => "hello";
public string Description => "Greets people.";
public string[] Alias => new []{ "hi", "hey" };
public bool Hide => false;
public Parameter[] Parameters => new []
{
new Parameter("name", ParameterType.Optional),
};
public bool Check(Command command, User user, Channel channel) => true;
public async Task Do(CommandEventArgs args)
{
var parameter = args.GetArg("name");
if (string.IsNullOrEmpty(parameter))
await args.Channel.SendMessage($"Hello {args.Message.User.Mention}");
else
await args.Channel.SendMessage($"Hello {parameter}");
}
}
}
|
using System;
namespace Hinode.Izumi.Data.Enums.DiscordEnums
{
public enum DiscordContext : byte
{
Guild = 1,
DirectMessage = 2,
Group = 3
}
public static class IzumiDiscordContextHelper
{
public static string Localize(this DiscordContext context) => context switch
{
// выводится в сообщениях об ошибке, необходимо склонение "в *контекст*"
DiscordContext.Guild => "канале сервера",
DiscordContext.DirectMessage => "личном сообщении",
DiscordContext.Group => "беседе",
_ => throw new ArgumentOutOfRangeException(nameof(context), context, null)
};
}
}
|
using Android.Content;
using Android.Runtime;
using Java.Util.Concurrent;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndroidX.Work
{
public partial class OneTimeWorkRequest
{
public static OneTimeWorkRequest From<TWorker>() where TWorker : AndroidX.Work.Worker
=> From(typeof(TWorker));
public static OneTimeWorkRequest From(Type type)
=> From(Java.Lang.Class.FromType(type));
public partial class Builder
{
public Builder(Type type)
: this(Java.Lang.Class.FromType(type))
{
}
public static Builder From<TWorker>() where TWorker : AndroidX.Work.Worker
=> new Builder(Java.Lang.Class.FromType(typeof(TWorker)));
// The base type returns a WorkRequest.Builder and we want it to return OneTimeWorkRequest.Builder instead
#region Base Builder New Implementations
public new OneTimeWorkRequest Build()
=> base.Build().JavaCast<OneTimeWorkRequest>();
public new Builder AddTag(string tag)
=> base.AddTag(tag).JavaCast<Builder>();
public new Builder KeepResultsForAtLeast(long duration, TimeUnit timeUnit)
=> base.KeepResultsForAtLeast(duration, timeUnit).JavaCast<Builder>();
public Builder KeepResultsForAtLeast(TimeSpan duration)
=> base.KeepResultsForAtLeast((long)duration.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
public new Builder SetBackoffCriteria(BackoffPolicy policy, long backoffDelay, TimeUnit timeUnit)
=> base.SetBackoffCriteria(policy, backoffDelay, timeUnit).JavaCast<Builder>();
public Builder SetBackoffCriteria(BackoffPolicy policy, TimeSpan backoffDelay)
=> base.SetBackoffCriteria(policy, (long)backoffDelay.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
public new Builder SetConstraints(Constraints constraints)
=> base.SetConstraints(constraints).JavaCast<Builder>();
public new Builder SetInitialRunAttemptCount(int runAttemptCount)
=> base.SetInitialRunAttemptCount(runAttemptCount).JavaCast<Builder>();
public new Builder SetInitialState(WorkInfo.State state)
=> base.SetInitialState(state).JavaCast<Builder>();
public new Builder SetInputData(Data data)
=> base.SetInputData(data).JavaCast<Builder>();
public new Builder SetPeriodStartTime(long periodStartTime, TimeUnit timeUnit)
=> base.SetPeriodStartTime(periodStartTime, timeUnit).JavaCast<Builder>();
public Builder SetPeriodStartTime(TimeSpan periodStartTime)
=> base.SetPeriodStartTime((long)periodStartTime.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
public new Builder SetScheduleRequestedAt(long scheduleRequestedAt, TimeUnit timeUnit)
=> base.SetPeriodStartTime(scheduleRequestedAt, timeUnit).JavaCast<Builder>();
public Builder SetScheduleRequestedAt(TimeSpan scheduleRequestedAt)
=> base.SetPeriodStartTime((long)scheduleRequestedAt.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
#endregion
}
}
public partial class PeriodicWorkRequest
{
public partial class Builder
{
public Builder(Type type, long repeatInterval, TimeUnit repeatIntervalTimeUnit)
: this(Java.Lang.Class.FromType(type), repeatInterval, repeatIntervalTimeUnit)
{ }
public Builder(Type type, long repeatInterval, TimeUnit repeatIntervalTimeUnit, long flexInterval, TimeUnit flexIntervalTimeUnit)
: this(Java.Lang.Class.FromType(type), repeatInterval, repeatIntervalTimeUnit, flexInterval, flexIntervalTimeUnit)
{ }
public Builder(Type type, TimeSpan repeatInterval)
: this(Java.Lang.Class.FromType(type), (long)repeatInterval.TotalMilliseconds, TimeUnit.Milliseconds)
{ }
public Builder(Type type, TimeSpan repeatInterval, TimeSpan flexInterval)
: this(Java.Lang.Class.FromType(type), (long)repeatInterval.TotalMilliseconds, TimeUnit.Milliseconds, (long)flexInterval.TotalMilliseconds, TimeUnit.Milliseconds)
{ }
public static Builder From<TWorker>(long repeatInterval, TimeUnit repeatIntervalTimeUnit) where TWorker : AndroidX.Work.Worker
=> new Builder(typeof(TWorker), repeatInterval, repeatIntervalTimeUnit);
public static Builder From<TWorker>(TimeSpan repeatInterval) where TWorker : AndroidX.Work.Worker
=> new Builder(typeof(TWorker), (long)repeatInterval.TotalMilliseconds, TimeUnit.Milliseconds);
public static Builder From<TWorker>(long repeatInterval, TimeUnit repeatIntervalTimeUnit, long flexInterval, TimeUnit flexIntervalTimeUnit) where TWorker : AndroidX.Work.Worker
=> new Builder(typeof(TWorker), repeatInterval, repeatIntervalTimeUnit, flexInterval, flexIntervalTimeUnit);
public static Builder From<TWorker>(TimeSpan repeatInterval, TimeSpan flexInterval) where TWorker : AndroidX.Work.Worker
=> new Builder(typeof(TWorker), (long)repeatInterval.TotalMilliseconds, TimeUnit.Milliseconds, (long)flexInterval.TotalMilliseconds, TimeUnit.Milliseconds);
// The base type returns a WorkRequest.Builder and we want it to return PeriodicWorkRequest.Builder instead
#region Base Builder New Implementations
public new PeriodicWorkRequest Build()
=> base.Build().JavaCast<PeriodicWorkRequest>();
public new Builder AddTag(string tag)
=> base.AddTag(tag).JavaCast<Builder>();
public new Builder KeepResultsForAtLeast(long duration, TimeUnit timeUnit)
=> base.KeepResultsForAtLeast(duration, timeUnit).JavaCast<Builder>();
public Builder KeepResultsForAtLeast(TimeSpan duration)
=> base.KeepResultsForAtLeast((long)duration.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
public new Builder SetBackoffCriteria(BackoffPolicy policy, long backoffDelay, TimeUnit timeUnit)
=> base.SetBackoffCriteria(policy, backoffDelay, timeUnit).JavaCast<Builder>();
public Builder SetBackoffCriteria(BackoffPolicy policy, TimeSpan backoffDelay)
=> base.SetBackoffCriteria(policy, (long)backoffDelay.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
public new Builder SetConstraints(Constraints constraints)
=> base.SetConstraints(constraints).JavaCast<Builder>();
public new Builder SetInitialRunAttemptCount(int runAttemptCount)
=> base.SetInitialRunAttemptCount(runAttemptCount).JavaCast<Builder>();
public new Builder SetInitialState(WorkInfo.State state)
=> base.SetInitialState(state).JavaCast<Builder>();
public new Builder SetInputData(Data data)
=> base.SetInputData(data).JavaCast<Builder>();
public new Builder SetPeriodStartTime(long periodStartTime, TimeUnit timeUnit)
=> base.SetPeriodStartTime(periodStartTime, timeUnit).JavaCast<Builder>();
public Builder SetPeriodStartTime(TimeSpan periodStartTime)
=> base.SetPeriodStartTime((long)periodStartTime.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
public new Builder SetScheduleRequestedAt(long scheduleRequestedAt, TimeUnit timeUnit)
=> base.SetPeriodStartTime(scheduleRequestedAt, timeUnit).JavaCast<Builder>();
public Builder SetScheduleRequestedAt(TimeSpan scheduleRequestedAt)
=> base.SetPeriodStartTime((long)scheduleRequestedAt.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
#endregion
}
}
public partial class Constraints
{
public partial class Builder
{
public Builder AddContentUriTrigger(System.Uri uri, bool triggerForDescendants)
=> this.AddContentUriTrigger(Android.Net.Uri.Parse(uri.OriginalString), triggerForDescendants).JavaCast<Builder>();
public Builder SetTriggerContentMaxDelay(TimeSpan duration)
=> this.SetTriggerContentMaxDelay((long)duration.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
public Builder SetTriggerContentUpdateDelay(TimeSpan duration)
=> this.SetTriggerContentUpdateDelay((long)duration.TotalMilliseconds, TimeUnit.Milliseconds).JavaCast<Builder>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;
public class MvcController : Controller {
[OutputCache(Duration = 60, VaryByParam = "none", Location = OutputCacheLocation.ServerAndClient)]
public ActionResult Index() {
this.ViewData["generated-at"] = DateTime.Now;
return View();
}
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult Ping() {
return Content("hello", "text/plain");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class ShaderGUIBase : ShaderGUI
{
protected MaterialEditor _editor;
protected MaterialProperty[] _properties;
private static GUIContent _staticLabel = new GUIContent();
protected GUIContent MakeLabel(MaterialProperty property, string tooltip = null)
{
return MakeLabel(property.displayName, tooltip);
}
protected GUIContent MakeLabel(string text, string tooltip = null)
{
_staticLabel.text = text;
_staticLabel.tooltip = tooltip;
return _staticLabel;
}
protected void SetKeyword(string keyword, bool state)
{
foreach (Material target in _editor.targets)
{
if (target)
{
if (state)
{
target.EnableKeyword(keyword);
}
else
{
target.DisableKeyword(keyword);
}
}
}
}
protected bool IsKeywordEnable(string keyword)
{
var target = _editor.target as Material;
return target.IsKeywordEnabled(keyword);
}
protected void RecordAction(string labal)
{
_editor.RegisterPropertyChangeUndo(labal);
}
}
|
using System;
namespace VS_Offline_Install_Cleaner
{
internal static class DirectorySize
{
public static string GetFolderSize(string folderPath)
{
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
Scripting.Folder folder = fso.GetFolder(folderPath);
dynamic dirSize = folder.Size;
long dirSizeInt = Convert.ToInt64(dirSize);
string dirSizeString = BytesToString(dirSizeInt);
return dirSizeString;
}
private static string BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num) + suf[place];
}
}
} |
namespace Core.Data
{
public interface IHtmlWidgetRepository : IRepository<HtmlWidget>
{
}
public class HtmlWidgetRepository : Repository<HtmlWidget>, IHtmlWidgetRepository
{
AppDbContext _db;
public HtmlWidgetRepository(AppDbContext db) : base(db)
{
_db = db;
}
}
}
|
using MarbleBot.Common.Games.Scavenge;
using MarbleBot.Common.Games.Siege;
using MarbleBot.Common.Games.War;
using System.Collections.Concurrent;
namespace MarbleBot.Modules.Games.Services
{
public class GamesService
{
public ConcurrentDictionary<ulong, Scavenge> Scavenges { get; set; } = new();
public ConcurrentDictionary<ulong, Siege> Sieges { get; set; } = new();
public ConcurrentDictionary<ulong, War> Wars { get; set; } = new();
}
}
|
using System;
using System.IO;
using System.Linq;
using ChromeCast.Desktop.AudioStreamer.Application.Interfaces;
using NAudio.Lame;
using NAudio.Wave;
namespace ChromeCast.Desktop.AudioStreamer.Classes
{
/// <summary>
/// MP3 encode a WAV stream.
/// </summary>
public class Mp3Stream
{
private MemoryStream Output { get; set; }
private LameMP3FileWriter Writer { get; set; }
private ILogger Logger { get; set; }
/// <summary>
/// Setup MP3 encoding with the selected WAV and stream formats.
/// </summary>
/// <param name="format">the WAV input format</param>
/// <param name="formatSelected">the mp3 output format</param>
public Mp3Stream(WaveFormat format, SupportedStreamFormat formatSelected, ILogger loggerIn)
{
Logger = loggerIn;
Output = new MemoryStream();
var bitRate = 128;
if (formatSelected.Equals(SupportedStreamFormat.Mp3_320))
bitRate = 320;
Writer = new LameMP3FileWriter(Output, format, bitRate);
}
/// <summary>
/// Add WAV data that should be encoded.
/// </summary>
/// <param name="buffer"></param>
public void Encode(byte[] buffer)
{
if (Writer == null || buffer == null)
return;
try
{
var writeBuffer = buffer.ToArray();
lock(Writer)
{
Writer.Write(writeBuffer, 0, writeBuffer.Length);
}
}
catch (Exception ex)
{
Logger.Log(ex, "Mp3Stream.Encode");
}
}
/// <summary>
/// Read the data that's encoded in MP3 format.
/// </summary>
/// <returns></returns>
public byte[] Read()
{
if (Output == null)
return new byte[0];
var byteArray = Output.ToArray();
Output.SetLength(0);
return byteArray;
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
// Sometimes you get a AccessViolationException when disposing Writer.
//try
//{
// Writer?.Dispose();
// Writer = null;
// Output?.Dispose();
// Output = null;
//}
//catch (Exception)
//{
//}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheckPoint : MonoBehaviour
{
public bool _reached = false;
Material _material;
private void Awake()
{
_material = GetComponent<Renderer>()?.material;
}
void Start()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.tag != "Player" || _reached == true)
return;
_reached = true;
if (_material != null)
_material.color = Color.green;
GlobalRefHolder.s_instance._checkPointController?.CheckPointReached(this);
}
public void ResetToDefault()
{
_reached = false;
if (_material != null)
_material.color = Color.red;
}
}
|
namespace Interfaces
{
public interface IThing
{
}
}
|
using Qurre.API.Events;
using Qurre.Events.Modules;
namespace Qurre.Events
{
public static class Round
{
public static event Main.AllEvents Waiting;
public static event Main.AllEvents Start;
public static event Main.AllEvents Restart;
public static event Main.AllEvents<RoundEndEvent> End;
public static event Main.AllEvents<CheckEvent> Check;
public static event Main.AllEvents<TeamRespawnEvent> TeamRespawn;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using SceneLoadingSystem;
/// <summary>
/// Main class for sceneloader.
///
/// Holds all ui and logic objects.
/// </summary>
public class SceneLoader : MonoBehaviour
{
[SerializeField]
private GameObject hintManager = null;
[SerializeField]
private GameObject loadingScreen = null;
[SerializeField]
private GameObject transitionManager = null;
private Canvas loadingCanvas;
private AsyncOperation operation;
private Slider slider;
private Text progressText;
private Text hint;
private HintManager hints;
private int sceneIndex;
private event LevelTransition.EventTransitionFinished OnSuchEvent;
private void EventHandlingTransitionFinished()
{
LoadScene();
}
private void LoadScene()
{
operation = SceneManager.LoadSceneAsync(sceneIndex);
StartCoroutine(LoadAsynchronously(sceneIndex));
}
private void Start()
{
loadingCanvas = loadingScreen.GetComponent<LoadingScreen>().GetLoadingCanvas();
slider = loadingScreen.GetComponent<LoadingScreen>().GetSlider();
progressText = loadingScreen.GetComponent<LoadingScreen>().GetSliderPercentageText();
hint = loadingScreen.GetComponent<LoadingScreen>().GetHintText();
hints = hintManager.GetComponent<HintManager>();
OnSuchEvent += EventHandlingTransitionFinished;
}
private IEnumerator LoadAsynchronously(int sceneIndex)
{
hint.text = hints.GetNextHint();
loadingCanvas.gameObject.SetActive(true);
float now = Time.time;
while (!operation.isDone)
{
if ((now + hints.GetHintTime()) <= Time.time)
{
hint.text = hints.GetNextHint();
now = Time.time;
}
float progress = Mathf.Clamp01(operation.progress / .9f);
progressText.text = ((int)(progress * 100)).ToString() + " %";
slider.value = progress;
yield return null;
}
}
public void DoTransition(int index)
{
sceneIndex = index;
transitionManager.GetComponent<LevelTransition>().FadeToOut(OnSuchEvent);
}
}
|
using System.Collections.Generic;
using Diablerie.Engine.IO.D2Formats;
using Diablerie.Engine.LibraryExtensions;
namespace Diablerie.Engine.Datasheets
{
[System.Serializable]
[Datasheet.Record]
public class ItemStat
{
public static List<ItemStat> sheet;
static Dictionary<string, ItemStat> map = new Dictionary<string, ItemStat>();
public static ItemStat Find(string code)
{
if (code == null)
return null;
return map.GetValueOrDefault(code);
}
public static void Load()
{
sheet = Datasheet.Load<ItemStat>("data/global/excel/ItemStatCost.txt");
foreach(var prop in sheet)
{
prop.descPositive = Translation.Find(prop.descStrPositive);
prop.descNegative = Translation.Find(prop.descStrNegative);
prop.desc2 = Translation.Find(prop.descStr2);
map.Add(prop.code, prop);
}
}
public string code;
public int id;
public int sendOther;
public bool signed;
public int sendBits;
public int sendParamBits;
public bool updateAnimRate;
public bool saved;
public bool csvSigned;
public int csvBits;
public int csvParam;
public bool fCallback;
public bool fMin;
public int minAccr;
public int encode;
public int add;
public int multiply;
public int divide;
public int valShift;
public int _1_09_SaveBits;
public int _1_09_SaveAdd;
public int saveBits;
public int saveAdd;
public int saveParamBits;
public int keepzero;
public int op;
public int opParam;
public string opBase;
public string opStat1;
public string opStat2;
public string opStat3;
public bool direct;
public string maxStat;
public int itemSpecific;
public int damageRelated;
public string itemEvent1;
public int itemEventFunc1;
public string itemEvent2;
public int itemEventFunc2;
public int descPriority;
public int descFunc;
public int descVal;
public string descStrPositive;
public string descStrNegative;
public string descStr2;
public int dgrp;
public int dgrpfunc;
public int dgrpval;
public string dgrpStrPositive;
public string dgrpStrNegative;
public string dgrpStr2;
public int stuff;
public string eol;
[System.NonSerialized]
public string descPositive;
[System.NonSerialized]
public string descNegative;
[System.NonSerialized]
public string desc2;
}
}
|
namespace Orleans.Consensus.Utilities
{
using System.Linq;
using Orleans.Consensus.Contract.Log;
public static class PersistentLogExtensions
{
public static string ProgressString<TOperation>(this IPersistentLog<TOperation> log)
{
return $"[{string.Join(", ", log.GetCursor(0).Select(_ => _.Id))}]";
}
}
} |
using System.Collections.ObjectModel;
namespace StartPagePlus.UI.ViewModels
{
using Options.Models;
public class StartViewModel : TabViewModel
{
public StartViewModel() : base()
{
Name = "Start";
Title = StartTabOptions.Instance.StartTabTitleText;
IsVisible = true;
Columns = new ObservableCollection<ColumnViewModel>
{
ViewModelLocator.RecentItemsViewModel,
ViewModelLocator.StartActionsViewModel,
ViewModelLocator.NewsItemsViewModel,
};
}
public ObservableCollection<ColumnViewModel> Columns { get; set; }
public bool ShowStartTabTitle
=> StartTabOptions.Instance.ShowStartTabTitle;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResolveScoreCommand : ICommand
{
private int _savedScore = -1;
private PlayerState _player;
private CustomerCardState _customer;
public static ResolveScoreCommand Create(
PlayerState player,
CustomerCardState customer)
{
ResolveScoreCommand command = new ResolveScoreCommand();
command._player = player;
command._customer = customer;
return command;
}
private ResolveScoreCommand()
{
}
public bool isLinked
{
get { return true; }
}
public void Execute()
{
_savedScore = _player.score;
_player.score += _customer.totalScore;
}
public void Undo()
{
_player.score = _savedScore;
}
}
|
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 dllPlanReport
{
public partial class frmTenants : Form
{
public int id_tenant = 0;
public string name_tenant = "";
public frmTenants()
{
InitializeComponent();
dgvTenants.AutoGenerateColumns = false;
}
DataTable dtTenants;
private void frmTenants_Load(object sender, EventArgs e)
{
Task<DataTable> task = Config.hCntMain.getTenants();
task.Wait();
dtTenants = task.Result;
dgvTenants.DataSource = dtTenants;
}
private void btnSelect_Click(object sender, EventArgs e)
{
DataRow dr = dtTenants.DefaultView[dgvTenants.CurrentRow.Index].Row;
id_tenant = (int)dr["id"];
name_tenant = dr["aren"].ToString();
this.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
void filter()
{
string filter = "";
try
{
if (tbTenant.Text.Length > 0)
filter += $"aren like '%{tbTenant.Text}%'";
}
catch
{
filter = "id = -1";
}
dtTenants.DefaultView.RowFilter = filter;
enabledButtons();
}
void enabledButtons()
{
btnSelect.Enabled = dgvTenants.CurrentRow != null;
}
private void tbTenant_TextChanged(object sender, EventArgs e)
{
filter();
}
}
}
|
using System.Text;
using System.Text.RegularExpressions;
namespace ThemesOfDotNet.Indexing.GitHub;
public readonly struct GitHubAreaPathExpression
{
private readonly Regex _regex;
public GitHubAreaPathExpression(string pattern)
{
ArgumentNullException.ThrowIfNull(pattern);
_regex = new Regex(CreateRegularExpression(pattern), RegexOptions.IgnoreCase);
Pattern = pattern;
}
public string Pattern { get; }
private static string CreateRegularExpression(string pattern)
{
var sb = new StringBuilder();
sb.Append('^');
var parts = pattern.Split('/');
foreach (var part in parts)
{
if (sb.Length > 1)
sb.Append('/');
if (part == "*")
sb.Append("[^/]+");
else if (part == "**")
sb.Append(".+");
else
sb.Append(Regex.Escape(part));
}
sb.Append('$');
return sb.ToString();
}
public bool IsMatch(GitHubAreaPath areaPath)
{
return _regex.IsMatch(areaPath.FullName);
}
public override string ToString()
{
return Pattern;
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using Aware.Model;
using Aware.Util;
using Aware.Util.Enum;
namespace Aware.File.Model
{
public class FileRelation : BaseEntity
{
public string FileName { get; set; }
public FileType Type { get; set; }
public string Path { get; set; }
public virtual string SortOrder { get; set; }
public int RelationType { get; set; }
public int RelationId { get; set; }
[NotMapped]
public virtual string Extension
{
get
{
return !string.IsNullOrEmpty(Path) ? System.IO.Path.GetExtension(Path) : string.Empty;
}
}
public override bool IsValid()
{
return FileName.Valid() && Extension.Valid();
}
public virtual FileRelation Clone()
{
var result = MemberwiseClone() as FileRelation;
result.ID = 0;
return result;
}
}
} |
namespace QuantConnect
{
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Indicators;
using QuantConnect.Orders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public partial class TimeOurMarketMoves : QCAlgorithm
{
private MomentumPercent spyMomentum;
private MomentumPercent bondMomentum;
public override void Initialize()
{
SetStartDate(2007, 8, 1);
SetEndDate(2010, 8, 1);
SetCash(3000);
AddEquity("SPY", Resolution.Daily);
AddEquity("BND", Resolution.Daily);
spyMomentum = MOMP("SPY", 50, Resolution.Daily);
bondMomentum = MOMP("BND", 50, Resolution.Daily);
SetBenchmark("SPY");
SetWarmUp(50);
}
public override void OnData(Slice data)
{
if (IsWarmingUp)
return;
//1. Limit trading to happen once per week
if (Time.DayOfWeek != DayOfWeek.Tuesday)
{
return;
}
if (spyMomentum > bondMomentum)
{
Liquidate("BND");
SetHoldings("SPY", 1);
}
else
{
Liquidate("SPY");
SetHoldings("BND", 1);
}
}
}
} |
using FluentValidation;
namespace MillionAndUp.Core.Application.Feautures.PropertyImages.Commands.CreatePropertyImageCommand
{
public class CreatePropertyImageCommandValidator : AbstractValidator<CreatePropertyImageCommand>
{
public CreatePropertyImageCommandValidator()
{
RuleFor(p => p.Title)
.NotEmpty().WithMessage("{PropertyName} vacío.")
.MaximumLength(30).WithMessage("{PropertyName} no debe exceder {MaxLength} caracteres.");
RuleFor(p => p.Description)
.NotEmpty().WithMessage("{PropertyName} vacío.")
.MaximumLength(100).WithMessage("{PropertyName} no debe exceder {MaxLength} caracteres.");
RuleFor(p => p.File)
.NotNull().WithMessage("{PropertyName} no debe ser nulo.");
RuleFor(p => p.IdProperty)
.GreaterThan(0).WithMessage("{PropertyName} debe ser mayor 0.")
.NotNull().WithMessage("{PropertyName} no debe ser nulo.");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.