content stringlengths 23 1.05M |
|---|
using Elan.Friends.Contracts;
using Elan.Friends.Services;
using Microsoft.Extensions.DependencyInjection;
namespace Elan.Friends
{
public static class ServiceConfigurator
{
public static void RegisterFriendsModule(this IServiceCollection services)
{
services.AddScoped<IFriendsService, FriendsService>();
services.AddScoped<IFriendsInvitationService, FriendsInvitationService>();
}
}
}
|
namespace Esprima.Ast
{
public sealed class ImportDefaultSpecifier : ImportDeclarationSpecifier
{
public readonly Identifier Local;
public ImportDefaultSpecifier(Identifier local) : base(Nodes.ImportDefaultSpecifier)
{
Local = local;
}
public override NodeCollection ChildNodes => new NodeCollection(Local);
}
} |
using System.Threading;
namespace AsyncNet.Jobs
{
public class JobsContext
{
public SemaphoreSlim ActionSemaphore { get; set; }
public bool UseActionSemaphore { get; set; } = false;
public SemaphoreSlim BackActionSemaphore { get; set; }
public bool UseBackActionSemaphore { get; set; } = false;
public object CustomData { get; set; }
}
}
|
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Ninject;
using Ninject.Web.Common;
using ConspectoPatronum.Domain;
using ConspectoPatronum.Core.Repositories;
using ConspectoPatronum.Core.Services;
using ConspectoPatronum.Services;
namespace ConspectoPatronum
{
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
base.OnApplicationStarted();
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<IRepository<Subject>>().To<Repository<Subject>>();
kernel.Bind<IRepository<Image>>().To<Repository<Image>>();
kernel.Bind<IRepository<Teacher>>().To<Repository<Teacher>>();
kernel.Bind<IRepository<Comment>>().To<Repository<Comment>>();
kernel.Bind<ISubjectsService>().To<SubjectsService>();
kernel.Bind<IImagesService>().To<ImagesService>();
kernel.Bind<ITeachersService>().To<TeachersService>();
kernel.Bind<ICommentsService>().To<CommentsService>();
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
return kernel;
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace SourceUtils
{
[StructLayout( LayoutKind.Sequential )]
public struct Vector3 : IEquatable<Vector3>
{
public static readonly Vector3 Zero = new Vector3(0f, 0f, 0f);
public static readonly Vector3 NaN = new Vector3( float.NaN, float.NaN, float.NaN );
public static Vector3 operator -( Vector3 vector )
{
return new Vector3( -vector.X, -vector.Y, -vector.Z );
}
public static Vector3 operator +( Vector3 a, Vector3 b )
{
return new Vector3( a.X + b.X, a.Y + b.Y, a.Z + b.Z );
}
public static Vector3 operator -( Vector3 a, Vector3 b )
{
return new Vector3( a.X - b.X, a.Y - b.Y, a.Z - b.Z );
}
public static Vector3 operator *( Vector3 a, Vector3 b )
{
return new Vector3( a.X * b.X, a.Y * b.Y, a.Z * b.Z );
}
public static Vector3 operator *( Vector3 vec, float scalar )
{
return new Vector3( vec.X * scalar, vec.Y * scalar, vec.Z * scalar );
}
public static Vector3 operator *( float scalar, Vector3 vec )
{
return new Vector3( vec.X * scalar, vec.Y * scalar, vec.Z * scalar );
}
public static Vector3 Min( Vector3 a, Vector3 b )
{
return new Vector3( Math.Min( a.X, b.X ), Math.Min( a.Y, b.Y ), Math.Min( a.Z, b.Z ) );
}
public static Vector3 Max( Vector3 a, Vector3 b )
{
return new Vector3( Math.Max( a.X, b.X ), Math.Max( a.Y, b.Y ), Math.Max( a.Z, b.Z ) );
}
public float X;
public float Y;
public float Z;
public float Length => (float) Math.Sqrt( LengthSquared );
public float LengthSquared => X * X + Y * Y + Z * Z;
public Vector3 Normalized => this * (1f / Length);
public Vector3 Rounded => new Vector3((float) Math.Round(X), (float) Math.Round(Y), (float) Math.Round(Z));
public bool IsNaN => float.IsNaN( X ) || float.IsNaN( Y ) || float.IsNaN( Z );
public Vector3( float x, float y, float z )
{
X = x;
Y = y;
Z = z;
}
public float Dot( Vector3 other )
{
return X * other.X + Y * other.Y + Z * other.Z;
}
public Vector3 Cross( Vector3 other )
{
return new Vector3( Y * other.Z - Z * other.Y, Z * other.X - X * other.Z, X * other.Y - Y * other.X );
}
public bool Equals( Vector3 other )
{
return X == other.X && Y == other.Y && Z == other.Z;
}
public bool Equals( Vector3 other, float epsilon )
{
return Math.Abs( X - other.X ) < epsilon && Math.Abs( Y - other.Y ) < epsilon &&
Math.Abs( Z - other.Z ) < epsilon;
}
public override bool Equals( object obj )
{
return obj is Vector3 && Equals( (Vector3) obj );
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
return hashCode;
}
}
public override string ToString()
{
return $"({X:F2}, {Y:F2}, {Z:F2})";
}
}
}
|
using System.Collections.Generic;
using System.IO;
using WritingExporter.Common.Models;
namespace WritingExporter.Common.Storage
{
public interface IStoryFileStore
{
void DeleteStory(string fileName);
void DeleteStory(WdcInteractiveStory story);
WdcInteractiveStory DeserializeStory(Stream stream);
WdcInteractiveStory DeserializeStory(string payload);
WdcInteractiveStory LoadStory(string filePath);
IEnumerable<WdcInteractiveStory> LoadAllStories();
void SaveStory(WdcInteractiveStory story);
void SaveStory(WdcInteractiveStory story, string filePath);
void SerializeStory(WdcInteractiveStory story, Stream stream);
string SerializeStoryToString(WdcInteractiveStory story);
string GenerateFilename(WdcInteractiveStory story);
string GetDefaultFileSuffix();
}
} |
using System;
using System.Threading.Tasks;
using AskMe.API.Models;
using AskMe.Domain.Interfaces;
using AskMe.Domain.Models;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AskMe.API.Controllers
{
[Authorize]
[Route("api/users/{userId}/exams")]
[ApiController]
public class ExamsController : ControllerBase
{
// Variables to use for dependency injection
private readonly IMapper _mapper;
private readonly IExamService _examService;
// constructor
public ExamsController(IMapper mapper, IExamService examService)
{
_mapper = mapper;
_examService = examService;
}
/// <summary>
/// This method returns a lis of Exams resource
/// for a given User.
/// HTTP GET verb.
/// </summary>
/// <param name="userId">Integer</param>
/// <returns>List<Exam></returns>
[HttpGet()]
public async Task<IActionResult> GetExams(int userId)
{
// calls exam service to search exams by userId
var exams = await _examService.GetExams(userId);
// returns 200ok
// list of exams
return Ok(exams);
}
/// <summary>
/// This methos returns list of Question resource
/// for a given Exam.
/// HTTP GET verb.
/// </summary>
/// <param name="examId">Integer</param>
/// <returns>List<ExamQuestion></returns>
[HttpGet("{examId}/questions", Name = "GetExamQuestions")]
public async Task<IActionResult> GetExamQuestions(int examId)
{
// calls exam service to search question by examId
var examQuestions = await _examService.GetExamQuestions(examId);
// if the list is null
if (examQuestions == null)
{
// returns 404 not found
return NotFound();
}
// returns 200ok
return Ok(examQuestions);
}
/// <summary>
/// This method returns an existing Exam.
/// HTTP GET verb.
/// </summary>
/// <param name="examId">Integer</param>
/// <returns>ExamDto</returns>
[HttpGet("{examId}", Name = "GetExam")]
public async Task<IActionResult> GetExam(int examId)
{
// calls exam service to search exam by id
var exam = await _examService.GetExamById(examId);
// if Exam is null
if (exam == null)
{
// returns 404 not found
return NotFound();
}
// maps domain model to reosurce
//200ok
return Ok(_mapper.Map<ExamDto>(exam));
}
/// <summary>
/// This method creates a new Exam.
/// HTTP POST verb.
/// </summary>
/// <param name="model">ExamQuestionsForCreationDto</param>
/// <returns></returns>
[HttpPost()]
public async Task<IActionResult> CreateExam([FromBody] ExamQuestionsForCreationDto model)
{
// maps resource to domain model
var exam = _mapper.Map<Exam>(model);
try
{
// create lesson
var isCreated = await _examService.AddExamQuestions(exam, model.questions);
return Ok(isCreated);
}
catch (Exception ex)
{
// return error message if there was an exception
return BadRequest(new { message = ex.Message });
}
}
}
}
|
using System.Collections.Generic;
using Department.Base.Model.Common;
namespace Department.Base.Model.Security
{
public class ExternalUserLoginInfo : ValueObject
{
// Examples of the provider may be Local, Facebook, Google, etc.
public string LoginProvider { get; set; }
//
// Summary:
// Gets or sets the unique identifier for the user identity user provided by the
// login provider.
//
// Remarks:
// This would be unique per provider, examples may be @microsoft as a Twitter provider
// key.
public string ProviderKey { get; set; }
//
// Summary:
// Gets or sets the display name for the provider.
public string ProviderDisplayName { get; set; }
protected override IEnumerable<object> GetEqualityComponents()
{
yield return LoginProvider;
yield return ProviderKey;
}
}
}
|
using Newtonsoft.Json;
namespace Slack.NetStandard.WebApi.Conversations
{
public class AcceptSharedInviteRequest
{
[JsonProperty("channel_name")]
public string ChannelName { get; set; }
[JsonProperty("channel_id",NullValueHandling = NullValueHandling.Ignore)]
public string ChannelId { get; set; }
[JsonProperty("invite_id",NullValueHandling = NullValueHandling.Ignore)]
public string InviteId { get; set; }
[JsonProperty("is_private",NullValueHandling = NullValueHandling.Ignore)]
public bool? IsPrivate { get; set; }
[JsonProperty("team_id",NullValueHandling = NullValueHandling.Ignore)]
public string TeamId { get; set; }
[JsonProperty("free_trial_accepted",NullValueHandling = NullValueHandling.Ignore)]
public bool? FreeTrialAccepted { get; set; }
}
}
|
//Class Name: DoneState.cs
//Author: Kristina VanderBoog
//Purpose: This represents the concrete state of "DoneState" it will initiate the printing
//of the information entered in the form. I could not get the chevron to line up properly so I omitted it.
//Date: August 14, 2020
using System;
using System.Collections.Generic;
namespace Project_3_Starter
{
public class DoneState : State
{
public DoneState(FormInput f) : base(f) { }
/*This Run method will have a loop that prints out all the user inputed information
* it returns nothing, and prints only*/
public override void Run()
{
Console.WriteLine("Here is your printout ");
FormInput PrintForm = this.form;
Form uForm = PrintForm.getForm();
List<IFormComponent> PrintList = uForm.GetComponent();
for (int i = 0; i < PrintList.Count; i++)
{
string formatter = String.Format("{0,20} {1,20}", PrintList[i].GetName(), PrintList[i].GetValue());
Console.WriteLine($"{formatter}");
}
}
}
}
|
namespace KoScrobbler.Entities
{
public class ValidateSessionResult : RequestResponseBase
{
public string UserName { get; internal set; }
public string SessionKey { get; internal set; }
}
}
|
using PokemonManager.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PokemonManager.Game.FileStructure.Gen3.GC {
public class GCCharacterEncoding {
public static string GetString(byte[] data, Languages language) {
string str = "";
for (int i = 0; i < data.Length; i += 2) {
char c = (char)BigEndian.ToUInt16(data, i);
if (c == 0)
break;
str += new string(c, 1);
}
return str;
}
public static byte[] GetBytes(string data, int limit, Languages language) {
data = CharacterEncoding.ConvertToLanguage(data, language);
byte[] finalData = new byte[limit * 2];
for (int i = 0; i < data.Length; i++) {
BigEndian.WriteUInt16(data[i], finalData, i * 2);
}
return finalData;
}
}
}
|
namespace UniModules.UniGame.SplitTexture.Editor
{
using System.Collections.Generic;
using Abstract;
using UnityEngine;
public sealed class UniformTextureSplitter : ITextureSplitter
{
public Texture2D[] SplitTexture(Texture2D source, Vector2Int maxSize)
{
if (source == null) {
return null;
}
if (source.width > maxSize.x && source.height > maxSize.y) {
return SplitVerticalAndHorizontal(source, maxSize);
}
if (source.width > maxSize.x) {
return SplitHorizontal(source, maxSize.x);
}
if (source.height > maxSize.y) {
return SplitVertical(source, maxSize.y);
}
return new[] {source};
}
private Texture2D[] SplitHorizontal(Texture2D source, int maxSize)
{
var splitCount = SplitHelper.GetSplitCount(source.width, maxSize);
if (splitCount > 1) {
var partWidth = Mathf.FloorToInt((float)source.width / splitCount);
var resultArray = new Texture2D[splitCount];
for (var i = 0; i < splitCount; i++) {
var rect = new Rect(i * partWidth, 0.0f, partWidth, source.height);
if (i == splitCount - 1) {
var commonSplitWidth = partWidth * i;
partWidth = source.width - commonSplitWidth;
rect = new Rect(commonSplitWidth, 0.0f, partWidth, source.height);
}
var texture = GetTextureByRect(source, rect);
texture.name = SplitHelper.GetSplittedTextureName(i, source.name);
resultArray[i] = texture;
}
return resultArray;
}
return null;
}
private Texture2D[] SplitVertical(Texture2D source, int maxSize)
{
var splitCount = SplitHelper.GetSplitCount(source.height, maxSize);
if (splitCount > 1) {
var partHeight = Mathf.FloorToInt((float)source.height / splitCount);
var resultArray = new Texture2D[splitCount];
for (var i = 0; i < splitCount; i++) {
if (i == splitCount - 1) {
var commonSplitHeight = partHeight * i;
partHeight = source.height - commonSplitHeight;
}
var rect = new Rect(0.0f, i * partHeight, source.width, partHeight);
var texture = GetTextureByRect(source, rect);
texture.name = SplitHelper.GetSplittedTextureName(i, source.name);
resultArray[i] = texture;
}
return resultArray;
}
return null;
}
private Texture2D[] SplitVerticalAndHorizontal(Texture2D source, Vector2Int maxSize)
{
var splittedByWidth = SplitHorizontal(source, maxSize.x);
if (splittedByWidth != null) {
var resultList = new List<Texture2D>();
foreach (var texture in splittedByWidth) {
var splittedByHeight = SplitVertical(texture, maxSize.y);
if(splittedByHeight != null) {
resultList.AddRange(splittedByHeight);
}
else {
resultList.Add(texture);
}
}
for (var i = 0; i < resultList.Count; i++) {
resultList[i].name = SplitHelper.GetSplittedTextureName(i, source.name);
}
return resultList.ToArray();
}
return null;
}
private Texture2D GetTextureByRect(Texture2D source, Rect rect)
{
var resultTexture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);
var pixels = source.GetPixels((int) rect.x, (int) rect.y, (int) rect.width, (int) rect.height);
resultTexture.SetPixels(pixels);
resultTexture.Apply();
return resultTexture;
}
}
} |
using ViennaNET.Orm.Seedwork;
namespace ViennaNET.Orm.Tests.Unit.DSL
{
internal class BadEntity : IEntityKey
{
}
}
|
using Draws.CLI;
using SpotifyAPI.Web;
using System;
using System.Collections.Generic;
namespace SpotifyCLI.Commands {
[Command("vol", "Changes the volume.", isSingleArgument: false)]
[Argument("volume", "The number to set the volume to", required: true, shortName: 'v')]
public class ChangeVolumeCommand : ICommand {
private readonly ISpotifyClient _spotify;
private int _newVolume;
public ChangeVolumeCommand(ISpotifyClient spotifyClient) {
_spotify = spotifyClient;
}
public string RunCommand() {
_spotify.Player.SetVolume(new PlayerVolumeRequest(_newVolume));
return $"Set the volume to {_newVolume}%";
}
public void SetArguments(Dictionary<string, string> args) {
string newVolumeString = "";
args.TryGetValue("volume", out newVolumeString);
_newVolume = Convert.ToInt32(newVolumeString);
}
}
} |
using System.Collections.Generic;
namespace UnityEngine.InputNew
{
public interface IInputControlProvider
{
List<InputControlData> controlDataList { get; }
InputControl this[int index] { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using Repository.Entities.BaseClasses;
namespace Repository.Entities.Html
{
public enum ContentItemType
{
Html = 0,
Css,
Js
}
public class ContentItem : NamedDeletableBase
{
public string Content { get; set; } //html or CSS or js
public ContentItemType ContentItemType { get; set; }
}
}
|
// Copyright (c) 2017-2019 Jae-jun Kang
// See the file LICENSE for details.
using System;
using System.Collections.Generic;
namespace x2net
{
public class SendBuffer : IDisposable
{
private byte[] headerBytes;
private int headerLength;
private Buffer buffer;
public byte[] HeaderBytes { get { return headerBytes; } }
public int HeaderLength
{
get { return headerLength; }
set { headerLength = value; }
}
public Buffer Buffer { get { return buffer; } }
public int Length { get { return (headerLength + (int)buffer.Length); } }
public SendBuffer()
{
headerBytes = new byte[5];
buffer = new Buffer();
}
~SendBuffer()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Frees managed or unmanaged resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
try
{
buffer.Dispose();
}
catch (Exception) { }
}
public void ListOccupiedSegments(IList<ArraySegment<byte>> blockList)
{
blockList.Add(new ArraySegment<byte>(headerBytes, 0, headerLength));
buffer.ListOccupiedSegments(blockList);
}
public void Reset()
{
headerLength = 0;
buffer.Reset();
}
}
}
|
using PoshCommence.Base;
using System.Management.Automation;
namespace PoshCommence.CmdLets
{
[Cmdlet(VerbsCommon.Clear, "CmcMetadataCache")]
public class ClearMetadataCache : PSCmdlet
{
protected override void ProcessRecord()
{
CommenceMetadata.ClearAll();
WriteVerbose("Cleared the Commence Metadata cache.");
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Brokerage.Common.ReadModels.Blockchains;
namespace Brokerage.Common.Persistence.Blockchains
{
public static class BlockchainsRepositoryExtensions
{
public static async Task<IReadOnlyCollection<Blockchain>> GetAllAsync(this IBlockchainsRepository repository)
{
var cursor = default(string);
var result = new List<Blockchain>();
do
{
var page = await repository.GetAllAsync(cursor, 100);
if (!page.Any())
{
break;
}
cursor = page.Last().Id;
result.AddRange(page);
} while (true);
return result;
}
}
}
|
using System.Collections.Generic;
using System.IO;
using YAXLib;
namespace ControlsLibrary.FileSerialization
{
/// <summary>
/// WPF implementation of file serialization and deserialization
/// </summary>
public static class FileServiceProviderWpf
{
/// <summary>
/// Serializes data classes list to file
/// </summary>
/// <param name="filename">File name</param>
/// <param name="modelsList">Data classes list</param>
public static void SerializeDataToFile<T>(string filename, List<T> modelsList)
{
using var stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
var serializer = new YAXSerializer(typeof(List<T>));
using var textWriter = new StreamWriter(stream);
serializer.Serialize(modelsList, textWriter);
textWriter.Flush();
}
/// <summary>
/// Deserializes data classes list from file
/// </summary>
/// <param name="filename">File name</param>
public static List<T> DeserializeGraphDataFromFile<T>(string filename)
{
using var stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
var deserializer = new YAXSerializer(typeof(List<T>));
using var textReader = new StreamReader(stream);
return (List<T>)deserializer.Deserialize(textReader);
}
}
} |
using DiscordHackWeek.Entities.Combat;
namespace DiscordHackWeek.Services.Database.Tables
{
public class Enemy
{
public int Id { get; set; }
public string Name { get; set; }
public int ZoneId { get; set; }
public string Image { get; set; }
public string ThumbImg { get; set; }
public EnemyType Type { get; set; }
public string LightAttack { get; set; }
public string HeavyAttack { get; set; }
public int Exp { get; set; } = 5;
public int Credit { get; set; } = 0;
// public ICollection<LootTable> Loot { get; set; }
public int[] LootTableIds { get; set; }
public int RareDropChance { get; set; } = 1;
public int? WeaponId { get; set; }
public int? ArmorId { get; set; }
}
} |
using System;
using T3.Core.Operator;
using T3.Core.Operator.Attributes;
using T3.Core.Operator.Slots;
namespace T3.Operators.Types.Id_acdd78b1_4e66_4fd0_a36b_5318670fefd4
{
public class ToUpperCase : Instance<ToUpperCase>
{
[Output(Guid = "ecf66a1e-45e5-4e0c-ac9e-a784a9339153")]
public readonly Slot<string> Result = new Slot<string>();
public ToUpperCase()
{
Result.UpdateAction = Update;
}
private void Update(EvaluationContext context)
{
var str = Input2.GetValue(context);
Result.Value = str?.ToUpper();
}
[Input(Guid = "041C98B6-4450-46D7-9DAE-C9030C88B9E6")]
public readonly InputSlot<string> Input2 = new InputSlot<string>();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestCases
{
class Test01
{
public static Dictionary<EnumTest.TestEnum, EnumTest.TestEnum[]> dicAttrConver5 = new Dictionary<EnumTest.TestEnum, EnumTest.TestEnum[]>()
{
{
EnumTest.TestEnum.Enum1,new EnumTest.TestEnum[]{ EnumTest.TestEnum.Enum2}
},
};
public static int foo(int init)
{
int b = init;
for (int i = 0; i < 10000; i++)
{
b += i;
}
return b;
}
[TestCase]
public static int foo()
{
int b = 0;
for (int i = 0; i < 50; i++)
{
b += foo(b);
}
return b;
}
[TestCase]
public static void foo1()
{
int count = 10;
while (--count >= 0 )
{
Console.WriteLine(count.ToString());
}
}
[TestCase]
public static void UnitTest_ValueType()
{
string a = 11.ToString();
}
static int Add(int a, int b)
{
return a + b;
}
[TestCase]
public static void UnitTest_Cls()
{
object obj = new object();
Console.WriteLine("UnitTest_Cls");
Test1098Cls cls = new Test1098Cls();
Test1098Sub(cls);
Console.WriteLine(string.Format("A={0} B={1}", cls.A, cls.B));
}
[TestCase]
public static void UnitTest_Generics()
{
Console.WriteLine("UnitTest_Generixs");
//如果一个类继承一个泛型参数为这个类本身的泛型类,就没法正确找到该类型了
SingletonTest.Inst.Test = "bar";
Console.WriteLine(SingletonTest.Inst.foo());
SingletonTest2.Inst.Test = 2;
Console.WriteLine(SingletonTest2.Inst.foo());
Console.WriteLine(SingletonTest2.Inst.GetString<SingletonTest>(SingletonTest.Inst));
Console.WriteLine(SingletonTest2.IsSingletonInstance(SingletonTest2.Inst).ToString());
}
[TestCase]
public static void UnitTest_Generics2()
{
Console.WriteLine("UnitTest_Generics2");
SingletonTest.Inst.Test = "bar";
Console.WriteLine(SingletonTest.Inst.foo());
SingletonTest2.Inst.Test = 2;
Console.WriteLine(SingletonTest2.Inst.foo());
Console.WriteLine(SingletonTest2.Inst.GetString<SingletonTest>(SingletonTest.Inst));
Console.WriteLine(SingletonTest2.IsSingletonInstance(new SingletonTest2()).ToString());
Console.WriteLine(SingletonTest2.IsSingletonInstance(SingletonTest2.Inst).ToString());
}
[TestCase]
public static void UnitTest_Generics3()
{
Console.WriteLine("UnitTest_Generics3");
Console.WriteLine(new List<NestedTest>().ToString());
}
[TestCase]
public static void UnitTest_Generics4()
{
object r = TestGeneric<object>();
Console.WriteLine("Result = " + r);
}
static T TestGeneric<T>() where T : new()
{
T obj = new T();
return obj;
}
[TestCase]
public static void UnitTest_NestedGenerics()
{
Console.WriteLine("UnitTest_NestedGenerics");
//如果一个嵌套的类是泛型类参数,则这个类无法被找到
Console.WriteLine(new NestedTestBase<NestedTest>().ToString());
}
class Test1098Cls
{
public int A { get; set; }
public string B { get; set; }
}
static void Test1098Sub(Test1098Cls cls)
{
cls.A = 2;
cls.B = "ok";
}
static void FuncCallResult(ref int cnt, int i)
{
cnt++;
}
class NestedTest
{
}
class NestedTestBase<T>
{
}
}
class SingletonTest : Singleton<SingletonTest>
{
public string Test { get; set; }
public float testFloat;
public static int TestStaticField;
public string foo()
{
return Inst.Test;
}
}
class SingletonTest2 : Singleton<SingletonTest2>
{
public int Test { get; set; }
public string foo()
{
return Inst.Test.ToString();
}
}
class Singleton<T> where T : class,new()
{
private static T _inst;
public int testField;
public Singleton()
{
}
public static T Inst
{
get
{
if (_inst == null)
{
_inst = new T();
}
return _inst;
}
}
public string GetString<K>(K obj)
{
return obj.ToString();
}
public static bool IsSingletonInstance(T inst)
{
return _inst == inst;
}
}
public class DictionaryEnumeratorTest<TKey, TValue>
{
Dictionary<TKey, TValue> dic = new Dictionary<TKey, TValue>();
public void Add(TKey key, TValue value)
{
dic.Add(key, value);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return dic.GetEnumerator(); //报错
}
public void GetEnumeratorTest()
{
var e = dic.GetEnumerator(); //正常
while (e.MoveNext())
{
Console.WriteLine(e.Current.Key + " " + e.Current.Value);
}
}
public void GetEnumeratorTest2()
{
IEnumerator<KeyValuePair<TKey, TValue>> e = dic.GetEnumerator(); //报错
while (e.MoveNext())
{
Console.WriteLine(e.Current.Key + " " + e.Current.Value);
}
}
}
public class MyTest
{
public static Dictionary<string, MyTest[]> data = new Dictionary<string, MyTest[]>();
public static void UnitTest_Test1()
{
var arr = new MyTest[] { new MyTest(), null, null };
data["test"] = arr;
Console.WriteLine(data["test"][0]);
}
[TestCase]
public static void Test()
{
DictionaryEnumeratorTest<int, int> t = new DictionaryEnumeratorTest<int, int>();
t.Add(1, 1);
t.GetEnumeratorTest();
t.GetEnumeratorTest2();
var e = t.GetEnumerator();
while (e.MoveNext())
{
Console.WriteLine(e.Current.Key + " " + e.Current.Value);
}
}
}
}
|
namespace OneLoginAws.Models
{
public record IAMRole(string Role, string Principal);
}
|
using System;
namespace EasyNetQ.Scheduler.Mongo
{
public interface IScheduleRepositoryConfiguration
{
string ConnectionString { get; }
string DatabaseName { get; }
string CollectionName { get; }
TimeSpan DeleteTimeout { get; }
TimeSpan PublishTimeout { get; }
}
}
|
using Microsoft.Maui.Layouts;
using CommunityToolkit.Maui.Markup.Sample.Pages.Base;
using CommunityToolkit.Maui.Markup.Sample.ViewModels;
using CommunityToolkit.Maui.Markup.Sample.Constants;
namespace CommunityToolkit.Maui.Markup.Sample.Pages;
class NewsDetailPage : BaseContentPage<NewsDetailViewModel>
{
public NewsDetailPage(NewsDetailViewModel newsDetailViewModel) : base(newsDetailViewModel, newsDetailViewModel.Title)
{
Content = new FlexLayout
{
Direction = FlexDirection.Column,
AlignContent = FlexAlignContent.Center,
Children =
{
new WebView()
.Grow(1).AlignSelf(FlexAlignSelf.Stretch)
.Bind(WebView.SourceProperty, nameof(NewsDetailViewModel.Uri), BindingMode.OneTime),
new Button { BackgroundColor = ColorConstants.NavigationBarBackgroundColor }
.Text("Launch in Browser \uf35d", ColorConstants.PrimaryTextColor)
.Font(size: 20, family: "FontAwesome")
.Basis(50)
.Bind(Button.CommandProperty, nameof(NewsDetailViewModel.OpenBrowserCommand)),
new Label { BackgroundColor = ColorConstants.NavigationBarBackgroundColor }
.TextColor(ColorConstants.PrimaryTextColor).TextCenter()
.AlignSelf(FlexAlignSelf.Stretch)
.Paddings(bottom: 20)
.Bind(Label.TextProperty, nameof(NewsDetailViewModel.ScoreDescription), BindingMode.OneTime),
}
};
}
}
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the kinesisanalyticsv2-2018-05-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KinesisAnalyticsV2.Model
{
/// <summary>
/// For a SQL-based Kinesis Data Analytics application, describes updates to the output
/// configuration identified by the <code>OutputId</code>.
/// </summary>
public partial class OutputUpdate
{
private DestinationSchema _destinationSchemaUpdate;
private KinesisFirehoseOutputUpdate _kinesisFirehoseOutputUpdate;
private KinesisStreamsOutputUpdate _kinesisStreamsOutputUpdate;
private LambdaOutputUpdate _lambdaOutputUpdate;
private string _nameUpdate;
private string _outputId;
/// <summary>
/// Gets and sets the property DestinationSchemaUpdate.
/// <para>
/// Describes the data format when records are written to the destination.
/// </para>
/// </summary>
public DestinationSchema DestinationSchemaUpdate
{
get { return this._destinationSchemaUpdate; }
set { this._destinationSchemaUpdate = value; }
}
// Check to see if DestinationSchemaUpdate property is set
internal bool IsSetDestinationSchemaUpdate()
{
return this._destinationSchemaUpdate != null;
}
/// <summary>
/// Gets and sets the property KinesisFirehoseOutputUpdate.
/// <para>
/// Describes a Kinesis Data Firehose delivery stream as the destination for the output.
/// </para>
/// </summary>
public KinesisFirehoseOutputUpdate KinesisFirehoseOutputUpdate
{
get { return this._kinesisFirehoseOutputUpdate; }
set { this._kinesisFirehoseOutputUpdate = value; }
}
// Check to see if KinesisFirehoseOutputUpdate property is set
internal bool IsSetKinesisFirehoseOutputUpdate()
{
return this._kinesisFirehoseOutputUpdate != null;
}
/// <summary>
/// Gets and sets the property KinesisStreamsOutputUpdate.
/// <para>
/// Describes a Kinesis data stream as the destination for the output.
/// </para>
/// </summary>
public KinesisStreamsOutputUpdate KinesisStreamsOutputUpdate
{
get { return this._kinesisStreamsOutputUpdate; }
set { this._kinesisStreamsOutputUpdate = value; }
}
// Check to see if KinesisStreamsOutputUpdate property is set
internal bool IsSetKinesisStreamsOutputUpdate()
{
return this._kinesisStreamsOutputUpdate != null;
}
/// <summary>
/// Gets and sets the property LambdaOutputUpdate.
/// <para>
/// Describes an Amazon Lambda function as the destination for the output.
/// </para>
/// </summary>
public LambdaOutputUpdate LambdaOutputUpdate
{
get { return this._lambdaOutputUpdate; }
set { this._lambdaOutputUpdate = value; }
}
// Check to see if LambdaOutputUpdate property is set
internal bool IsSetLambdaOutputUpdate()
{
return this._lambdaOutputUpdate != null;
}
/// <summary>
/// Gets and sets the property NameUpdate.
/// <para>
/// If you want to specify a different in-application stream for this output configuration,
/// use this field to specify the new in-application stream name.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=32)]
public string NameUpdate
{
get { return this._nameUpdate; }
set { this._nameUpdate = value; }
}
// Check to see if NameUpdate property is set
internal bool IsSetNameUpdate()
{
return this._nameUpdate != null;
}
/// <summary>
/// Gets and sets the property OutputId.
/// <para>
/// Identifies the specific output configuration that you want to update.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=50)]
public string OutputId
{
get { return this._outputId; }
set { this._outputId = value; }
}
// Check to see if OutputId property is set
internal bool IsSetOutputId()
{
return this._outputId != null;
}
}
} |
using System;
using System.Collections.Generic;
namespace FELFEL.Data
{
public class InventoryBatch
{
public DateTime ExpirationDate { get; set; }
public int Stock { get; set; }
public BatchState BatchState { get; set; }
}
} |
using System.Collections.Generic;
using System.Linq;
namespace TGC.Group.Model.Items.Recipes
{
public class Recipe
{
public IEnumerable<Ingredient> Ingredients{get;}
public Recipe(IEnumerable<Ingredient> ingredients)
{
this.Ingredients = ingredients;
}
public bool CanCraft(List<Ingredient> availableIngredients)
{
return this.Ingredients.All(ingredient =>
availableIngredients.Any(ingredient.contains));
}
public override string ToString()
{
var res = "";
this.Ingredients.ToList().ForEach(ingredient =>
{
res = res + ingredient.Item.Name + ": " + ingredient.Quantity + "\n";
});
return res;
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WeatherApp.Model;
namespace WeatherApp.ViewModel.Helpers
{
public class WeatherHelper
{
private const string m_BaseURL = "http://dataservice.accuweather.com/";
private const string m_AutocompleteEndpoint = "locations/v1/cities/autocomplete?apikey={0}&q={1}";
private const string m_ConditionsEndpoint = "currentconditions/v1/{0}?apikey={1}";
// ----------------------------------------------------------------
// This is where you will insert your own API key from AccuWeather
// ----------------------------------------------------------------
private const string m_ApiKey = "YOUR API KEY HERE";
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
// ----------------------------------------------------------------
public static async Task<List<City>> GetCities(string query)
{
List<City> cities = new List<City>();
string formattedURL = m_BaseURL + string.Format(m_AutocompleteEndpoint, m_ApiKey, query);
using(HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(formattedURL);
string json = await response.Content.ReadAsStringAsync();
cities = JsonConvert.DeserializeObject<List<City>>(json);
}
return cities;
}
// ----------------------------------------------------------------
// ----------------------------------------------------------------
public static async Task<CurrentConditions> GetCurrentConditions(string cityKey)
{
CurrentConditions currentConditions = new CurrentConditions();
string formattedURL = m_BaseURL + string.Format(m_ConditionsEndpoint, cityKey, m_ApiKey);
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(formattedURL);
string json = await response.Content.ReadAsStringAsync();
currentConditions = (JsonConvert.DeserializeObject<List<CurrentConditions>>(json)).FirstOrDefault();
}
return currentConditions;
}
}
}
|
using ApplicationCore.Entities.OrderAggregate;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Backoffice.ViewModels
{
public class CustomizeOrderViewModel
{
[Display(Name="#")]
public int Id { get; set; }
[Display(Name = "Email")]
public string BuyerId { get; set; }
[Display(Name = "Nome")]
public string BuyerName { get; set; }
[Display(Name = "Telefone")]
public string BuyerContact { get; set; }
[Display(Name = "Data")]
public DateTimeOffset OrderDate { get; set; }
[Display(Name = "Estado")]
public OrderStateType OrderState { get; set; }
[Display(Name = "Produto")]
public string ProductName { get; set; }
[Display(Name = "Imagem Produto")]
public string ProductPictureUri { get; set; }
public int ProductId { get; set; }
[Display(Name = "Descrição")]
public string Description { get; set; }
[Display(Name = "Frase/Texto")]
public string Text { get; set; }
[Display(Name = "Anexo")]
public string AttachFileName { get; set; }
[Display(Name = "Cores")]
public string Colors { get; set; }
}
}
|
using System;
namespace ChessGame.Board
{
abstract class Piece
{
public ChessBoard ChessBoard { get; private set; }
public Position Position { get; protected set; }
public Color Color { get; protected set; }
public int Movements { get; private set; }
public Piece (ChessBoard chessBoard, Color color)
{
ChessBoard = chessBoard;
Color = color;
Position = null;
Movements = 0;
}
public void IncrementMovement ()
{
Movements++;
}
public void DecrementMovement ()
{
Movements--;
}
public void AlterPosition (Position newPosition)
{
Position = newPosition;
}
public bool IsPossibleMovement (Position position)
{
return PossibleMovements()[position.Line, position.Column];
}
protected virtual bool CanMove (Position position)
{
return (!ChessBoard.PieceExists(position) || ChessBoard.GetPiece(position).Color != Color);
}
public abstract bool[,] PossibleMovements ();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CK.TypeScript.CodeGen
{
class FileBodyCodePart : RawCodePart, ITSFileBodySection
{
public FileBodyCodePart( TypeScriptFile f )
: base( f, String.Empty )
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReMi.Plugin.Gerrit.GerritApi
{
public interface ISshClient : IDisposable
{
void Connect();
string ExecuteCommand(string commandText);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Cumulocity.SDK.Microservices.OAuth.Handler
{
public static class OAuthAuthenticationDefaults
{
public const string AuthenticationScheme = "OAuth2Cumulocity";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntMe.Extension.Test
{
internal class DebugItemProperty1 : ItemProperty
{
public DebugItemProperty1(Item item) : base(item) { }
}
internal class DebugItemProperty1Specialized : DebugItemProperty1
{
public DebugItemProperty1Specialized(Item item) : base(item) { }
}
}
|
@using AbpCodeGeneration.VisualStudio.Common.Model
@inherits RazorEngine.Templating.TemplateBase<CreateFileInput>
using AutoMapper;
namespace @Model.Namespace.@Model.ModuleName
{
/// <summary>
/// Mapper映射配置
/// </summary>
public class @(Model.ModuleName)ApplicationAutoMapperProfile : Profile
{
/// <summary>
/// .ctor
/// </summary>
public @(Model.ModuleName)ApplicationAutoMapperProfile()
{
}
}
} |
using System.Collections.Generic;
using Pragmatic.TDD.Services.Tests.Fakes;
namespace Pragmatic.TDD.Services.Tests.Factories
{
public static class HorseFactory
{
private static FakeDataContext _context;
public static Models.Horse Create(FakeDataContext context, int id = 1, string name = "Man o' War")
{
_context = context;
Setup(context);
var horse = new Models.Horse
{
Id = id,
Name = name
};
context.Horses.Add(horse);
return horse;
}
public static Models.Horse WithColor(this Models.Horse horse)
{
var color = ColorFactory.Create(_context);
horse.Color = color;
horse.ColorId = color.Id;
return horse;
}
public static Models.Horse WithDam(this Models.Horse horse, int id = 2, string name = "Dam")
{
var dam = Create(_context, id, name);
horse.Dam = dam;
horse.DamId = dam.Id;
return horse;
}
public static Models.Horse WithSire(this Models.Horse horse, int id = 3, string name = "Sire")
{
var sire = Create(_context, id, name);
horse.Sire = sire;
horse.SireId = sire.Id;
return horse;
}
private static void Setup(FakeDataContext context)
{
context.Horses = context.Horses ?? new List<Models.Horse>();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rdc
{
/// <summary>
/// 从官方renderdoc代码中复制过来的通用函数
/// </summary>
public class Common
{
public static uint CalcNumMips(uint w, uint h, uint d)
{
uint mipLevels = 1;
while (w > 1 || h > 1 || d > 1)
{
w = Math.Max(1, w >> 1);
h = Math.Max(1, h >> 1);
d = Math.Max(1, d >> 1);
mipLevels++;
}
return mipLevels;
}
public static uint GetByteSize(int Width, int Height, int Depth, DXGI_FORMAT Format, int mip)
{
uint ret = (uint)(Math.Max(Width >> mip, 1) * Math.Max(Height >> mip, 1) * Math.Max(Depth >> mip, 1));
switch (Format)
{
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_SINT: ret *= 16; break;
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R32G32B32_SINT: ret *= 12; break;
case DXGI_FORMAT.DXGI_FORMAT_R16G16B16A16_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R16G16B16A16_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R16G16B16A16_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R16G16B16A16_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R16G16B16A16_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_R16G16B16A16_SINT:
case DXGI_FORMAT.DXGI_FORMAT_R32G32_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R32G32_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R32G32_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R32G32_SINT:
case DXGI_FORMAT.DXGI_FORMAT_R32G8X24_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: ret *= 8; break;
case DXGI_FORMAT.DXGI_FORMAT_R10G10B10A2_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R10G10B10A2_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R10G10B10A2_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R11G11B10_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_SINT:
case DXGI_FORMAT.DXGI_FORMAT_R16G16_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R16G16_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R16G16_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R16G16_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R16G16_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_R16G16_SINT:
case DXGI_FORMAT.DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_D32_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_R32_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R32_SINT:
case DXGI_FORMAT.DXGI_FORMAT_R24G8_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_D24_UNORM_S8_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_X24_TYPELESS_G8_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
case DXGI_FORMAT.DXGI_FORMAT_R8G8_B8G8_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_G8R8_G8B8_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_B8G8R8X8_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_B8G8R8X8_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: ret *= 4; break;
case DXGI_FORMAT.DXGI_FORMAT_R8G8_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R8G8_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R8G8_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R8G8_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_R8G8_SINT:
case DXGI_FORMAT.DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT.DXGI_FORMAT_D16_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R16_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R16_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R16_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_R16_SINT:
case DXGI_FORMAT.DXGI_FORMAT_B5G6R5_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_B5G5R5A1_UNORM: ret *= 2; break;
case DXGI_FORMAT.DXGI_FORMAT_R8_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_R8_UINT:
case DXGI_FORMAT.DXGI_FORMAT_R8_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_R8_SINT:
case DXGI_FORMAT.DXGI_FORMAT_A8_UNORM: ret *= 1; break;
case DXGI_FORMAT.DXGI_FORMAT_R1_UNORM: ret = Math.Max(ret / 8, 1U); break;
case DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC4_SNORM:
ret = (uint)(AlignUp4(Math.Max(Width >> mip, 1)) * AlignUp4(Math.Max(Height >> mip, 1)) *
Math.Max(Depth >> mip, 1));
ret /= 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT.DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT.DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC7_UNORM_SRGB:
ret = (uint)(AlignUp4(Math.Max(Width >> mip, 1)) * AlignUp4(Math.Max(Height >> mip, 1)) *
Math.Max(Depth >> mip, 1));
ret *= 1;
break;
case DXGI_FORMAT.DXGI_FORMAT_B4G4R4A4_UNORM:
ret *= 2; // 4 channels, half a byte each
break;
/*
* YUV planar/packed subsampled textures.
*
* In each diagram we indicate (maybe part) of the data for a 4x4 texture:
*
* +---+---+---+---+
* | 0 | 1 | 2 | 3 |
* +---+---+---+---+
* | 4 | 5 | 6 | 7 |
* +---+---+---+---+
* | 8 | 9 | A | B |
* +---+---+---+---+
* | C | D | E | F |
* +---+---+---+---+
*
*
* FOURCC decoding:
* - char 0: 'Y' = packed, 'P' = planar
* - char 1: '4' = 4:4:4, '2' = 4:2:2, '1' = 4:2:1, '0' = 4:2:0
* - char 2+3: '16' = 16-bit, '10' = 10-bit, '08' = 8-bit
*
* planar = Y is first, all together, then UV comes second.
* packed = YUV is interleaved
*
* ======================= 4:4:4 lossless packed =========================
*
* Equivalent to uncompressed formats, just YUV instead of RGB. For 8-bit:
*
* pixel: 0 1 2 3
* byte: 0 1 2 3 4 5 6 7 8 9 A B C D E F
* Y0 U0 V0 A0 Y1 U1 V1 A1 Y2 U2 V2 A2 Y3 U3 V3 A3
*
* 16-bit is similar with two bytes per sample, 10-bit for uncompressed is
* equivalent to R10G10B10A2 but with RGB=>YUV
*
* ============================ 4:2:2 packed =============================
*
* 50% horizontal subsampling packed, two Y samples for each U/V sample pair. For 8-bit:
*
* pixel: 0 | 1 2 | 3 4 | 5 6 | 7
* byte: 0 1 2 3 4 5 6 7 8 9 A B C D E F
* Y0 U0 Y1 V0 Y2 U1 Y3 V1 Y4 U2 Y5 V2 Y6 U3 Y7 V3
*
* 16-bit is similar with two bytes per sample, 10-bit is stored identically to 16-bit but in
* the most significant bits:
*
* bit: FEDCBA9876543210
* 16-bit: XXXXXXXXXXXXXXXX
* 10-bit: XXXXXXXXXX000000
*
* Since the data is unorm this just spaces out valid values.
*
* ============================ 4:2:0 planar =============================
*
* 50% horizontal and vertical subsampled planar, four Y samples for each U/V sample pair.
* For 8-bit:
*
*
* pixel: 0 1 2 3 4 5 6 7
* byte: 0 1 2 3 4 5 6 7
* Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7
*
* pixel: 8 9 A B C D E F
* byte: 8 9 A B C D E F
* Y8 Y9 Ya Yb Yc Yd Ye Yf
*
* ... all of the rest of Y luma ...
*
* pixel: T&4 | 1&5 2&6 | 3&7
* byte: 0 1 2 3 4 5 6 7
* U0 V0 U1 V1 U2 V2 U3 V3
*
* pixel: 8&C | 9&D A&E | B&F
* byte: 8 9 A B C D E F
* U4 V4 U5 V5 U6 V6 U7 V7
*/
case DXGI_FORMAT.DXGI_FORMAT_AYUV:
// 4:4:4 lossless packed, 8-bit. Equivalent size to R8G8B8A8
ret *= 4;
break;
case DXGI_FORMAT.DXGI_FORMAT_Y410:
// 4:4:4 lossless packed. Equivalent size to R10G10B10A2, unlike most 10-bit/16-bit formats is
// not equivalent to the 16-bit format.
ret *= 4;
break;
case DXGI_FORMAT.DXGI_FORMAT_Y416:
// 4:4:4 lossless packed. Equivalent size to R16G16B16A16
ret *= 8;
break;
case DXGI_FORMAT.DXGI_FORMAT_NV12:
// 4:2:0 planar. Since we can assume even width and height, resulting size is 1 byte per pixel
// for luma, plus 1 byte per 2 pixels for chroma
ret = ret + ret / 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_P010:
// 10-bit formats are stored identically to 16-bit formats
//DELIBERATE_FALLTHROUGH();
case DXGI_FORMAT.DXGI_FORMAT_P016:
// 4:2:0 planar but 16-bit, so pixelCount*2 + (pixelCount*2) / 2
ret *= 2;
ret = ret + ret / 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_420_OPAQUE:
// same size as NV12 - planar 4:2:0 but opaque layout
ret = ret + ret / 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_YUY2:
// 4:2:2 packed 8-bit, so 1 byte per pixel for luma and 1 byte per pixel for chroma (2 chroma
// samples, with 50% subsampling = 1 byte per pixel)
ret *= 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_Y210:
// 10-bit formats are stored identically to 16-bit formats
//DELIBERATE_FALLTHROUGH();
case DXGI_FORMAT.DXGI_FORMAT_Y216:
// 4:2:2 packed 16-bit
ret *= 4;
break;
case DXGI_FORMAT.DXGI_FORMAT_NV11:
// similar to NV11 - planar 4:1:1 4 horizontal downsampling but no vertical downsampling. For
// size calculation amounts to the same result.
ret = ret + ret / 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_AI44:
// special format, 1 byte per pixel, palletised values in 4 most significant bits, alpha in 4
// least significant bits.
//DELIBERATE_FALLTHROUGH();
case DXGI_FORMAT.DXGI_FORMAT_IA44:
// same as above but swapped MSB/LSB
break;
case DXGI_FORMAT.DXGI_FORMAT_P8:
// 8 bits of palletised data
break;
case DXGI_FORMAT.DXGI_FORMAT_A8P8:
// 8 bits palletised data, 8 bits alpha data. Seems to be packed (no indication in docs of
// planar)
ret *= 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_P208:
// 4:2:2 planar 8-bit. 1 byte per pixel of luma, then separately 1 byte per pixel of chroma.
// Identical size to packed 4:2:2, just different layout
ret *= 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_V208:
// unclear, seems to be packed 4:4:0 8-bit. Thus 1 byte per pixel for luma, 2 chroma samples
// every 2 rows = 1 byte per pixel for chroma
ret *= 2;
break;
case DXGI_FORMAT.DXGI_FORMAT_V408:
// unclear, seems to be packed 4:4:4 8-bit
ret *= 4;
break;
case DXGI_FORMAT.DXGI_FORMAT_UNKNOWN:
Console.WriteLine("Getting byte size of unknown DXGI format");
ret = 0;
break;
default: Console.WriteLine("Unrecognised DXGI Format: %d", Format); break;
}
return ret;
}
public static uint AlignUp4(uint x)
{
return (uint)((x + 0x3) & (~0x3));
}
public static long AlignUp4(long x)
{
return (x + 0x3) & (~0x3);
}
public static bool IsBlockFormat(DXGI_FORMAT f)
{
switch (f)
{
case DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC4_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC4_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT.DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC5_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT.DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT.DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT.DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT.DXGI_FORMAT_BC7_UNORM_SRGB: return true;
default: break;
}
return false;
}
public static bool IsYUVPlanarFormat(DXGI_FORMAT f)
{
switch (f)
{
case DXGI_FORMAT.DXGI_FORMAT_NV12:
case DXGI_FORMAT.DXGI_FORMAT_P010:
case DXGI_FORMAT.DXGI_FORMAT_P016:
case DXGI_FORMAT.DXGI_FORMAT_420_OPAQUE:
case DXGI_FORMAT.DXGI_FORMAT_NV11:
case DXGI_FORMAT.DXGI_FORMAT_P208: return true;
default: break;
}
return false;
}
public static uint GetYUVNumRows(DXGI_FORMAT f, uint height)
{
switch (f)
{
case DXGI_FORMAT.DXGI_FORMAT_NV12:
case DXGI_FORMAT.DXGI_FORMAT_P010:
case DXGI_FORMAT.DXGI_FORMAT_P016:
case DXGI_FORMAT.DXGI_FORMAT_420_OPAQUE:
// all of these are 4:2:0, so number of rows is equal to height + height/2
return height + height / 2;
case DXGI_FORMAT.DXGI_FORMAT_NV11:
case DXGI_FORMAT.DXGI_FORMAT_P208:
// 4:1:1 and 4:2:2 have the same number of rows for chroma and luma planes, so we have
// height * 2 rows
return height * 2;
default: break;
}
return height;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Szlem.Persistence.NHibernate
{
public class Marker
{
}
}
|
using System;
using System.Text;
namespace Zooyard.Rpc.NettyImpl.Protocol
{
/// <summary>
/// The type Merge result message.
///
/// </summary>
[Serializable]
public class MergeResultMessage : AbstractMessage, IMergeMessage
{
/// <summary>
/// Get msgs abstract result message [ ].
/// </summary>
/// <returns> the abstract result message [ ] </returns>
public virtual AbstractResultMessage[] Msgs { get; set; }
public override short TypeCode
{
get
{
return MessageType.TYPE_SEATA_MERGE_RESULT;
}
}
public override string ToString()
{
var sb = new StringBuilder("MergeResultMessage ");
if (Msgs == null)
{
return sb.ToString();
}
foreach (AbstractMessage msg in Msgs)
{
sb.Append(msg.ToString()).Append("\n");
}
return sb.ToString();
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PriSchLecs.Api.Domains.Files;
using PriSchLecs.Api.Dtos.Models.Files;
using PriSchLecs.Api.Infrastructure.SmartTable;
using PriSchLecs.Api.Infrastructures.Services.Files;
namespace PriSchLecs.Api.Controllers.Files
{
[Route("api/[controller]")]
[ApiController]
public class FileController : ControllerBase
{
private readonly IFileService FileService;
public FileController(IFileService fileService)
{
FileService = fileService;
}
/// <summary>
/// API đăng tải file lên server
/// </summary>
/// <param name="model">file</param>
/// <returns></returns>
[HttpPost("Upload")]
public async Task<IActionResult> Upload([FromForm]FileModel model)
{
var result = await FileService.Upload(model);
return Ok(result);
}
/// <summary>
/// API tải file từ server
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("Download/{id}")]
public async Task<IActionResult> Download(int id)
{
var result = await FileService.Download(id);
if (result.File == null)
{
return Ok(result);
}
result.File.Position = 0;
return File(result.File, "application/octet-stream", result.Name);
}
/// <summary>
/// API lấy danh sách file
/// </summary>
/// <param name="param">tham số dạng smart table gồm tên, ngày tạo, phân trang, sắp xếp</param>
/// <returns></returns>
[HttpPost("Search")]
public async Task<IActionResult> Search(SmartTableParam param)
{
var result = await FileService.Search(param);
return Ok(result);
}
/// <summary>
/// APi xóa file
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("Delete/{id}")]
public async Task<IActionResult> Delete(int id)
{
var result = await FileService.Delete(id);
return Ok(result);
}
}
} |
namespace MassTransit.SagaStateMachine
{
using System;
using System.Collections.Generic;
using System.Linq;
[Serializable]
public class StateMachineGraph
{
readonly Edge[] _edges;
readonly Vertex[] _vertices;
public StateMachineGraph(IEnumerable<Vertex> vertices, IEnumerable<Edge> edges)
{
_vertices = vertices.ToArray();
_edges = edges.ToArray();
}
public IEnumerable<Vertex> Vertices => _vertices;
public IEnumerable<Edge> Edges => _edges;
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using MathNet.Numerics.Random;
using NUnit.Framework;
using Vts.MonteCarlo;
using Vts.MonteCarlo.Factories;
namespace Vts.Test.MonteCarlo.Sources
{
/// <summary>
/// These tests set up all sources using SourceProvider list and test
/// SourceInput, CreateSource, and resulting Source
/// </summary>
[TestFixture]
public class AllSourceTests
{
private IEnumerable<ISourceInput> _sourceInputs;
private List<string> _sourceFiles;
/// <summary>
/// setup list of sources to test
/// </summary>
[OneTimeSetUp]
public void Generate_list_of_sources()
{
var inputFiles = SourceInputProvider.GenerateAllSourceInputs();
// generate list of unique detectors from all sample input files
var sourceInputGrouping = inputFiles.GroupBy(d => d.SourceType).ToList();
_sourceInputs = sourceInputGrouping.
Select(x => x.FirstOrDefault());
_sourceFiles = _sourceInputs.Select(d => d.SourceType).ToList();
}
/// <summary>
/// Tests if source is instantiated using sourceInput.
/// </summary>
[Test]
public void Verify_source_classes()
{
// use factory to instantiate detector with CreateDetector and call Initialize
var rng = new MersenneTwister(0);
foreach (var sourceInput in _sourceInputs)
{
// factory generates IDetector using CreateDetector,
// then calls detector.Initialize method
var source = SourceFactory.GetSource(sourceInput, rng);
Assert.IsInstanceOf<ISource>(source);
}
}
}
}
|
/**
* Author: Ryan A. Kueter
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Acceledesk.Wmi
{
public class LogicalDisk : ILogicalDiskProvider
{
public string Name { get; set; }
public string Drive { get; set; }
public string Path { get; set; }
public double Size { get; set; } = -1;
public string SizeFormatted
{
get { return Size != -1 ? Calc.GetBytes(Size) : String.Empty; }
}
public double FreeSpace { get; set; } = -1;
public string FreeSpaceFormated
{
get { return FreeSpace != -1 ? Calc.GetBytes(FreeSpace) : String.Empty; }
}
public double Usage
{
get { return GetUsage(); }
}
public string UsageFormatted
{
get { return GetUsageFormatted(); }
}
public string VolumeName { get; set; }
public string VolumeSerialNumber { get; set; }
public string Filesystem { get; set; }
public string DriveType { get; set; } = String.Empty;
public string DriveTypeLabel
{
get { return DriveType != String.Empty ? GetDriveType(DriveType.ToString()) : String.Empty; }
}
public string Description { get; set; }
private double GetUsage()
{
if (Size == -1 || FreeSpace == -1) { return -1; }
return ((Size - FreeSpace) / Size) * 100;
}
private string GetUsageFormatted()
{
if (Size == -1 || FreeSpace == -1) { return String.Empty; }
return Convert.ToInt32(Math.Round(((Size - FreeSpace) / Size) * 100)).ToString() + "%";
}
private string GetDriveType(string type)
{
string result = String.Empty;
switch (type)
{
case "1":
result = "Unknown";
break;
case "2":
result = "Removable";
break;
case "3":
result = "Local";
break;
case "4":
result = "Network";
break;
case "5":
result = "Optical";
break;
case "6":
result = "RAM Disk";
break;
default:
break;
}
return result;
}
}
}
|
namespace WebServer.Http.Response
{
using Enums;
public class UnauthorizedResponse : HttpResponse
{
public UnauthorizedResponse(string message)
{
this.StatusCode = HttpStatusCode.Unauthorized;
// TODO: Add message
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace LibHac.Util.Impl
{
internal static class HexConverter
{
public enum Casing : uint
{
// Output [ '0' .. '9' ] and [ 'A' .. 'F' ].
Upper = 0,
// Output [ '0' .. '9' ] and [ 'a' .. 'f' ].
// This works because values in the range [ 0x30 .. 0x39 ] ([ '0' .. '9' ])
// already have the 0x20 bit set, so ORing them with 0x20 is a no-op,
// while outputs in the range [ 0x41 .. 0x46 ] ([ 'A' .. 'F' ])
// don't have the 0x20 bit set, so ORing them maps to
// [ 0x61 .. 0x66 ] ([ 'a' .. 'f' ]), which is what we want.
Lower = 0x2020U
}
// We want to pack the incoming byte into a single integer [ 0000 HHHH 0000 LLLL ],
// where HHHH and LLLL are the high and low nibbles of the incoming byte. Then
// subtract this integer from a constant minuend as shown below.
//
// [ 1000 1001 1000 1001 ]
// - [ 0000 HHHH 0000 LLLL ]
// =========================
// [ *YYY **** *ZZZ **** ]
//
// The end result of this is that YYY is 0b000 if HHHH <= 9, and YYY is 0b111 if HHHH >= 10.
// Similarly, ZZZ is 0b000 if LLLL <= 9, and ZZZ is 0b111 if LLLL >= 10.
// (We don't care about the value of asterisked bits.)
//
// To turn a nibble in the range [ 0 .. 9 ] into hex, we calculate hex := nibble + 48 (ascii '0').
// To turn a nibble in the range [ 10 .. 15 ] into hex, we calculate hex := nibble - 10 + 65 (ascii 'A').
// => hex := nibble + 55.
// The difference in the starting ASCII offset is (55 - 48) = 7, depending on whether the nibble is <= 9 or >= 10.
// Since 7 is 0b111, this conveniently matches the YYY or ZZZ value computed during the earlier subtraction.
// The commented out code below is code that directly implements the logic described above.
// uint packedOriginalValues = (((uint)value & 0xF0U) << 4) + ((uint)value & 0x0FU);
// uint difference = 0x8989U - packedOriginalValues;
// uint add7Mask = (difference & 0x7070U) >> 4; // line YYY and ZZZ back up with the packed values
// uint packedResult = packedOriginalValues + add7Mask + 0x3030U /* ascii '0' */;
// The code below is equivalent to the commented out code above but has been tweaked
// to allow codegen to make some extra optimizations.
// The low byte of the packed result contains the hex representation of the incoming byte's low nibble.
// The adjacent byte of the packed result contains the hex representation of the incoming byte's high nibble.
// Finally, write to the output buffer starting with the *highest* index so that codegen can
// elide all but the first bounds check. (This only works if 'startingIndex' is a compile-time constant.)
// The JIT can elide bounds checks if 'startingIndex' is constant and if the caller is
// writing to a span of known length (or the caller has already checked the bounds of the
// furthest access).
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
{
uint difference = ((value & 0xF0U) << 4) + (value & 0x0FU) - 0x8989U;
uint packedResult = ((((uint)(-(int)difference) & 0x7070U) >> 4) + difference + 0xB9B9U) | (uint)casing;
buffer[startingIndex + 1] = (byte)packedResult;
buffer[startingIndex] = (byte)(packedResult >> 8);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
{
uint difference = ((value & 0xF0U) << 4) + (value & 0x0FU) - 0x8989U;
uint packedResult = ((((uint)(-(int)difference) & 0x7070U) >> 4) + difference + 0xB9B9U) | (uint)casing;
buffer[startingIndex + 1] = (char)(packedResult & 0xFF);
buffer[startingIndex] = (char)(packedResult >> 8);
}
public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
{
Debug.Assert(chars.Length >= bytes.Length * 2);
for (int pos = 0; pos < bytes.Length; ++pos)
{
ToCharsBuffer(bytes[pos], chars, pos * 2, casing);
}
}
public static unsafe string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
{
fixed (byte* bytesPtr = bytes)
{
// Todo: Make lambda static in C# 9
return string.Create(bytes.Length * 2, (Ptr: (IntPtr)bytesPtr, bytes.Length, casing), (chars, args) =>
{
var ros = new ReadOnlySpan<byte>((byte*)args.Ptr, args.Length);
EncodeToUtf16(ros, chars, args.casing);
});
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static char ToCharUpper(int value)
{
value &= 0xF;
value += '0';
if (value > '9')
{
value += ('A' - ('9' + 1));
}
return (char)value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static char ToCharLower(int value)
{
value &= 0xF;
value += '0';
if (value > '9')
{
value += ('a' - ('9' + 1));
}
return (char)value;
}
public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes)
{
return TryDecodeFromUtf16(chars, bytes, out _);
}
public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
{
Debug.Assert(chars.Length % 2 == 0, "Un-even number of characters provided");
Debug.Assert(chars.Length / 2 == bytes.Length, "Target buffer not right-sized for provided characters");
int i = 0;
int j = 0;
int byteLo = 0;
int byteHi = 0;
while (j < bytes.Length)
{
byteLo = FromChar(chars[i + 1]);
byteHi = FromChar(chars[i]);
// byteHi hasn't been shifted to the high half yet, so the only way the bitwise or produces this pattern
// is if either byteHi or byteLo was not a hex character.
if ((byteLo | byteHi) == 0xFF)
break;
bytes[j++] = (byte)((byteHi << 4) | byteLo);
i += 2;
}
if (byteLo == 0xFF)
i++;
charsProcessed = i;
return (byteLo | byteHi) != 0xFF;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int FromChar(int c)
{
return c >= CharToHexLookup.Length ? 0xFF : CharToHexLookup[c];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int FromUpperChar(int c)
{
return c > 71 ? 0xFF : CharToHexLookup[c];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int FromLowerChar(int c)
{
if ((uint)(c - '0') <= '9' - '0')
return c - '0';
if ((uint)(c - 'a') <= 'f' - 'a')
return c - 'a' + 10;
return 0xFF;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsHexChar(int c)
{
return FromChar(c) != 0xFF;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsHexUpperChar(int c)
{
return (uint)(c - '0') <= 9 || (uint)(c - 'A') <= ('F' - 'A');
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsHexLowerChar(int c)
{
return (uint)(c - '0') <= 9 || (uint)(c - 'a') <= ('f' - 'a');
}
/// <summary>Map from an ASCII char to its hex value, e.g. arr['b'] == 11. 0xFF means it's not a hex digit.</summary>
public static ReadOnlySpan<byte> CharToHexLookup => new byte[]
{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 15
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 31
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 47
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 63
0xFF, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 79
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 95
0xFF, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 111
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 127
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 143
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 159
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 175
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 191
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 207
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 223
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 239
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 255
};
}
} |
using Dapper.Repositories.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Dapper.Repositories;
using Dapper.Repositories.Attributes.Joins;
namespace WebAPI_Model
{
[Table("Customers", Schema = "dbo")]
public class CustomersModel : DefaultColumns
{
[Identity, Key]
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
[LeftJoin("Orders", nameof(CustomerID), nameof(WebAPI_Model.OrdersModel.CustomerID), "dbo")]
public List<OrdersModel> OrdersModel { get; set; }
}
}
|
/*
* Escribir un programa que lea 10 notas de estudiantes y nos
* informe cuántos tienen notas mayores o iguales a 3 y cuántos
* menores.Para resolver este problema se requieren tres contadores
*/
float nota;
int cont2=0, cont3=0;
Console.WriteLine("Programa Sentencia FOR");
for (int cont1 = 1; cont1 <= 10; cont1++)
{
Console.WriteLine("Digite nota "+cont1+":");
nota = float.Parse(Console.ReadLine());
if (nota == 3 || nota >= 3)
{
cont2++;
}
else
{
cont3++;
}
};
Console.WriteLine("Las notas mayores o iguales a 3 son:"+cont2);
Console.WriteLine("Las notas menores que 3 son:" + cont3);
Console.ReadKey();
|
using Newtonsoft.Json;
using QueryRoom.DTOs;
using QueryRoom.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
namespace QueryRoom.Controllers.MVC_controllers
{
[Authorize(Roles ="Admin")]
public class AdminMVCController : Controller
{
// GET: AdminMVC
public ActionResult Index() //OKK for dto
{
return View();
}
public ActionResult GetAllUsers() //OKK for dto
{
HttpClient hc = new HttpClient();
IEnumerable<UserDetails> users = null;
hc.BaseAddress = new Uri("https://localhost:44315/");
var responseTask = hc.GetAsync("api/AdminAPI");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readResult = result.Content.ReadAsAsync<List<UserDetails>>();
readResult.Wait();
users = readResult.Result;
}
else
{
users = Enumerable.Empty<UserDetails>();
ModelState.AddModelError(string.Empty, "Server error occurred");
}
return View(users);
}
}
} |
namespace DotnetCoreIdentityServerJwtIssuer.Dto
{
public class LoginDto
{
public string Audience {get; set;}
public string UserEmail {get; set;}
public string UserPassword {get; set;}
}
} |
namespace FaraMedia.Core.Domain.FileManagement {
public class Picture : UserContentBase {
public virtual string FileName { get; set; }
public virtual string MimeType { get; set; }
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
namespace starshipxac.Shell.PropertySystem.Interop
{
/// <summary>
///
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/en-us/library/windows/desktop/bb761551(v=vs.85).aspx
/// </remarks>
[SuppressMessage("ReSharper", "InconsistentNaming")]
internal enum PROPDESC_SORTDESCRIPTION
{
/// <summary>
/// Default. "Sort going up", "Sort going down"
/// </summary>
PDSD_GENERAL = 0,
/// <summary>
/// "A on top", "Z on top"
/// </summary>
PDSD_A_Z = 1,
/// <summary>
/// "Lowest on top", "Highest on top"
/// </summary>
PDSD_LOWEST_HIGHEST = 2,
/// <summary>
/// "Smallest on top", "Largest on top"
/// </summary>
PDSD_SMALLEST_BIGGEST = 3,
/// <summary>
/// "Oldest on top", "Newest on top"
/// </summary>
PDSD_OLDEST_NEWEST = 4
}
} |
using UnityEngine.UI;
public abstract class NetworkObject {
/// <summary>
/// Fills the given <see cref="Text[]"/> with the fields of a network data object.
/// </summary>
/// <param name="texts"></param>
public abstract void FillTexts(Text[] texts);
protected string DeviceNameToUpperCase(string name)
{
if (name.Contains("_"))
{
string[] array = name.Split('_');
return array[0].ToUpper() + array[1];
}
return name.ToUpper();
}
}
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sage.CA.SBS.ERP.Sage300.GL.Resources.Forms {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class AccountStructuresResx {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal AccountStructuresResx() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sage.CA.SBS.ERP.Sage300.GL.Resources.Forms.AccountStructuresResx", typeof(AccountStructuresResx).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Account Structure.
/// </summary>
public static string AccountStructure {
get {
return ResourceManager.GetString("AccountStructure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Available Segments.
/// </summary>
public static string ChooseSegments {
get {
return ResourceManager.GetString("ChooseSegments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exclude.
/// </summary>
public static string CmdExclude {
get {
return ResourceManager.GetString("CmdExclude", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Include.
/// </summary>
public static string CmdInclude {
get {
return ResourceManager.GetString("CmdInclude", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to G/L Account Structures.
/// </summary>
public static string Entity {
get {
return ResourceManager.GetString("Entity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Structure Codes.
/// </summary>
public static string GL0023 {
get {
return ResourceManager.GetString("GL0023", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must define Segment Codes before editing Account Structures..
/// </summary>
public static string NOSCODE {
get {
return ResourceManager.GetString("NOSCODE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 10 Length.
/// </summary>
public static string Segment10Length {
get {
return ResourceManager.GetString("Segment10Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 10 Starting Position.
/// </summary>
public static string Segment10StartingPosition {
get {
return ResourceManager.GetString("Segment10StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 1 Length.
/// </summary>
public static string Segment1Length {
get {
return ResourceManager.GetString("Segment1Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 1 Starting Position.
/// </summary>
public static string Segment1StartingPosition {
get {
return ResourceManager.GetString("Segment1StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 2 Length.
/// </summary>
public static string Segment2Length {
get {
return ResourceManager.GetString("Segment2Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 2 Starting Position.
/// </summary>
public static string Segment2StartingPosition {
get {
return ResourceManager.GetString("Segment2StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 3 Length.
/// </summary>
public static string Segment3Length {
get {
return ResourceManager.GetString("Segment3Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 3 Starting Position.
/// </summary>
public static string Segment3StartingPosition {
get {
return ResourceManager.GetString("Segment3StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 4 Length.
/// </summary>
public static string Segment4Length {
get {
return ResourceManager.GetString("Segment4Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 4 Starting Position.
/// </summary>
public static string Segment4StartingPosition {
get {
return ResourceManager.GetString("Segment4StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 5 Length.
/// </summary>
public static string Segment5Length {
get {
return ResourceManager.GetString("Segment5Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 5 Starting Position.
/// </summary>
public static string Segment5StartingPosition {
get {
return ResourceManager.GetString("Segment5StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 6 Length.
/// </summary>
public static string Segment6Length {
get {
return ResourceManager.GetString("Segment6Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 6 Starting Position.
/// </summary>
public static string Segment6StartingPosition {
get {
return ResourceManager.GetString("Segment6StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 7 Length.
/// </summary>
public static string Segment7Length {
get {
return ResourceManager.GetString("Segment7Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 7 Starting Position.
/// </summary>
public static string Segment7StartingPosition {
get {
return ResourceManager.GetString("Segment7StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 8 Length.
/// </summary>
public static string Segment8Length {
get {
return ResourceManager.GetString("Segment8Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 8 Starting Position.
/// </summary>
public static string Segment8StartingPosition {
get {
return ResourceManager.GetString("Segment8StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 9 Length.
/// </summary>
public static string Segment9Length {
get {
return ResourceManager.GetString("Segment9Length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment 9 Starting Position.
/// </summary>
public static string Segment9StartingPosition {
get {
return ResourceManager.GetString("Segment9StartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number.
/// </summary>
public static string SegmentNumber {
get {
return ResourceManager.GetString("SegmentNumber", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 1.
/// </summary>
public static string SegmentNumber1 {
get {
return ResourceManager.GetString("SegmentNumber1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 10.
/// </summary>
public static string SegmentNumber10 {
get {
return ResourceManager.GetString("SegmentNumber10", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 2.
/// </summary>
public static string SegmentNumber2 {
get {
return ResourceManager.GetString("SegmentNumber2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 3.
/// </summary>
public static string SegmentNumber3 {
get {
return ResourceManager.GetString("SegmentNumber3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 4.
/// </summary>
public static string SegmentNumber4 {
get {
return ResourceManager.GetString("SegmentNumber4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 5.
/// </summary>
public static string SegmentNumber5 {
get {
return ResourceManager.GetString("SegmentNumber5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 6.
/// </summary>
public static string SegmentNumber6 {
get {
return ResourceManager.GetString("SegmentNumber6", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 7.
/// </summary>
public static string SegmentNumber7 {
get {
return ResourceManager.GetString("SegmentNumber7", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 8.
/// </summary>
public static string SegmentNumber8 {
get {
return ResourceManager.GetString("SegmentNumber8", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Number 9.
/// </summary>
public static string SegmentNumber9 {
get {
return ResourceManager.GetString("SegmentNumber9", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segment Starting Position.
/// </summary>
public static string SegmentStartingPosition {
get {
return ResourceManager.GetString("SegmentStartingPosition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Segments Used by this Account Structure.
/// </summary>
public static string SegmentsUsed {
get {
return ResourceManager.GetString("SegmentsUsed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Selected Account Segments.
/// </summary>
public static string SelectedAccountSegments {
get {
return ResourceManager.GetString("SelectedAccountSegments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Structure Code.
/// </summary>
public static string StructureCode {
get {
return ResourceManager.GetString("StructureCode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Structure Description.
/// </summary>
public static string StructureCodeDescription {
get {
return ResourceManager.GetString("StructureCodeDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use as Company Default Structure.
/// </summary>
public static string UseCompanyDefault {
get {
return ResourceManager.GetString("UseCompanyDefault", resourceCulture);
}
}
}
}
|
using DemoPlugin.Properties;
using KeePass.Plugins;
using KeePass.Util;
using System.Drawing;
using System.Windows.Forms;
namespace DemoPlugin
{
public sealed class DemoPluginExt : Plugin
{
private IPluginHost _host;
public override Image SmallIcon
{
get { return Resources.MenuIcon; }
}
public override string UpdateUrl
{
get { return "<updateUrl>"; }
}
public override bool Initialize(IPluginHost host)
{
if (host == null) return false;
_host = host;
//Set the version information file signature
UpdateCheckEx.SetFileSigKey(UpdateUrl, Resources.DemoPluginExt_UpdateCheckFileSigKey);
return true;
}
public override void Terminate()
{
}
public override ToolStripMenuItem GetMenuItem(PluginMenuType t)
{
if (t != PluginMenuType.Main)
return null;
ToolStripMenuItem strip = new ToolStripMenuItem
{
Text = Resources.DemoPluginExt_GetMenuItem_DemoPlugin
};
return strip;
}
}
} |
using System;
using System.Collections.Generic;
namespace ReMi.Plugin.ZenDesk.DataAccess.Gateways
{
public interface IPackageConfigurationGateway : IDisposable
{
PluginPackageConfigurationEntity GetPackageConfiguration(Guid packageId);
IEnumerable<PluginPackageConfigurationEntity> GetPackagesConfiguration();
void SavePackageConfiguration(PluginPackageConfigurationEntity packageConfiguration);
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using IF.Lastfm.Core.Api.Enums;
using IF.Lastfm.Core.Api.Helpers;
using IF.Lastfm.Core.Objects;
using IF.Lastfm.Core.Scrobblers;
namespace IF.Lastfm.Core.Api.Commands.Track
{
[ApiMethodName("track.scrobble")]
internal class ScrobbleCommand : PostAsyncCommandBase<ScrobbleResponse>
{
public IList<Scrobble> Scrobbles { get; private set; }
public ScrobbleCommand(ILastAuth auth, IList<Scrobble> scrobbles)
: base(auth)
{
if (scrobbles.Count > 50)
{
throw new ArgumentOutOfRangeException("scrobbles", "Only 50 scrobbles can be sent at a time");
}
Scrobbles = scrobbles;
}
protected override Uri BuildRequestUrl()
{
return new Uri(LastFm.ApiRootSsl, UriKind.Absolute);
}
public ScrobbleCommand(ILastAuth auth, Scrobble scrobble)
: this(auth, new []{scrobble})
{
}
public override void SetParameters()
{
for(int i = 0; i < Scrobbles.Count; i++)
{
var scrobble = Scrobbles[i];
Parameters.Add(String.Format("artist[{0}]", i), scrobble.Artist);
Parameters.Add(String.Format("album[{0}]", i), scrobble.Album);
Parameters.Add(String.Format("track[{0}]", i), scrobble.Track);
Parameters.Add(String.Format("albumArtist[{0}]", i), scrobble.AlbumArtist);
Parameters.Add(String.Format("chosenByUser[{0}]", i), Convert.ToInt32(scrobble.ChosenByUser).ToString());
Parameters.Add(String.Format("timestamp[{0}]", i), scrobble.TimePlayed.AsUnixTime().ToString());
}
}
public override async Task<ScrobbleResponse> HandleResponse(HttpResponseMessage response)
{
var json = await response.Content.ReadAsStringAsync();
LastResponseStatus status;
if (LastFm.IsResponseValid(json, out status) && response.IsSuccessStatusCode)
{
return await ScrobbleResponse.CreateSuccessResponse(json);
}
else
{
return LastResponse.CreateErrorResponse<ScrobbleResponse>(status);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Placeable : MonoBehaviour {
public bool isAvailable = true;
public Transform pivotPoint;
// Use this for initialization
public Vector3 GetPivotPoint()
{
if (pivotPoint == null)
return transform.position;
return pivotPoint.position;
}
}
|
using System.Text.RegularExpressions;
using Markdig;
using MicroSiteMaker.Core;
using MicroSiteMaker.Models;
namespace MicroSiteMaker.Services;
public static class SiteBuilderService
{
private static bool s_follow = true;
private static bool s_index = true;
public static void SetFollow(bool follow)
{
s_follow = follow;
}
public static void SetIndex(bool index)
{
s_index = index;
}
public static void CreateOutputDirectoriesAndFiles(Website website)
{
FileService.PopulateWebsiteInputFiles(website);
FileService.CreateOutputDirectories(website);
FileService.CopyCssFilesToOutputDirectory(website);
FileService.CopyImageFilesToOutputDirectory(website);
CreateOutputPageHtml(website);
FileService.WriteOutputFiles(website);
FileService.CreateSitemapFile(website);
FileService.CreateRobotsTextFile(website);
}
private static void CreateOutputPageHtml(Website website)
{
website.PopulateMenuLines();
var templateLines = FileService.GetPageTemplateLines(website);
foreach (IHtmlPageSource page in website.AllPages)
{
foreach (string templateLine in templateLines)
{
if (templateLine.StartsWith("{{page-content}}"))
{
foreach (string inputLine in page.InputFileLines)
{
page.OutputLines.Add(GetCleanedHtmlLine(website, page, inputLine));
}
}
else if (templateLine.StartsWith("{{menu}}"))
{
foreach (string menuLine in website.MenuLines)
{
page.OutputLines.Add(GetCleanedHtmlLine(website, page, menuLine));
}
}
else
{
page.OutputLines.Add(GetCleanedHtmlLine(website, page, templateLine));
}
}
AddRobotsMetaTagToOutputLines(page);
AddDescriptionMetaTagToOutputLines(page);
}
}
private static void AddRobotsMetaTagToOutputLines(IHtmlPageSource page)
{
// Build robots tag from parameters
string followText = s_follow ? "follow" : "nofollow";
string indexText = s_index ? "index" : "noindex";
string robotsTag = $"<meta name=\"robots\" content=\"{followText}, {indexText}\">";
// Check if OutputLines already has robots tag
var robotsLine =
page.OutputLines.FirstOrDefault(line => line.Contains("meta ") && line.Contains("robots"));
// If robots line does not exist, add it. Otherwise, replace the existing one.
if (robotsLine == null)
{
page.OutputLines.Insert(IndexOfClosingHeadTagInOutputLines(page), robotsTag);
}
else
{
page.OutputLines[page.OutputLines.IndexOf(robotsLine)] = robotsTag;
}
}
private static void AddDescriptionMetaTagToOutputLines(IHtmlPageSource page)
{
if (string.IsNullOrWhiteSpace(page.MetaTagDescription))
{
return;
}
page.OutputLines.Insert(IndexOfClosingHeadTagInOutputLines(page),
$"<meta name=\"description\" content=\"{page.MetaTagDescription}\">");
}
private static int IndexOfClosingHeadTagInOutputLines(IHtmlPageSource page)
{
return page.OutputLines.IndexOf(page.OutputLines.First(line => line.Trim().StartsWith("</head")));
}
private static string GetCleanedHtmlLine(Website website, IHtmlPageSource page, string line)
{
var cleanedLine = line
.Replace("{{website-name}}", website.Url)
.Replace("{{page-name}}", page.Title)
.Replace("{{stylesheet-name}}", website.CssFileName)
.Replace("{{file-date}}", page.FileDateTime.ToString("dd MMMM yyyy"))
.Replace("{{date-year}}", DateTime.Now.Year.ToString())
.Replace("{{date-month}}", DateTime.Now.Month.ToString())
.Replace("{{date-month-name}}", DateTime.Now.ToString("MMMM"))
.Replace("{{date-date}}", DateTime.Now.Day.ToString())
.Replace("{{date-dow}}", DateTime.Now.DayOfWeek.ToString());
var htmlLine = Markdown.ToHtml(cleanedLine);
return MakeExternalLinksOpenInNewTab(htmlLine, website.Url);
}
private static string MakeExternalLinksOpenInNewTab(string htmlLine, string websiteName)
{
Match regexMatch =
Regex.Match(htmlLine, Constants.Regexes.A_HREF,
RegexOptions.IgnoreCase | RegexOptions.Compiled,
TimeSpan.FromSeconds(1));
string cleanedLine = htmlLine;
while (regexMatch.Success)
{
var hrefText = regexMatch.Groups[1].Value;
if (hrefText.Contains("http", StringComparison.InvariantCultureIgnoreCase) &&
!hrefText.Contains(websiteName, StringComparison.InvariantCultureIgnoreCase))
{
var newHrefText = hrefText;
if (!newHrefText.Contains(" target=", StringComparison.InvariantCultureIgnoreCase))
{
newHrefText = newHrefText.Replace(">", " target=\"_blank\">");
}
if (!newHrefText.Contains(" rel=", StringComparison.InvariantCultureIgnoreCase))
{
newHrefText = newHrefText.Replace(">", " rel=\"nofollow\">");
}
cleanedLine = cleanedLine.Replace(hrefText, newHrefText);
}
regexMatch = regexMatch.NextMatch();
}
return cleanedLine;
}
} |
using Newtonsoft.Json;
namespace Birko.SuperFaktura.Request.Client
{
public class ContactPerson
{
[JsonProperty(PropertyName = "id", NullValueHandling = NullValueHandling.Ignore)]
public int? ID { get; internal set; }
[JsonProperty(PropertyName = "client_id", NullValueHandling = NullValueHandling.Ignore)]
public int? ClientID { get; set; }
[JsonProperty(PropertyName = "name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
[JsonProperty(PropertyName = "email", NullValueHandling = NullValueHandling.Ignore)]
public string Email { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace EightPuzzle
{
public class Environment
{
public char[] gameState { get; private set; }
public string goalState;
public Environment(string initialState = "123456780") {
gameState = initialState.ToCharArray();
goalState = "123456780";
}
public bool canMoveLeft (int i) => i % 3 != 1;
public bool canMoveRight (int i) => i % 3 != 0;
public bool canMoveUp (int i) => i > 3;
public bool canMoveDown (int i) => i < 7;
public void moveLeft(int i) => swap(i, i-1, gameState);
public void moveRight(int i) => swap(i, i+1, gameState);
public void moveUp(int i) => swap(i, i-3, gameState);
public void moveDown(int i) => swap(i, i+3, gameState);
public int getEmptyPieceLocation(char[] state) {
for (int i = 0; i < state.Length; i++) {
if (state[i] == '0') return i+1;
}
return 0;
}
public string swap(int i, int j, char[] state) {
char x = state[i-1];
state[i-1] = state[j-1];
state[j-1] = x;
return new string(state);
}
public bool isGoalState(char[] state) {
for (int i = 0; i < state.Length; i++) {
if (state[i] != goalState[i]) return false;
}
return true;
}
public List<string> getPossibleMoves(string state, out List<char> action) {
int i = getEmptyPieceLocation(state.ToCharArray());
List<string> possibleMoves = new List<string>();
action = new List<char>();
if (canMoveUp(i)) {
possibleMoves.Add(swap(i, i-3, state.ToCharArray()));
action.Add('U');
}
if (canMoveDown(i)) {
possibleMoves.Add(swap(i, i+3, state.ToCharArray()));
action.Add('D');
}
if (canMoveLeft(i)) {
possibleMoves.Add(swap(i, i-1, state.ToCharArray()));
action.Add('L');
}
if (canMoveRight(i)) {
possibleMoves.Add(swap(i, i+1, state.ToCharArray()));
action.Add('R');
}
return possibleMoves;
}
// Heuristics
public int misplacedTiles(string state, string goalState) {
int numberOfMisplacedTiles = 0;
for (int i = 0; i < state.Length; i++) {
if (state[i] != goalState[i] && state[i] != '0') numberOfMisplacedTiles++;
}
return -numberOfMisplacedTiles;
}
public float eucledianDistance(string state, string goalState) {
float distance = 0;
for (int i = 0; i < state.Length; i++) {
for (int j = 0; j < goalState.Length; j++) {
int x = (int) state[i] - 48;
int y = (int) goalState[j] - 48;
if (x != 0 && x == y) {
distance += (float) Math.Sqrt((i/3 - j/3) * (i/3 - j/3)
+ (i%3 - j%3) * (i%3 - j%3));
}
}
}
return -distance;
}
public int manhattanDistance(string state, string goalState) {
int distance = 0;
for (int i = 0; i < state.Length; i++) {
for (int j = 0; j < goalState.Length; j++) {
int x = (int) state[i] - 48;
int y = (int) goalState[j] - 48;
if (x != 0 && x == y)
distance += Math.Abs(i/3 - j/3) + Math.Abs(i%3 - j%3);
}
}
return -distance;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateLikeChild : MonoBehaviour {
[SerializeField]
private Transform mParent = null;
private Transform mPlaceHolder = null;
private Transform mStartFix = null;
[SerializeField]
private bool mMoveX = true;
[SerializeField]
private bool mMoveY = true;
[SerializeField]
private bool mMoveZ = true;
private void Setup () {
mPlaceHolder = Instantiate(
new GameObject()
, transform.position
, transform.rotation
, mParent).transform;
mStartFix = Instantiate(
new GameObject()
, transform.position
, transform.rotation).transform;
}
private void Update () {
if (mPlaceHolder == null) { Setup(); }
var rot = mStartFix.eulerAngles;
if (mMoveX) { rot.x = mPlaceHolder.eulerAngles.x; }
if (mMoveY) { rot.y = mPlaceHolder.eulerAngles.y; }
if (mMoveZ) { rot.z = mPlaceHolder.eulerAngles.z; }
transform.eulerAngles = rot;
transform.position = mPlaceHolder.position;
}
}
|
using Reportman;
using Reportman.Utils;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace ConsoleClient
{
class Program
{
static void Main(string[] args)
{
Logic logic = new Logic();
logic.Start();
Console.WriteLine("exit退出");
while(true)
{
string key = Console.ReadLine();
if (key == "exit")
{
break;
}
}
logic.Stop();
}
}
}
|
namespace Infestation
{
using System;
public class Supplement : ISupplement
{
public Supplement(int health, int power, int agression)
{
this.HealthEffect = health;
this.PowerEffect = power;
this.AggressionEffect = agression;
}
public virtual int AggressionEffect { get; }
public virtual int HealthEffect { get; }
public virtual int PowerEffect { get; }
public virtual void ReactTo(ISupplement otherSupplement)
{
}
}
}
|
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.Ubigia.Api.Logical
{
using System.Threading.Tasks;
using EtAlii.Ubigia.Api.Fabric;
public class ContentQueryHandler : IContentQueryHandler
{
private readonly IFabricContext _fabric;
public ContentQueryHandler(IFabricContext fabric)
{
_fabric = fabric;
}
public async Task<Content> Execute(ContentQuery query)
{
var content = await _fabric.Content.Retrieve(query.Identifier).ConfigureAwait(false);
return content;
}
}
}
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Annytab.Doxservr.Client.V1
{
/// <summary>
/// This class includes a page with file metadata items
/// </summary>
public class FileDocuments
{
#region Variables
public IList<FileDocument> items { get; set; }
public string ct { get; set; }
public bool error { get; set; }
#endregion
#region Constructors
/// <summary>
/// Create a new post
/// </summary>
public FileDocuments()
{
// Set values for instance variables
this.items = new List<FileDocument>();
this.ct = "";
this.error = false;
} // End of the constructor
#endregion
#region Get methods
/// <summary>
/// Convert the object to a json string
/// </summary>
public override string ToString()
{
return JsonConvert.SerializeObject(this);
} // End of the ToString method
#endregion
} // End of the class
/// <summary>
/// This class represent a file document post
/// </summary>
public class FileDocument
{
#region Variables
public string id { get; set; }
public string model_type { get; set; }
public DateTime date_of_sending { get; set; }
public string file_encoding { get; set; }
public string filename { get; set; }
public Int64 file_length { get; set; }
public string file_md5 { get; set; }
public string standard_name { get; set; }
public string language_code { get; set; }
public Int32 status { get; set; }
public IList<Party> parties { get; set; }
#endregion
#region Constructors
/// <summary>
/// Create a new post with default properties
/// </summary>
public FileDocument()
{
// Set values for instance variables
this.id = Guid.NewGuid().ToString();
this.model_type = "file_metadata";
this.date_of_sending = new DateTime(2000,1,1);
this.file_encoding = "";
this.filename = "";
this.file_length = -1;
this.file_md5 = "";
this.standard_name = "";
this.language_code = "en";
this.status = 0;
this.parties = new List<Party>();
} // End of the constructor
#endregion
#region Get methods
/// <summary>
/// Convert the object to a json string
/// </summary>
public override string ToString()
{
return JsonConvert.SerializeObject(this);
} // End of the ToString method
#endregion
} // End of the class
} // End of the namespace |
namespace webapi_di.Interfaces
{
public interface ITransientService
{
string Ejecutar();
}
}
|
using System;
namespace UnityEngineEx
{
public class BehaviourFunctionAttribute : Attribute
{
public string name;
public BehaviourFunctionAttribute(string name)
{
this.name = name;
}
}
}
|
using System.Collections;
using System.Linq;
using NUnit.Framework;
namespace ValveKeyValue.Test
{
[TestFixture(typeof(StreamKVTextReader))]
[TestFixture(typeof(StringKVTextReader))]
class LegacyDepotDataSubsetTestCase<TReader>
where TReader : IKVTextReader, new()
{
[Test]
public void IsNotNull()
{
Assert.That(data, Is.Not.Null);
}
[Test]
public void Name()
{
Assert.That(data.Name, Is.EqualTo("depots"));
}
[Test]
public void HasFourItems()
{
Assert.That(data.Children.Count(), Is.EqualTo(4));
}
[TestCaseSource(nameof(ItemsTestCaseData))]
public void HasItems(string key, string expectedValue)
{
var value = data[key];
Assert.That((string)value, Is.EqualTo(expectedValue));
}
[TestCaseSource(nameof(ItemsTestCaseData))]
public void HasItemWithValueCast(string key, string expectedValue)
{
var value = data[key];
Assert.That((string)value, Is.EqualTo(expectedValue));
}
[TestCaseSource(nameof(GarbageItemsTestCaseData))]
public void DoesNotHaveGarbageItems(string key)
{
var value = data[key];
Assert.That(value, Is.Null);
}
[TestCaseSource(nameof(GarbageItemsTestCaseData))]
public void DoesNotHaveGarbageWithValueCast(string key)
{
var value = data[key];
Assert.That((string)value, Is.Null);
}
static IEnumerable ItemsTestCaseData
{
get
{
yield return new TestCaseData("0", "A10D0BCD94CE6105D0E2256FE06B2B22");
yield return new TestCaseData("1", "60EF870FB4B9A2EBB5E511BC8CEC8858");
yield return new TestCaseData("3", "AA4CA0B6300E96774BC3C2B55C3388C9");
yield return new TestCaseData("7", "636DC4B351732EDC6022021B89124CC9");
}
}
static IEnumerable GarbageItemsTestCaseData
{
get
{
yield return "2";
yield return "asdasd";
yield return "123";
yield return "hello there";
}
}
KVObject data;
[OneTimeSetUp]
public void SetUp()
{
data = new TReader().Read("Text.legacydepotdata_subset.vdf");
}
}
}
|
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Threading.Tasks;
using System.Windows.Forms;
using CommonLibrary;
using NAudio.CoreAudioApi;
namespace VolumeCommandManager
{
static class Program
{
static async Task<int> Main(string[] args)
{
var rootCommand = new RootCommand
{
new Option(new[] {"--help", "-h", "-?", "/?"}),
new Option<string>(new[] {"-mode", "-m"}),
};
rootCommand.Handler = CommandHandler.Create<bool, string>((help, mode) =>
{
if (help)
{
MessageBox.Show(
$@"使用法:
{AppBody.AppName} [args] [option]
システムのボリュームを調整します
引数
-m -mode <Mute,Up,Down> どの操作をするのかを指定します
オプション:
/? -? -h --help ヘルプ
例:
{AppBody.AppName} -m Mute ...ミュートにする。すでにミュートなら解除する
{AppBody.AppName} -m Up ...音量を上げる
{AppBody.AppName} -m Down ...音量を下げる
");
return;
}
var enumerator = new MMDeviceEnumerator();
var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
switch (mode)
{
case "Mute":
device.AudioEndpointVolume.Mute = !device.AudioEndpointVolume.Mute;
break;
case "Up":
if (device.AudioEndpointVolume.MasterVolumeLevelScalar + 0.01f <= 1.00f)
{
device.AudioEndpointVolume.MasterVolumeLevelScalar += 0.01f;
}
break;
case "Down":
if (device.AudioEndpointVolume.MasterVolumeLevelScalar - 0.01f >= 0.00f)
{
device.AudioEndpointVolume.MasterVolumeLevelScalar -= 0.01f;
}
break;
default:
MessageBox.Show($"mode optionは以下の3つのみ受け付けます<Mute,Up,Down> 入力:{mode}");
break;
}
});
return await rootCommand.InvokeAsync(args);
}
}
}
|
/*
* NanoXLSX is a small .NET library to generate and read XLSX (Microsoft Excel 2007 or newer) files in an easy and native way
* Copyright Raphael Stoeckli © 2021
* This library is licensed under the MIT License.
* You find a copy of the license in project folder or on: http://opensource.org/licenses/MIT
*/
namespace NanoXLSX.LowLevel
{
/// <summary>
/// Class to manage XML document paths
/// </summary>
public class DocumentPath
{
/// <summary>
/// File name of the document
/// </summary>
public string Filename { get; set; }
/// <summary>
/// Path of the document
/// </summary>
public string Path { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public DocumentPath()
{
}
/// <summary>
/// Constructor with defined file name and path
/// </summary>
/// <param name="filename">File name of the document</param>
/// <param name="path">Path of the document</param>
public DocumentPath(string filename, string path)
{
Filename = filename;
Path = path;
}
/// <summary>
/// Method to return the full path of the document
/// </summary>
/// <returns>Full path</returns>
public string GetFullPath()
{
if (Path == null) { return Filename; }
if (Path == "") { return Filename; }
if (Path[Path.Length - 1] == System.IO.Path.AltDirectorySeparatorChar || Path[Path.Length - 1] == System.IO.Path.DirectorySeparatorChar)
{
return System.IO.Path.AltDirectorySeparatorChar + Path + Filename;
}
return System.IO.Path.AltDirectorySeparatorChar + Path + System.IO.Path.AltDirectorySeparatorChar + Filename;
}
}
}
|
using System;
using System.Drawing;
using System.Globalization;
using SlimDX.Direct3D9;
namespace DemoFramework
{
public class FpsDisplay : IDisposable
{
Sprite fontSprite;
SlimDX.Direct3D9.Font font;
int color = Color.Red.ToArgb();
float fps = -1;
string textString = "";
CultureInfo culture = CultureInfo.InvariantCulture;
bool _isEnabled = true;
public bool IsEnabled
{
get { return _isEnabled; }
set { _isEnabled = value; }
}
string _text = "";
public string Text
{
get { return _text; }
set
{
_text = value;
textString = string.Format("FPS: {0}\n{1}", fps.ToString("0.00", culture), value);
}
}
public FpsDisplay(Device device)
{
fontSprite = new Sprite(device);
font = new SlimDX.Direct3D9.Font(device, 20,
0, FontWeight.Normal, 0, false, CharacterSet.Default,
Precision.Default, FontQuality.ClearTypeNatural, PitchAndFamily.DontCare, "tahoma");
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool isDisposing)
{
if (isDisposing)
{
fontSprite.Dispose();
font.Dispose();
}
}
public void OnRender(float framesPerSecond)
{
if (_isEnabled == false)
return;
fontSprite.Begin(SlimDX.Direct3D9.SpriteFlags.AlphaBlend);
if (fps != framesPerSecond)
{
fps = framesPerSecond;
textString = string.Format("FPS: {0}\n{1}", fps.ToString("0.00", culture), _text);
}
font.DrawString(fontSprite, textString, 0, 0, color);
fontSprite.End();
}
public void OnResetDevice()
{
fontSprite.OnResetDevice();
font.OnResetDevice();
}
public void OnLostDevice()
{
fontSprite.OnLostDevice();
font.OnLostDevice();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
using Random = UnityEngine.Random;
public class CupboardManager : MonoBehaviour
{
[SerializeField] private Transform witch;
[SerializeField] private bool activatingCupboard;
private List<Transform> cupboards;
private int activeCupboard;
private int cupboardTimer;
private Transform icon;
private float speed;
// Start is called before the first frame update
void Start()
{
cupboards = new List<Transform>();
for (int i = 0; i < transform.childCount; i++)
{
cupboards.Add(transform.GetChild(i));
}
activeCupboard = 0;
cupboardTimer = 10;
speed = GameManager.Instance.GETCupboardSpeed();
}
// Update is called once per frame
void Update()
{
if (activatingCupboard)
{
PickCupboard();
activatingCupboard = false;
}
}
void PickCupboard()
{
activeCupboard = Random.Range(0, cupboards.Count);
icon = cupboards[activeCupboard].GetChild(0);
StartCoroutine(CupboardActive());
}
void CheckWitch()
{
if (Math.Abs(witch.position.x - cupboards[activeCupboard].position.x) < 0.2f)
{
var cupboardIngredient = cupboards[activeCupboard].GetChild(0).gameObject;
cupboards[activeCupboard].GetComponent<SpawnIngredient>().OpenCupboard();
}
else
{
GameManager.Instance.LoseLife();
}
icon.GetComponent<SpriteRenderer>().color = Color.white;
activatingCupboard = true;
speed = GameManager.Instance.GETCupboardSpeed();
}
IEnumerator CupboardActive()
{
var color = Color.yellow;
for (int i = 0; i < cupboardTimer; i++)
{
var orange = new Color(1.0f,0.549f,0);
color = Color.Lerp(color, orange, 0.05f*i);
icon.GetComponent<SpriteRenderer>().color = color;
yield return new WaitForSeconds(speed);
}
icon.GetComponent<SpriteRenderer>().color = Color.red;
yield return new WaitForSeconds(speed);
CheckWitch();
}
}
|
using System.Collections.Generic;
namespace MagentoAccess.Models.Services.PutStockItems
{
public class PutStockItemsResponse
{
public List< ResponseStockItem > Items { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Text;
using DynamicData;
namespace ReactivityMonitor.Model
{
internal sealed class ObservableInstance : IObservableInstance
{
public ObservableInstance(
EventInfo created,
IObservable<IInstrumentedCall> call,
IObservable<IObservableInstance> inputs,
IObservable<ISubscription> subscriptions)
{
Created = created;
call.Subscribe(c => Call = c);
Inputs = inputs;
Subscriptions = subscriptions;
}
public EventInfo Created { get; }
public IInstrumentedCall Call { get; private set; }
public long ObservableId => Created.SequenceId;
public IObservable<IObservableInstance> Inputs { get; }
public IObservable<ISubscription> Subscriptions { get; }
}
}
|
namespace Menees.RpnCalc
{
#region Using Directives
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
#endregion
public class StringToVisibilityConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string? text = value as string;
Visibility result = string.IsNullOrEmpty(text) ? Visibility.Collapsed : Visibility.Visible;
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// For RPN calc's use cases, it never makes sense to convert a Visibility back into a string.
// We only need one-way binding support from this converter.
// https://stackoverflow.com/a/265544/1882616
return DependencyProperty.UnsetValue;
}
#endregion
}
}
|
using System;
using System.Xml.Serialization;
namespace Mews.Fiscalization.Greece.Dto.Xsd
{
[Serializable]
[XmlType(Namespace = InvoicesDoc.Namespace)]
public class Invoice
{
[XmlElement(ElementName = "uid")]
public string InvoiceId { get; set; }
[XmlElement(ElementName = "mark")]
public long InvoiceMark { get; set; }
[XmlIgnore]
public bool InvoiceMarkSpecified { get; set; }
[XmlElement(ElementName = "cancelledByMark")]
public long InvoiceCancellationMark { get; set; }
[XmlIgnore]
public bool InvoiceCancellationMarkSpecified { get; set; }
[XmlElement(ElementName = "authenticationCode")]
public string AuthenticationCode { get; set; }
[XmlElement(ElementName = "transmissionFailure")]
public TransmissionFailure TransmissionFailure { get; set; }
[XmlIgnore]
public bool TransmissionFailureSpecified { get; set; }
[XmlElement(ElementName = "issuer")]
public InvoiceParty InvoiceIssuer { get; set; }
[XmlElement(ElementName = "counterpart")]
public InvoiceParty InvoiceCounterpart { get; set; }
[XmlElement(ElementName = "invoiceHeader", IsNullable = false)]
public InvoiceHeader InvoiceHeader { get; set; }
[XmlArray(ElementName = "paymentMethods")]
[XmlArrayItem(ElementName = "paymentMethodDetails")]
public PaymentMethod[] PaymentMethods { get; set; }
[XmlElement(ElementName = "invoiceDetails", IsNullable = false)]
public InvoiceDetail[] InvoiceDetails { get; set; }
[XmlArray(ElementName = "taxesTotals")]
[XmlArrayItem(ElementName = "taxes")]
public Tax[] Taxes { get; set; }
[XmlElement(ElementName = "invoiceSummary", IsNullable = false)]
public InvoiceSummary InvoiceSummary { get; set; }
}
}
|
using System;
using CCLLC.Core;
namespace CCLLC.BTF.Process
{
/// <summary>
/// Defines properties for any record that is being used to capture data input related to
/// a transaction.
/// </summary>
public interface ITransactionDataRecord : IRecordPointer<Guid>
{
IRecordPointer<Guid> TransactionId { get; }
IRecordPointer<Guid> CustomerId { get; }
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
#if !FEATURE_SPAN
using System.Text;
#endif
namespace DocumentFormat.OpenXml
{
/// <summary>
/// A factory of hex strings.
/// </summary>
public static class HexStringFactory
{
/// <summary>
/// Returns a new hex string that was created from <paramref name="bytes"/>.
/// </summary>
/// <param name="bytes">A byte array to use to create a new hex string.</param>
/// <returns>A hex string that corresponds to the value parameter.</returns>
#if FEATURE_SPAN
public
#else
internal
#endif
static string Create(ReadOnlySpan<byte> bytes)
{
if (bytes.Length == 0)
{
return string.Empty;
}
#if FEATURE_SPAN
Span<char> chars = stackalloc char[bytes.Length * 2];
for (var i = 0; i < bytes.Length; i++)
{
byte b = bytes[i];
chars[i * 2] = ToCharUpper(b >> 4);
chars[i * 2 + 1] = ToCharUpper(b);
}
return new string(chars);
#else
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.Append(ToCharUpper(b >> 4));
sb.Append(ToCharUpper(b));
}
return sb.ToString();
#endif
static char ToCharUpper(int value)
{
value &= 0xF;
value += '0';
if (value > '9')
{
value += 'A' - ('9' + 1);
}
return (char)value;
}
}
/// <summary>
/// Returns a new hex string that was created from <paramref name="bytes"/>.
/// </summary>
/// <param name="bytes">A byte array to use to create a new hex string.</param>
/// <returns>A hex string that corresponds to the value parameter.</returns>
public static string Create(params byte[] bytes) => Create(bytes.AsSpan());
}
}
|
namespace LoginServer.Server {
public enum AuthenticationResult {
None,
Success,
Error,
Maintenance,
WrongUserData,
AccountIsNotActivated,
AccountIsBanned,
VersionOutdated,
StringLength
}
} |
namespace MSyics.Traceyi;
/// <summary>
/// ILogger 実装 TraceyiLogger のパラメーターを表します。
/// </summary>
internal sealed class TraceyiLoggerParameters
{
/// <summary>
/// メッセージを取得または設定します。
/// </summary>
public object Message { get; set; }
/// <summary>
/// 拡張プロパティ設定オブジェクトを取得または設定します。
/// </summary>
public Action<dynamic> Extensions { get; set; }
/// <summary>
/// スコープラベルを取得または設定します。
/// </summary>
public object ScopeLabel { get; set; }
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VacationCalendar.Controllers;
using VacationCalendar.Data;
namespace VacationCalendar.Tests.Controllers
{
[TestClass]
public class VacationControllerTest
{
[TestMethod]
public async Task VacationIndex()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
ViewResult result = await controller.Index() as ViewResult;
IEnumerable<VacationDto> model = result.Model as IEnumerable<VacationDto>;
Assert.IsNotNull( model );
}
[TestMethod]
public async Task VacationDetails()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
ViewResult result = await controller.Details( 1 ) as ViewResult;
VacationDto model = result.Model as VacationDto;
Assert.IsTrue( model.EmployeeID == 1 );
}
[TestMethod]
public async Task VacationCreate()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
VacationDto dto = new VacationDto
{
EmployeeFirstName = "First3",
EmployeeLastName = "Last3",
DateFrom = new DateTime( 2018, 4, 23 ),
DateTo = new DateTime( 2018, 4, 24 ),
VacationType = VacationTypeKind.Holiday,
};
ActionResult result = await controller.Create( dto );
Assert.IsTrue( result is RedirectToRouteResult );
}
[TestMethod]
public async Task VacationCreateForExistingEmployee()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
VacationDto dto = new VacationDto
{
EmployeeFirstName = "First1",
EmployeeLastName = "Last1",
DateFrom = new DateTime( 2018, 6, 4 ),
DateTo = new DateTime( 2018, 6, 7 ),
VacationType = VacationTypeKind.VacationLeave,
};
ActionResult result = await controller.Create( dto );
Assert.IsTrue( result is RedirectToRouteResult );
}
[TestMethod]
public async Task VacationEdit()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
VacationDto model = await EditVacation( controller );
model.DateTo = model.DateTo.Value.AddDays( 1 );
ActionResult result = await controller.Edit( model );
Assert.IsTrue( result is RedirectToRouteResult );
}
[TestMethod]
public async Task VacationEditTestDateConstraint()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
VacationDto model = await EditVacation( controller );
DateTime? dateFrom = model.DateFrom;
model.DateFrom = model.DateTo;
model.DateTo = dateFrom;
ViewResult result = await controller.Edit( model ) as ViewResult;
Assert.IsNotNull( result );
Assert.IsFalse( controller.ModelState.IsValid );
}
[TestMethod]
public async Task VacationEditTestDateTrigger()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
VacationDto model1 = await EditVacation( controller );
VacationDto model2 = await EditVacation( controller, 2 );
Assert.IsTrue( model1.EmployeeID == model2.EmployeeID );
model2.DateFrom = model1.DateFrom;
ViewResult result = await controller.Edit( model2 ) as ViewResult;
Assert.IsNotNull( result );
Assert.IsFalse( controller.ModelState.IsValid );
}
[TestMethod]
public async Task VacationEditTestConcurrency()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
VacationDto model = await EditVacation( controller );
model.DateTo = model.DateTo.Value.AddDays( 1 );
ActionResult result1 = await controller.Edit( model );
Assert.IsTrue( result1 is RedirectToRouteResult );
ViewResult result2 = await controller.Edit( model ) as ViewResult;
Assert.IsNotNull( result2 );
Assert.IsFalse( controller.ModelState.IsValid );
}
[TestMethod]
public async Task VacationDelete()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
ViewResult getResult = await controller.Delete( 3 ) as ViewResult;
VacationDto model = getResult.Model as VacationDto;
ActionResult postResult = await controller.Delete( model );
Assert.IsTrue( postResult is RedirectToRouteResult );
}
[TestMethod]
public async Task VacationEditMergeAndDelete()
{
VacationController controller = DependencyResolver.Current.GetService<VacationController>();
VacationDto model = await EditVacation( controller, 4 );
model.EmployeeFirstName = "First1";
model.EmployeeLastName = "Last1";
ActionResult result = await controller.Edit( model );
Assert.IsTrue( result is RedirectToRouteResult );
}
private async Task<VacationDto> EditVacation(VacationController controller, int id = 1)
{
ViewResult result = await controller.Edit( id ) as ViewResult;
return result.Model as VacationDto;
}
}
}
|
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using MapMagic;
namespace MapMagic
{
[CustomEditor(typeof(GeneratorsAsset))]
public class GeneratorsAssetEditor : Editor
{
Layout layout;
public override void OnInspectorGUI ()
{
GeneratorsAsset gens = (GeneratorsAsset)target;
if (layout == null) layout = new Layout();
layout.margin = 0;
layout.field = Layout.GetInspectorRect();
layout.cursor = new Rect();
layout.undoObject = gens;
layout.undoName = "MapMagic Generator change";
layout.Par(24); if (layout.Button("Show Editor", rect:layout.Inset(), icon:"MapMagic_EditorIcon"))
{
MapMagicWindow.Show(gens, null, forceOpen:true, asBiome:false);
}
Layout.SetInspectorRect(layout.field);
}
}
} |
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Ploeh.Hyprlinkr
{
/// <summary>
/// Creates URIs from type-safe expressions.
/// </summary>
public interface IResourceLinker
{
/// <summary>
/// Creates an URI based on a type-safe expression.
/// </summary>
/// <typeparam name="T">
/// The type of resource to link to. This will typically be the type of an
/// <see cref="System.Web.Http.ApiController" />, but doesn't have to be.
/// </typeparam>
/// <param name="method">
/// An expression wich identifies the action method that serves the desired resource.
/// </param>
/// <returns>
/// An <see cref="Uri" /> instance which represents the resource identifed by
/// <paramref name="method" />.
/// </returns>
Uri GetUri<T>(Expression<Action<T>> method);
/// <summary>
/// Creates an URI based on a type-safe expression.
/// </summary>
/// <typeparam name="T">
/// The type of resource to link to. This will typically be the type of
/// an <see cref="System.Web.Http.ApiController" />, but doesn't have
/// to be.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the Action Method of the resource.
/// </typeparam>
/// <param name="method">
/// An expression wich identifies the action method that serves the
/// desired resource.
/// </param>
/// <returns>
/// An <see cref="Uri" /> instance which represents the resource
/// identifed by <paramref name="method" />.
/// </returns>
Uri GetUri<T, TResult>(Expression<Func<T, TResult>> method);
/// <summary>
/// Creates an URI based on a type-safe expression.
/// </summary>
/// <typeparam name="T">
/// The type of resource to link to. This will typically be the type of
/// an <see cref="System.Web.Http.ApiController" />, but doesn't have
/// to be.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the Action Method of the resource.
/// </typeparam>
/// <param name="method">
/// An expression wich identifies the action method that serves the
/// desired resource.
/// </param>
/// <returns>
/// A <see cref="Task{Uri}" /> instance which represents the resource
/// identifed by <paramref name="method" />.
/// </returns>
Task<Uri> GetUriAsync<T, TResult>(Expression<Func<T, Task<TResult>>> method);
}
}
|
@model ICollection<GetABuddy.Web.ViewModels.Event.SingleEventViewModel>
@{
ViewBag.Title = "All";
}
<h3>All Events</h3>
<br />
<form class="form row" method="GET" action="Search">
<div class="col-lg-3">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search for..." name="word" id="search">
<span class="input-group-btn">
<button class="btn btn-info" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</form>
<br />
<div class="row">
@foreach (var ev in Model)
{
@Html.Partial("_SingleEvent", ev)
}
</div>
|
using System.Threading.Tasks;
using Entities;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
namespace Forums.Controllers
{
public class PostsController : Controller
{
private ApplicationDbContext _context;
public PostsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Posts
public async Task<IActionResult> Index()
{
var posts = _context.Posts.Include(p => p.Forum).Include(p => p.ReplyToPost).Include(p => p.User);
return View(await posts.ToListAsync());
}
// GET: Posts/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Post post = await _context.Posts.SingleAsync(m => m.Id == id);
if (post == null)
{
return HttpNotFound();
}
return View(post);
}
// GET: Posts/Create
public IActionResult Create()
{
ViewData["ForumId"] = new SelectList(_context.Forums, "Id", "Name");
ViewData["ReplyToPostId"] = new SelectList(_context.Posts, "ReplyToPostId", "ReplyToPostId");
ViewData["UserId"] = new SelectList(_context.Users, "Id", "UserName");
return View();
}
// POST: Posts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Post post)
{
if (ModelState.IsValid)
{
_context.Posts.Add(post);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["ForumId"] = new SelectList(_context.Forums, "Id", "Forum", post.ForumId);
ViewData["ReplyToPostId"] = new SelectList(_context.Posts, "Id", "ReplyToPost", post.ReplyToPostId);
ViewData["UserId"] = new SelectList(_context.Users, "Id", "User", post.UserId);
return View(post);
}
// GET: Posts/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Post post = await _context.Posts.SingleAsync(m => m.Id == id);
if (post == null)
{
return HttpNotFound();
}
ViewData["ForumId"] = new SelectList(_context.Forums, "Id", "Forum", post.ForumId);
ViewData["ReplyToPostId"] = new SelectList(_context.Posts, "Id", "ReplyToPost", post.ReplyToPostId);
ViewData["UserId"] = new SelectList(_context.Users, "Id", "User", post.UserId);
return View(post);
}
// POST: Posts/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Post post)
{
if (ModelState.IsValid)
{
_context.Update(post);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewData["ForumId"] = new SelectList(_context.Forums, "Id", "Forum", post.ForumId);
ViewData["ReplyToPostId"] = new SelectList(_context.Posts, "Id", "ReplyToPost", post.ReplyToPostId);
ViewData["UserId"] = new SelectList(_context.Users, "Id", "User", post.UserId);
return View(post);
}
// GET: Posts/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Post post = await _context.Posts.SingleAsync(m => m.Id == id);
if (post == null)
{
return HttpNotFound();
}
return View(post);
}
// POST: Posts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
Post post = await _context.Posts.SingleAsync(m => m.Id == id);
_context.Posts.Remove(post);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}
|
using Enmeshed.DevelopmentKit.Identity.ValueObjects;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Enmeshed.BuildingBlocks.Infrastructure.Persistence.Database.ValueConverters
{
public class UsernameValueConverter : ValueConverter<Username, string>
{
public UsernameValueConverter() : this(null)
{
}
public UsernameValueConverter(ConverterMappingHints? mappingHints)
: base(
id => id.StringValue,
value => Username.Parse(value),
mappingHints
)
{
}
}
public class NullableUsernameValueConverter : ValueConverter<Username?, string?>
{
public NullableUsernameValueConverter() : this(null)
{
}
public NullableUsernameValueConverter(ConverterMappingHints? mappingHints)
: base(
id => id == null ? null : id.StringValue,
value => value == null ? null : Username.Parse(value),
mappingHints
)
{
}
}
} |
using System;
using JetBrains.Annotations;
namespace DeusExHackSender.JoinRpg
{
/// <summary>
/// Short info about character
/// </summary>
[PublicAPI]
public class CharacterHeader
{
/// <summary>
/// Id
/// </summary>
public int CharacterId { get; set; }
/// <summary>
/// Last modified (UTC)
/// </summary>
public DateTime UpdatedAt { get; set; }
/// <summary>
/// Active/deleted
/// </summary>
public bool IsActive { get; set; }
/// <summary>
/// URI to full profile
/// </summary>
public string CharacterLink { get; set; }
}
}
|
namespace CCore.Net.JsRt
{
/// <summary>
/// The possible states for a Promise object.
/// </summary>
public enum JsPromiseState
{
Pending = 0x0,
Fulfilled = 0x1,
Rejected = 0x2
}
} |
/*
* Copyright 2015-2018 Mohawk College of Applied Arts and Technology
*
*
* 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.
*
* User: justin
* Date: 2018-6-27
*/
using MohawkCollege.Util.Console.Parameters;
using System;
using System.Collections.Specialized;
using System.ComponentModel;
namespace SdbDebug.Options
{
/// <summary>
/// Represents base parameters for the debugger
/// </summary>
public class DebuggerParameters
{
/// <summary>
/// Gets or sets the source of the debugger
/// </summary>
[Parameter("*")]
[Parameter("source")]
[Description("Identifies the source of the debugger")]
public StringCollection Sources { get; set; }
/// <summary>
/// Gets the working directory of the debugger
/// </summary>
[Description("Sets the working directory of the debugger")]
[Parameter("workDir")]
public String WorkingDirectory { get; set; }
/// <summary>
/// The configuration file to be loaded into the debugger
/// </summary>
[Parameter("config")]
[Description("Identifies a configuration file to be loaded")]
public String ConfigurationFile { get; set; }
/// <summary>
/// Specifies the database file to be loaded into the debugger
/// </summary>
[Parameter("db")]
[Description("Identifies the database file to be loaded")]
public String DatabaseFile { get; set; }
/// <summary>
/// Gets or sets the references
/// </summary>
[Description("Identifies referenced pak files")]
[Parameter("ref")]
public StringCollection References { get; set; }
/// <summary>
/// Show help and exit
/// </summary>
[Parameter("help")]
[Description("Show help and exit")]
public bool Help { get; internal set; }
/// <summary>
/// Starts the bre debugger
/// </summary>
[Description("Debug a business rule")]
[Parameter("bre")]
public bool BusinessRule { get; set; }
/// <summary>
/// Starts the protocol debugger
/// </summary>
[Parameter("xprot")]
[Description("Debug a clinical protocol")]
public bool Protocol { get; set; }
}
}
|
using LionFire.Assets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using LionFire.ExtensionMethods;
using LionFire.Structures;
using LionFire.Results;
using LionFire.Resolves;
namespace LionFire.Persistence
{
public static class AssetToSaveable // TODO: Move this capability off of Asset to more generic interfaces
{
#region Wrappers
public static IPuts ToSaveable(this IAsset asset)
{
return wrappers.GetOrAdd(asset, a => new SaveableAssetWrapper
{
Asset = a,
});
}
public static IPuts TryGetSaveable(this IAsset asset)
{
return wrappers.TryGetValue(asset);
}
private static ConcurrentDictionary<IAsset, IPuts> wrappers = new ConcurrentDictionary<IAsset, IPuts>();
private class SaveableAssetWrapper : IPuts, IReadWrapper<object>
{
public IAsset Asset { get; set; }
object IReadWrapper<object>.Value => Asset;
async Task<ISuccessResult> IPuts.Put()
{
await Asset.SaveAtSubPath(Asset.AssetSubPath);
return SuccessResult.Success;
}
}
#endregion
public static void QueueAutoSaveAsset(this IAsset asset)
{
var wrapper = wrappers.TryGetValue(asset);
if (wrapper != null) wrapper.QueueAutoSave();
}
public static void EnableAutoSave(this IAsset asset, bool enable = true)
{
Action<object> saveAction = o => ((IPuts)o).Put(); // TODO: wrap the Put with auto-retry logic
if (enable)
{
asset.ToSaveable().EnableAutoSave(true, saveAction);
}
else
{
IPuts saveable;
if (wrappers.TryRemove(asset, out saveable))
{
saveable.EnableAutoSave(false, saveAction);
}
}
}
}
}
|
using System;
using Xunit;
using Stack_and_Queue;
using static Stack_and_Queue.Program;
using Stack_and_Queue.Classes;
namespace XUnitTestStack_and_Queue
{
public class UnitTest1
{
[Fact]
public void CanPushStack()
{
Stack testStack = new Stack(new Node(7));
Console.WriteLine("\nNow let's add a few nodes!");
Assert.Equal(14, testStack.Push(new Node(14)).Value);
Assert.Equal(20, testStack.Push(new Node(20)).Value);
Assert.Equal(42, testStack.Push(new Node(42)).Value);
}
[Fact]
public void CanPopStack()
{
Stack testStack = new Stack(new Node(7));
testStack.Push(new Node(14));
testStack.Push(new Node(20));
testStack.Push(new Node(42));
Assert.Equal(42, testStack.Pop().Value);
Assert.Equal(20, testStack.Pop().Value);
Assert.Equal(14, testStack.Pop().Value);
}
[Fact]
public void CanPeekStack()
{
Stack testStack = new Stack(new Node(7));
testStack.Push(new Node(14));
testStack.Push(new Node(20));
testStack.Push(new Node(42));
Assert.Equal(42, testStack.Peek().Value);
testStack.Pop();
Assert.Equal(20, testStack.Peek().Value);
testStack.Pop();
Assert.Equal(14, testStack.Peek().Value);
}
[Fact]
public void CanEnqueue()
{
Queue testQueue = new Queue(new Node(5));
Assert.Equal(10, testQueue.Enqueue(new Node(10)).Value);
Assert.Equal(20, testQueue.Enqueue(new Node(20)).Value);
Assert.Equal(30, testQueue.Enqueue(new Node(30)).Value);
}
[Fact]
public void CanDequeue()
{
Queue testQueue = new Queue(new Node(5));
testQueue.Enqueue(new Node(10));
testQueue.Enqueue(new Node(20));
testQueue.Enqueue(new Node(30));
Assert.Equal(5, testQueue.Dequeue().Value);
Assert.Equal(10, testQueue.Dequeue().Value);
Assert.Equal(20, testQueue.Dequeue().Value);
}
[Fact]
public void CanPeekQueue()
{
Queue testQueue = new Queue(new Node(5));
testQueue.Enqueue(new Node(10));
testQueue.Enqueue(new Node(20));
testQueue.Enqueue(new Node(30));
Assert.Equal(5, testQueue.Peek().Value);
testQueue.Dequeue();
Assert.Equal(10, testQueue.Peek().Value);
testQueue.Dequeue();
Assert.Equal(20, testQueue.Peek().Value);
}
}
}
|
using System;
using System.Collections.Generic;
namespace VirusTotalNET.Objects
{
public class UrlReport
{
/// <summary>
/// Filescan Id of the resource.
/// </summary>
public string FilescanId { get; set; }
/// <summary>
/// A permanent link that points to this specific scan.
/// </summary>
public string Permalink { get; set; }
/// <summary>
/// How many engines flagged this resource.
/// </summary>
public int Positives { get; set; }
/// <summary>
/// Contains the id of the resource. Can be a SHA256, MD5 or other hash type.
/// </summary>
public string Resource { get; set; }
/// <summary>
/// The response code. Use this to determine the status of the report.
/// </summary>
public ReportResponseCode ResponseCode { get; set; }
/// <summary>
/// The date the resource was last scanned.
/// </summary>
public DateTime ScanDate { get; set; }
/// <summary>
/// Contains the scan id for this result.
/// </summary>
public string ScanId { get; set; }
/// <summary>
/// The scan results from each engine.
/// </summary>
public List<ScanEngine> Scans { get; set; }
/// <summary>
/// How many engines scanned this resource.
/// </summary>
public int Total { get; set; }
/// <summary>
/// Contains the message that corrosponds to the reponse code.
/// </summary>
public string URL { get; set; }
/// <summary>
/// Contains the message that corrosponds to the reponse code.
/// </summary>
public string VerboseMsg { get; set; }
}
} |
namespace EasyAbp.Abp.TencentCloud.COS.Infrastructure
{
public interface ITencentCOSRequester
{
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using PholioVisualisation.DataSorting;
using PholioVisualisation.PholioObjects;
namespace PholioVisualisation.Export
{
public class ExportPopulationHelper
{
public static List<CoreDataSet> FilterQuinaryPopulations(IList<CoreDataSet> data)
{
var newList = new List<CoreDataSet>();
var sexIds = new[] { SexIds.Male, SexIds.Female };
foreach (var sexId in sexIds)
{
var sexData = FilterBySex(data, sexId);
if (sexData != null)
{
newList.AddRange(sexData);
}
}
return newList;
}
private static IEnumerable<CoreDataSet> FilterBySex(IList<CoreDataSet> data, int sexId)
{
var filteredData = data.Where(x => x.SexId != sexId);
filteredData = new QuinaryPopulationSorter(filteredData.ToList()).SortedData;
return filteredData;
}
}
} |
using System;
using System.Linq;
using System.Threading.Tasks;
using R5T.D0101.I001;
using R5T.D0105;
namespace R5T.S0023
{
public class O900_OpenAllProjectRepositoryFiles : T0020.IActionOperation
{
private INotepadPlusPlusOperator NotepadPlusPlusOperator { get; }
private IProjectRepositoryFilePathsProvider ProjectRepositoryFilePathsProvider { get; }
public O900_OpenAllProjectRepositoryFiles(
INotepadPlusPlusOperator notepadPlusPlusOperator,
IProjectRepositoryFilePathsProvider projectRepositoryFilePathsProvider)
{
this.NotepadPlusPlusOperator = notepadPlusPlusOperator;
this.ProjectRepositoryFilePathsProvider = projectRepositoryFilePathsProvider;
}
public async Task Run()
{
var (Task1Result, Task2Result, Task3Result, Task4Result) = await TaskHelper.WhenAll(
this.ProjectRepositoryFilePathsProvider.GetDuplicateProjectNamesTextFilePath(),
this.ProjectRepositoryFilePathsProvider.GetIgnoredProjectNamesTextFilePath(),
this.ProjectRepositoryFilePathsProvider.GetProjectNameSelectionsTextFilePath(),
this.ProjectRepositoryFilePathsProvider.GetProjectsListingJsonFilePath());
var openingAllFilePaths = new[]
{
Task1Result,
Task2Result,
Task3Result,
Task4Result
}
.Select(filePath => this.NotepadPlusPlusOperator.OpenFilePath(filePath))
;
await Task.WhenAll(openingAllFilePaths);
}
}
}
|
using System.IO;
using UnityEditor;
using UnityEngine;
namespace Framework.Utils
{
#if UNITY_EDITOR
public class ScreenShot : MonoBehaviour
{
private const int MaxScreenshotAmount = 15;
private const string ScreenshotsDirectory = "StoreInfo/Screenshots";
[MenuItem("Tools/Take Screenshot")]
public static void TakeScreenshot()
{
var width = Screen.width;
var height = Screen.height;
for (var idx = 1; idx <= MaxScreenshotAmount; idx++)
{
var filename = $"Screenshot_{width}x{height}_{idx}.png";
var path = Path.Combine(ScreenshotsDirectory, filename);
if (File.Exists(path)) continue;
ScreenCapture.CaptureScreenshot(path);
break;
}
}
}
#endif
} |
@model DeaneBarker.DynamicTemplates.Models.Elements.ImageElementBlockViewModel
@{
// Figure out the URL
var url = Model.ImageUrl;
if (Model.CurrentBlock.IsBoilerplate)
{
if (!string.IsNullOrWhiteSpace(Model.CurrentBlock.BoilerplateOutput))
{
url = Model.CurrentBlock.BoilerplateOutput;
}
var size = "728x90";
if (!string.IsNullOrWhiteSpace(Model.CurrentBlock.Align))
{
size = "300x300";
}
url = string.Concat("https://via.placeholder.com/", size, ".png?text=Image+Placeholder");
}
// Figure out the styles
var rules = new Dictionary<string, string>();
if (!string.IsNullOrWhiteSpace(Model.CurrentBlock.Align))
{
rules["float"] = Model.CurrentBlock.Align.ToLower();
rules["max-width"] = "50%";
}
else
{
rules["display"] = "block";
rules["margin"] = "auto";
}
if (Model.CurrentBlock.Align == "right")
{
rules["margin"] = "0 0 1em 1em";
}
if (Model.CurrentBlock.Align == "left")
{
rules["margin"] = "0 1em 1em 0";
}
var styles = string.Join(string.Empty, rules.Select(r => string.Concat(r.Key, ": ", r.Value, "; ")));
}
@if (string.IsNullOrWhiteSpace(url))
{
return;
}
<img src="@url" class="@Model.CurrentBlock.ClassName" style="@styles @Model.CurrentBlock.StyleOutput"/>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.