content stringlengths 23 1.05M |
|---|
using OpenKh.Imaging;
using OpenKh.Kh2.SystemData;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace OpenKh.Kh2.Contextes
{
public class FontContext
{
private IImageRead imageSystem;
private IImageRead imageSystem2;
private IImageRead imageEvent;
private IImageRead imageEvent2;
private IImageRead imageIcon;
private byte[] spacingSystem;
private byte[] spacingEvent;
private byte[] spacingIcon;
public IImageRead ImageSystem { get => imageSystem; set => imageSystem = value; }
public IImageRead ImageSystem2 { get => imageSystem2; set => imageSystem2 = value; }
public IImageRead ImageEvent { get => imageEvent; set => imageEvent = value; }
public IImageRead ImageEvent2 { get => imageEvent2; set => imageEvent2 = value; }
public IImageRead ImageIcon { get => imageIcon; set => imageIcon = value; }
public byte[] SpacingSystem { get => spacingSystem; set => spacingSystem = value; }
public byte[] SpacingEvent { get => spacingEvent; set => spacingEvent = value; }
public byte[] SpacingIcon { get => spacingIcon; set => spacingIcon = value; }
public Dictionary<int, Ftst.Entry> palette;
public void Read(IEnumerable<Bar.Entry> entries)
{
foreach (var entry in entries)
{
switch (entry.Name)
{
case "sys":
ReadFont(entry, ref imageSystem, ref imageSystem2, ref spacingSystem);
break;
case "evt":
ReadFont(entry, ref imageEvent, ref imageEvent2, ref spacingEvent);
break;
case "icon":
ReadIcon(entry, ref imageIcon, ref spacingIcon, 256, 160);
break;
case "ftst":
if (entry.Type == Bar.EntryType.List)
palette = Ftst.Read(entry.Stream).ToDictionary(x => x.Id, x => x);
break;
}
}
}
private void ReadFont(Bar.Entry entry, ref IImageRead image1, ref IImageRead image2, ref byte[] spacing)
{
switch (entry.Type)
{
case Bar.EntryType.List:
spacing = ReadSpacing(entry);
break;
case Bar.EntryType.RawBitmap:
entry.Stream.Position = 0;
image1 = ReadImagePalette1(entry);
entry.Stream.Position = 0;
image2 = ReadImagePalette2(entry);
break;
}
}
private void ReadIcon(Bar.Entry entry, ref IImageRead image, ref byte[] spacing, int width, int height)
{
switch (entry.Type)
{
case Bar.EntryType.List:
spacing = ReadSpacing(entry);
break;
case Bar.EntryType.RawBitmap:
entry.Stream.Position = 0;
image = ReadImage8bit(entry, width, height);
break;
}
}
private static byte[] ReadSpacing(Bar.Entry entry)
{
return new BinaryReader(entry.Stream).ReadBytes((int)entry.Stream.Length);
}
private static IImageRead ReadImage8bit(Bar.Entry entry, int width, int height)
{
return RawBitmap.Read8bit(entry.Stream, width, height);
}
private static IImageRead ReadImagePalette1(Bar.Entry entry)
{
DeductImageSize((int)entry.Stream.Length, out var width, out var height);
return RawBitmap.Read4bitPalette1(entry.Stream, width, height);
}
private static IImageRead ReadImagePalette2(Bar.Entry entry)
{
DeductImageSize((int)entry.Stream.Length, out var width, out var height);
return RawBitmap.Read4bitPalette2(entry.Stream, width, height);
}
private static bool DeductImageSize(int rawLength, out int width, out int height)
{
if (rawLength < 128 * 1024)
{
width = 512;
height = 256;
}
else if (rawLength < 256 * 1024)
{
width = 512;
height = 512;
}
else if (rawLength < 512 * 1024)
{
width = 512;
height = 1024;
}
else
{
width = 0;
height = 0;
return false;
}
return true;
}
}
}
|
using System.Linq;
using DeusVultClicker.Client.Shared.Store.Actions;
using Fluxor;
namespace DeusVultClicker.Client.Buildings.Store
{
public static class BuildingReducers
{
[ReducerMethod]
public static BuildingState ReduceBuyBuildingAction(BuildingState state, BuyBuildingAction action)
{
var building = BuildingStorage.Buildings[action.Id];
return state with
{
OwnedBuildings = state.OwnedBuildings.Concat(new[] { building }),
Reach = state.Reach + building.Reach,
};
}
[ReducerMethod]
public static BuildingState ReduceDemolishBuildingAction(BuildingState state, DemolishBuildingAction action)
{
var building = BuildingStorage.Buildings[action.Id];
return state with
{
OwnedBuildings = state.OwnedBuildings.Where(b => b.Id != building.Id),
Reach = state.Reach - building.Reach,
};
}
[ReducerMethod]
public static BuildingState ReduceSetBuildingStateAction(BuildingState state, SetBuildingStateAction action)
{
return action.BuildingState;
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Amazon.Pay.API.WebStore.Types
{
/// <summary>
/// Specify whether the buyer will return to your website to review their order before completing checkout.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum CheckoutMode
{
ProcessOrder
}
}
|
#region Packages
using System.Linq;
using Mfknudsen.Battle.Systems;
using Mfknudsen.Battle.Systems.Interfaces;
using Mfknudsen.Battle.Systems.Spots;
using Mfknudsen.Pokémon;
using Mfknudsen.Pokémon.Conditions;
using UnityEngine;
#endregion
namespace Mfknudsen.Weathers.Irritants
{
public class PheromonesWeather : IrritantWeather, IStatModifier, IOnPokemonEnter
{
#region Values
[Header("Stat Modifier"), SerializeField]
private TypeName[] affectedTypes;
[SerializeField] private Stat[] affectedStats;
[Header("On Pokemon Enter"), SerializeField]
private VolatileCondition confusion;
#endregion
public override void Setup()
{
base.Setup();
foreach (Pokemon pokemon in BattleManager.instance.GetSpotOversight().GetSpots()
.Select(spot => spot.GetActivePokemon()).Where(pokemon =>
pokemon.GetTypes().Any(type => affectedTypes.Contains(type.GetTypeName()))))
{
pokemon.GetConditionOversight().ApplyVolatileCondition(confusion);
}
}
#region Interface Overrides
//IStatModifier
public float Modify(Pokemon pokemon, Stat stat)
{
return affectedStats.Contains(stat) &&
pokemon.GetTypes().Any(type => affectedTypes.Contains(type.GetTypeName()))
? 1.25f
: 1;
}
//IOnPokemonEnter
public void Trigger(Pokemon pokemon)
{
}
#endregion
}
} |
using System;
using NUnit.Framework;
namespace ZenDeskSharp.Mobile.Tests
{
[TestFixture]
public class describe_zendeskclient_ticket
{
ZenDeskConfig _config;
[SetUp]
public void setup()
{
_config = new ZenDeskConfig() {
Url = "http://cutepuppy.zendesk.com",
Email = "anuj.bhatia@xamarin.com",
Password = "Xam_z3ndesk",
AdminEmail = "anuj.bhatia@xamarin.com",
};
}
[Test]
public void should_get_tickets()
{
var client = new ZenDeskClient(_config);
var result = client.GetTicket("1");
Assert.NotNull(result);
}
}
}
|
using System;
class EnglishNameOfLastDigit
{
static void Main()
{
long number = long.Parse(Console.ReadLine());
GetNumbersName(number);
}
public static void GetNumbersName(long number)
{
var LastDigit = Math.Abs(number % 10);
switch (LastDigit)
{
case 0: Console.WriteLine("zero"); break;
case 1: Console.WriteLine("one"); break;
case 2: Console.WriteLine("two"); break;
case 3: Console.WriteLine("three"); break;
case 4: Console.WriteLine("four"); break;
case 5: Console.WriteLine("five"); break;
case 6: Console.WriteLine("six"); break;
case 7: Console.WriteLine("seven"); break;
case 8: Console.WriteLine("eight"); break;
case 9: Console.WriteLine("nine"); break;
default: Console.WriteLine(); break;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Invi.Extensions.Configuration.Validation
{
public class ValidationStartupFilter
{
public ValidationStartupFilter(IEnumerable<IValidation> validationList)
{
validationList.ToList().ForEach(v => v.Validate());
}
}
} |
namespace XpressTest;
public interface IVoidAsserter<TSut>
:
IAsserter<ISutArrangement<TSut>>,
IThenWhenItAsserter<TSut>
{
IVoidMockVerifier<TSut, TMock> ThenThe<TMock>()
where TMock : class;
IVoidMockVerifier<TSut, TMock> ThenThe<TMock>(
string name
)
where TMock : class;
IVoidMockVerifier<TSut, TMock> Then<TMock>(
Moq.Mock<TMock> mock
)
where TMock : class;
} |
namespace VTEX.ValueObjects
{
using System.Collections.Generic;
using Newtonsoft.Json;
/// <summary>
/// The cart tag class.
/// </summary>
public class Tag
{
/// <summary>
/// Gets or sets the display value.
/// </summary>
/// <value>
/// The display value.
/// </value>
[JsonProperty("DisplayValue")]
public string DisplayValue { get; set; }
/// <summary>
/// Gets or sets the scores.
/// </summary>
/// <value>
/// The scores.
/// </value>
[JsonProperty("Scores")]
public Dictionary<string, Score[]> Scores { get; set; }
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Vi2B {
public class Config {
public static string ConnectionString;
public static string DataRoot;
public static void Load() {
StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/config.json"));
dynamic config = JsonConvert.DeserializeObject(reader.ReadToEnd());
ConnectionString = config.ConnectionString;
DataRoot = config.DataRoot;
if (DataRoot == "")
DataRoot = HttpContext.Current.Server.MapPath("~/data");
Console.WriteLine("DataRoot: " + DataRoot);
}
}
} |
using Android.Content;
using Android.Webkit;
using System;
namespace Cnblogs.Droid.UI.Widgets
{
public class WebViewJSInterface : Java.Lang.Object
{
Context context { get; set; }
public WebViewJSInterface(Context context)
{
this.context = context;
}
[Java.Interop.Export]
[JavascriptInterface]
public void OpenImage(string srcs, int index)
{
CallFromPageReceived?.Invoke(this, new CallFromPageReceivedEventArgs
{
Result = srcs,
Index = index
});
}
[Java.Interop.Export]
[JavascriptInterface]
public void OpenHref(string href)
{
CallFromPageReceived?.Invoke(this, new CallFromPageReceivedEventArgs
{
Result = href,
Index = 0
});
}
public event EventHandler<CallFromPageReceivedEventArgs> CallFromPageReceived;
public class CallFromPageReceivedEventArgs : EventArgs
{
public string Result { get; set; }
public int Index { get; set; }
}
}
} |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace WellBot.Domain.Chats.Entities
{
/// <summary>
/// Contains information about a chat.
/// </summary>
public class Chat
{
/// <summary>
/// Chat id.
/// </summary>
[Key]
public int Id { get; set; }
/// <summary>
/// Chat id in Telegram.
/// </summary>
[Required]
public long TelegramId { get; set; }
/// <summary>
/// List of registrations for daily Pidor game in this chat.
/// </summary>
public IList<PidorRegistration> PidorRegistrations { get; set; } = new List<PidorRegistration>();
/// <summary>
/// List of chat pidor winners.
/// </summary>
public IList<ChatPidor> Pidors { get; set; } = new List<ChatPidor>();
/// <summary>
/// Associated chat data.
/// </summary>
public IList<ChatData> Data { get; set; } = new List<ChatData>();
}
}
|
namespace bytePassion.Lib.Communication.MessageBus
{
/// <summary>
/// NOT IN USE ... JUST AN IDEA
/// </summary>
public interface IRequestHandler<in TMessage, out TResult>
{
TResult Process(TMessage message);
}
}
|
using Amazon.DynamoDBv2;
using Amazon.S3;
using JKang.EventSourcing.Persistence;
using JKang.EventSourcing.Persistence.CosmosDB;
using JKang.EventSourcing.Snapshotting.Persistence;
using JKang.EventSourcing.TestingFixtures;
using JKang.EventSourcing.TestingWebApp.Database;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.Cosmos.Fluent;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace JKang.EventSourcing.TestingWebApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services
.AddScoped<IGiftCardRepository, GiftCardRepository>();
// change the following value to switch persistence mode
PersistenceMode persistenceMode = PersistenceMode.S3;
switch (persistenceMode)
{
case PersistenceMode.FileSystem:
ConfigureServicesForFileSystem(services);
break;
case PersistenceMode.CosmosDB:
ConfigureServicesForCosmosDB(services);
break;
case PersistenceMode.DynamoDB:
ConfigureServicesForDynamoDB(services);
break;
case PersistenceMode.EfCore:
ConfigureServicesForEfCore(services);
break;
case PersistenceMode.S3:
ConfigureServicesForS3(services);
break;
default:
break;
}
}
public void ConfigureServicesForFileSystem(IServiceCollection services)
{
services.AddEventSourcing(builder =>
builder
.UseTextFileEventStore<GiftCard, Guid>(x => x.Folder = "C:/Temp/GiftcardEvents")
.UseTextFileSnapshotStore<GiftCard, Guid>(x => x.Folder = "C:/Temp/GiftcardEvents"));
}
public void ConfigureServicesForCosmosDB(IServiceCollection services)
{
services
.AddSingleton(_ =>
new CosmosClientBuilder(Configuration.GetConnectionString("CosmosDB"))
.WithConnectionModeDirect()
.WithCustomSerializer(new EventSourcingCosmosSerializer())
.Build())
.AddEventSourcing(builder =>
builder
.UseCosmosDBEventStore<GiftCard, Guid>(x =>
{
x.DatabaseId = "EventSourcingTestingWebApp";
x.ContainerId = "GiftcardEvents";
})
.UseCosmosDBSnapshotStore<GiftCard, Guid>(x =>
{
x.DatabaseId = "EventSourcingTestingWebApp";
x.ContainerId = "GiftcardSnapshots";
}));
}
public void ConfigureServicesForDynamoDB(IServiceCollection services)
{
#if DEBUG
services.AddSingleton<IAmazonDynamoDB>(sp => new AmazonDynamoDBClient(new AmazonDynamoDBConfig
{
ServiceURL = "http://localhost:8800"
}));
#else
services.AddAWSService<IAmazonDynamoDB>();
#endif
services.AddEventSourcing(builder =>
{
builder
.UseDynamoDBEventStore<GiftCard, Guid>(x => x.TableName = "GiftcardEvents")
.UseDynamoDBSnapshotStore<GiftCard, Guid>(x => x.TableName = "GiftcardSnapshots")
;
});
}
public void ConfigureServicesForEfCore(IServiceCollection services)
{
services
.AddDbContext<SampleDbContext>(x => x.UseInMemoryDatabase("eventstore"));
services
.AddEventSourcing(builder =>
{
builder
.UseEfCoreEventStore<SampleDbContext, GiftCard, Guid>()
.UseEfCoreSnapshotStore<SampleDbContext, GiftCard, Guid>()
;
});
}
public void ConfigureServicesForS3(IServiceCollection services)
{
services
.AddDefaultAWSOptions(Configuration.GetAWSOptions())
.AddAWSService<IAmazonS3>();
services
.AddDbContext<SampleDbContext>(x => x.UseInMemoryDatabase("eventstore"));
services
.AddEventSourcing(builder =>
{
builder
.UseEfCoreEventStore<SampleDbContext, GiftCard, Guid>()
.UseS3SnapshotStore<GiftCard, Guid>(x =>
{
x.BucketName = "jkang-eventsourcing-dev";
x.Prefix = "giftcards";
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IEventStoreInitializer<GiftCard, Guid> eventStoreInitializer,
ISnapshotStoreInitializer<GiftCard, Guid> snapshotStoreInitializer)
{
eventStoreInitializer.EnsureCreatedAsync().Wait();
snapshotStoreInitializer.EnsureCreatedAsync().Wait();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
|
// written by: Thomas Stewart
// tested by: Michael Quinn
// debugged by: Diane Gregory, Shane Barry
// balanced by: Diane Gregory, Metin Erman, Thomas Stewart
using UnityEngine;
using System.Collections;
/// <summary>
/// LazerShot is a NonInteractiveObject that moves forward with its initial speed, unless it is
/// modifed by something else, until it collides with an InteractiveObject or its life timer runs
/// out, which will cause it to be destroyed. When it collides with an enemy DestructableObject
/// it will damage it.
/// </summary>
public class LazerShot : NonInteractiveObject
{
public float damage = 10;
private int timeAlive = 0;
public float timeToLiveSecs = 2;
protected override void StartNonInteractiveObject()
{
}
public void ResetTimeAlive()
{
timeAlive = 0;
}
/// <summary>
/// If the timeToLiveSecs is set to a positive number and this has been alive for
/// longer than that many seconds, destroy this
/// </summary>
protected override void UpdateNonInteractiveObject()
{
if (timeToLiveSecs > 0)
{
timeAlive++;
if (timeAlive > timeToLiveSecs * level.updatesPerSec)
{
DestroyThis();
}
}
}
protected override void DestroyNonInteractiveObject()
{
}
protected override void PlayerCollision(Player other)
{
if (team != other.team)
{
other.DamageThis(damage);
}
DestroyThis();
}
protected override void DestructableObjectCollision(DestructableObject other)
{
if (team != other.team)
{
other.DamageThis(damage);
}
DestroyThis();
}
protected override void IndestructableObjectCollision(IndestructableObject other)
{
DestroyThis();
}
}
|
using System;
using Timestamp;
using Xunit;
namespace XUnitTestTimestamp
{
public class UnitTestToTimeSpan
{
[Fact]
public void TimeShort()
{
// Arrange
var factory = new TimestampFactory();
// Act
var zero = factory.ToTimeSpan(0);
// Assert
Assert.Equal(TimeSpan.Zero, zero);
}
[Fact]
public void TimeLong()
{
// Arrange
var factory = new LongTimestampFactory();
// Act
var zero = factory.ToTimeSpan(0);
// Assert
Assert.Equal(TimeSpan.Zero, zero);
}
[Fact]
public void TimeUnix()
{
// Arrange
var factory = new UnixTimestampFactory();
// Act
var zero = factory.ToTimeSpan(0);
// Assert
Assert.Equal(TimeSpan.Zero, zero);
}
[Fact]
public void TimeUnixLong()
{
// Arrange
var factory = new UnixLongTimestampFactory();
// Act
var zero = factory.ToTimeSpan(0);
// Assert
Assert.Equal(TimeSpan.Zero, zero);
}
}
}
|
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine.UI;
public abstract class AccionDeOpciones : AccionGenerica
{
protected bool pasarAlSiguienteDialogo;
protected List<string> opciones;
protected virtual void ColocarOpcionesEnPantlla(List<string> opciones)
{
if(opciones.Count <= 0)
{
throw new Exception("No hay opciones que mostrar");
}
//buscamos lo que necesitamos
controlador.texto.gameObject.SetActive(false);
controlador.panelOpciones.SetActive(true);
if (opciones.Count > 0)
{
TextMeshProUGUI opcion11 = controlador.opcion1.GetComponent<TextMeshProUGUI>();
opcion11.text = opciones[0];
Button opcion111 = controlador.opcion1.GetComponent<Button>();
opcion111.onClick.AddListener(delegate { Opcion1(); });
}
if(opciones.Count > 1)
{
TextMeshProUGUI opcion22 = controlador.opcion2.GetComponent<TextMeshProUGUI>();
opcion22.text = opciones[1];
Button opcion222 = controlador.opcion2.GetComponent<Button>();
opcion222.onClick.AddListener(delegate { Opcion2(); });
}
if(opciones.Count > 2)
{
TextMeshProUGUI opcion33 = controlador.opcion3.GetComponent<TextMeshProUGUI>();
opcion33.text = opciones[2];
Button opcion333 = controlador.opcion3.GetComponent<Button>();
opcion333.onClick.AddListener(delegate { Opcion3(); });
}
//desabilitamos el boton siguiente
controlador.botonSiguienteGO.gameObject.SetActive(false);
}
public abstract void Opcion1();
public abstract void Opcion2();
public abstract void Opcion3();
} |
using System;
namespace SharpGfx.Primitives
{
public interface Matrix3 : Primitive
{
public float this[int row, int col] { get; }
public Vector3 Mul(Vector3 r);
public static Vector3 operator *(Matrix3 l, Vector3 r)
{
if (!IsVisible(l, r)) throw new ArgumentException("cross space operation");
return l.Mul(r);
}
}
}
|
using System;
using Moq;
using NUnit.Framework;
using PortkablePass.Cryptography;
using PortkablePass.Interfaces.Cryptography;
using PortkablePass.Interfaces.Encoding;
using PortkablePass.Tests.Mocks;
namespace PortkablePass.Tests.TestFixtures
{
[TestFixture]
public class HmacSha256GeneratorTest
{
private IHmacSha256Generator generator;
[SetUp]
public void SetUp()
{
Mock<IUtf8Converter> mockUtf8Converter = Uft8ConverterMockCreator.CreateUtf8Mock();
generator = new HmacSha256Generator(mockUtf8Converter.Object);
}
[TestCase("aaa", new byte[] {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0xde, 0xad, 0xbe, 0xef},
ExpectedResult = new byte[]
{
0x8c, 0x38, 0xa1, 0xa9, 0xe8, 0xe8, 0x2a, 0xe0, 0xe4, 0xdf, 0xcf, 0xb8, 0x3a, 0xfe, 0x0f, 0x7f, 0xa4,
0xdc, 0x53, 0xca, 0x19, 0xed, 0xca, 0x7d, 0x70, 0xcb, 0x25, 0x80, 0x16, 0xee, 0xda, 0x69
})]
[TestCase("ść", new byte[] {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0xde, 0xad, 0xbe, 0xef},
ExpectedResult = new byte[]
{
0x9e, 0x97, 0xa1, 0xc1, 0xd9, 0xa0, 0x58, 0x86, 0x03, 0x67, 0xd0, 0x34, 0x08, 0x13, 0x6c, 0x8a, 0xcd,
0xc7, 0x44, 0xfa, 0x3a, 0x1e, 0x8e, 0x5c, 0x1b, 0x68, 0xfa, 0x6b, 0x3c, 0xd1, 0x42, 0x08
})]
[TestCase("", new byte[] {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0xde, 0xad, 0xbe, 0xef},
ExpectedResult = new byte[]
{
0x03, 0xfc, 0x58, 0x6e, 0xb5, 0xd8, 0x44, 0x3a, 0xc2, 0x86, 0x9d, 0x97, 0xc5, 0x8d, 0xd4, 0x78, 0x42,
0x59, 0x24, 0xd8, 0x05, 0x60, 0xfd, 0x0c, 0x13, 0x2d, 0x0f, 0x5e, 0xe9, 0xf3, 0xc3, 0x11
})]
public byte[] TestComputeStringHash(string input, byte[] key)
{
return generator.GenerateHmacHash(input, key);
}
[TestCase(new byte[] {0x61, 0x61, 0x61},
new byte[] {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0xde, 0xad, 0xbe, 0xef},
ExpectedResult = new byte[]
{
0x8c, 0x38, 0xa1, 0xa9, 0xe8, 0xe8, 0x2a, 0xe0, 0xe4, 0xdf, 0xcf, 0xb8, 0x3a, 0xfe, 0x0f, 0x7f, 0xa4,
0xdc, 0x53, 0xca, 0x19, 0xed, 0xca, 0x7d, 0x70, 0xcb, 0x25, 0x80, 0x16, 0xee, 0xda, 0x69
})]
[TestCase(new byte[] {0xc5, 0x9b, 0xc4, 0x87}, new byte[]
{0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0xde, 0xad, 0xbe, 0xef},
ExpectedResult = new byte[]
{
0x9e, 0x97, 0xa1, 0xc1, 0xd9, 0xa0, 0x58, 0x86, 0x03, 0x67, 0xd0, 0x34, 0x08, 0x13, 0x6c, 0x8a, 0xcd,
0xc7, 0x44, 0xfa, 0x3a, 0x1e, 0x8e, 0x5c, 0x1b, 0x68, 0xfa, 0x6b, 0x3c, 0xd1, 0x42, 0x08
})]
[TestCase(new byte[] { }, new byte[] {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0xde, 0xad, 0xbe, 0xef},
ExpectedResult = new byte[]
{
0x03, 0xfc, 0x58, 0x6e, 0xb5, 0xd8, 0x44, 0x3a, 0xc2, 0x86, 0x9d, 0x97, 0xc5, 0x8d, 0xd4, 0x78, 0x42,
0x59, 0x24, 0xd8, 0x05, 0x60, 0xfd, 0x0c, 0x13, 0x2d, 0x0f, 0x5e, 0xe9, 0xf3, 0xc3, 0x11
})]
public byte[] TestComputeStringHash(byte[] input, byte[] key)
{
return generator.GenerateHmacHash(input, key);
}
}
} |
using System;
namespace WindowsDesktop.Interop
{
[ComInterfaceWrapper]
internal class ApplicationViewCollection : ComInterfaceWrapperBase
{
public ApplicationViewCollection(ComInterfaceAssembly assembly)
: base(assembly) { }
public ApplicationView GetViewForHwnd(IntPtr hWnd)
{
var param = Args(hWnd, null);
this.Invoke(param);
return new ApplicationView(this.ComInterfaceAssembly, param[1]);
}
}
}
|
using UnityEngine;
public class FadeWalls : MonoBehaviour{
private UnityEngine.Camera mainCamera;
private GameObject player;
private GameObject[] walls;
private Color _color;
[Range(0.0f, 1.0f)]
public float alphaValueSlider;
RaycastHit hitInfo;
private void Start(){
mainCamera = UnityEngine.Camera.main;
player = this.gameObject;
walls = GameObject.FindGameObjectsWithTag("Wall");
}
private void Update(){
var dir = player.transform.position - mainCamera.transform.position;
if (Physics.Raycast(mainCamera.transform.position, dir, out hitInfo, 1000)){
foreach (GameObject wall in walls){
if (hitInfo.collider.gameObject == wall){
wall.GetComponent<Renderer>().material.color = new Color(1,1,1,alphaValueSlider);
}
else if (hitInfo.collider.gameObject != wall){
wall.GetComponent<Renderer>().material.color = new Color(1,1,1,1);
}
}
}
}
}
|
// RegistrationPermissionWriteOnce
using Disney.Mix.SDK;
public class RegistrationPermissionWriteOnce : IRegistrationPermissionWriteOnce, IRegistrationPermission
{
}
|
using HashidsNet;
using System;
using System.Security.Cryptography;
using System.Text;
namespace YattWpf.Models
{
class UserModel
{
public string ID
{
get {
string userName = GetSHA256HashAsString(Environment.UserName);
byte[] byteArray = Encoding.Default.GetBytes(userName);
var integerRepresentingUsername = BitConverter.ToInt32(byteArray,0);
var hashids = new Hashids(GetSHA256HashAsString(Environment.MachineName));
return hashids.Encode(integerRepresentingUsername).ToUpper();
}
}
private String GetSHA256HashAsString(String value)
{
StringBuilder Sb = new StringBuilder();
using (SHA256 hash = SHA256.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString().Replace(" ", "").Replace("-", "").ToUpper();
}
}
}
|
<h4 class="card-title"><i class="fa fa-cloud-download"></i>@T["Unpublish Content"]</h4>
<p>@T["Unpublish a content item."]</p> |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Compiler.Common;
using static Microsoft.DotNet.Cli.Compiler.Common.AssemblyInfoOptions;
namespace Microsoft.DotNet.Tools.Compiler
{
internal class AssemblyInfoOptionsCommandLine
{
public CommandOption VersionOption { get; set; }
public CommandOption TitleOption { get; set; }
public CommandOption DescriptionOption { get; set; }
public CommandOption CopyrightOption { get; set; }
public CommandOption NeutralCultureOption { get; set; }
public CommandOption CultureOption { get; set; }
public CommandOption InformationalVersionOption { get; set; }
public CommandOption FileVersionOption { get; set; }
public CommandOption TargetFrameworkOption { get; set; }
public static AssemblyInfoOptionsCommandLine AddOptions(CommandLineApplication app)
{
AssemblyInfoOptionsCommandLine commandLineOptions = new AssemblyInfoOptionsCommandLine();
commandLineOptions.VersionOption = AddOption(app, AssemblyVersionOptionName, "Assembly version");
commandLineOptions.TitleOption = AddOption(app, TitleOptionName, "Assembly title");
commandLineOptions.DescriptionOption = AddOption(app, DescriptionOptionName, "Assembly description");
commandLineOptions.CopyrightOption = AddOption(app, CopyrightOptionName, "Assembly copyright");
commandLineOptions.NeutralCultureOption = AddOption(app, NeutralCultureOptionName, "Assembly neutral culture");
commandLineOptions.CultureOption = AddOption(app, CultureOptionName, "Assembly culture");
commandLineOptions.InformationalVersionOption = AddOption(app, InformationalVersionOptionName, "Assembly informational version");
commandLineOptions.FileVersionOption = AddOption(app, AssemblyFileVersionOptionName, "Assembly file version");
commandLineOptions.TargetFrameworkOption = AddOption(app, TargetFrameworkOptionName, "Assembly target framework");
return commandLineOptions;
}
private static CommandOption AddOption(CommandLineApplication app, string optionName, string description)
{
return app.Option($"--{optionName} <arg>", description, CommandOptionType.SingleValue);
}
public AssemblyInfoOptions GetOptionValues()
{
return new AssemblyInfoOptions()
{
AssemblyVersion = UnescapeNewlines(VersionOption.Value()),
Title = UnescapeNewlines(TitleOption.Value()),
Description = UnescapeNewlines(DescriptionOption.Value()),
Copyright = UnescapeNewlines(CopyrightOption.Value()),
NeutralLanguage = UnescapeNewlines(NeutralCultureOption.Value()),
Culture = UnescapeNewlines(CultureOption.Value()),
InformationalVersion = UnescapeNewlines(InformationalVersionOption.Value()),
AssemblyFileVersion = UnescapeNewlines(FileVersionOption.Value()),
TargetFramework = UnescapeNewlines(TargetFrameworkOption.Value()),
};
}
private static string UnescapeNewlines(string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
return text.Replace("\\r", "\r").Replace("\\n", "\n");
}
}
} |
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Runtime.Serialization;
namespace ReactiveUI
{
/// <summary>
/// RoutingState manages the ViewModel Stack and allows ViewModels to
/// navigate to other ViewModels.
/// </summary>
[DataContract]
public class RoutingState : ReactiveObject
{
static RoutingState()
{
RxApp.EnsureInitialized();
}
[DataMember] ReactiveList<IRoutableViewModel> _NavigationStack;
/// <summary>
/// Represents the current navigation stack, the last element in the
/// collection being the currently visible ViewModel.
/// </summary>
[IgnoreDataMember]
public ReactiveList<IRoutableViewModel> NavigationStack {
get { return _NavigationStack; }
protected set { _NavigationStack = value; }
}
[IgnoreDataMember]
IScheduler scheduler;
/// <summary>
/// The scheduler used for commands. Defaults to <c>RxApp.MainThreadScheduler</c>.
/// </summary>
[IgnoreDataMember]
public IScheduler Scheduler {
get { return this.scheduler; }
set {
if (this.scheduler != value) {
this.scheduler = value;
this.setupRx();
}
}
}
/// <summary>
/// Navigates back to the previous element in the stack.
/// </summary>
[IgnoreDataMember]
public ReactiveCommand<Unit, Unit> NavigateBack { get; protected set; }
/// <summary>
/// Navigates to the a new element in the stack - the Execute parameter
/// must be a ViewModel that implements IRoutableViewModel.
/// </summary>
[IgnoreDataMember]
public ReactiveCommand<IRoutableViewModel, IRoutableViewModel> Navigate { get; protected set; }
/// <summary>
/// Navigates to a new element and resets the navigation stack (i.e. the
/// new ViewModel will now be the only element in the stack) - the
/// Execute parameter must be a ViewModel that implements
/// IRoutableViewModel.
/// </summary>
[IgnoreDataMember]
public ReactiveCommand<IRoutableViewModel, IRoutableViewModel> NavigateAndReset { get; protected set; }
[IgnoreDataMember]
public IObservable<IRoutableViewModel> CurrentViewModel { get; protected set; }
public RoutingState()
{
_NavigationStack = new ReactiveList<IRoutableViewModel>();
setupRx();
}
[OnDeserialized]
void setupRx(StreamingContext sc) { setupRx(); }
void setupRx()
{
var scheduler = this.scheduler ?? RxApp.MainThreadScheduler;
var countAsBehavior = Observable.Concat(
Observable.Defer(() => Observable.Return(_NavigationStack.Count)),
NavigationStack.CountChanged);
NavigateBack =
ReactiveCommand.CreateFromObservable(() => {
NavigationStack.RemoveAt(NavigationStack.Count - 1);
return Observables.Unit;
},
countAsBehavior.Select(x => x > 1),
scheduler);
Navigate = ReactiveCommand.CreateFromObservable<IRoutableViewModel, IRoutableViewModel>(x => {
var vm = x as IRoutableViewModel;
if (vm == null) {
throw new Exception("Navigate must be called on an IRoutableViewModel");
}
NavigationStack.Add(vm);
return Observable.Return(x);
},
outputScheduler: scheduler);
NavigateAndReset = ReactiveCommand.CreateFromObservable<IRoutableViewModel, IRoutableViewModel>(x => {
NavigationStack.Clear();
return Navigate.Execute(x);
},
outputScheduler: scheduler);
CurrentViewModel = Observable.Concat(
Observable.Defer(() => Observable.Return(NavigationStack.LastOrDefault())),
NavigationStack.Changed.Select(_ => NavigationStack.LastOrDefault()));
}
}
public static class RoutingStateMixins
{
/// <summary>
/// Locate the first ViewModel in the stack that matches a certain Type.
/// </summary>
/// <returns>The matching ViewModel or null if none exists.</returns>
public static T FindViewModelInStack<T>(this RoutingState This)
where T : IRoutableViewModel
{
return This.NavigationStack.Reverse().OfType<T>().FirstOrDefault();
}
/// <summary>
/// Returns the currently visible ViewModel
/// </summary>
public static IRoutableViewModel GetCurrentViewModel(this RoutingState This)
{
return This.NavigationStack.LastOrDefault();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Sandbox.LINQ_Lab
{
public static class Task6
{
public static List<(int, string[])> GroupByLength(string str)
{
return Regex.Split(str, @"\W+")
.GroupBy(s => s.Length)
.OrderByDescending(g => g.Key)
.Select(g => (g.Key, g.ToArray()))
.ToList();
}
public static void RunExample()
{
var result= GroupByLength("Это что же получается: ходишь, ходишь в школу, а потом бац - вторая смена");
foreach (var g in result)
{
Console.WriteLine($"Длина {g.Item1}. Количество {g.Item2.Length}");
foreach (var str in g.Item2)
{
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FaladorTradingSystems.Backtesting.Events
{
/// <summary>
/// Event which represents a signal being generated
/// by a trading strategy
/// </summary>
public class SignalEvent : IEvent
{
public SignalEvent(DateTime dateTimeGenerated,
string ticker,
SignalDirection direction,
decimal strength)
{
Type = EventType.SignalEvent;
DateTimeGenerated = dateTimeGenerated;
Ticker = ticker;
Direction = direction;
Strenth = strength;
}
public EventType Type { get; }
public DateTime DateTimeGenerated { get; }
public string Ticker { get; }
public SignalDirection Direction { get; }
public decimal Strenth { get; }
}
}
|
namespace Brightcove.MediaFramework.Brightcove.Upload
{
public class VideoUploadServiceConfigBase
{
public bool CaptureImages { get; set; }
public string Profile { get; set; }
public bool AlwaysCreateVideoItem { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bing.Caching.Abstractions;
using Newtonsoft.Json;
namespace Bing.Serialization.Json
{
/// <summary>
/// 默认Json序列化器
/// </summary>
public class DefaultJsonSerializer:ICacheSerializer
{
/// <summary>
/// Json序列化器
/// </summary>
static readonly JsonSerializer JsonSerializer=new JsonSerializer();
public byte[] Serialize<T>(T value)
{
using (var ms=new MemoryStream())
{
using (var sr=new StreamWriter(ms,Encoding.UTF8))
{
using (var jtr=new JsonTextWriter(sr))
{
JsonSerializer.Serialize(jtr,value);
}
}
return ms.ToArray();
}
}
public T Deserialize<T>(byte[] bytes)
{
using (var ms=new MemoryStream(bytes))
{
using (var sr=new StreamWriter(ms,Encoding.UTF8))
{
}
}
}
public ArraySegment<byte> SerializeObject(object obj)
{
throw new NotImplementedException();
}
public object DeserializeObject(ArraySegment<byte> value)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Data.Services.Providers;
using LinqToDB.ServiceModel;
using NUnit.Framework;
namespace Tests.Linq
{
using Model;
[TestFixture]
public class DataServiceTests
{
#if !MONO
[Test]
public void Test1()
{
var ds = new DataService<NorthwindDB>();
var mp = ds.GetService(typeof(IDataServiceMetadataProvider));
}
#endif
}
}
|
using ChristInSong.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Christ_in_song
{
/// <summary>
/// Locates view models from the IoC for use in binding in Xaml files
/// </summary>
public class ViewModelLocator
{
#region Public Properties
/// <summary>
/// Singleton instance of the locator
/// </summary>
public static ViewModelLocator Instance { get; private set; } = new ViewModelLocator();
/// <summary>
/// The actual application view model
/// </summary>
public static ApplicationViewModel ApplicationViewModel => CoreDi.VM_Application_Dna;
#endregion
}
}
|
using System.Reflection;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Santiago.Infrastructure.DependencyResolution;
namespace Santiago.Web
{
public static class ContainerConfig
{
public static void Register()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterControllers(Assembly.GetAssembly(typeof(MvcApplication)));
containerBuilder.RegisterModule(new AutofacWebTypesModule());
AutofacConfig.Register(containerBuilder);
DependencyResolver.SetResolver(new AutofacDependencyResolver(AutofacConfig.Container));
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Sircl.Website.Data.Localize
{
/// <summary>
/// Represents a localized value for a localization key.
/// </summary>
[Table(nameof(KeyValue), Schema = "localize")]
public class KeyValue
{
/// <summary>
/// Id of the value.
/// </summary>
[Key]
public virtual int Id { get; set; }
/// <summary>
/// Key id of the value.
/// </summary>
public virtual int KeyId { get; set; }
/// <summary>
/// Key of the value.
/// </summary>
[ForeignKey(nameof(KeyId))]
public virtual Key Key { get; set; }
/// <summary>
/// Culture of this value.
/// </summary>
[Required, MaxLength(200)]
public virtual string Culture { get; set; }
/// <summary>
/// Localized value string.
/// </summary>
public virtual string Value { get; set; }
/// <summary>
/// Whether this value is reviewed.
/// </summary>
public virtual bool Reviewed { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLiteDBProject.Model;
using Microsoft.Data.Sqlite;
using System.Collections.ObjectModel;
namespace SQLiteDBProject.Helper
{
public static class DataAccess
{
private static readonly string _databasePath = "Automata.db";
public static void InitializeDatabase()
{
//In this statement It creates db and store it in local data store
using (SqliteConnection conn = new SqliteConnection("Filename=" + _databasePath))
{
conn.Open();
//this statement Initializes a employee's table
string tableCommand = "CREATE TABLE IF NOT EXISTS Employee" +
"(Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE," +
"Email NVARCHAR(2048) NOT NULL UNIQUE," +
"Password NVARCHAR(2048) NOT NULL," +
"Name NVARCHAR(2048) NOT NULL);";
SqliteCommand createTable = new SqliteCommand(tableCommand, conn);
createTable.ExecuteNonQuery();
}
}
public static ObservableCollection<Employee> GetEmployees()
{
ObservableCollection<Employee> employees =
new ObservableCollection<Employee>();
using (SqliteConnection conn =
new SqliteConnection("Filename=" + _databasePath))
{
conn.Open();
SqliteCommand getEmployeesCommand = new SqliteCommand("SELECT * FROM Employee", conn);
SqliteDataReader query = getEmployeesCommand.ExecuteReader();
while (query.Read())
{
//You can use this as well as ;)
//employees.Add(new Employee()
//{
// Id = (int)query["Id"],
// Email = (string)query["Email"],
// Password = (string)query["Password"],
// Name = (string)query["Name"]
//});
employees.Add(new Employee()
{
Id = query.GetInt32(0),
Email = query.GetString(1),
Password = query.GetString(2),
Name = query.GetString(3)
});
}
conn.Close();
}
return employees;
}
public static void AddEmployee(Employee employee)
{
using (SqliteConnection conn =
new SqliteConnection("Filename=" + _databasePath))
{
conn.Open();
SqliteCommand addEmployeeCommand = new SqliteCommand();
addEmployeeCommand.Connection = conn;
// Use parameterized query to prevent SQL injection attacks
addEmployeeCommand.CommandText = "INSERT INTO Employee VALUES (@Entry0, @Entry1, @Entry2, @Entry3);";
addEmployeeCommand.Parameters.AddWithValue("@Entry0", employee.Id);
addEmployeeCommand.Parameters.AddWithValue("@Entry1", employee.Email);
addEmployeeCommand.Parameters.AddWithValue("@Entry2", employee.Password);
addEmployeeCommand.Parameters.AddWithValue("@Entry3", employee.Name);
addEmployeeCommand.ExecuteNonQuery();
conn.Close();
}
}
public static void UpdateEmployee(int id, Employee employee)
{
using (SqliteConnection conn =
new SqliteConnection("Filename=" + _databasePath))
{
conn.Open();
SqliteCommand updateEmployeeCommand = new SqliteCommand();
updateEmployeeCommand.Connection = conn;
// Use parameterized query to prevent SQL injection attacks
//please attention to the distance between @Entry3 and WHERE
updateEmployeeCommand.CommandText = "UPDATE Employee SET Password=@Entry1," +
"Name=@Entry2 " +
"WHERE Id = @Entry3;";
updateEmployeeCommand.Parameters.AddWithValue("@Entry1", employee.Password);
updateEmployeeCommand.Parameters.AddWithValue("@Entry2", employee.Name);
updateEmployeeCommand.Parameters.AddWithValue("@Entry3", id);
updateEmployeeCommand.ExecuteNonQuery();
conn.Close();
}
}
public static void DeleteEmployee(int id)
{
using (SqliteConnection conn =
new SqliteConnection("Filename=" + _databasePath))
{
conn.Open();
SqliteCommand deleteEmployeeCommand = new SqliteCommand();
deleteEmployeeCommand.Connection = conn;
deleteEmployeeCommand.CommandText = "DELETE FROM Employee WHERE Id=@Entry;";
deleteEmployeeCommand.Parameters.AddWithValue("@Entry", id);
deleteEmployeeCommand.ExecuteNonQuery();
conn.Close();
}
}
public static bool EmailIsFound(string email)
{
bool isFound = false;
using (SqliteConnection conn =
new SqliteConnection("Filename=" + _databasePath))
{
conn.Open();
SqliteCommand findEmailCommand = new SqliteCommand();
findEmailCommand.Connection = conn;
findEmailCommand.CommandText = "SELECT Email FROM Employee WHERE Email LIKE @Entry;";
findEmailCommand.Parameters.AddWithValue("@Entry", email);
SqliteDataReader query = findEmailCommand.ExecuteReader();
while (query.Read())
{
if (!string.IsNullOrEmpty(query.GetString(0)))
{
isFound = true;
}
}
conn.Close();
}
return isFound;
}
}
}
|
namespace BinarySerializer
{
/// <summary>
/// Signed number representation for bit serializing
/// </summary>
public enum SignedNumberRepresentation
{
Unsigned,
TwosComplement,
SignMagnitude
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Yasb.Redis.Messaging.Client.Interfaces;
namespace Yasb.Redis.Messaging.Client.Commands
{
public class EvalShaCommand : IRedisCommand<byte[]>
{
private byte[] _sha1;
private byte[][] _keys;
public EvalShaCommand(byte[] sha, params byte[][] args)
{
_keys = args;
_sha1 = sha;
}
public byte[] ProcessResponse(ICommandResultProcessor processor)
{
return processor.ExpectMultiLine()[0];
}
public byte[][] ToBinary
{
get { return BinaryUtils.MergeCommandWithArgs(CommandNames.EvalSha, _sha1, _keys); }
}
}
}
|
namespace Soapbox.Web.Areas.Admin.Models.Posts
{
using Soapbox.Models;
public class SelectableCategoryViewModel : PostCategory
{
public bool Selected { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RestWebApi.Tools
{
/// <summary>
/// 表示一个空的任务
/// </summary>
static class EmptyTask
{
static readonly Task Null = new Task(() => { });
public static bool IsNull(this Task task)
{
return task == null || ReferenceEquals(task, Null);
}
public static bool IsNull<T>(this Task<T> task)
{
return task == null || ReferenceEquals(task, EmptyTask<T>.Null);
}
}
/// <summary>
/// 表示一个空的任务
/// </summary>
static class EmptyTask<T>
{
public static readonly Task<T> Null = Task.FromResult(default(T));
}
}
|
using System;
using System.Runtime.InteropServices;
using GodLesZ.Library.Win7.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
namespace GodLesZ.Library.Win7.Shell.PropertySystem {
/// <summary>
/// Defines a partial class that implements helper methods for retrieving Shell properties
/// using a canonical name, property key, or a strongly-typed property. Also provides
/// access to all the strongly-typed system properties and default properties collections.
/// </summary>
public partial class ShellProperties : IDisposable {
private ShellObject ParentShellObject { get; set; }
private ShellPropertyCollection defaultPropertyCollection;
internal ShellProperties(ShellObject parent) {
ParentShellObject = parent;
}
/// <summary>
/// Returns a property available in the default property collection using
/// the given property key.
/// </summary>
/// <param name="key">The property key.</param>
/// <returns>An IShellProperty.</returns>
public IShellProperty GetProperty(PropertyKey key) {
return CreateTypedProperty(key);
}
/// <summary>
/// Returns a property available in the default property collection using
/// the given canonical name.
/// </summary>
/// <param name="canonicalName">The canonical name.</param>
/// <returns>An IShellProperty.</returns>
public IShellProperty GetProperty(string canonicalName) {
return CreateTypedProperty(canonicalName);
}
/// <summary>
/// Returns a strongly typed property available in the default property collection using
/// the given property key.
/// </summary>
/// <typeparam name="T">The type of property to retrieve.</typeparam>
/// <param name="key">The property key.</param>
/// <returns>A strongly-typed ShellProperty for the given property key.</returns>
public ShellProperty<T> GetProperty<T>(PropertyKey key) {
return CreateTypedProperty(key) as ShellProperty<T>;
}
/// <summary>
/// Returns a strongly typed property available in the default property collection using
/// the given canonical name.
/// </summary>
/// <typeparam name="T">The type of property to retrieve.</typeparam>
/// <param name="canonicalName">The canonical name.</param>
/// <returns>A strongly-typed ShellProperty for the given canonical name.</returns>
public ShellProperty<T> GetProperty<T>(string canonicalName) {
return CreateTypedProperty(canonicalName) as ShellProperty<T>;
}
private PropertySystem propertySystem;
/// <summary>
/// Gets all the properties for the system through an accessor.
/// </summary>
public PropertySystem System {
get {
if (propertySystem == null) {
propertySystem = new PropertySystem(ParentShellObject);
}
return propertySystem;
}
}
/// <summary>
/// Gets the collection of all the default properties for this item.
/// </summary>
public ShellPropertyCollection DefaultPropertyCollection {
get {
if (defaultPropertyCollection == null) {
defaultPropertyCollection = new ShellPropertyCollection(ParentShellObject);
}
return defaultPropertyCollection;
}
}
/// <summary>
/// Returns the shell property writer used when writing multiple properties.
/// </summary>
/// <returns>A ShellPropertyWriter.</returns>
/// <remarks>Use the Using pattern with the returned ShellPropertyWriter or
/// manually call the Close method on the writer to commit the changes
/// and dispose the writer</remarks>
public ShellPropertyWriter GetPropertyWriter() {
return new ShellPropertyWriter(ParentShellObject);
}
internal IShellProperty CreateTypedProperty<T>(PropertyKey propKey) {
ShellPropertyDescription desc = ShellPropertyDescriptionsCache.Cache.GetPropertyDescription(propKey);
return new ShellProperty<T>(propKey, desc, ParentShellObject);
}
internal IShellProperty CreateTypedProperty(PropertyKey propKey) {
return ShellPropertyFactory.CreateShellProperty(propKey, ParentShellObject);
}
internal IShellProperty CreateTypedProperty(string canonicalName) {
// Otherwise, call the native PropertyStore method
PropertyKey propKey;
int result = PropertySystemNativeMethods.PSGetPropertyKeyFromName(canonicalName, out propKey);
if (!CoreErrorHelper.Succeeded(result)) {
throw new ArgumentException(
LocalizedMessages.ShellInvalidCanonicalName,
Marshal.GetExceptionForHR(result));
}
return CreateTypedProperty(propKey);
}
#region IDisposable Members
/// <summary>
/// Cleans up memory
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Cleans up memory
/// </summary>
protected virtual void Dispose(bool disposed) {
if (disposed && defaultPropertyCollection != null) {
defaultPropertyCollection.Dispose();
}
}
#endregion
}
} |
namespace MW.Blazor
{
public class TreeStyle
{
public static readonly TreeStyle Bootstrap = new TreeStyle
{
ExpandNodeIconClass = "far fa-plus-square uic-tree--cursor-pointer",
CollapseNodeIconClass = "far fa-minus-square uic-tree--cursor-pointer",
NodeTitleClass = "p-1",
NodeTitleSelectableClass = "text-body uic-tree--cursor-pointer",
NodeTitleSelectedClass = "bg-primary text-white",
NodeTitleDisabledClass = "text-black-50",
NodeLoadingClass = "fas fa-spinner"
};
public string ExpandNodeIconClass { get; set; }
public string CollapseNodeIconClass { get; set; }
public string NodeTitleClass { get; set; }
public string NodeTitleSelectableClass { get; set; }
public string NodeTitleSelectedClass { get; set; }
public string NodeTitleDisabledClass { get; set; }
public string NodeLoadingClass { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Git_Watcher_Client;
using Git_Watcher_Client.Dto;
using Git_Watcher_Client.GitHubRestServices.Interfaces;
using Git_Watcher_Client.GitHubRestServices;
using Git_Watcher_Client.Models;
using NSubstitute;
using Xunit;
using GitWatcher.ApiModels;
namespace GitWatcher.Tests.GitHubServices
{
public class IssuseServiceTest
{
private readonly GitHubRestService _gitHubRestService;
public IssuseServiceTest()
{
_gitHubRestService = new GitHubRestService();
}
#region UnitTest
#endregion
#region IntegrationTest
#region GetMethode
public class GetMethode
{
[Fact]
public async Task CanGetIssueWithRepositoryId()
{
var gitHubRestService = new GitHubRestService();
var issue = await gitHubRestService.Issue.Get(1296269, 512);
Assert.Equal("https://api.github.com/repos/octocat/Hello-World", issue.RepositoryUrl.ToString());
Assert.Equal("https://api.github.com/repos/octocat/Hello-World/issues/512",issue.Url.ToString());
Assert.Equal("",issue.Body);
Assert.Equal("Update README",issue.Title);
}
}
#endregion
#region GetAll
public class TheGetAllPublicMethod
{
[Fact]
public async Task ReturnsIssuesForARepository()
{
var gitHubRestService = new GitHubRestService();
var issues = await gitHubRestService.Issue.GetAllForRepository("octocat", "Hello-World");
Assert.Equal(30, issues.Count);
}
[Fact]
public async Task ReturnsIssuesForARepositoryWithRepositoryId()
{
var gitHubRestService = new GitHubRestService();
var issues = await gitHubRestService.Issue.GetAllForRepository(1296269);
Assert.Equal(30, issues.Count);
}
}
#endregion
#endregion
}
} |
namespace RegularExpressionScratchpad
{
using System;
using System.Text;
/// <summary>
/// RegexConditional.
/// </summary>
public class RegexConditional : RegexItem
{
private readonly RegexExpression expression;
private readonly RegexExpression yesNo;
private readonly int startLocation;
/// <summary>
/// Initializes a new instance of the <see cref="RegexConditional"/> class.
/// </summary>
/// <param name="buffer">The buffer.</param>
public RegexConditional(RegexBuffer buffer)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), "RegexBuffer is null");
}
this.startLocation = buffer.Offset;
this.expression = new RegexExpression(buffer);
this.CheckClosingParen(buffer);
this.yesNo = new RegexExpression(buffer);
this.CheckClosingParen(buffer);
buffer.AddLookup(this, this.startLocation, buffer.Offset - 1);
}
/// <summary>
/// Toes the string.
/// </summary>
/// <param name="indent">The indent.</param>
/// <returns>string</returns>
public override string ToString(int indent)
{
string indents = new string(' ', indent);
StringBuilder result = new StringBuilder();
result.Append(indents + "if: " + this.expression.ToString(0));
result.Append(indents + "match: ");
// walk through until we find an alternation
foreach (RegexItem item in this.yesNo.Items)
{
if (item is RegexAlternate)
{
result.Append("\r\n" + indent + "else match: ");
}
else
{
result.Append(item.ToString(indent));
}
}
result.Append("\r\n");
return result.ToString();
}
/// <summary>
/// Checks the closing paren.
/// </summary>
/// <param name="buffer">The buffer.</param>
private void CheckClosingParen(RegexBuffer buffer)
{
// check for closing ")"
char current;
try
{
current = buffer.Current;
}
catch (Exception e)
{
// no closing brace. Set highlight for this capture...
buffer.ErrorLocation = this.startLocation;
buffer.ErrorLength = 1;
throw new Exception("Missing closing \')\' in capture", e);
}
if (current != ')')
{
throw new Exception($"Unterminated closure at offset {buffer.Offset}");
}
// eat closing parenthesis
buffer.Offset++;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Configuration
{
public sealed class IriParsingElement : ConfigurationElement
{
internal const bool EnabledDefaultValue = false;
private readonly ConfigurationPropertyCollection _properties =
new ConfigurationPropertyCollection();
private readonly ConfigurationProperty _enabled = new ConfigurationProperty(
CommonConfigurationStrings.Enabled,
typeof(bool),
EnabledDefaultValue,
ConfigurationPropertyOptions.None
);
public IriParsingElement()
{
_properties.Add(_enabled);
}
protected internal override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}
[ConfigurationProperty(
CommonConfigurationStrings.Enabled,
DefaultValue = EnabledDefaultValue
)]
public bool Enabled
{
get { return (bool)this[_enabled]; }
set { this[_enabled] = value; }
}
}
}
|
@using TensileStrength.Web
@using TensileStrength.Web.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
using Microsoft.AspNetCore.Identity;
using System;
using System.Text;
using OnlineBankingApp.Models;
using System.Security.Cryptography;
namespace OnlineBankingApp.Identity
{
public class PasswordHasher : IPasswordHasher<Customer>
{
public string HashPassword(Customer customer, string password)
{
using (var md5 = new MD5CryptoServiceProvider()) {
var hashedBytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
var hashedPassword = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
return hashedPassword;
}
}
public PasswordVerificationResult VerifyHashedPassword(Customer customer,
string hashedPassword, string password)
{
var hash = HashPassword(customer, password);
if (hashedPassword == hash)
return PasswordVerificationResult.Success;
else
return PasswordVerificationResult.Failed;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Windows.Forms;
namespace WorkMonit
{
public partial class SettingsForm : Form
{
public SettingsForm()
{
InitializeComponent();
homeOfficeEnableElements();
}
private void SettingsForm_FormClosed(object sender, FormClosedEventArgs e)
{
Properties.Settings.Default.Save();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
homeOfficeEnableElements();
}
private void homeOfficeEnableElements()
{
homeOfficeDays.Enabled = false;
urlRules.Enabled = false;
if (comboBox1.SelectedItem.ToString() == "Reach url and process run")
{
urlRules.Enabled = true;
}
if (comboBox1.SelectedItem.ToString() == "Define home office days")
{
homeOfficeDays.Enabled = true;
}
}
private void homeOfficeDays_SelectedIndexChanged(object sender, EventArgs e)
{
StringCollection dayList = new StringCollection();
foreach (var item in homeOfficeDaysCheckedList.CheckedItems)
dayList.Add(item.ToString());
Properties.Settings.Default.HomeOfficeDays = dayList;
}
}
}
|
using Acmion.CshtmlComponent;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SampleRazorPagesApplication.Pages.Components
{
[HtmlTargetElement("Box")]
public class Box : CshtmlComponentReferenceableBase<Box>
{
public string FontSize { get; set; } = "1rem";
public string BackgroundColor { get; set; } = "rgba(255, 0, 0, 0.1)";
public Box(IHtmlHelper htmlHelper) : base(htmlHelper, "/Pages/Components/Box.cshtml", "div")
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//this was made because of issues with using TMPro
public class TextChanger : MonoBehaviour
{
public Text Shadow;
private Text Self;
// Use this for initialization
void Start()
{
Self = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
Shadow.text = Self.text;
}
}
|
using System.Globalization;
using System.Numerics;
static partial class main_package
{
// const Big = 1 << 100
private static BigInteger? __Big__value;
private static BigInteger __init__Big() => __Big__value ??= BigInteger.Parse("1", NumberStyles.Float) << 100;
public const float Big__f32 = 1267650600228229401496703205376F;
public const double Big__f64 = 1267650600228229401496703205376D;
private static readonly Complex? __Big_c64;
public static readonly Complex Big_c64 = __Big_c64 ??= new Complex(Big__f32, 0.0F);
private static readonly Complex? __Big_c128;
public static readonly Complex Big_c128 = __Big_c128 ??= new Complex(Big__f64, 0.0D);
// const Small = Big >> 99
private static BigInteger? __Small__value;
private static BigInteger __init__Small() => __Small__value ??= Big >> 99;
public const int Small__i = 2;
public const byte Small__ui8 = 2;
public const sbyte Small__i8 = 2;
public const short Small__i16 = 2;
public const ushort Small__ui16 = 2;
public const int Small__i32 = 2;
public const uint Small__ui32 = 2U;
public const long Small__i64 = 2L;
public const ulong Small__ui64 = 2UL;
public const float Small__f32 = 2F;
public const double Small__f64 = 2D;
private static readonly Complex? __Small__c64;
public static readonly Complex Small__c64 = __Small__c64 ??= new Complex(Big__f32, 0.0F);
private static readonly Complex? __Small__c128;
public static readonly Complex Small__c128 = __Small__c128 ??= new Complex(Big__f64, 0.0D);
}
|
using System.Threading.Tasks;
using Nodegem.Engine.Data;
using Nodegem.Engine.Data.Attributes;
using Nodegem.Engine.Data.Fields;
namespace Nodegem.Engine.Core.Nodes.Utils
{
[DefinedNode("33ABFC2F-BC96-4D36-99D5-86B27B3F5E55")]
[NodeNamespace("Core.Utils")]
public class Concat : Node
{
public IValueInputField A { get; set; }
public IValueInputField B { get; set; }
public IValueOutputField String { get; set; }
protected override void Define()
{
A = AddValueInput<string>(nameof(A));
B = AddValueInput<string>(nameof(B));
String = AddValueOutput(nameof(String), ConcatString);
}
private async Task<string> ConcatString(IFlow flow)
{
var a = await flow.GetValueAsync<string>(A);
var b = await flow.GetValueAsync<string>(B);
return a + b;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.