content stringlengths 23 1.05M |
|---|
using MySql.Data.MySqlClient;
using RepoDb.Extensions;
using RepoDb.Interfaces;
using RepoDb.Resolvers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace RepoDb.DbHelpers
{
/// <summary>
/// A helper class for database specially for the direct access. This class is only meant for MySql.
/// </summary>
public sealed class MySqlConnectorDbHelper : IDbHelper
{
private IDbSetting m_dbSetting = DbSettingMapper.Get<MySqlConnection>();
/// <summary>
/// Creates a new instance of <see cref="MySqlConnectorDbHelper"/> class.
/// </summary>
public MySqlConnectorDbHelper()
: this(new MySqlConnectorDbTypeNameToClientTypeResolver())
{ }
/// <summary>
/// Creates a new instance of <see cref="MySqlConnectorDbHelper"/> class.
/// </summary>
/// <param name="dbTypeResolver">The type resolver to be used.</param>
public MySqlConnectorDbHelper(IResolver<string, Type> dbTypeResolver)
{
DbTypeResolver = dbTypeResolver;
}
#region Properties
/// <summary>
/// Gets the type resolver used by this <see cref="MySqlConnectorDbHelper"/> instance.
/// </summary>
public IResolver<string, Type> DbTypeResolver { get; }
#endregion
#region Helpers
/// <summary>
/// Returns the command text that is being used to extract schema definitions.
/// </summary>
/// <returns>The command text.</returns>
private string GetCommandText()
{
return $@"SELECT COLUMN_NAME AS ColumnName
, CASE WHEN COLUMN_KEY = 'PRI' THEN 1 ELSE 0 END AS IsPrimary
, CASE WHEN EXTRA LIKE '%auto_increment%' THEN 1 ELSE 0 END AS IsIdentity
, CASE WHEN IS_NULLABLE = 'YES' THEN 1 ELSE 0 END AS IsNullable
, DATA_TYPE AS ColumnType /*COLUMN_TYPE AS ColumnType*/
, CHARACTER_MAXIMUM_LENGTH AS Size
, COALESCE(NUMERIC_PRECISION, DATETIME_PRECISION) AS `Precision`
, NUMERIC_SCALE AS Scale
, DATA_TYPE AS DatabaseType
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = @TableSchema
AND TABLE_NAME = @TableName
ORDER BY ORDINAL_POSITION;";
}
/// <summary>
/// Get the list of type names for all blob-types for MySql.
/// </summary>
/// <returns>The list of column type names.</returns>
private IEnumerable<string> GetBlobTypes()
{
return new[]
{
"blob",
"blobasarray",
"binary",
"longtext",
"mediumtext",
"longblob",
"mediumblob",
"tinyblob",
"varbinary"
};
}
/// <summary>
/// Converts the <see cref="IDataReader"/> object into <see cref="DbField"/> object.
/// </summary>
/// <param name="reader">The instance of <see cref="IDataReader"/> object.</param>
/// <returns>The instance of converted <see cref="DbField"/> object.</returns>
private DbField ReaderToDbField(IDataReader reader)
{
var columnType = reader.GetString(4);
var excluded = GetBlobTypes();
var size = (int?)null;
if (excluded.Contains(columnType.ToLower()))
{
size = null;
}
else
{
size = reader.IsDBNull(5) ? (int?)null : reader.GetInt32(5);
}
return new DbField(reader.GetString(0),
reader.GetBoolean(1),
reader.GetBoolean(2),
reader.GetBoolean(3),
DbTypeResolver.Resolve(columnType),
size,
reader.IsDBNull(6) ? (byte?)null : byte.Parse(reader.GetInt32(6).ToString()),
reader.IsDBNull(7) ? (byte?)null : byte.Parse(reader.GetInt32(7).ToString()),
reader.GetString(8));
}
/// <summary>
/// Gets the actual schema of the table from the database.
/// </summary>
/// <param name="tableName">The passed table name.</param>
/// <returns>The actual table schema.</returns>
private string GetSchema(string tableName)
{
// Get the schema and table name
if (tableName.IndexOf(m_dbSetting.SchemaSeparator) > 0)
{
var splitted = tableName.Split(m_dbSetting.SchemaSeparator.ToCharArray());
return splitted[0].AsUnquoted(true, m_dbSetting);
}
// Return the unquoted
return m_dbSetting.DefaultSchema;
}
/// <summary>
/// Gets the actual name of the table from the database.
/// </summary>
/// <param name="tableName">The passed table name.</param>
/// <returns>The actual table name.</returns>
private string GetTableName(string tableName)
{
// Get the schema and table name
if (tableName.IndexOf(m_dbSetting.SchemaSeparator) > 0)
{
var splitted = tableName.Split(m_dbSetting.SchemaSeparator.ToCharArray());
return splitted[1].AsUnquoted(true, m_dbSetting);
}
// Return the unquoted
return tableName.AsUnquoted(true, m_dbSetting);
}
#endregion
#region Methods
#region GetFields
/// <summary>
/// Gets the list of <see cref="DbField"/> of the table.
/// </summary>
/// <param name="connection">The instance of the connection object.</param>
/// <param name="tableName">The name of the target table.</param>
/// <param name="transaction">The transaction object that is currently in used.</param>
/// <returns>A list of <see cref="DbField"/> of the target table.</returns>
public IEnumerable<DbField> GetFields(IDbConnection connection,
string tableName,
IDbTransaction transaction = null)
{
// Variables
var commandText = GetCommandText();
var param = new
{
TableSchema = connection.Database,
TableName = GetTableName(tableName)
};
// Iterate and extract
using (var reader = connection.ExecuteReader(commandText, param, transaction: transaction))
{
var dbFields = new List<DbField>();
// Iterate the list of the fields
while (reader.Read())
{
dbFields.Add(ReaderToDbField(reader));
}
// Return the list of fields
return dbFields;
}
}
/// <summary>
/// Gets the list of <see cref="DbField"/> of the table in an asychronous way.
/// </summary>
/// <param name="connection">The instance of the connection object.</param>
/// <param name="tableName">The name of the target table.</param>
/// <param name="transaction">The transaction object that is currently in used.</param>
/// <returns>A list of <see cref="DbField"/> of the target table.</returns>
public async Task<IEnumerable<DbField>> GetFieldsAsync(IDbConnection connection,
string tableName,
IDbTransaction transaction = null)
{
// Variables
var commandText = GetCommandText();
var param = new
{
TableSchema = connection.Database,
TableName = GetTableName(tableName)
};
// Iterate and extract
using (var reader = await connection.ExecuteReaderAsync(commandText, param, transaction: transaction))
{
var dbFields = new List<DbField>();
// Iterate the list of the fields
while (reader.Read())
{
dbFields.Add(ReaderToDbField(reader));
}
// Return the list of fields
return dbFields;
}
}
#endregion
#region GetScopeIdentity
/// <summary>
/// Gets the newly generated identity from the database.
/// </summary>
/// <param name="connection">The instance of the connection object.</param>
/// <param name="transaction">The transaction object that is currently in used.</param>
/// <returns>The newly generated identity from the database.</returns>
public object GetScopeIdentity(IDbConnection connection,
IDbTransaction transaction = null)
{
return connection.ExecuteScalar("SELECT LAST_INSERT_ID();");
}
/// <summary>
/// Gets the newly generated identity from the database in an asychronous way.
/// </summary>
/// <param name="connection">The instance of the connection object.</param>
/// <param name="transaction">The transaction object that is currently in used.</param>
/// <returns>The newly generated identity from the database.</returns>
public async Task<object> GetScopeIdentityAsync(IDbConnection connection,
IDbTransaction transaction = null)
{
return await connection.ExecuteScalarAsync("SELECT LAST_INSERT_ID();");
}
#endregion
#endregion
}
}
|
using VulkaNetGenerator.Attributes;
using VulkaNetGenerator.Dummies;
namespace VulkaNetGenerator.GenStructs
{
public unsafe struct GenPipelineMultisampleStateCreateInfo
{
public VkStructureType sType;
public void* pNext;
public VkPipelineMultisampleStateCreateFlags flags;
public VkSampleCount rasterizationSamples;
public VkBool32 sampleShadingEnable;
public float minSampleShading;
[IsArray] public int* pSampleMask;
public VkBool32 alphaToCoverageEnable;
public VkBool32 alphaToOneEnable;
}
} |
//
// Author:
// Aaron Bockover <abock@xamarin.com>
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using DiffPlex;
using DiffPlex.DiffBuilder;
using DiffPlex.DiffBuilder.Model;
namespace Xamarin.Interactive.Tests
{
sealed class DiffRenderer
{
public sealed class DiffPieceGroup
{
public ChangeType Type { get; }
public List<DiffPiece> Lines { get; }
public DiffPieceGroup Previous { get; private set; }
public DiffPieceGroup Next { get; private set; }
public DiffPieceGroup (DiffPieceGroup previous, ChangeType type)
{
Previous = previous;
if (previous != null)
previous.Next = this;
Lines = new List<DiffPiece> ();
Type = type;
}
}
readonly int maxContextLines;
readonly int maxLineNumberDigits;
readonly int maxLineWidth;
public DiffPieceGroup FirstGroup { get; }
// if we have no groups or only an 'unchanged' group, then there is no diff
public bool HasDiff => FirstGroup != null &&
(FirstGroup.Type != ChangeType.Unchanged || FirstGroup.Next != null);
public DiffRenderer (string oldText, string newText, int maxContextLines = 3, int tabWidth = 8)
{
this.maxContextLines = maxContextLines;
var inlineBuilder = new InlineDiffBuilder (new Differ ());
var diff = inlineBuilder.BuildDiffModel (oldText, newText);
int maxLineNumber = 0;
DiffPieceGroup currentGroup = null;
foreach (var line in diff.Lines) {
if (currentGroup == null || currentGroup.Type != line.Type) {
currentGroup = new DiffPieceGroup (currentGroup, line.Type);
if (FirstGroup == null)
FirstGroup = currentGroup;
}
if (line.Position != null)
maxLineNumber = Math.Max (maxLineNumber, line.Position.Value);
maxLineWidth = Math.Max (maxLineWidth, GetLineWidth (line.Text, tabWidth));
currentGroup.Lines.Add (line);
}
maxLineNumberDigits = (int)Math.Floor (Math.Log10 (maxLineNumber) + 1);
}
static int GetLineWidth (string line, int tabWidth)
{
int lineWidth = 0;
for (int i = 0; i < line.Length; i++) {
switch (line [i]) {
case '\t':
lineWidth += tabWidth;
break;
case '\n':
case '\r':
break;
default:
lineWidth++;
break;
}
}
return lineWidth;
}
public void Write (TextWriter writer)
{
if (!HasDiff)
return;
var group = FirstGroup;
while (group != null) {
var lines = group.Lines;
switch (group.Type) {
case ChangeType.Inserted:
case ChangeType.Deleted:
foreach (var line in lines)
WriteDiffLine (writer, line);
break;
case ChangeType.Unchanged:
var nTotal = lines.Count;
var nTail = Math.Min (nTotal, maxContextLines);
var nHead = Math.Min (nTotal - nTail, maxContextLines);
if (group.Previous != null) {
for (int i = 0; i < nHead; i++)
WriteDiffLine (writer, lines [i]);
}
if (nTotal > maxContextLines * 2)
WriteDiffLine (writer, null);
if (group.Next != null) {
for (int i = nTotal - nTail; i < nTotal; i++)
WriteDiffLine (writer, lines [i]);
}
break;
}
group = group.Next;
}
}
void WriteDiffLine (TextWriter writer, DiffPiece line)
{
if (line == null) {
writer.Write ("@@ ↕ ");
writer.Write (new string ('-', maxLineWidth + maxLineNumberDigits));
writer.WriteLine (" ↕ @@");
return;
}
var lineNumber = line.Position == null
? string.Empty
: line.Position.Value.ToString (CultureInfo.InvariantCulture);
switch (line.Type) {
case ChangeType.Unchanged:
writer.Write (' ');
break;
case ChangeType.Inserted:
writer.Write ('+');
break;
case ChangeType.Deleted:
writer.Write ('-');
break;
}
writer.Write (' ');
writer.Write (lineNumber.PadLeft (maxLineNumberDigits));
writer.Write (" | ");
writer.WriteLine (line.Text);
}
}
} |
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static class SaveLoad {
private static string tutorial = "SceneAlex";
private static string level = tutorial;
private static string saveName = "/.save";
public static void Save(string levelName)
{
SaveLoad.level = levelName;
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create (Application.persistentDataPath + saveName);
bf.Serialize(file, SaveLoad.level);
file.Close();
}
public static string Load() {
if(File.Exists(Application.persistentDataPath + saveName))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + saveName, FileMode.Open);
SaveLoad.level = (string)bf.Deserialize(file);
file.Close();
}
return SaveLoad.level;
}
public static void Reset()
{
SaveLoad.Save(tutorial);
}
} |
using UnityEngine;
namespace BaseTools.Utils
{
[RequireComponent(typeof(CanvasGroup))]
public class CanvasGroupOnOff : MonoBehaviour
{
public CanvasGroup Canvas;
private bool _visible;
void Reset()
{
Canvas = GetComponent<CanvasGroup>();
}
/// <summary>
/// Set The CanvasGroup Visitable and Intractable
/// </summary>
public void On()
{
_visible = true;
Canvas.alpha = 1;
Canvas.interactable = true;
Canvas.blocksRaycasts = true;
}
/// <summary>
/// Set The CanvasGroup Hiden and not Intractable
/// </summary>
public void Off()
{
_visible = false;
Canvas.alpha = 0;
Canvas.interactable = false;
Canvas.blocksRaycasts = false;
}
/// <summary>
/// Toggle Between Visible and Hidden
/// </summary>
public void Toggle()
{
if (_visible)
Off();
else
On();
}
/// <summary>
/// Toggle Between Visible and Hidden with an specific Value
/// </summary>
/// <param name="visible">true = Show, false = Hide</param>
public void Toggle(bool visible)
{
if (visible)
On();
else
Off();
}
/// <summary>
/// returns the Curret visibility State
/// </summary>
/// <returns>true = visible false = hidden</returns>
public bool GetVisibility()
{
return _visible;
}
}
}
|
using MahjongBuddy.Core;
using System.Collections.Generic;
namespace MahjongBuddy.Application.Rounds.Scorings
{
abstract class FindHandType
{
protected FindHandType _successor;
public void SetSuccessor(FindHandType successor)
{
_successor = successor;
}
public abstract List<HandType> HandleRequest(IEnumerable<RoundTile> tiles, List<HandType> result);
}
}
|
#region COPYRIGHT© 2009-2013 Phillip Clark.
// For licensing information see License.txt (MIT style licensing).
#endregion
using System;
using System.Data.Common;
using FlitBit.Core;
using FlitBit.Core.Parallel;
namespace FlitBit.Data
{
public interface IDbContext : IInterrogateDisposable, IParallelShared
{
DbContextBehaviors Behaviors { get; }
int CacheAttempts { get; }
int CacheHits { get; }
int CachePuts { get; }
int CacheRemoves { get; }
int QueryCount { get; }
T Add<T>(T item)
where T : IDisposable;
C EnsureCache<K, C>(K key)
where C : new();
DbProviderHelper HelperForConnection(DbConnection cn);
int IncrementQueryCounter();
int IncrementQueryCounter(int count);
DbConnection NewConnection(string connection);
TConnection NewConnection<TConnection>(string connectionName)
where TConnection : DbConnection, new();
void PutCacheItem<TCacheKey, TItemKey, TItem>(TCacheKey cacheKey, TItem item, TItemKey key,
Func<TItemKey, TItem, TItem> updateCachedItem);
void RemoveCacheItem<TCacheKey, TItemKey, TItem>(TCacheKey cacheKey, TItem item, TItemKey key);
DbConnection SharedOrNewConnection(string connection);
TConnection SharedOrNewConnection<TConnection>(string connectionName)
where TConnection : DbConnection, new();
bool TryGetCacheItem<TCacheKey, TItemKey, TItem>(TCacheKey cacheKey, TItemKey key, out TItem item);
}
} |
namespace Gm1KonverterCrossPlatform.TexturePack
{
public class IncludedFile
{
public enum Filetype { TGX, GM1 };
public Filetype Type;
public string FileName;
public byte[] FileData;
}
}
|
using System.Threading.Tasks;
namespace OMP.Connector.Domain.OpcUa.Services
{
public interface ISubscriptionRestoreService
{
Task RestoreSubscriptionsAsync(IOpcSession opcSession);
}
} |
using System.Collections.Generic;
namespace Ploeh.Samples.Commerce.Domain
{
public abstract partial class ProductRepository
{
public abstract IEnumerable<Product> GetFeaturedProducts();
}
public abstract partial class ProductRepository
{
public abstract void DeleteProduct(int id);
public abstract void InsertProduct(Product product);
public abstract Product SelectProduct(int id);
public abstract IEnumerable<Product> SelectAllProducts();
public abstract void UpdateProduct(Product product);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab2.Test.Assets
{
public static class AssetsPathHepler
{
const string AssetsFolerPrefix = "Assets/";
const string AssetsTestsSuffix = "Tests";
const string AssetsDefinitionsSuffix = "Definition";
const string AssetsAutomatonTestsPrefix = "Automaton";
const int AssetsAutomatonTestsCount = 3;
public static string[] GetAssetsAutomatonTestsPaths()
{
return GenerateFilePaths(AssetsAutomatonTestsPrefix, AssetsTestsSuffix, AssetsAutomatonTestsCount);
}
public static string[] GetAssetsAutomatonDefinitionsPaths()
{
return GenerateFilePaths(AssetsAutomatonTestsPrefix, AssetsDefinitionsSuffix, AssetsAutomatonTestsCount);
}
private static string[] GenerateFilePaths(string prefix, string suffix, int count, string extension = ".txt")
{
List<string> result = new List<string>();
for (int i = 0; i <= count; i++)
result.Add(string.Format("{0}{1}{2}{3}{4}", AssetsFolerPrefix, prefix, i, suffix, extension));
return result.ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeEditor.QScript
{
internal sealed class Token
{
public enum TokenType
{
Print,
PrintIn,
Set,
Name,
StringLiteral
}
public TokenType Type { get; }
public string Value { get; }
public Token(TokenType type, string value)
{
Type = type;
Value = value;
}
}
}
|
using System.Collections.Generic;
namespace SSRSDataProcessingExtensions.JsonDPE.Client
{
public class RequestCommand
{
public string Path { get; set; }
public string Method { get; set; }
public string ContentType { get; set; }
public string Accept { get; set; }
public bool IsRequestTypeInHeader { get; set; } = true;
public Dictionary<string, string> HttpHeader { get; set; }
public object Payload { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Inventory;
public class QuestSlot : MonoBehaviour
{
public Quest quest;
public GameObject Validate;
private static InventoryController inventoryController;
private void Awake()
{
if (inventoryController == null)
inventoryController = new List<InventoryController>(GameObject.FindObjectsOfType<InventoryController>()).Find(x => x.inventoryType == InventoryController.Inventory.Ship);
}
public void DisplayValidateButton()
{
if (CheckForCompletion())
{
Validate.SetActive(true);
}
else
{
Validate.SetActive(false);
}
}
public void DisplayQuestName()
{
GetComponentInChildren<Text>().text = quest.QuestName;
}
public void DisplayNoQuest()
{
GetComponentInChildren<Text>().text = "No subquest";
}
public void StartTimer()
{
StartCoroutine(TimerTick());
}
private IEnumerator TimerTick()
{
while (true)
{
quest.TimeLimit--;
yield return new WaitForSeconds(1);
if (quest.TimeLimit <= 0)
{
OnFailure();
}
}
}
public void StopTimer()
{
StopCoroutine(TimerTick());
}
public bool CheckForCompletion()
{
if (quest.ID != -1)
{
int currentQuantity = 0;
using (var e1 = quest.ObjectiveList.GetEnumerator())
using (var e2 = quest.ObjectiveQuantityList.GetEnumerator())
{
while (e1.MoveNext() && e2.MoveNext())
{
currentQuantity = inventoryController.GetQuantity(e1.Current);
if (e2.Current > currentQuantity)
{
return false;
}
}
}
return true;
}
else return false;
}
public void OnFailure()
{
//condition de game over a mettre ici
}
public void OnSuccess()
{
using (var e1 = quest.ObjectiveList.GetEnumerator())
using (var e2 = quest.ObjectiveQuantityList.GetEnumerator())
{
while (e1.MoveNext() && e2.MoveNext())
{
inventoryController.RemoveItem(e1.Current, e2.Current);
}
}
GameObject.Find("Data").GetComponentInChildren<QuestProgress>().CompletedQuests.Add(quest.ID);
GameObject.Find("Data").GetComponentInChildren<QuestProgress>().questTimer = -1000;
DeliverRewards();
}
public void DeliverRewards()
{
using (var e1 = quest.RewardList.GetEnumerator())
using (var e2 = quest.RewardQuantityList.GetEnumerator())
{
while (e1.MoveNext() && e2.MoveNext())
{
inventoryController.AddItem(e1.Current, e2.Current);
}
}
if (quest.IsMainQuest)
{
GameObject.Find("Data").GetComponentInChildren<QuestProgress>().questProgress++;
}
if (quest.Victory == 1)
{
SceneManager.LoadSceneAsync("HiveVictory", LoadSceneMode.Single);
}
else if (quest.Victory == 2)
{
SceneManager.LoadSceneAsync("AIRVictory", LoadSceneMode.Single);
}
else if (quest.Victory == 3)
{
SceneManager.LoadSceneAsync("SelfVictory", LoadSceneMode.Single);
}
GameObject.Find("QuestLog").GetComponent<QuestLogController>().UpdateQuestLog();
}
}
|
namespace Gifuser.Options.Settings.Models
{
public class MainSettingsModel
{
public bool UploadOnStop
{
get;
set;
}
public string UploadServiceName
{
get;
set;
}
public RecordingModel Recordings
{
get;
set;
}
}
}
|
using System;
using AutoGenerated.Message;
using NF.Network.Transfer.Protobuf;
using NF.Results;
using UnityEngine;
namespace Game
{
public class _main : MonoBehaviour
{
private async void Start()
{
ProtobufHttpSender sender = new ProtobufHttpSender(new Uri("http://127.0.0.1:8080/"), 3000);
Result<RHello, int> t = await sender.Hello(1, 2);
if (t.IsErr)
{
Debug.LogError(t.Err);
return;
}
Debug.Log(t.Ok);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinecraftClient.Mapping;
namespace MinecraftClient.Commands
{
public class Move : Command
{
public override string CmdName { get { return "move"; } }
public override string CmdUsage { get { return "move <on|off|get|up|down|east|west|north|south|x y z>"; } }
public override string CmdDesc { get { return "walk or start walking."; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars)
{
string[] args = getArgs(command);
string argStr = getArg(command).Trim().ToLower();
if (argStr == "on")
{
handler.SetTerrainEnabled(true);
return Translations.Get("cmd.move.enable");
}
else if (argStr == "off")
{
handler.SetTerrainEnabled(false);
return Translations.Get("cmd.move.disable");
}
else if (handler.GetTerrainEnabled())
{
if (args.Length == 1)
{
Direction direction;
switch (argStr)
{
case "up": direction = Direction.Up; break;
case "down": direction = Direction.Down; break;
case "east": direction = Direction.East; break;
case "west": direction = Direction.West; break;
case "north": direction = Direction.North; break;
case "south": direction = Direction.South; break;
case "get": return handler.GetCurrentLocation().ToString();
default: return Translations.Get("cmd.look.unknown", argStr);
}
if (Movement.CanMove(handler.GetWorld(), handler.GetCurrentLocation(), direction))
{
handler.MoveTo(Movement.Move(handler.GetCurrentLocation(), direction));
return Translations.Get("cmd.move.moving", argStr);
}
else return Translations.Get("cmd.move.dir_fail");
}
else if (args.Length == 3)
{
try
{
int x = int.Parse(args[0]);
int y = int.Parse(args[1]);
int z = int.Parse(args[2]);
Location goal = new Location(x, y, z);
if (handler.MoveTo(goal))
return Translations.Get("cmd.move.walk", goal);
return Translations.Get("cmd.move.fail", goal);
}
catch (FormatException) { return GetCmdDescTranslated(); }
}
else return GetCmdDescTranslated();
}
else return Translations.Get("extra.terrainandmovement_required");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JyFramework
{
public sealed class EventConst
{
public const string ExitGame = "ExitGame";
public const string StartModule = "StartModule";
public const string PauseModule = "PauseModule";
public const string UpdateModule = "UpdateModule";
}
}
|
using System;
using System.Collections.Generic;
public class PopulationGenerator {
public static List<TileLocation> GetPopulationLoaf()
{
// Sample initial population for 6x6 board - loaf
List<TileLocation> population = new List<TileLocation>();
population.Add(new TileLocation(4, 2));
population.Add(new TileLocation(3, 3));
population.Add(new TileLocation(5, 3));
population.Add(new TileLocation(2, 4));
population.Add(new TileLocation(5, 4));
population.Add(new TileLocation(3, 5));
population.Add(new TileLocation(4, 5));
return population;
}
public static List<TileLocation> GetPopulationToad()
{
// Sample initial population for 6x6 board - toad
List<TileLocation> population = new List<TileLocation>();
population.Add(new TileLocation(4, 2));
population.Add(new TileLocation(5, 2));
population.Add(new TileLocation(4, 3));
population.Add(new TileLocation(5, 3));
population.Add(new TileLocation(2, 4));
population.Add(new TileLocation(3, 4));
population.Add(new TileLocation(2, 5));
population.Add(new TileLocation(3, 5));
return population;
}
public static HashSet<int> GetRandomPopulation(int rows, int cols, int maxElements = 0)
{
HashSet<int> population = new HashSet<int>();
var random = new Random();
if (maxElements == 0)
maxElements = random.Next(1, rows * cols);
while(population.Count < maxElements)
population.Add(random.Next(rows * cols));
return population;
}
}
|
using Highway.Data;
using TT.Domain.World.DTOs;
namespace TT.Domain.World.Queries
{
public class GetWorld : DomainQuerySingle<WorldDetail>
{
public override WorldDetail Execute(IDataContext context)
{
ContextQuery = ctx =>
{
return ctx.AsQueryable<Entities.World>()
.ProjectToFirstOrDefault<WorldDetail>();
};
return ExecuteInternal(context);
}
}
}
|
namespace MyStaging.xUnitTest.Core
{
public class SQLExecuteTest
{
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AppGet.PackageRepository
{
public interface IPackageRepository
{
Task<PackageInfo> GetAsync(string id, string tag);
Task<List<PackageInfo>> Search(string term, bool select = false);
}
} |
//------------------------------------------------------------------------------
// <auto-generated>
// 這個程式碼是由範本產生。
//
// 對這個檔案進行手動變更可能導致您的應用程式產生未預期的行為。
// 如果重新產生程式碼,將會覆寫對這個檔案的手動變更。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Employee_system
{
using System;
using System.Collections.Generic;
public partial class customer
{
public int CustomerID { get; set; }
public System.DateTime DateTIMEofcreation { get; set; }
public string Name { get; set; }
public int Phone { get; set; }
public string email { get; set; }
public string Customer_Username { get; set; }
public string Customer_password { get; set; }
public System.DateTime DateOfBirth { get; set; }
}
}
|
using System;
using System.Reflection;
using MonoDevelop.Core;
namespace MonoDevelop.DotNetCore.Extensions
{
class DotNetCoreSdkPathsExtension
{
public DotNetCoreSdkPathsExtension(string dotNetCorePath, bool initializeSdkLocation)
{
try
{
DotNetCoreSdkPathsInstance = typeof(DotNetCoreRuntime).Assembly.CreateInstance(
"MonoDevelop.DotNetCore.DotNetCoreSdkPaths",
false,
BindingFlags.Instance | BindingFlags.Public,
null,
new object[] { dotNetCorePath, initializeSdkLocation },
null,
new object[0]);
}
catch (Exception ex)
{
LoggingService.LogError("Could not find DotNetCoreSdkPaths via reflection", ex);
return;
}
if (DotNetCoreSdkPathsInstance == null)
{
LoggingService.LogError("Could not find DotNetCoreSdkPaths via reflection");
}
}
public object? DotNetCoreSdkPathsInstance { get; }
public void ResolveSDK(string workingDir = "", bool forceLookUpGlobalJson = false)
{
if (DotNetCoreSdkPathsInstance == null)
{
return;
}
Type type = DotNetCoreSdkPathsInstance.GetType();
MethodInfo? method = type.GetMethod("ResolveSDK", BindingFlags.Instance | BindingFlags.Public);
if (method != null)
{
method.Invoke(DotNetCoreSdkPathsInstance, new object[] { workingDir, forceLookUpGlobalJson });
}
else
{
LoggingService.LogError("Could not find DotNetCoreSdkPaths.ResolveSDK method via reflection");
}
}
}
}
|
/* Benjamin Lanza
* F117Reader.cs
* October 11th, 2018 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using static LibSimTelem.F117Defs;
using System.Runtime.InteropServices;
namespace LibSimTelem
{
public class F117Reader : TelemReader
{
/* Event handler declarations */
public delegate void PacketReceived(object sender, F117ReceivedEventArgs args);
public event PacketReceived PacketReceivedEvent;
/* Fields */
private int port;
private string ip;
private int timeout;
private volatile bool isRunning = false;
private static Mutex flagMtx = new Mutex();
private Thread receiverThread;
/* Constructor */
public F117Reader(int port = DEFAULT_PORT, string ip = DEFAULT_IP,
int timeout = DEFAULT_TIMEOUT)
{
this.port = port;
this.ip = ip;
this.timeout = timeout;
}
/* Starts listening for data */
public bool Start(params object[] args)
{
/* Returns false if Start() has previously been called */
flagMtx.WaitOne();
if (isRunning) { flagMtx.ReleaseMutex(); return false; }
else { isRunning = true; flagMtx.ReleaseMutex(); }
/* Starts the receiving thread and returns true */
receiverThread = new Thread(ThreadRoutine);
receiverThread.Start();
return true;
}
/* Signals the receiver thread to stop and cleans up */
public bool Stop()
{
/* Returns false if the program isn't already running */
flagMtx.WaitOne();
if (!isRunning) { flagMtx.ReleaseMutex(); return false; }
else { isRunning = false; flagMtx.ReleaseMutex(); }
/* Waits for the receiver thread to join and returns true */
receiverThread.Join();
return true;
}
/* Receives packets and raises events continuously on a thread */
private void ThreadRoutine()
{
/* Sets up UDP connection objects */
UdpClient client = new UdpClient(port);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port);
client.Client.ReceiveTimeout = timeout;
/* Loops until broken by the isRunning flag */
while (true)
{
/* Break if isRunning is false */
flagMtx.WaitOne();
if(!isRunning) { flagMtx.ReleaseMutex(); break; }
else { flagMtx.ReleaseMutex(); }
byte[] data;
/* Try to get data from the socket and restart the loop on timeout */
try { data = client.Receive(ref ep); }
catch (SocketException e) { continue; }
/* Restart the loop if the packet is invalid */
if(!IsValidPacketData(ref data)) continue;
/* Create arguments object for triggering event */
F117ReceivedEventArgs args = new F117ReceivedEventArgs(ParsePacket(ref data));
/* Raise event */
RaisePacketReceived(args);
}
client.Close();
}
/* Raises a PacketReceivedEvent if someone has subscribed to it */
private void RaisePacketReceived(F117ReceivedEventArgs args)
{
PacketReceivedEvent?.Invoke(this, args);
}
/* Returns true if the passed byte array is the same size as a UDPPacket */
private bool IsValidPacketData(ref byte[] bytes)
{
return (bytes.Length == PACKET_SIZE);
}
/* Parses a packet from the given bytes */
private UDPPacket ParsePacket(ref byte[] bytes)
{
UDPPacket ret;
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try { ret = Marshal.PtrToStructure<UDPPacket>(handle.AddrOfPinnedObject()); }
finally { handle.Free(); }
return ret;
}
}
/* F117ReceivedEventArgs class definition */
public class F117ReceivedEventArgs : EventArgs
{
public UDPPacket packet;
public F117ReceivedEventArgs(UDPPacket packet)
{
this.packet = packet;
}
}
}
|
// Jeebs Unit Tests
// Copyright (c) bcg|design - licensed under https://mit.bcgdesign.com/2013
namespace Jeebs.Link_Tests.WithState
{
public interface ILink_Run_WithState : ILink_Run
{
void IOk_ValueType_WithState_Input_When_IError_Returns_IError();
void IOk_ValueType_WithState_Input_When_IOk_Catches_Exception();
void IOk_ValueType_WithState_Input_When_IOk_Runs_Action();
void IOk_Value_WithState_Input_When_IError_Returns_IError();
void IOk_Value_WithState_Input_When_IOk_Catches_Exception();
void IOk_Value_WithState_Input_When_IOk_Runs_Action();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TalentenShow.Domain.Business.Contracts.Business;
using TalentenShow.Domain.Business.Contracts.Repository;
using TalentenShow.Domain.Models.Events;
using TalentenShow.Domain.Models.Users;
namespace TalentenShow.Domain.Business.Users
{
public class PersonService : IPersonService
{
private IPersonRepository _repository;
public PersonService(IPersonRepository repository)
{
_repository = repository;
}
public string GenerateEventKey(string eventCode)
{
Guid randomId = Guid.NewGuid();
return eventCode + "-" + randomId;
}
public List<Participant> GetParticipants()
{
return _repository.GetParticipants();
}
public string SaveParticipant(Participant participant, Event eventObj)
{
string code = GenerateEventKey(eventObj.EventCode);
return _repository.SaveParticipant(participant, eventObj, code);
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
namespace SpaceGraphicsToolkit
{
/// <summary>This class can be used to pool normal C# classes.</summary>
public static class SgtPoolClass<T>
where T : class
{
private static List<T> pool = new List<T>();
public static int Count
{
get
{
return pool.Count;
}
}
static SgtPoolClass()
{
if (typeof(T).IsSubclassOf(typeof(Object)))
{
Debug.LogError("Attempting to use " + typeof(T).Name + " with SgtPoolClass. Use SgtPoolObject instead.");
}
}
public static T Add(T entry)
{
return Add(entry, null);
}
public static T Add(T element, System.Action<T> onAdd)
{
if (element != null)
{
if (onAdd != null)
{
onAdd(element);
}
pool.Add(element);
}
return null;
}
public static T Pop()
{
if (pool.Count > 0)
{
var index = pool.Count - 1;
var element = pool[index];
pool.RemoveAt(index);
return element;
}
return null;
}
}
} |
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
public GameObject floor;
Vector3 offset;
float highest;
// Use this for initialization
void Start()
{
highest = -15.0f;
}
// Update is called once per frame
void Update()
{
GameObject[] allTetros = GameObject.FindGameObjectsWithTag("Tetro"); //returns GameObject[]
float height = 0;
highest = -15.0f;
foreach (GameObject o in allTetros)
{
if (o.GetComponent<Rigidbody2D>().velocity.y < -4.0f)
{
}
else {
height = o.transform.position.y;
if (height > highest)
{
highest = height - 1.0f;
}
}
}
}
void LateUpdate()
{
if (transform.position.y - 5.0f < highest)
{
transform.position += new Vector3(0, 0.01f, 0);
}
else if (transform.position.y - 15.0f > highest)
{
transform.position -= new Vector3(0, 0.01f, 0);
}
}
} |
using LinqToDB.Mapping;
using WDE.Common.Database;
namespace WDE.SkyFireMySqlDatabase.Models
{
[Table(Name = "broadcast_text")]
public class MySqlBroadcastText : IBroadcastText
{
[PrimaryKey]
[Column(Name = "ID")]
public uint Id { get; set;}
[Column(Name = "LanguageID")]
public uint Language { get; set;}
[Column(Name = "Text")]
public string? Text { get; set;}
[Column(Name = "Text1")]
public string? Text1 { get; set; }
}
} |
namespace TfsWebApi.Services.Entities
{
public class Story
{
public long id { get; internal set; }
public dynamic title { get; internal set; }
public dynamic status { get; internal set; }
}
} |
using Armut.Iterable.Client.Models.Base;
namespace Armut.Iterable.Client.Models.BrowserModels
{
public class RegisterBrowserTokenRequest : BaseUserModel
{
public string BrowserToken { get; set; }
}
} |
using System;
using System.Linq;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using Bunit;
using dotnetnotts.Pages;
using Xunit;
namespace dotnetnotts.tests.unit
{
public class LearnTests : IDisposable
{
private readonly TestContext _context;
private readonly IRenderedComponent<Learn> _learn;
public LearnTests()
{
_context = new TestContext();
_learn = _context.RenderComponent<Learn>();
}
[Fact]
public void LearnTitleIsDisplayed()
{
Assert.Contains("<h1 tabindex=\"1\">Learn</h1>", _learn.Markup);
}
[Fact]
public void HeadersForLearningSectionsAreDisplayed()
{
var learnCards = _learn.FindAll(".card");
var cardHeaders = learnCards.Children(".card-header").ToList();
Assert.Single(cardHeaders, header => header.ToMarkup().Contains("Learn .NET"));
Assert.Single(cardHeaders, header => header.ToMarkup().Contains("Learn Azure"));
}
[Fact]
public void AllLinksToLearningResourcesAreProvided()
{
var learnCards = _learn.FindAll(".card");
var links = learnCards
.Children(".list-group-item a")
.Select(a => a as IHtmlAnchorElement);
Assert.All(links, link => Uri.IsWellFormedUriString(link?.Href,
UriKind.RelativeOrAbsolute));
}
public void Dispose()
{
_context.Dispose();
}
}
} |
using System;
namespace MockAllTheThings.Core
{
public interface IMockProvider
{
object CreateMock(Type type);
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using prayzzz.Common.Attributes;
using prayzzz.Common.Mapping;
namespace FlatMate.Module.Offers.Domain.Offers
{
public interface IOfferViewService
{
Task<IEnumerable<OfferDto>> GetOffers(int marketId, OfferDuration offerDuration);
Task<IEnumerable<OfferDto>> GetOffersInMarkets(List<int> marketIds, OfferDuration offerDuration);
}
[Inject]
public class OfferViewViewService : IOfferViewService
{
private readonly OffersDbContext _dbContext;
private readonly IMapper _mapper;
public OfferViewViewService(OffersDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
public async Task<IEnumerable<OfferDto>> GetOffers(int marketId, OfferDuration offerDuration)
{
return await GetOffersInMarkets(new List<int> { marketId }, offerDuration);
}
public async Task<IEnumerable<OfferDto>> GetOffersInMarkets(List<int> marketIds, OfferDuration offerDuration)
{
var validatedMarketIds = new List<int>(marketIds);
if (validatedMarketIds.Count > 5)
{
validatedMarketIds = marketIds.GetRange(0, 5);
}
var offers = await (from o in _dbContext.Offers.Include(of => of.Product)
where validatedMarketIds.Contains(o.MarketId)
where o.From >= offerDuration.From.Date && o.To <= offerDuration.To.Date
select o).AsNoTracking().ToListAsync();
return offers.Select(_mapper.Map<OfferDto>);
}
}
} |
using JustSaying.Messaging.MessageHandling;
namespace JustSaying.IntegrationTests.WhenRegisteringASqsSubscriber
{
[ExactlyOnce]
public class ExactlyOnceHandlerNoTimeout : ExactlyOnceHandlerWithTimeout
{
}
}
|
/******************************************************************************\
* Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. *
* Leap Motion proprietary and confidential. Not for distribution. *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
\******************************************************************************/
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
public class Slideable : MonoBehaviour {
[Tooltip("Called when the Slideable finished a slide.")]
public UnityEvent OnFinishedSliding;
// Positional sliding logic
public AnimationCurve slideCurve;
private Vector3 fromSlide = Vector3.zero;
private Vector3 toSlide = Vector3.zero;
private float slideDuration = 1.5F;
private float slideTimer = 0F;
private bool sliding = false;
protected virtual void Update() {
if (sliding) {
slideTimer += Time.deltaTime - 0.003F + Random.value * 0.006F;
transform.position = Vector3.LerpUnclamped(fromSlide, toSlide, slideCurve.Evaluate(slideTimer / slideDuration));
if (slideTimer > slideDuration) {
sliding = false;
slideTimer = 0F;
OnFinishedSliding.Invoke();
}
}
}
public void StartSlide(Vector3 from, Vector3 to) {
StartSlide(from, to, 1F);
}
public void StartSlide(Vector3 from, Vector3 to, float slideTime) {
if (sliding) {
Debug.LogWarning("[Slideable] StartSlide called, but the Slideable was not finished with its original slide.");
}
fromSlide = from;
toSlide = to;
transform.position = fromSlide;
sliding = true;
}
}
|
using System;
namespace RDS.TextParser.Types
{
public class SplitInfo
{
public string[] Split { get; set; }
public string Indices { get; set; }
public string Delimiter { get; set; }
public bool Exclusion { get; set; }
public SplitInfo()
{
Split = Array.Empty<string>();
Indices = string.Empty;
Delimiter = string.Empty;
Exclusion = false;
}
public SplitInfo(string[] split, string indices, string delimiter)
{
Split = split;
Indices = indices;
Delimiter = delimiter;
Exclusion = false;
}
public SplitInfo(string[] split, string indices, string delimiter, bool exclusion)
{
Split = split;
Indices = indices;
Delimiter = delimiter;
Exclusion = exclusion;
}
}
}
|
using System;
namespace TradeCompany
{
public class Article : IComparable<Article>
{
public Article(string barCode, string vendor, double price)
{
this.BarCode = barCode;
this.Vendor = vendor;
this.Price = price;
}
public string BarCode { get; set; }
public string Vendor { get; set; }
public double Price { get; set; }
public int CompareTo(Article other)
{
return this.BarCode.CompareTo(other.BarCode);
}
public override string ToString()
{
return string.Format("{0}-{1}-{2}", this.BarCode, this.Price, this.Vendor);
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using XLua;
namespace Extend.Common {
[LuaCallCSharp]
public class IniRead {
private class Section {
public string Name { get; }
public Dictionary<string, string> KeyValue { get; } = new Dictionary<string, string>();
public Section(string n) {
Name = n;
}
}
private readonly List<Section> iniSections = new List<Section>();
[BlackList]
public static IniRead Parse(TextReader reader) {
var ini_reader = new IniRead();
string line;
while( ( line = reader.ReadLine() ) != null ) {
line = TrimComment(line);
if( line.Length == 0 ) continue;
if( line.StartsWith("[") && line.Contains("]") ) {
var index = line.IndexOf(']');
var name = line.Substring(1, index - 1).Trim();
var foundSection = ini_reader.iniSections.Find(x => x.Name == name);
if( foundSection == null )
ini_reader.iniSections.Add(new Section(name));
else
continue;
}
if( line.Contains("=") ) {
var index = line.IndexOf('=');
var key = line.Substring(0, index).Trim();
var value = line.Substring(index + 1).Trim();
ini_reader.iniSections.Last().KeyValue.Add(key, value);
}
}
return ini_reader;
}
private static string TrimComment(string s) {
if( s.Contains(";") ) {
var index = s.IndexOf(';');
s = s.Substring(0, index).Trim();
}
return s;
}
private bool FindOne(string section, string key, out string val) {
var s = iniSections.Find(x => x.Name == section);
if( s == null ) {
val = string.Empty;
return false;
}
return s.KeyValue.TryGetValue(key, out val);
}
public int GetInt(string section, string key) {
return FindOne(section, key, out var val) ? int.Parse(val) : default;
}
public bool GetBool(string section, string key) {
return FindOne(section, key, out var val) && (val == "true" || val == "1");
}
public string GetString(string section, string key) {
FindOne(section, key, out var val);
return val;
}
public double GetDouble(string section, string key) {
return FindOne(section, key, out var val) ? double.Parse(val) : default;
}
private IniRead() {
}
public static IniRead SystemSetting { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Status.Data.Entities;
namespace Status.Data
{
public class IdentityContext : IdentityDbContext
{
public IdentityContext(DbContextOptions<IdentityContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<IdentityUser>(b =>
{
// Primary key
b.HasKey(u => u.Id);
// Indexes for "normalized" username and email, to allow efficient lookups
b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique();
b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex");
// Maps to the AspNetUsers table
b.ToTable("AspNetUsers");
// A concurrency token for use with the optimistic concurrency checking
b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();
// Limit the size of columns to use efficient database types
b.Property(u => u.UserName).HasMaxLength(256);
b.Property(u => u.NormalizedUserName).HasMaxLength(256);
b.Property(u => u.Email).HasMaxLength(256);
b.Property(u => u.NormalizedEmail).HasMaxLength(256);
// The relationships between User and other entity types
// Note that these relationships are configured with no navigation properties
// Each User can have many UserClaims
b.HasMany<IdentityUserClaim<string>>().WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
// Each User can have many UserLogins
b.HasMany<IdentityUserLogin<string>>().WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
// Each User can have many UserTokens
b.HasMany<IdentityUserToken<string>>().WithOne().HasForeignKey(ut => ut.UserId).IsRequired();
// Each User can have many entries in the UserRole join table
b.HasMany<IdentityUserRole<string>>().WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
b.HasMany<Update>().WithOne(u => u.AspNetUser).HasForeignKey(us => us.UserId);
});
builder.Entity<IdentityUserClaim<string>>(b =>
{
// Primary key
b.HasKey(uc => uc.Id);
// Maps to the AspNetUserClaims table
b.ToTable("AspNetUserClaims");
});
builder.Entity<IdentityUserLogin<string>>(b =>
{
// Composite primary key consisting of the LoginProvider and the key to use
// with that provider
b.HasKey(l => new { l.LoginProvider, l.ProviderKey });
// Limit the size of the composite key columns due to common DB restrictions
b.Property(l => l.LoginProvider).HasMaxLength(128);
b.Property(l => l.ProviderKey).HasMaxLength(128);
// Maps to the AspNetUserLogins table
b.ToTable("AspNetUserLogins");
});
builder.Entity<IdentityUserToken<string>>(b =>
{
// Composite primary key consisting of the UserId, LoginProvider and Name
b.HasKey(t => new { t.UserId, t.LoginProvider, t.Name });
// Limit the size of the composite key columns due to common DB restrictions
b.Property(t => t.LoginProvider).HasMaxLength(128);
b.Property(t => t.Name).HasMaxLength(128);
// Maps to the AspNetUserTokens table
b.ToTable("AspNetUserTokens");
});
builder.Entity<IdentityRole>(b =>
{
// Primary key
b.HasKey(r => r.Id);
// Index for "normalized" role name to allow efficient lookups
b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex").IsUnique();
// Maps to the AspNetRoles table
b.ToTable("AspNetRoles");
// A concurrency token for use with the optimistic concurrency checking
b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();
// Limit the size of columns to use efficient database types
b.Property(u => u.Name).HasMaxLength(256);
b.Property(u => u.NormalizedName).HasMaxLength(256);
// The relationships between Role and other entity types
// Note that these relationships are configured with no navigation properties
// Each Role can have many entries in the UserRole join table
b.HasMany<IdentityUserRole<string>>().WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
// Each Role can have many associated RoleClaims
b.HasMany<IdentityRoleClaim<string>>().WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
});
builder.Entity<IdentityRoleClaim<string>>(b =>
{
// Primary key
b.HasKey(rc => rc.Id);
// Maps to the AspNetRoleClaims table
b.ToTable("AspNetRoleClaims");
});
builder.Entity<IdentityUserRole<string>>(b =>
{
// Primary key
b.HasKey(r => new { r.UserId, r.RoleId });
// Maps to the AspNetUserRoles table
b.ToTable("AspNetUserRoles");
});
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace EventStore.Projections.Core.Tests.Services.parallel_processing_load_balancer {
[TestFixture]
public class when_scheduling_first_tasks : specification_with_parallel_processing_load_balancer {
private List<string> _scheduledTasks;
private List<int> _scheduledOnWorkers;
private int _scheduled;
protected override void Given() {
_scheduled = 0;
_scheduledTasks = new List<string>();
_scheduledOnWorkers = new List<int>();
}
protected override void When() {
_balancer.ScheduleTask("task1", OnScheduled);
_balancer.ScheduleTask("task2", OnScheduled);
}
private void OnScheduled(string task, int worker) {
_scheduled++;
_scheduledTasks.Add(task);
_scheduledOnWorkers.Add(worker);
}
[Test]
public void schedules_all_tasks() {
Assert.AreEqual(2, _scheduled);
}
[Test]
public void schedules_correct_tasks() {
Assert.That(new[] {"task1", "task2"}.SequenceEqual(_scheduledTasks));
}
[Test]
public void schedules_on_different_workers() {
Assert.That(_scheduledOnWorkers.Distinct().Count() == 2);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PointOnCircleColor : MonoBehaviour
{
private SpriteRenderer sprite;
[Range(0, 1)] public float Hue;
[Range(0, 1)] public float Sat;
[Range(0, 1)] public float Val;
public float speed;
public float r;
// Start is called before the first frame update
void Start()
{
sprite = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
Vector3 changingColor = PointOnCircle(Hue * Time.time, Sat);
sprite.color = Color.HSVToRGB(changingColor.x, changingColor.y, changingColor.z, true);
}
public Vector3 PointOnCircle(float angle, float radius)
{
return new Vector3(radius * Mathf.Cos(angle), radius * Mathf.Sin(angle), Val);
}
}
|
using System.Collections;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests
{
public class NetworkVarBufferCopyTest : BaseMultiInstanceTest
{
public class DummyNetVar : NetworkVariableBase
{
private const int k_DummyValue = 0x13579BDF;
public bool DeltaWritten;
public bool FieldWritten;
public bool DeltaRead;
public bool FieldRead;
public bool Dirty = true;
public override void ResetDirty()
{
Dirty = false;
}
public override bool IsDirty()
{
return Dirty;
}
public override void WriteDelta(FastBufferWriter writer)
{
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(k_DummyValue) + 1);
using (var bitWriter = writer.EnterBitwiseContext())
{
bitWriter.WriteBits((byte)1, 1);
}
writer.WriteValue(k_DummyValue);
DeltaWritten = true;
}
public override void WriteField(FastBufferWriter writer)
{
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(k_DummyValue) + 1);
using (var bitWriter = writer.EnterBitwiseContext())
{
bitWriter.WriteBits((byte)1, 1);
}
writer.WriteValue(k_DummyValue);
FieldWritten = true;
}
public override void ReadField(FastBufferReader reader)
{
reader.TryBeginRead(FastBufferWriter.GetWriteSize(k_DummyValue) + 1);
using (var bitReader = reader.EnterBitwiseContext())
{
bitReader.ReadBits(out byte b, 1);
}
reader.ReadValue(out int i);
Assert.AreEqual(k_DummyValue, i);
FieldRead = true;
}
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
{
reader.TryBeginRead(FastBufferWriter.GetWriteSize(k_DummyValue) + 1);
using (var bitReader = reader.EnterBitwiseContext())
{
bitReader.ReadBits(out byte b, 1);
}
reader.ReadValue(out int i);
Assert.AreEqual(k_DummyValue, i);
DeltaRead = true;
}
}
public class DummyNetBehaviour : NetworkBehaviour
{
public DummyNetVar NetVar = new DummyNetVar();
}
protected override int NbClients => 1;
[UnitySetUp]
public override IEnumerator Setup()
{
yield return StartSomeClientsAndServerWithPlayers(useHost: true, nbClients: NbClients,
updatePlayerPrefab: playerPrefab =>
{
var dummyNetBehaviour = playerPrefab.AddComponent<DummyNetBehaviour>();
});
}
[UnityTest]
public IEnumerator TestEntireBufferIsCopiedOnNetworkVariableDelta()
{
// This is the *SERVER VERSION* of the *CLIENT PLAYER*
var serverClientPlayerResult = new MultiInstanceHelpers.CoroutineResultWrapper<NetworkObject>();
yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation(
x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId,
m_ServerNetworkManager, serverClientPlayerResult));
// This is the *CLIENT VERSION* of the *CLIENT PLAYER*
var clientClientPlayerResult = new MultiInstanceHelpers.CoroutineResultWrapper<NetworkObject>();
yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation(
x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId,
m_ClientNetworkManagers[0], clientClientPlayerResult));
var serverSideClientPlayer = serverClientPlayerResult.Result;
var clientSideClientPlayer = clientClientPlayerResult.Result;
var serverComponent = (serverSideClientPlayer).GetComponent<DummyNetBehaviour>();
var clientComponent = (clientSideClientPlayer).GetComponent<DummyNetBehaviour>();
var waitResult = new MultiInstanceHelpers.CoroutineResultWrapper<bool>();
yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.WaitForCondition(
() => clientComponent.NetVar.DeltaRead == true,
waitResult,
maxFrames: 120));
if (!waitResult.Result)
{
Assert.Fail("Failed to send a delta within 120 frames");
}
Assert.True(serverComponent.NetVar.FieldWritten);
Assert.True(serverComponent.NetVar.DeltaWritten);
Assert.True(clientComponent.NetVar.FieldRead);
Assert.True(clientComponent.NetVar.DeltaRead);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.IO;
using System.Diagnostics;
using System.Xml.Serialization;
using SharpDX;
using Fusion;
using Fusion.Graphics;
using System.Threading;
using Fusion.Mathematics;
namespace UberFxc {
/// <summary>
/// Creates definition list by declaration.
/// </summary>
public class UbershaderEnumerator {
List<string> defineList;
/// <summary>
/// Define list.
/// </summary>
public ICollection<string> DefineList {
get {
return defineList;
}
}
/// <summary>
/// Creates list of definitions using given string and leading keyword.
/// </summary>
/// <param name="inputString"></param>
/// <param name="prefix"></param>
public UbershaderEnumerator ( string inputString, string leadingKeyword )
{
defineList = Parse( inputString, leadingKeyword );
}
/*-----------------------------------------------------------------------------------------------
*
* Generator :
*
-----------------------------------------------------------------------------------------------*/
enum Operation {
Combination,
Sequence,
Exclusion,
Definition,
}
class Node {
public bool Optional = false;
public Operation Operation = Operation.Combination;
public string Definition = null;
public List<Node> Nodes = new List<Node>();
public Node ( string define )
{
Operation = Operation.Definition;
Definition = define;
}
public Node ( Operation op, bool optional )
{
Operation = op;
Optional = optional;
}
public void Add ( Node node )
{
Nodes.Add( node );
}
public List<string> Enumerate ()
{
var R = new List<string>();
if ( Optional ) {
R.Add("");
}
if ( Operation==Operation.Combination ) {
foreach (var child in Nodes) {
R = Combine( R, child.Enumerate() );
}
} else if ( Operation==Operation.Sequence ) {
var Q = new List<string>();
foreach (var child in Nodes) {
Q = Combine( Q, child.Enumerate() );
R.AddRange( Q );
}
} else if ( Operation==Operation.Exclusion ) {
foreach (var child in Nodes) {
R.AddRange( child.Enumerate() );
}
} else if ( Operation==Operation.Definition ) {
R.Add( Definition );
}
return R;
}
}
/// <summary>
/// Sorts words and removed duplicates
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static string CleanupString ( string str )
{
//return str;
var words = str
.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)
//.OrderBy( w => w )
.Distinct()
.ToArray();
return string.Join(" ", words);
}
/// <summary>
/// Removed duplicates
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
static List<string> CleanupList ( List<string> list )
{
return list.ToList();
//return list.OrderBy( w => w ).Distinct().ToList();
}
/// <summary>
/// Combines define sets
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <returns></returns>
static List<string> Combine ( List<string> A, List<string> B )
{
var C = new List<string>();
if ( !A.Any() ) return B;
if ( !B.Any() ) return A;
foreach ( var a in A ) {
foreach ( var b in B ) {
C.Add( CleanupString( a + " " + b ) );
}
}
return CleanupList( C );
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
List<string> Parse ( string line, string leadingKeyword )
{
cs = new CharStream( line );
var root = Expression( leadingKeyword );
var list = root.Enumerate();
return list;
}
CharStream cs;
/*-----------------------------------------------------------------------------------------------
*
* Recursive Descent Parser Stuff :
*
-----------------------------------------------------------------------------------------------*/
/// <summary>
///
/// </summary>
Node Expression ( string leadingKeyword )
{
if (!string.IsNullOrEmpty(leadingKeyword)) {
cs.Expect( leadingKeyword );
}
if (cs.AcceptSpace()) {
return Combination();
} else {
return new Node("");
}
}
Node Combination()
{
var node = new Node( Operation.Combination, false );
node.Add( Sequence() );
while (cs.AcceptSpace()) {
node.Add( Sequence() );
}
return node;
}
Node Sequence()
{
var node = new Node( Operation.Sequence, cs.Accept("+") );
node.Add( Exclusion() );
while (cs.Accept("..")) {
node.Add( Exclusion() );
}
return node;
}
Node Exclusion ()
{
var node = new Node( Operation.Exclusion, false );
node.Add( Factor() );
while (cs.Accept("|")) {
node.Add( Factor() );
}
return node;
}
Node Factor ()
{
if ( cs.Accept("(") ) {
var node = Combination();
cs.Expect(")");
return node;
} else {
return Definition();
}
}
Node Definition ()
{
var s = cs.ExpectIdent();
return new Node( s );
}
}
}
|
using System;
namespace Verses.Portable
{
public class InvalidVerseException : Exception
{
public InvalidVerseException ()
: base () { }
public InvalidVerseException (string message)
: base (message) { }
public InvalidVerseException (string format, params object[] args)
: base (string.Format (format, args)) { }
public InvalidVerseException (string message, Exception innerException)
: base (message, innerException) { }
public InvalidVerseException (string format, Exception innerException, params object[] args)
: base (string.Format (format, args), innerException) { }
}
} |
// This file was @generated with LibOVRPlatform/codegen/main. Do not modify it!
#pragma warning disable 0618
namespace Oculus.Platform.Models
{
using System;
using System.Collections;
using Oculus.Platform.Models;
using System.Collections.Generic;
using UnityEngine;
public class Leaderboard
{
public readonly string ApiName;
// May be null. Check before using.
public readonly Destination DestinationOptional;
[Obsolete("Deprecated in favor of DestinationOptional")]
public readonly Destination Destination;
public readonly UInt64 ID;
public Leaderboard(IntPtr o)
{
ApiName = CAPI.ovr_Leaderboard_GetApiName(o);
{
var pointer = CAPI.ovr_Leaderboard_GetDestination(o);
Destination = new Destination(pointer);
if (pointer == IntPtr.Zero) {
DestinationOptional = null;
} else {
DestinationOptional = Destination;
}
}
ID = CAPI.ovr_Leaderboard_GetID(o);
}
}
public class LeaderboardList : DeserializableList<Leaderboard> {
public LeaderboardList(IntPtr a) {
var count = (int)CAPI.ovr_LeaderboardArray_GetSize(a);
_Data = new List<Leaderboard>(count);
for (int i = 0; i < count; i++) {
_Data.Add(new Leaderboard(CAPI.ovr_LeaderboardArray_GetElement(a, (UIntPtr)i)));
}
_NextUrl = CAPI.ovr_LeaderboardArray_GetNextUrl(a);
}
}
}
|
namespace DBTek.BugGuardian.WebForms.Helpers
{
public class ConfigurationHelper
{
private const string DefaultCollectionName = "DefaultCollection";
public static string Url
=> Config.ConfigurationSettings.AppSettings["Url"];
public static string Username
=> Config.ConfigurationSettings.AppSettings["Username"];
public static string Password
=> Config.ConfigurationSettings.AppSettings["Password"];
public static string CollectiontName
=> Config.ConfigurationSettings.AppSettings["CollectiontName"] ?? DefaultCollectionName;
public static string ProjectName
=> Config.ConfigurationSettings.AppSettings["ProjectName"];
public static bool AvoidMultipleReport
=> bool.Parse(Config.ConfigurationSettings.AppSettings["AvoidMultipleReport"] ?? "true");
public static bool AssignToCurrentIteration
=> bool.Parse(Config.ConfigurationSettings.AppSettings["AssignToCurrentIteration"] ?? "true");
}
}
|
using AndcultureCode.CSharp.Core.Interfaces;
using AndcultureCode.CSharp.Core.Models.Errors;
using RestSharp;
using System.Collections.Generic;
using System.Net;
namespace AndcultureCode.CSharp.Sitefinity.Core.Models.Services
{
public class RestResponseResult<T> : Result<T>
{
public HttpStatusCode ExpectedStatusCode { get; }
/// <summary>
/// Provides the actual rest response data in its original format
/// </summary>
public IRestResponse RestResponse { get; }
/// <summary>
/// Indicates whether the RestResponse's StatusCode was of the expected type after the request was made
/// and its data value was returned
/// </summary>
public bool WasExpectedStatusCode => ExpectedStatusCode == RestResponse.StatusCode;
public bool WasUnexpectedStatusCode => !WasExpectedStatusCode;
public RestResponseResult(HttpStatusCode expectedStatusCode, IRestResponse restResponse) : base()
{
Errors = new List<IError>();
ExpectedStatusCode = expectedStatusCode;
RestResponse = restResponse;
}
}
}
|
namespace KittensApp.WebIt.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KittenApp.Models;
using Microsoft.EntityFrameworkCore;
using Models.BindingModels;
using Models.ViewModels;
using Services;
using SimpleMvc.Framework.Attributes.Methods;
using SimpleMvc.Framework.Attributes.Security;
using SimpleMvc.Framework.Interfaces;
public class KittensController : BaseController
{
private KittensService kittens;
public KittensController()
{
this.kittens = new KittensService();
}
[PreAuthorize]
public IActionResult Add()
{
if (!this.User.IsAuthenticated)
{
return this.RedirectToHome();
}
return View();
}
[HttpPost]
[PreAuthorize]
public IActionResult Add(KittenAddingModel model)
{
if (!this.User.IsAuthenticated)
{
return RedirectToHome();
}
if (!this.IsValidModel(model))
{
SetValidatorErrors();
return this.View();
}
Breed breed = this.kittens.GetBreed(model.Breed);
if (breed == null)
{
this.ShowError("Invalid Breed!");
return this.View();
}
var kitten = this.kittens.Create(model.Name, model.Age, breed);
if (kitten == null)
{
ShowError("Unsuccessfull operation!");
return this.View();
}
return RedirectToAction("/kittens/all");
}
[HttpGet]
[PreAuthorize]
public IActionResult All()
{
var kittens = PrepareKittensDetails();
var kittensResult = PrepareHtmlDetails(kittens);
this.Model.Data["allKittens"] = kittensResult.ToString();
return this.View();
}
private static StringBuilder PrepareHtmlDetails(List<string> kittens)
{
var kittensResult = new StringBuilder();
kittensResult.Append(@"<div class=""row text-center"">");
for (int i = 0; i < kittens.Count; i++)
{
kittensResult.Append(kittens[i]);
if (i % 3 == 2)
{
kittensResult.Append(@"</div><div class=""row text-center"">");
}
}
kittensResult.Append("</div>");
return kittensResult;
}
private List<string> PrepareKittensDetails()
{
return this.Context.Kittens
.Include(k => k.Breed)
.Select(KittenDetailsViewModel.FromKitten)
.Select(kdvm =>
$@"<div class=""col-4"">
<img class=""img-thumbnail"" src={kdvm.PictureUrl} alt=""{kdvm.Name}'s photo"" />
<div>
<h5>Name: {kdvm.Name}</h5>
<h5>Age: {kdvm.Age}</h5>
<h5>Breed: {kdvm.Breed}</h5>
</div>
</div>")
.ToList();
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class UGUIButon : MonoBehaviour,IPointerClickHandler,IPointerEnterHandler,IPointerExitHandler {
public string sceneName;
public GameObject myGameObject;
public string gameObjectName;
public string LoadLevelOrLoadAddtive;
public delegate void delegateOnClicked();
public delegateOnClicked OnClicked;
public delegate void delegateOnEntered();
public delegateOnEntered OnEntered;
public delegate void delegateOnExited();
public delegateOnExited OnExited;
void myOnEntered(){
}
void myOnClicked(){
}
void myOnExited(){
}
void Start(){
OnClicked+=myOnClicked;
OnEntered+=myOnEntered;
OnExited+=myOnExited;
gameObjectName=gameObject.name;
/////////////////////////////////////////////////////////////////////////////
//string modelDirStr = AssetDatabase.GetAssetPath (modelAsset);
Debug.Log ("gameObjectName=" + gameObjectName);
string[] modelDirArr;
modelDirArr=gameObjectName.Split("/"[0]);
string buildDir = modelDirArr[0];
//for(int i = 1; i < modelDirArr.Length-1; i++){
// buildDir = buildDir +"/"+ modelDirArr [i];
//}
//CharaDir = buildDir;
//Debug.Log ("CharaDir="+CharaDir);
//CharaName = modelDirArr [modelDirArr.Length-1];
//Debug.Log ("CharaName="+CharaName);
////////////////////////////////////////////////////////////////////////////////
}
public void OnPointerClick (PointerEventData eventData){
GameObject gameobject=eventData.selectedObject.gameObject;
Debug.Log(gameobject.name);
if(OnClicked != null)
{
OnClicked();
}
}
public void OnPointerExit (PointerEventData eventData){
if(OnExited != null)
{
OnExited();
}
}
public void OnPointerEnter (PointerEventData eventData){
if(OnEntered != null)
{
OnEntered();
}
}
}
|
using System;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using YiSha.Util;
using System.ComponentModel;
namespace YiSha.Entity.HotelManage
{
/// <summary>
/// 创 建:admin
/// 日 期:2020-11-07 12:27
/// 描 述:实体类
/// </summary>
[Table("HtlGroups")]
public class GroupsEntity : BaseExtensionEntity
{
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("资源名称")]
public string GroupName { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("用途")]
public string Purpose { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("联系人")]
public string Contacts { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("手机")]
public string Phone { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("微信")]
public string Wechat { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("区域")]
public string Area { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("等级")]
public int? Rank { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("备注")]
public string Remark { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
[Description("分类Id")]
public long? CategoryId { get; set; }
[NotMapped]
[Description("分类")]
public string CategoryName { get; set; }
}
}
|
using System.Collections.Generic;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.ViewModels;
using MvxDemo.Core.Widgets;
using MvxDemo.Models;
namespace MvxDemo.Core.ViewModels {
public class FirstViewModel
: MvxViewModel {
private string apiBaseUrl = "http://192.168.1.109/MvxDemo/";
private string _emailAddress = "";
public string EmailAddress {
get { return _emailAddress; }
set { _emailAddress = value; RaisePropertyChanged(() => EmailAddress); }
}
private string _password = "";
public string Password {
get { return _password; }
set { _password = value; RaisePropertyChanged(() => Password); }
}
private MvxCommand _loginCommand;
public System.Windows.Input.ICommand LoginCommand {
get { _loginCommand = _loginCommand ?? new MvxCommand(DoLogin); return _loginCommand; }
}
private async void DoLogin() {
if (_emailAddress.Trim() != "" && _password.Trim() != "") {
using (var apiClient = new WebApiClient(apiBaseUrl)) {
User user = await apiClient.GetAsync<User>("User", _emailAddress, _password);
IAlertMessage alertMsg = Mvx.Resolve<IAlertMessage>();
if (user != null && user.UserId != 0) {
AlertMessageResult msgResult =
await alertMsg.ShowAsync(
"Welcome back, " + user.FirstName + " " + user.LastName + ".",
"Login Successful",
AlertMessageButtons.OK);
ShowViewModel<QuestionViewModel>(new { userId = user.UserId, apiBaseUrl = this.apiBaseUrl });
}
else {
AlertMessageResult msgResult =
await alertMsg.ShowAsync(
"Unable to login with this username and password.",
"Login Unsuccessful",
AlertMessageButtons.OK);
}
}
}
}
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using Yarp.ReverseProxy.Utilities;
namespace Yarp.ReverseProxy.Configuration
{
/// <summary>
/// Route criteria for a query parameter that must be present on the incoming request.
/// </summary>
public sealed record RouteQueryParameter
{
/// <summary>
/// Name of the query parameter to look for.
/// This field is case insensitive and required.
/// </summary>
public string Name { get; init; } = default!;
/// <summary>
/// A collection of acceptable query parameter values used during routing.
/// </summary>
public IReadOnlyList<string>? Values { get; init; }
/// <summary>
/// Specifies how query parameter values should be compared (e.g. exact matches Vs. contains).
/// Defaults to <see cref="QueryParameterMatchMode.Exact"/>.
/// </summary>
public QueryParameterMatchMode Mode { get; init; }
/// <summary>
/// Specifies whether query parameter value comparisons should ignore case.
/// When <c>true</c>, <see cref="StringComparison.Ordinal" /> is used.
/// When <c>false</c>, <see cref="StringComparison.OrdinalIgnoreCase" /> is used.
/// Defaults to <c>false</c>.
/// </summary>
public bool IsCaseSensitive { get; init; }
public bool Equals(RouteQueryParameter? other)
{
if (other == null)
{
return false;
}
return string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& Mode == other.Mode
&& IsCaseSensitive == other.IsCaseSensitive
&& (IsCaseSensitive
? CaseSensitiveEqualHelper.Equals(Values, other.Values)
: CaseInsensitiveEqualHelper.Equals(Values, other.Values));
}
public override int GetHashCode()
{
return HashCode.Combine(
Name?.GetHashCode(StringComparison.OrdinalIgnoreCase),
Mode,
IsCaseSensitive,
IsCaseSensitive
? CaseSensitiveEqualHelper.GetHashCode(Values)
: CaseInsensitiveEqualHelper.GetHashCode(Values));
}
}
}
|
using System.Collections.Generic;
using SignInCheckIn.Models.DTO;
namespace SignInCheckIn.Services.Interfaces
{
public interface ILookupService
{
List<StateDto> GetStates();
List<CountryDto> GetCountries();
}
}
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.Billing.Common;
using Microsoft.Azure.Commands.Billing.Models;
using Microsoft.Azure.Management.Billing;
using Microsoft.Azure.Management.Billing.Models;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Billing.Cmdlets.InvoiceSections
{
[Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "InvoiceSection", DefaultParameterSetName = Constants.ParameterSetNames.ListParameterSet), OutputType(typeof(PSInvoiceSection))]
public class GetAzureRmInvoiceSection : AzureBillingCmdletBase
{
[Parameter(Mandatory = true, HelpMessage = "Name of a specific billing account to get.", ParameterSetName = Constants.ParameterSetNames.SingleItemParameterSet)]
[ValidateNotNullOrEmpty]
public List<string> Name { get; set; }
[Parameter(Mandatory = true, Position = 0, HelpMessage = "Name of the billing account.")]
[ValidateNotNullOrEmpty]
public string BillingAccountName { get; set; }
[Parameter(Mandatory = true, Position = 0, HelpMessage = "Name of the billing profile to get invoice sections under it.")]
[ValidateNotNullOrEmpty]
public string BillingProfileName { get; set; }
public override void ExecuteCmdlet()
{
try
{
if (ParameterSetName.Equals(Constants.ParameterSetNames.ListParameterSet))
{
WriteObject(
BillingManagementClient.InvoiceSections
.ListByBillingProfile(BillingAccountName, BillingProfileName)
.Select(x => new PSInvoiceSection(x)), true);
return;
}
if (ParameterSetName.Equals(Constants.ParameterSetNames.SingleItemParameterSet))
{
foreach (var invoiceSectionName in Name)
{
try
{
var invoiceSection = new PSInvoiceSection(BillingManagementClient.InvoiceSections.Get(BillingAccountName, BillingProfileName, invoiceSectionName));
WriteObject(invoiceSection);
}
catch (ErrorResponseException error)
{
WriteWarning(invoiceSectionName + ": " + error.Body.Error.Message);
// continue with the next
}
}
}
}
catch (ErrorResponseException e)
{
WriteWarning(e.Body.Error.Message);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dimer.Models
{
public class MessageTimer : IDisposable
{
private readonly IObservable<long> _timer;
private IDisposable _subscription;
public TimeSpan Time { get; }
public event Action Finished;
public string Message { get; set; }
public MessageTimer(TimeSpan time)
{
Time = time;
_timer = Observable
.Interval(Time)
.FirstAsync();
}
public void Start(Func<string, Task> execute)
{
_subscription = _timer
.Select(x => Message)
.Finally(() => Finished?.Invoke())
.Subscribe(
async _ => await execute(Message),
async ex => await execute(ExceptionToMessage(ex)));
}
public void Cancel() => _subscription?.Dispose();
private static string ExceptionToMessage(Exception ex)
=> ex.InnerException switch
{
OperationCanceledException => $"キャンセルされました。",
_ => $"不明なエラーによりタイマーが終了しました。"
};
public void Dispose()
{
_subscription?.Dispose();
GC.SuppressFinalize(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch13_DataBinding.Models
{
public class EmployeesViewModel
{
public EmployeesViewModel()
{
Employees = new HashSet<Employee>();
Employees.Add(new Employee { Id = 1, Name = "Alice", DoB = new DateTime(1992, 1, 27), Salary = 34000M });
Employees.Add(new Employee { Id = 2, Name = "Bob", DoB = new DateTime(1995, 4, 13), Salary = 64000M });
}
public HashSet<Employee> Employees { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Regression;
using System;
#if UNITY_V4
using Microsoft.Practices.Unity;
#else
using Unity.Injection;
using Unity;
#endif
namespace Injection
{
public abstract partial class Pattern
{
protected virtual void Assert_Injection(Type type, InjectionMember member, object @default, object expected)
{
// Inject
Container.RegisterType(null, type, null, null, member);
// Act
Assert.ThrowsException<ResolutionFailedException>(() => Container.Resolve(type, null));
// Register missing types
RegisterTypes();
// Act
var instance = Container.Resolve(type, null) as PatternBaseType;
// Validate
Assert.IsNotNull(instance);
Assert.AreEqual(expected, instance.Value);
}
}
}
|
namespace Bugfree.OracleHospitality.Clients.UnitTests.Builders
{
// See http://natpryce.com/articles/000714.html for A pattern.
public static class A
{
public static OracleHospitalityClientOptionsBuilder OracleHospitalityClientOptions =>
new OracleHospitalityClientOptionsBuilder();
}
} |
using System;
using RustMacroExpander;
using Microsoft.CSharp;
using Xunit;
using RustMacroExpander.ViewModels;
namespace RustMacroExpander.Tests
{
public class UnitTest1
{
public class Person
{
public string Trait { get; set; } = "Ugly";
public uint Age { get; set; } = 10;
}
public class ViewModel : ViewModelBase
{
public ViewModel() : base(new Person())
{
}
}
[Fact]
public void PropertyAvailability()
{
dynamic vm = new ViewModel();
dynamic trait = vm.Trait;
Assert.Equal(trait, "Ugly");
Assert.Equal<uint>(vm.Age, 10);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Photosphere.DependencyInjection.Types
{
internal interface ITypesProvider
{
IReadOnlyCollection<Type> GetAllDerivedTypesFrom(Type type, Assembly assembly);
IReadOnlyCollection<Type> GetMarkedTypes(Type attributeType);
}
} |
using System.Collections.Generic;
using System.IO;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace XCharts
{
public static class XThemeMgr
{
/// <summary>
/// 重新加载主题列表
/// </summary>
public static void ReloadThemeList()
{
//Debug.Log("LoadThemesFromResources");
XChartsMgr.Instance.m_ThemeDict.Clear();
XChartsMgr.Instance.m_ThemeNames.Clear();
AddTheme(ChartTheme.Default);
AddTheme(ChartTheme.Light);
AddTheme(ChartTheme.Dark);
foreach (var json in XChartsSettings.customThemes)
{
if (json != null && !string.IsNullOrEmpty(json.text))
{
var theme = JsonUtility.FromJson<ChartTheme>(json.text);
AddTheme(theme);
}
}
//Debug.Log("LoadThemesFromResources DONE: theme count=" + m_ThemeDict.Keys.Count);
}
public static void AddTheme(ChartTheme theme)
{
if (theme == null) return;
if (!XChartsMgr.Instance.m_ThemeDict.ContainsKey(theme.themeName))
{
XChartsMgr.Instance.m_ThemeDict.Add(theme.themeName, theme);
XChartsMgr.Instance.m_ThemeNames.Add(theme.themeName);
}
else
{
Debug.LogError("Theme name is exist:" + theme.themeName);
}
}
public static ChartTheme GetTheme(string themeName)
{
if (!XChartsMgr.Instance.m_ThemeDict.ContainsKey(themeName))
{
return null;
}
return XChartsMgr.Instance.m_ThemeDict[themeName];
}
public static List<string> GetAllThemeNames()
{
return XChartsMgr.Instance.m_ThemeNames;
}
public static bool ContainsTheme(string themeName)
{
return XChartsMgr.Instance.m_ThemeNames.Contains(themeName);
}
public static void SwitchTheme(BaseChart chart, string themeName)
{
Debug.Log("SwitchTheme:" + themeName);
#if UNITY_EDITOR
if (XChartsMgr.Instance.m_ThemeDict.Count == 0)
{
ReloadThemeList();
}
#endif
if (!XChartsMgr.Instance.m_ThemeDict.ContainsKey(themeName))
{
Debug.LogError("SwitchTheme ERROR: not exist theme:" + themeName);
return;
}
var target = XChartsMgr.Instance.m_ThemeDict[themeName];
chart.theme.CopyTheme(target);
chart.RefreshAllComponent();
}
public static bool ExportTheme(ChartTheme theme, string themeNewName)
{
#if UNITY_EDITOR
var newtheme = ChartTheme.EmptyTheme;
newtheme.CopyTheme(theme);
newtheme.theme = Theme.Custom;
newtheme.themeName = themeNewName;
var themeFileName = "XTheme-" + newtheme.themeName;
var assetPath = string.Format("Assets/XCharts/Resources/{0}", themeFileName);
var filePath = string.Format("{0}/../{1}.json", Application.dataPath, assetPath);
var json = JsonUtility.ToJson(newtheme, true);
File.WriteAllText(filePath, json);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
var obj = Resources.Load<TextAsset>(themeFileName);
XChartsSettings.AddJsonTheme(obj);
ReloadThemeList();
return true;
#else
return false;
#endif
}
public static string GetThemeAssetPath(string themeName)
{
return string.Format("Assets/XCharts/Resources/XTheme-{0}.json", themeName);
}
}
} |
using Day17Task1Solution.Enums;
using Shared.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Day17Task1Solution.Models
{
internal class MapPoint : PointLong
{
internal MapPoint(long x, long y, PointType type)
: base(x, y)
{
Type = type;
}
internal PointType Type { get; private set; }
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Ogmas.Models.Dtos.Get;
namespace Ogmas.Exceptions
{
public static class ErrorHandler
{
public static async Task HandleError(HttpContext context)
{
var exception = context.Features.Get<IExceptionHandlerPathFeature>().Error;
var error = new ErrorResponse()
{
ErrorType = exception.GetType().Name,
Message = exception.Message
};
context.Response.StatusCode = exception switch
{
InvalidActionException _ => context.Response.StatusCode = 400,
NotFoundException _ => context.Response.StatusCode = 404,
ArgumentException _ => context.Response.StatusCode = 400,
_ => context.Response.StatusCode = 500
};
await context.Response.WriteJsonAsync(error, "application/json");
}
}
} |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
// Modified by TimCodes.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel;
using IdentityModel.Client;
using IdentityServer.IntegrationTests.Clients.Setup;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class CustomTokenResponseClients
{
private const string TokenEndpoint = "https://server/connect/token";
private readonly HttpClient _client;
public CustomTokenResponseClients()
{
var builder = new WebHostBuilder()
.UseStartup<StartupWithCustomTokenResponses>();
var server = new TestServer(builder);
_client = server.CreateClient();
}
[Fact]
public async Task Resource_owner_success_should_return_custom_response()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
UserName = "bob",
Password = "bob",
Scope = "api1"
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeFalse();
fields.TryGetValue("error_description", out temp).Should().BeFalse();
fields.TryGetValue("token_type", out temp).Should().BeTrue();
fields.TryGetValue("expires_in", out temp).Should().BeTrue();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(false);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
// token content
var payload = GetPayload(response);
payload.Count().Should().Be(12);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "roclient");
payload.Should().Contain("sub", "bob");
payload.Should().Contain("idp", "local");
payload["aud"].Should().Be("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("password");
}
[Fact]
public async Task Resource_owner_failure_should_return_custom_error_response()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
UserName = "bob",
Password = "invalid",
Scope = "api1"
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeTrue();
fields.TryGetValue("error_description", out temp).Should().BeTrue();
fields.TryGetValue("token_type", out temp).Should().BeFalse();
fields.TryGetValue("expires_in", out temp).Should().BeFalse();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(true);
response.Error.Should().Be("invalid_grant");
response.ErrorDescription.Should().Be("invalid_credential");
response.ExpiresIn.Should().Be(0);
response.TokenType.Should().BeNull();
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
}
[Fact]
public async Task Extension_grant_success_should_return_custom_response()
{
var response = await _client.RequestTokenAsync(new TokenRequest
{
Address = TokenEndpoint,
GrantType = "custom",
ClientId = "client.custom",
ClientSecret = "secret",
Parameters =
{
{ "scope", "api1" },
{ "outcome", "succeed"}
}
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeFalse();
fields.TryGetValue("error_description", out temp).Should().BeFalse();
fields.TryGetValue("token_type", out temp).Should().BeTrue();
fields.TryGetValue("expires_in", out temp).Should().BeTrue();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(false);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
// token content
var payload = GetPayload(response);
payload.Count().Should().Be(12);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", "client.custom");
payload.Should().Contain("sub", "bob");
payload.Should().Contain("idp", "local");
payload["aud"].Should().Be("api");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
var amr = payload["amr"] as JArray;
amr.Count().Should().Be(1);
amr.First().ToString().Should().Be("custom");
}
[Fact]
public async Task Extension_grant_failure_should_return_custom_error_response()
{
var response = await _client.RequestTokenAsync(new TokenRequest
{
Address = TokenEndpoint,
GrantType = "custom",
ClientId = "client.custom",
ClientSecret = "secret",
Parameters =
{
{ "scope", "api1" },
{ "outcome", "fail"}
}
});
// raw fields
var fields = GetFields(response);
fields.Should().Contain("string_value", "some_string");
((Int64)fields["int_value"]).Should().Be(42);
object temp;
fields.TryGetValue("identity_token", out temp).Should().BeFalse();
fields.TryGetValue("refresh_token", out temp).Should().BeFalse();
fields.TryGetValue("error", out temp).Should().BeTrue();
fields.TryGetValue("error_description", out temp).Should().BeTrue();
fields.TryGetValue("token_type", out temp).Should().BeFalse();
fields.TryGetValue("expires_in", out temp).Should().BeFalse();
var responseObject = fields["dto"] as JObject;
responseObject.Should().NotBeNull();
var responseDto = GetDto(responseObject);
var dto = CustomResponseDto.Create;
responseDto.string_value.Should().Be(dto.string_value);
responseDto.int_value.Should().Be(dto.int_value);
responseDto.nested.string_value.Should().Be(dto.nested.string_value);
responseDto.nested.int_value.Should().Be(dto.nested.int_value);
// token client response
response.IsError.Should().Be(true);
response.Error.Should().Be("invalid_grant");
response.ErrorDescription.Should().Be("invalid_credential");
response.ExpiresIn.Should().Be(0);
response.TokenType.Should().BeNull();
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
}
private CustomResponseDto GetDto(JObject responseObject)
{
return responseObject.ToObject<CustomResponseDto>();
}
private Dictionary<string, object> GetFields(TokenResponse response)
{
return response.Json.ToObject<Dictionary<string, object>>();
}
private Dictionary<string, object> GetPayload(TokenResponse response)
{
var token = response.AccessToken.Split('.').Skip(1).Take(1).First();
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(
Encoding.UTF8.GetString(Base64Url.Decode(token)));
return dictionary;
}
}
} |
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace DldUtil
{
public static class GetRspDefines
{
static string SmcsFilePath { get { return Application.dataPath + "/smcs.rsp"; } }
static string UsFilePath { get { return Application.dataPath + "/us.rsp"; } }
static string BooFilePath { get { return Application.dataPath + "/boo.rsp"; } }
public struct Entry
{
public int TimesDefinedInSmcs;
public int TimesDefinedInUs;
public int TimesDefinedInBoo;
public int TimesDefinedInBuiltIn;
}
// Unity-made defines are in EditorUserBuildSettings.activeScriptCompilationDefines
static bool IsDefineAlreadyInUnity(string defineName)
{
string[] builtInDefines = EditorUserBuildSettings.activeScriptCompilationDefines;
for (int n = 0, len = builtInDefines.Length; n < len; n++)
{
if (builtInDefines[n] == defineName)
{
return true;
}
}
return false;
}
// ========================================================================================
static void IncrementTimesDefinedInBuiltIn(Dictionary<string, Entry> table, string define)
{
if (!table.ContainsKey(define))
{
table[define] = new Entry();
}
Entry currentDef = table[define];
currentDef.TimesDefinedInBuiltIn++;
// assign it back to store it
table[define] = currentDef;
}
static void IncrementTimesDefinedInSmcs(Dictionary<string, Entry> table, string define)
{
if (!table.ContainsKey(define))
{
table[define] = new Entry();
}
Entry currentDef = table[define];
currentDef.TimesDefinedInSmcs++;
// assign it back to store it
table[define] = currentDef;
}
static void IncrementTimesDefinedInUs(Dictionary<string, Entry> table, string define)
{
if (!table.ContainsKey(define))
{
table[define] = new Entry();
}
Entry currentDef = table[define];
currentDef.TimesDefinedInUs++;
// assign it back to store it
table[define] = currentDef;
}
static void IncrementTimesDefinedInBoo(Dictionary<string, Entry> table, string define)
{
if (!table.ContainsKey(define))
{
table[define] = new Entry();
}
Entry currentDef = table[define];
currentDef.TimesDefinedInBoo++;
// assign it back to store it
table[define] = currentDef;
}
// ========================================================================================
public static Dictionary<string, Entry> GetDefines()
{
Dictionary<string, Entry> result = new Dictionary<string, Entry>();
// ---------------------------------------------------------
string[] definesInSmcs = GetDefinesInsideFile(SmcsFilePath);
if (definesInSmcs != null && definesInSmcs.Length > 0)
{
for (int n = 0, len = definesInSmcs.Length; n < len; n++)
{
IncrementTimesDefinedInSmcs(result, definesInSmcs[n]);
if (IsDefineAlreadyInUnity(definesInSmcs[n]))
{
IncrementTimesDefinedInBuiltIn(result, definesInSmcs[n]);
}
}
}
// ---------------------------------------------------------
string[] definesInUs = GetDefinesInsideFile(UsFilePath);
if (definesInUs != null && definesInUs.Length > 0)
{
for (int n = 0, len = definesInUs.Length; n < len; n++)
{
IncrementTimesDefinedInUs(result, definesInUs[n]);
if (IsDefineAlreadyInUnity(definesInUs[n]))
{
IncrementTimesDefinedInBuiltIn(result, definesInUs[n]);
}
}
}
// ---------------------------------------------------------
string[] definesInBoo = GetDefinesInsideFile(BooFilePath);
if (definesInBoo != null && definesInBoo.Length > 0)
{
for (int n = 0, len = definesInBoo.Length; n < len; n++)
{
IncrementTimesDefinedInBoo(result, definesInBoo[n]);
if (IsDefineAlreadyInUnity(definesInBoo[n]))
{
IncrementTimesDefinedInBuiltIn(result, definesInBoo[n]);
}
}
}
// ---------------------------------------------------------
return result;
}
static string[] GetDefinesInsideFile(string filePath)
{
if (!File.Exists(filePath))
{
return null;
}
string rawContents = File.ReadAllText(filePath);
if (!rawContents.StartsWith("-define:"))
{
// malformed .rsp file
return null;
}
// remove "-define:"
string allDefines = rawContents.Substring(8);
//LogMgr.Ins.LogInfo(allDefines);
return allDefines.Split(';');
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using API.Source.Server_Connections;
using CrystalDecisions.Shared.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Formatting = Newtonsoft.Json.Formatting;
namespace API.Controllers
{
public class StoreProceduresController : ApiController
{
Tools dataInfo = new Tools();
DatabaseDataHolder connection = new DatabaseDataHolder();
/// <summary>
/// Function in charge of getting all infected data of a country
/// </summary>
/// <param name="country">
/// Name of the country
/// </param>
/// <returns>
/// JObject with all the data
/// </returns>
[Route("api/StoreProcedure/Home/{country}")]
[HttpGet]
public JObject Get(string country)
{
connection.openConnection();
var json = dataInfo.spCasesByCountry(country);
connection.closeConnection();
return json;
}
}
} |
//using System;
//using System.IO;
//using JiiLib.Media.Metadata.Ogg;
//using Xunit;
//namespace JiiLib.Media.Tests.Ogg
//{
// public sealed class OggParseTests
// {
// [Theory]
// [InlineData(@"Ogg/Riders on the Storm.ogg")]
// public void BasicReadTag(string fileName)
// {
// var fileInfo = new FileInfo(fileName);
// Assert.True(fileInfo.Exists);
// var mediaFile = MediaFile.Parse(fileInfo);
// Assert.NotNull(mediaFile);
// Assert.IsType<OggFile>(mediaFile);
// var tags = MediaTag.GetTagFromFile(mediaFile);
// Assert.NotNull(tags);
// Assert.IsType<OggTag>(tags);
// Assert.Equal(expected: @"Riders on the Storm", actual: tags.Title);
// Assert.Equal(expected: @"The Doors", actual: tags.Artist);
// Assert.Equal(expected: 1971, actual: tags.Year);
// Assert.Equal(expected: @"Rock", actual: tags.Genre);
// Assert.Equal(expected: @"L.A. Woman", actual: tags.Album);
// Assert.Equal(expected: @"The Doors", actual: tags.AlbumArtist);
// Assert.Equal(expected: 5, actual: tags.TrackNumber);
// Assert.Equal(expected: 5, actual: tags.TotalTracks);
// Assert.Equal(expected: 2, actual: tags.DiscNumber);
// Assert.Equal(expected: 2, actual: tags.TotalDiscs);
// Assert.Equal(expected: @"Space", actual: tags.Comment);
// }
// }
//}
|
using FreeAgent.Helpers;
using NUnit.Framework;
using System.Runtime.Serialization;
namespace FreeAgent.Tests
{
[TestFixture]
public class ExtensionTests
{
[Test]
public void Enum_Helper_Returns_EnumMember_Value()
{
var input = TestEnum.Test1;
var result = input.GetMemberValue();
Assert.AreEqual("test_value", result);
}
[Test]
public void Enum_Helper_Returns_DefaultEnum_Value()
{
var input = TestEnum.Test2;
var result = input.GetMemberValue();
Assert.AreEqual("Test2", result);
}
[Test]
public void Enum_Helper_Returns_Null_EnumMember_Value()
{
var input = TestEnum.Test3;
var result = input.GetMemberValue();
Assert.IsNull(result);
}
public enum TestEnum
{
[EnumMember(Value = "test_value")] Test1,
Test2,
[EnumMember(Value = null)] Test3
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Session;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
namespace WebshopHPWcore.Models
{
public class OrderHistory
{
private readonly ShopContext _dbContext;
private readonly string _shoppingCartId;
private readonly string _userId;
private OrderHistory(ShopContext dbContext, string id, string UserId)
{
_dbContext = dbContext;
_shoppingCartId = id;
_userId = UserId;
}
public static OrderHistory GetCart(ShopContext db, HttpContext context, string UserId)
=> GetCart(db, "", UserId);
public static OrderHistory GetCart(ShopContext db, string cartId, string UserId)
=> new OrderHistory(db, cartId, UserId);
public Task<List<History>> GetHistoryItems()
{
return _dbContext
.History
.Where(car => car.userid == _userId)
.Include(c => c.Car)
.ToListAsync();
}
public Task<List<Orderdetail>> GetOrderDetails()
{
return _dbContext
.orderdetail
.Where(car => car.Userid == _userId)
.ToListAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using HotChocolate.Configuration;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using HotChocolate.Utilities;
using Snapshooter;
using Snapshooter.Xunit;
using Xunit;
namespace HotChocolate
{
public class TypeInitializerTests
{
[Fact]
public void Register_SchemaType_ClrTypeExists()
{
// arrange
var initialTypes = new List<ITypeReference>();
initialTypes.Add(new ClrTypeReference(
typeof(FooType),
TypeContext.Output));
var serviceProvider = new EmptyServiceProvider();
var typeInitializer = new TypeInitializer(
serviceProvider,
DescriptorContext.Create(),
initialTypes,
new List<Type>(),
new Dictionary<string, object>(),
null,
t => t is FooType);
// act
typeInitializer.Initialize(() => null, new SchemaOptions());
// assert
bool exists = typeInitializer.Types.TryGetValue(
new ClrTypeReference(typeof(FooType), TypeContext.Output),
out RegisteredType type);
Assert.True(exists);
Assert.IsType<FooType>(type.Type).Fields.ToDictionary(
t => t.Name.ToString(),
t => TypeVisualizer.Visualize(t.Type))
.MatchSnapshot(new SnapshotNameExtension("FooType"));
exists = typeInitializer.Types.TryGetValue(
new ClrTypeReference(typeof(BarType), TypeContext.Output),
out type);
Assert.True(exists);
Assert.IsType<BarType>(type.Type).Fields.ToDictionary(
t => t.Name.ToString(),
t => TypeVisualizer.Visualize(t.Type))
.MatchSnapshot(new SnapshotNameExtension("BarType"));
}
[Fact]
public void Register_ClrType_InferSchemaTypes()
{
// arrange
var initialTypes = new List<ITypeReference>();
initialTypes.Add(new ClrTypeReference(
typeof(Foo),
TypeContext.Output));
var serviceProvider = new EmptyServiceProvider();
var typeInitializer = new TypeInitializer(
serviceProvider,
DescriptorContext.Create(),
initialTypes,
new List<Type>(),
new Dictionary<string, object>(),
null,
t => t is ObjectType<Foo>);
// act
typeInitializer.Initialize(() => null, new SchemaOptions());
// assert
bool exists = typeInitializer.Types.TryGetValue(
new ClrTypeReference(
typeof(ObjectType<Foo>),
TypeContext.Output),
out RegisteredType type);
Assert.True(exists);
Assert.IsType<ObjectType<Foo>>(type.Type).Fields.ToDictionary(
t => t.Name.ToString(),
t => TypeVisualizer.Visualize(t.Type))
.MatchSnapshot(new SnapshotNameExtension("FooType"));
exists = typeInitializer.Types.TryGetValue(
new ClrTypeReference(typeof(ObjectType<Bar>), TypeContext.Output),
out type);
Assert.True(exists);
Assert.IsType<ObjectType<Bar>>(type.Type).Fields.ToDictionary(
t => t.Name.ToString(),
t => TypeVisualizer.Visualize(t.Type))
.MatchSnapshot(new SnapshotNameExtension("BarType"));
}
[Fact]
public void Initializer_SchemaResolver_Is_Null()
{
// arrange
var initialTypes = new List<ITypeReference>();
initialTypes.Add(new ClrTypeReference(
typeof(Foo),
TypeContext.Output));
var serviceProvider = new EmptyServiceProvider();
var typeInitializer = new TypeInitializer(
serviceProvider,
DescriptorContext.Create(),
initialTypes,
new List<Type>(),
new Dictionary<string, object>(),
null,
t => t is ObjectType<Foo>);
// act
Action action =
() => typeInitializer.Initialize(null, new SchemaOptions());
// assert
Assert.Throws<ArgumentNullException>(action);
}
[Fact]
public void Initializer_SchemaOptions_Are_Null()
{
// arrange
var initialTypes = new List<ITypeReference>();
initialTypes.Add(new ClrTypeReference(
typeof(Foo),
TypeContext.Output));
var serviceProvider = new EmptyServiceProvider();
var typeInitializer = new TypeInitializer(
serviceProvider,
DescriptorContext.Create(),
initialTypes,
new List<Type>(),
new Dictionary<string, object>(),
null,
t => t is ObjectType<Foo>);
// act
Action action =
() => typeInitializer.Initialize(() => null, null);
// assert
Assert.Throws<ArgumentNullException>(action);
}
public class FooType
: ObjectType<Foo>
{
protected override void Configure(
IObjectTypeDescriptor<Foo> descriptor)
{
descriptor.Field(t => t.Bar).Type<NonNullType<BarType>>();
}
}
public class BarType
: ObjectType<Bar>
{
}
public class Foo
{
public Bar Bar { get; }
}
public class Bar
{
public string Baz { get; }
}
}
}
|
using System;
using System.Threading;
namespace DP20Memento
{
public class Game : IOriginator
{
private int _life = 100;
public void Fight()
{
Thread.Sleep(1000);
_life = new Random().Next(100);
}
public void Load(Memento memento)
{
_life = memento.Life;
}
public Memento Save()
{
return new Memento { Life = _life };
}
public override string ToString()
{
return $"当前生命值:{_life},游戏结束:{_life < 1}";
}
}
}
|
//**************************************************
// Copyright©2018 何冠峰
// Licensed under the MIT license
//**************************************************
using System;
using MotionEngine.IO;
namespace MotionEngine.Net
{
public interface IPackage
{
/// <summary>
/// 消息类型
/// </summary>
Int16 MsgType { get; set; }
/// <summary>
/// 包体大小
/// </summary>
Int32 MsgSize { get; set; }
void Decode(MoByteBuffer bb, MoByteBuffer tempDecodeByteBuf);
void Encode(MoByteBuffer bb, MoByteBuffer tempEncodeByteBuf);
}
} |
namespace Api.Core.Exceptions
{
public class RetryOperationException: System.Exception
{
public string FullStackTrace { get; set; }
public RetryOperationException(string message, System.Exception ex) : base(message, ex)
{
FullStackTrace = ex.StackTrace;
}
public RetryOperationException(string message) : base(message)
{
}
}
} |
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
namespace Smellyriver.TankInspector.Modeling
{
internal class MatchmakingWeightRules : ISectionDeserializable
{
internal Dictionary<string, double> SpecialTankMmWeights;
internal List<double> TierWeights;
internal Dictionary<TankClass, double> ClassWeights;
public MatchmakingWeightRules()
{
SpecialTankMmWeights = new Dictionary<string, double>();
TierWeights = new List<double>();
ClassWeights = new Dictionary<TankClass, double>();
}
public bool DeserializeSection(string name, XmlReader reader)
{
switch (name)
{
case "byVehicleModule":
while (reader.IsStartElement("name"))
{
var tankKey = reader.ReadString();
reader.ReadStartElement("weight");
reader.Read(out double weight);
reader.ReadEndElement();
reader.ReadEndElement();
SpecialTankMmWeights[tankKey] = weight;
}
return true;
case "byComponentLevels":
var weights = reader.ReadString();
var weightsArray = weights.Split(' ');
foreach (var weight in weights.Split(' '))
TierWeights.Add(double.Parse(weight, CultureInfo.InvariantCulture));
return true;
case "byVehicleClasses":
while (reader.IsStartElement())
{
var className = reader.Name;
reader.ReadStartElement();
reader.Read(out double weight);
reader.ReadEndElement();
switch (className)
{
case "lightTank":
ClassWeights[TankClass.LightTank] = weight;
break;
case "mediumTank":
ClassWeights[TankClass.MediumTank] = weight;
break;
case "heavyTank":
ClassWeights[TankClass.HeavyTank] = weight;
break;
case "AT-SPG":
ClassWeights[TankClass.TankDestroyer] = weight;
break;
case "SPG":
ClassWeights[TankClass.SelfPropelledGun] = weight;
break;
}
}
return true;
case "modulesWeightMultipliers":
case "bySquadSize":
return false;
default:
return false;
}
}
public bool IsWrapped => false;
public void Deserialize(XmlReader reader)
{
SectionDeserializableImpl.Deserialize(this, reader);
}
internal double GetMatchmakingWeight(Tank tank)
{
if (this.SpecialTankMmWeights.TryGetValue(tank.ColonFullKey, out double weight))
return weight;
return this.TierWeights[tank.Tier - 1] * this.ClassWeights[tank.Class];
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SARoleplay.Data
{
public class Character
{
public int Id { get; set; }
public int AccountId { get; set; }
public string RegisteredDate { get; set; }
public string LastOnlineDate { get; set; }
public Boolean Online { get; set; }
public int PlaytimeHours { get; set; }
public int PlaytimeMinutes { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Gender { get; set; }
public string CharacterStyle { get; set; }
public float PositionX { get; set; }
public float PositionY { get; set; }
public float PositionZ { get; set; }
public float Rotation { get; set; }
public int Money { get; set; }
public int Bank { get; set; }
public int JobID { get; set; }
public int FactionID { get; set; }
}
}
|
using Halcyon.HAL.Attributes;
using Threax.AspNetCore.Halcyon.Ext;
using Files.Controllers.Api;
namespace Files.ViewModels
{
[HalActionLink(typeof(PathInfosController), nameof(PathInfosController.List), "ListPathInfos")]
[HalActionLink(typeof(PathInfosController), nameof(PathInfosController.Add), "AddPathInfo")]
public partial class EntryPoint
{
}
} |
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
namespace Tests
{
public class SceneLoaderTest
{
private bool isButtonClicked = false;
private string sceneToLoad = null;
[UnityTest]
public IEnumerator MenuScene_ARButton_Press_Test()
{
//Arrange
SceneManager.LoadScene("PreloadScene");
while (SceneManager.GetSceneByName("PreloadScene").isLoaded == false)
{
yield return new WaitForSeconds(1);
}
while (SceneManager.GetActiveScene().name != "MenuScene")
{
yield return new WaitForSeconds(1);
}
var buttonARObject = GameObject.Find("ButtonAR");
var buttonAR = buttonARObject.GetComponent<Button>();
Debug.Log(buttonAR);
var controlScriptObject = GameObject.FindGameObjectWithTag("SceneControl");
var controlScript = controlScriptObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
Debug.Log(controlScript);
isButtonClicked = false;
//Act
buttonAR.onClick.AddListener(() => { ClickButton("ARScene"); });
buttonAR.onClick.Invoke();
//Assert
Assert.True(isButtonClicked);
if (isButtonClicked)
{
Assert.DoesNotThrow(() => { controlScript.LoadNextScene(sceneToLoad); });
}
}
[UnityTest]
public IEnumerator MenuScene_GalleryButton_Press_Test()
{
//Arrange
SceneManager.LoadScene("PreloadScene");
while (SceneManager.GetSceneByName("PreloadScene").isLoaded == false)
{
yield return new WaitForSeconds(1);
}
while (SceneManager.GetActiveScene().name != "MenuScene")
{
yield return new WaitForSeconds(1);
}
var buttonGalleryObject = GameObject.Find("ButtonGallery");
var buttonGallery = buttonGalleryObject.GetComponent<Button>();
var controlScriptObject = GameObject.FindGameObjectWithTag("SceneControl");
var controlScript = controlScriptObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
isButtonClicked = false;
//Act
buttonGallery.onClick.AddListener(() => { ClickButton("GalleryScene"); });
buttonGallery.onClick.Invoke();
//Assert
Assert.True(isButtonClicked);
if (isButtonClicked)
{
Assert.DoesNotThrow(() => { controlScript.LoadNextScene(sceneToLoad); });
}
}
[UnityTest]
public IEnumerator MenuScene_GamesButton_Press_Test()
{
//Arrange
SceneManager.LoadScene("PreloadScene");
while (SceneManager.GetSceneByName("PreloadScene").isLoaded == false)
{
yield return new WaitForSeconds(1);
}
while (SceneManager.GetActiveScene().name != "MenuScene")
{
yield return new WaitForSeconds(1);
}
var buttonGamesObject = GameObject.Find("ButtonGames");
var buttonGames = buttonGamesObject.GetComponent<Button>();
var controlScriptObject = GameObject.FindGameObjectWithTag("SceneControl");
var controlScript = controlScriptObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
isButtonClicked = false;
//Act
buttonGames.onClick.AddListener(() => { ClickButton("Menu"); });
buttonGames.onClick.Invoke();
//Assert
Assert.True(isButtonClicked);
if (isButtonClicked)
{
Assert.DoesNotThrow(() => { controlScript.LoadNextScene(sceneToLoad); });
}
}
[UnityTest]
public IEnumerator ARScene_BackButton_Press_Test()
{
//Arrange
SceneManager.LoadScene("PreloadScene");
while (SceneManager.GetSceneByName("PreloadScene").isLoaded == false)
{
yield return new WaitForSeconds(1);
}
yield return new WaitForSeconds(1);
SceneManager.LoadScene("ARScene");
yield return new WaitForSeconds(1);
var buttonBackObject = GameObject.Find("ButtonBack");
var buttonBack = buttonBackObject.GetComponent<Button>();
var controlScriptObject = GameObject.FindGameObjectWithTag("SceneControl");
var controlScript = controlScriptObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
isButtonClicked = false;
//Act
buttonBack.onClick.AddListener(() => { ClickButton(""); });
buttonBack.onClick.Invoke();
//Assert
Assert.True(isButtonClicked);
if (isButtonClicked)
{
Assert.DoesNotThrow(() => { controlScript.LoadBackScene(); });
}
}
// Galeria nu are buton de back
/*[UnityTest]
public IEnumerator GalleryScene_BackButton_Press_Test()
{
//Arrange
SceneManager.LoadScene("GalleryScene");
yield return new WaitForSeconds(1);
var buttonBackObject = GameObject.Find("ButtonBack");
var buttonBack = buttonBackObject.GetComponent<Button>();
var controlScriptObject = GameObject.FindGameObjectWithTag("SceneControl");
var controlScript = controlScriptObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
isButtonClicked = false;
//Act
buttonBack.onClick.AddListener(() => { ClickButton(""); });
buttonBack.onClick.Invoke();
//Assert
Assert.True(isButtonClicked);
if (isButtonClicked)
{
Assert.DoesNotThrow(() => { controlScript.LoadBackScene(); });
}
}*/
[UnityTest]
public IEnumerator GamesScene_BackButton_Press_Test()
{
//Arrange
SceneManager.LoadScene("PreloadScene");
while (SceneManager.GetSceneByName("PreloadScene").isLoaded == false)
{
yield return new WaitForSeconds(1);
}
yield return new WaitForSeconds(1);
SceneManager.LoadScene("Menu");
yield return new WaitForSeconds(1);
var buttonBackObject = GameObject.Find("BackButton");
var buttonBack = buttonBackObject.GetComponent<Button>();
var controlScriptObject = GameObject.FindGameObjectWithTag("SceneControl");
var controlScript = controlScriptObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
isButtonClicked = false;
//Act
buttonBack.onClick.AddListener(() => { ClickButton(""); });
buttonBack.onClick.Invoke();
//Assert
Assert.True(isButtonClicked);
if (isButtonClicked)
{
Assert.DoesNotThrow(() => { controlScript.LoadBackScene(); });
}
}
private void ClickButton(string nextScene)
{
isButtonClicked = true;
sceneToLoad = nextScene;
}
[UnityTest]
public IEnumerator LoadScene_WrongScene_Test()
{
//Arrange
SceneManager.LoadScene("PreloadScene");
while (SceneManager.GetSceneByName("PreloadScene").isLoaded == false)
{
yield return new WaitForSeconds(1);
}
while (SceneManager.GetActiveScene().name != "MenuScene")
{
yield return new WaitForSeconds(1);
}
var menuControlObject = GameObject.FindGameObjectWithTag("SceneControl");
var menuControl = menuControlObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
sceneToLoad = "Scene";
//Act
//Assert
Assert.Catch(typeof(System.ArgumentException), () => { menuControl.LoadNextScene(sceneToLoad); });
}
[UnityTest]
public IEnumerator LoadScene_RightScene_Test()
{
//Arrange
SceneManager.LoadScene("PreloadScene");
while (SceneManager.GetSceneByName("PreloadScene").isLoaded == false)
{
yield return new WaitForSeconds(1);
}
while (SceneManager.GetActiveScene().name != "MenuScene")
{
yield return new WaitForSeconds(1);
}
var menuControlObject = GameObject.FindGameObjectWithTag("SceneControl");
var menuControl = menuControlObject.gameObject.GetComponent(typeof(SceneLoader)) as SceneLoader;
sceneToLoad = "ARScene";
//Act
//Assert
Assert.DoesNotThrow(() => { menuControl.LoadNextScene(sceneToLoad); });
}
}
}
|
using System;
using SalaryLibrary;
namespace Salary.NET
{
public class SalaryItemChangedEventArgs : EventArgs
{
private SalaryType _salaryType;
private double _amount;
public SalaryType SalaryType { get { return this._salaryType; } }
public double Amount { get { return this._amount; } }
public SalaryItemChangedEventArgs(SalaryType salaryType, double amount)
{
this._salaryType = salaryType;
this._amount = amount;
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Swetugg.Tix.Infrastructure
{
public interface IViewBuilder
{
Task HandleEvents(IEnumerable<PublishedEvent> events);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace NameFindLibrary.Test
{
public class NameFind_Tests
{
[Fact]
public void TriesLeft_CorrectStartCountDefault()
{
FindName n = new();
Assert.Equal(n.TriesLeft, n.MaxTries);
Assert.True(n.TriesLeft > 0);
}
[Fact]
public void TriesLeft_CorrectStartCountSetValue()
{
FindName n = new(25);
Assert.Equal(n.TriesLeft, n.MaxTries);
Assert.Equal(25, n.TriesLeft);
}
//[Theory]
//[InlineData('C', false)]
//[InlineData('M', true)]
//[InlineData('i', true)]
//public void GuessDict_KeyFoundStored(char keyEntered, bool isKeyFound_Expected)
//{
// FindName s = new();
// Assert.Empty(s.GuessDict);
// s.GuessChar(keyEntered);
// Assert.Single(s.GuessDict);
// s.GuessChar(keyEntered); // Duplication to make sure no exception is thrown
// Assert.Single(s.GuessDict);
// bool actual = s.GuessDict[Char.ToUpper(keyEntered)];
// Assert.Equal(isKeyFound_Expected, actual);
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ficha11
{
public enum Travel
{
LAND,
WATER,
AIR
}
public abstract class Vehicle: IVehicle
{
private string brand;
private Engine engine;
private Travel travel;
public Travel Travel { get { return travel; } }
public Vehicle(string brand, Engine engine, Travel travel)
{
this.brand = brand;
this.engine = engine;
this.travel = travel;
}
public abstract void Start();
}
}
|
#region copyright
/*******************************************************
* Copyright (C) 2017-2018 Holo-Light GmbH -> <info@holo-light.com>
*
* This file is part of the Stylus SDK.
*
* Stylus SDK can not be copied and/or distributed without the express
* permission of the Holo-Light GmbH
*
* Author of this file is Peter Roth
*******************************************************/
#endregion
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace HoloLight.HoloStylus.Examples.DrawScenes
{
/// <summary>
/// Simple color selection for the painting.
/// </summary>
[RequireComponent(typeof(Button))]
public class ChangeColorButton : MonoBehaviour
{
// Attached button
private Button _button;
// Button normal color
[SerializeField]
private Color _color;
/// <summary>
/// Initialize
/// </summary>
private void Start()
{
_button = GetComponent<Button>();
_color = _button.colors.normalColor;
_button.onClick.AddListener(SetColor);
}
/// <summary>
/// Set the color in the coloring manager
/// </summary>
private void SetColor()
{
var manager = FindObjectOfType<ColoringManager>();
manager.SetColor(_color);
}
}
}
|
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayEcoTokenFastGetResponse.
/// </summary>
public class AlipayEcoTokenFastGetResponse : AlipayResponse
{
/// <summary>
/// 访问易联云凭证
/// </summary>
[JsonPropertyName("access_token")]
public string AccessToken { get; set; }
/// <summary>
/// 预计过期时间秒
/// </summary>
[JsonPropertyName("expected_expires_in")]
public string ExpectedExpiresIn { get; set; }
/// <summary>
/// 过期时长秒
/// </summary>
[JsonPropertyName("expires_in")]
public string ExpiresIn { get; set; }
/// <summary>
/// 终端号
/// </summary>
[JsonPropertyName("machine_code")]
public string MachineCode { get; set; }
/// <summary>
/// 更新AccessToken凭证
/// </summary>
[JsonPropertyName("refresh_token")]
public string RefreshToken { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using UnityStandardAssets.ImageEffects;
public class AddBloomToMainCamera : MonoBehaviour {
public bool activateOnStart;
public float bloomIntensity;
public float bloomThreshold;
/*public enum BloomScreenBlendMode
{
Screen = 0,
Add = 1,
}*/
public BloomScreenBlendMode bloomScreenBlendMode = BloomScreenBlendMode.Add;
private GameObject mainCamera;
void Start () {
mainCamera = GameObject.FindGameObjectWithTag (Tags.mainCamera);
if (activateOnStart) {
AddBloomComponent();
}
}
public void AddBloomComponent () {
mainCamera.AddComponent<Bloom> ();
Bloom bloom = mainCamera.GetComponent<Bloom> ();
bloom.bloomIntensity = bloomIntensity;
bloom.bloomThreshold = bloomThreshold;
//bloom.screenBlendMode = bloomScreenBlendMode; Not working
}
public void RemoveBloomComponent(){
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using SharpGL;
using SharpGL.SceneGraph.Assets;
namespace SharpGLTexturesSample
{
public partial class FormSharpGLTexturesSample : Form
{
public FormSharpGLTexturesSample()
{
InitializeComponent();
// Get the OpenGL object, for quick access.
SharpGL.OpenGL gl = this.openGLControl1.OpenGL;
// A bit of extra initialisation here, we have to enable textures.
gl.Enable(OpenGL.GL_TEXTURE_2D);
// Create our texture object from a file. This creates the texture for OpenGL.
texture.Create(gl, "Crate.bmp");
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://nehe.gamedev.net");
}
private void openGLControl1_OpenGLDraw(object sender, PaintEventArgs e)
{
// Get the OpenGL object, for quick access.
SharpGL.OpenGL gl = this.openGLControl1.OpenGL;
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
gl.LoadIdentity();
gl.Translate(0.0f, 0.0f, -6.0f);
gl.Rotate(rtri, 0.0f, 1.0f, 0.0f);
// Bind the texture.
texture.Bind(gl);
gl.Begin(OpenGL.GL_QUADS);
// Front Face
gl.TexCoord(0.0f, 0.0f); gl.Vertex(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
gl.TexCoord(1.0f, 0.0f); gl.Vertex(1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
gl.TexCoord(1.0f, 1.0f); gl.Vertex(1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
gl.TexCoord(0.0f, 1.0f); gl.Vertex(-1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad
// Back Face
gl.TexCoord(1.0f, 0.0f); gl.Vertex(-1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
gl.TexCoord(1.0f, 1.0f); gl.Vertex(-1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
gl.TexCoord(0.0f, 1.0f); gl.Vertex(1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
gl.TexCoord(0.0f, 0.0f); gl.Vertex(1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad
// Top Face
gl.TexCoord(0.0f, 1.0f); gl.Vertex(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
gl.TexCoord(0.0f, 0.0f); gl.Vertex(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Texture and Quad
gl.TexCoord(1.0f, 0.0f); gl.Vertex(1.0f, 1.0f, 1.0f); // Bottom Right Of The Texture and Quad
gl.TexCoord(1.0f, 1.0f); gl.Vertex(1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
// Bottom Face
gl.TexCoord(1.0f, 1.0f); gl.Vertex(-1.0f, -1.0f, -1.0f); // Top Right Of The Texture and Quad
gl.TexCoord(0.0f, 1.0f); gl.Vertex(1.0f, -1.0f, -1.0f); // Top Left Of The Texture and Quad
gl.TexCoord(0.0f, 0.0f); gl.Vertex(1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
gl.TexCoord(1.0f, 0.0f); gl.Vertex(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
// Right face
gl.TexCoord(1.0f, 0.0f); gl.Vertex(1.0f, -1.0f, -1.0f); // Bottom Right Of The Texture and Quad
gl.TexCoord(1.0f, 1.0f); gl.Vertex(1.0f, 1.0f, -1.0f); // Top Right Of The Texture and Quad
gl.TexCoord(0.0f, 1.0f); gl.Vertex(1.0f, 1.0f, 1.0f); // Top Left Of The Texture and Quad
gl.TexCoord(0.0f, 0.0f); gl.Vertex(1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
// Left Face
gl.TexCoord(0.0f, 0.0f); gl.Vertex(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Texture and Quad
gl.TexCoord(1.0f, 0.0f); gl.Vertex(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
gl.TexCoord(1.0f, 1.0f); gl.Vertex(-1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
gl.TexCoord(0.0f, 1.0f); gl.Vertex(-1.0f, 1.0f, -1.0f); // Top Left Of The Texture and Quad
gl.End();
gl.Flush();
rtri += 1.0f;// 0.2f; // Increase The Rotation Variable For The Triangle
}
float rtri = 0;
// The texture identifier.
Texture texture = new Texture();
private void buttonLoad_Click(object sender, EventArgs e)
{
// Show a file open dialog.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// Destroy the existing texture.
texture.Destroy(openGLControl1.OpenGL);
// Create a new texture.
texture.Create(openGLControl1.OpenGL, openFileDialog1.FileName);
// Redraw.
openGLControl1.Invalidate();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using CommandFramework.Annotation;
using CommandFramework.Utils;
namespace ToDoApp
{
[CommandGroup("todo")]
public class TaskManager
{
private readonly List<Task> _tasks = new List<Task>();
[Command("List created all tasks", Name = "list")]
public void ListTasks([Parameter(Synonyms = "c")] bool completed = false)
{
if (!_tasks.Any())
{
Console.WriteLine("No tasks");
return;
}
Console.WriteLine("Tasks");
int n = 1;
foreach (var task in _tasks)
{
if (completed && !task.Completed)
{
continue;
}
var color = task.Completed ? ConsoleColor.Green : ConsoleColor.Gray;
ConsoleEx.Write(color, "{0}. ", n++);
ConsoleEx.Write(color, task.Completed ? "[x]" : "[ ]");
ConsoleEx.Write(color, " {0}", task.Title);
ConsoleEx.WriteLine(color, " {0}", string.Join(" ", task.Tags.Select(t => $"[{t}]")));
}
}
[Command(Name = "task", IsDefault = true)]
public void CreateTask(
[Parameter] string title,
[Parameter(Synonyms = "c")] bool completed = false,
[Parameter(Synonyms = "t")] IEnumerable<string> tags = null)
{
var task = new Task
{
Title = title,
Completed = completed,
Tags = new List<string>(tags ?? Enumerable.Empty<string>())
};
_tasks.Add(task);
Console.WriteLine("Task created");
Console.WriteLine();
ListTasks();
}
[Command]
public void Done(int taskNum = 1)
{
if (taskNum < 1 || taskNum > _tasks.Count)
{
ConsoleEx.WriteLine(ConsoleColor.Red, "No task with number: {0}", taskNum);
}
var task = _tasks[taskNum-1];
task.Completed = true;
ConsoleEx.WriteLine(ConsoleColor.Green, "Completed: {0}", task.Title);
Console.WriteLine();
ListTasks();
}
}
} |
using System.Collections.Specialized;
using System.IO;
namespace TinyAsp.netCore
{
public class HttpResponse
{
public Stream Body { get; set; }
public int StatusCode { get; set; }
public NameValueCollection Headers { get; set; }
public HttpResponse(IHttpFeature httpFeature)
{
Body = httpFeature.RequestBody;
StatusCode = httpFeature.StatusCode;
Headers = httpFeature.ResponeseHeaders;
}
}
}
|
namespace SampleApi.Logic.Utilities
{
using System;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SampleApi.Logic.Errors;
using SampleApi.Plumbing.Errors;
/*
* A utility reader class
*/
public class JsonReader
{
/*
* Read JSON text and deserialize it into objects
*/
public async Task<T> ReadDataAsync<T>(string filePath)
{
try
{
string jsonText = await File.ReadAllTextAsync(filePath);
return JsonConvert.DeserializeObject<T>(jsonText);
}
catch (Exception ex)
{
// Report the error including an error code and exception details
throw ErrorFactory.CreateServerError(
SampleErrorCodes.FileReadError,
"Problem encountered reading data",
ex);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace BaiduMapAPI.YingYan.V3.Fence
{
/// <summary>
/// 查询围栏监控的所有entity 结果
/// </summary>
public class ListMonitoredPersonResult : Models.ResponseOld
{
/// <summary>
/// 查询监控entity的总个数
/// </summary>
[Newtonsoft.Json.JsonProperty("total")]
public int? Total { get; set; }
/// <summary>
/// 本页返回的entity个数
/// </summary>
[Newtonsoft.Json.JsonProperty("size")]
public int? Size { get; set; }
/// <summary>
/// entity列表
/// </summary>
[Newtonsoft.Json.JsonProperty("monitored_person")]
public List<string> MonitoredPerson { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace DynamicLinqCore.Test
{
public class TestEntity1
{
public int Id { get; set; }
public int? NullableInt { get; set; }
public string Name { get; set; }
public TestEntity2 ChildEntity { get; set; }
}
public class TestEntity2
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<TestEntity3> Children { get; set; }
}
public class TestEntity3
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TestContext : DbContext
{
private static bool isSeeded = false;
public DbSet<TestEntity1> TestEntity1s { get; set; }
public DbSet<TestEntity1> TestEntity2s { get; set; }
public DbSet<TestEntity1> TestEntity3s { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("TestDatabase");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public static void EnsureSeed()
{
if (isSeeded)
{
return;
}
SeedDatabase();
isSeeded = true;
}
private static void SeedDatabase()
{
var dbContext = new TestContext();
var childchild1 = new TestEntity3() { Id = 10, Name = "ChildChild1" };
var childchild2 = new TestEntity3() { Id = 11, Name = "ChildChild2" };
var childchild3 = new TestEntity3() { Id = 12, Name = "ChildChild3" };
var child1 = new TestEntity2()
{
Id = 5,
Name = "Child1",
Children = new List<TestEntity3> { childchild1, childchild2 }
};
var child2 =
new TestEntity2() { Id = 6, Name = "Child2", Children = new List<TestEntity3> { childchild3 } };
dbContext.Add(new TestEntity1() { Id = 1, NullableInt = 2, Name = "John", ChildEntity = child1 });
dbContext.Add(new TestEntity1() { Id = 2, Name = "James", ChildEntity = child2 });
dbContext.Add(new TestEntity1() { Id = 3, NullableInt = 4, Name = "Lea" });
dbContext.Add(new TestEntity1() { Id = 4, Name = "James", ChildEntity = child1});
dbContext.SaveChanges();
}
}
public static class DbSetHelper
{
public static IQueryable AsQueryable<T>(this DbSet<T> dbSet)
where T : class
{
return dbSet;
}
}
} |
using LambdicSql.BuilderServices.CodeParts;
using System;
using System.Linq.Expressions;
namespace LambdicSql.ConverterServices.SymbolConverters
{
/// <summary>
/// SQL symbol converter attribute for constructor.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor)]
public abstract class NewConverterAttribute : Attribute
{
/// <summary>
/// Convert expression to code.
/// </summary>
/// <param name="expression">Expression.</param>
/// <param name="converter">Expression converter.</param>
/// <returns>Parts.</returns>
public abstract ICode Convert(NewExpression expression, ExpressionConverter converter);
}
}
|
namespace Sonneville.FidelityWebDriver.Data
{
public enum AccountType
{
Unknown,
InvestmentAccount,
RetirementAccount,
HealthSavingsAccount,
Other,
CreditCard
}
} |
namespace Gobi.InSync.App.Persistence.Models
{
public sealed class SyncWatch
{
public string SourcePath { get; set; }
public string TargetPath { get; set; }
}
} |
namespace TinyMapper.Mappers
{
internal abstract class MapperOf<TSource, TTarget> : Mapper
{
protected override object MapCore(object source, object target)
{
return source is null ? default : MapCore((TSource) source, (TTarget) target);
}
protected abstract TTarget MapCore(TSource source, TTarget target);
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.
namespace Nivaes.App.Cross.Watch.Wear.Sample
{
using Android.App;
using Android.OS;
using Android.Support.Wearable.Activity;
using Android.Widget;
[Activity(Label = "@string/app_name", MainLauncher = true)]
public class MainActivity
: WearableActivity
{
protected override void OnCreate(Bundle? bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
_ = FindViewById<TextView>(Resource.Id.text);
SetAmbientEnabled();
}
}
}
|
using System;
using Bpmtk.Bpmn2.DC;
namespace Bpmtk.Bpmn2.DI
{
public class BPMNLabelStyle : Style
{
public virtual Font Font
{
get;
set;
}
}
}
|
using Godot;
using System;
public class UIPlayerListEntry : MenuButton
{
// Declare member variables here. Examples:
// private int a = 2;
// private string b = "text";
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
}
public void setInfo(String pName)
{
((Label)(GetNode("PlayerRow/lblName"))).Text = pName;
//((TextureRect)(GetNode("PlayerRow/Icon"))).Texture = "";
}
public void setLatency(float latency)
{
((Label)(GetNode("PlayerRow/lblLatency"))).Text = "(" + latency + ")";
}
}
|
using Newtonsoft.Json;
namespace Microsoft.Deployment.Common.Model.PowerApp
{
public class PowerAppDocumentUri
{
[JsonProperty("value")]
public string Value;
public PowerAppDocumentUri(string value)
{
Value = value;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.