hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a90bc2b91eb16a79a5d4cb47f1bf5f6b160cfd5c | 266 | cs | C# | src/clearance/GroupBudget.Clearance.Business/Domain/IUserSettingsService.cs | JurgenStillaert/GroupBudget | 1d8ebf8c3e2e0d66c3ac31efbd9ddb1923e460bd | [
"MIT"
] | null | null | null | src/clearance/GroupBudget.Clearance.Business/Domain/IUserSettingsService.cs | JurgenStillaert/GroupBudget | 1d8ebf8c3e2e0d66c3ac31efbd9ddb1923e460bd | [
"MIT"
] | null | null | null | src/clearance/GroupBudget.Clearance.Business/Domain/IUserSettingsService.cs | JurgenStillaert/GroupBudget | 1d8ebf8c3e2e0d66c3ac31efbd9ddb1923e460bd | [
"MIT"
] | null | null | null | using GroupBudget.SharedKernel;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GroupBudget.Clearance.Business.Domain
{
internal interface IUserSettingsService
{
Task<List<Guid>> GetUserGroupByUserId(UserId userId);
}
} | 22.166667 | 55 | 0.815789 |
1c091f8886199dd02dfefda3769df47c56861de3 | 366 | cs | C# | src/ClientApp/DevNews/Components/CurrentNewsControl.xaml.cs | AterDev/DevPlatform | ce084389bd3673d36ddcb7dbcaa9d8bc35090cfa | [
"Apache-2.0"
] | null | null | null | src/ClientApp/DevNews/Components/CurrentNewsControl.xaml.cs | AterDev/DevPlatform | ce084389bd3673d36ddcb7dbcaa9d8bc35090cfa | [
"Apache-2.0"
] | null | null | null | src/ClientApp/DevNews/Components/CurrentNewsControl.xaml.cs | AterDev/DevPlatform | ce084389bd3673d36ddcb7dbcaa9d8bc35090cfa | [
"Apache-2.0"
] | null | null | null | using Windows.UI.Xaml.Controls;
// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板
namespace DevNews.Components
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class CurrentNewsControl : Page
{
public CurrentNewsControl()
{
this.InitializeComponent();
}
}
}
| 20.333333 | 62 | 0.617486 |
29ce3a49c5423648a23a2d118a67326d3dcebf5e | 623 | cs | C# | App/App.Test/IntegrationTest1.cs | TeamSpark-Learning/quality-gateway | b2480d2a1ce2a7c307a5c6871c0cbaf4c30536e7 | [
"MIT"
] | null | null | null | App/App.Test/IntegrationTest1.cs | TeamSpark-Learning/quality-gateway | b2480d2a1ce2a7c307a5c6871c0cbaf4c30536e7 | [
"MIT"
] | null | null | null | App/App.Test/IntegrationTest1.cs | TeamSpark-Learning/quality-gateway | b2480d2a1ce2a7c307a5c6871c0cbaf4c30536e7 | [
"MIT"
] | null | null | null | using System;
using System.Threading;
using NUnit.Framework;
namespace App.Test
{
[TestFixture]
[Category("Category1")]
public class IntegrationTest1
{
[Test]
public void Test1_1()
{
Thread.Sleep(TimeSpan.FromSeconds(3));
Assert.Pass();
}
[Test]
public void Test1_2()
{
Thread.Sleep(TimeSpan.FromSeconds(3));
Assert.Pass();
}
[Test]
public void Test1_3()
{
Thread.Sleep(TimeSpan.FromSeconds(3));
Assert.Pass();
}
}
} | 19.46875 | 50 | 0.492777 |
b17ab5b128757bfb9338b0926783cf6de5e834f8 | 497 | cs | C# | src/MitternachtBot/Common/TypeReaders/ModerationPointsTypeReader.cs | offical-Cromatin/Mitternacht-NEW | f43737331f3419a4b41f4285631b93af0a2db176 | [
"MIT"
] | 2 | 2021-12-24T17:00:29.000Z | 2021-12-24T17:03:44.000Z | src/MitternachtBot/Common/TypeReaders/ModerationPointsTypeReader.cs | offical-Cromatin/Mitternacht-NEW | f43737331f3419a4b41f4285631b93af0a2db176 | [
"MIT"
] | null | null | null | src/MitternachtBot/Common/TypeReaders/ModerationPointsTypeReader.cs | offical-Cromatin/Mitternacht-NEW | f43737331f3419a4b41f4285631b93af0a2db176 | [
"MIT"
] | null | null | null | using Discord.Commands;
using System;
using System.Threading.Tasks;
namespace Mitternacht.Common.TypeReaders {
public class ModerationPointsTypeReader : TypeReader {
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services){
try {
return Task.FromResult(TypeReaderResult.FromSuccess(ModerationPoints.FromString(input)));
} catch(ArgumentException e) {
return Task.FromResult(TypeReaderResult.FromError(e));
}
}
}
}
| 31.0625 | 117 | 0.784708 |
973d9f039c4477a35995a3a1d99cf5b6a020e5fa | 997 | cs | C# | Scripts/Utility/FeedAnimation.cs | Alfabits/Pip-Pup-Source-Backup | 0c700e4bdcab77ad2f17c5cc036472b0fe4ce660 | [
"MIT"
] | null | null | null | Scripts/Utility/FeedAnimation.cs | Alfabits/Pip-Pup-Source-Backup | 0c700e4bdcab77ad2f17c5cc036472b0fe4ce660 | [
"MIT"
] | null | null | null | Scripts/Utility/FeedAnimation.cs | Alfabits/Pip-Pup-Source-Backup | 0c700e4bdcab77ad2f17c5cc036472b0fe4ce660 | [
"MIT"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class FeedAnimation : MonoBehaviour
{
Animator m_Animator;
public bool isEating = false;
public float animAddTime;
private float animTime;
void Awake()
{
m_Animator = GetComponent<Animator>();
}
// Use this for initialization
void Start()
{
m_Animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
UpdateIsEating();
}
void UpdateIsEating()
{
Animation anim = GetComponent<Animation>();
if (m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1.0f)
{
StopAnimation();
}
}
public void BeginAnimation()
{
m_Animator.Play("Eating", 0, 0f);
isEating = true;
}
public void StopAnimation()
{
m_Animator.Stop();
isEating = false;
}
}
| 19.173077 | 77 | 0.601805 |
9582408a337e0db097d49b6eaff31a7f6f41ee37 | 3,499 | cs | C# | src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/LinterRuleTestsBase.cs | StefanIvemo/bicep | 71f6ce7bafc3ffc1137f0db66de1a263beb16269 | [
"MIT"
] | null | null | null | src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/LinterRuleTestsBase.cs | StefanIvemo/bicep | 71f6ce7bafc3ffc1137f0db66de1a263beb16269 | [
"MIT"
] | null | null | null | src/Bicep.Core.UnitTests/Diagnostics/LinterRuleTests/LinterRuleTestsBase.cs | StefanIvemo/bicep | 71f6ce7bafc3ffc1137f0db66de1a263beb16269 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Bicep.Core.Analyzers.Linter;
using Bicep.Core.Analyzers.Linter.Rules;
using Bicep.Core.Diagnostics;
using Bicep.Core.UnitTests.Assertions;
using Bicep.Core.UnitTests.Utils;
using FluentAssertions;
using FluentAssertions.Execution;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Bicep.Core.UnitTests.Diagnostics.LinterRuleTests
{
public class LinterRuleTestsBase
{
public enum OnCompileErrors
{
Fail, // Assertion fails if there are compiler errors
Ignore,
}
protected void AssertLinterRuleDiagnostics(string ruleCode, string bicepText, string[] expectedMessagesForCode, OnCompileErrors onCompileErrors = OnCompileErrors.Fail)
{
AssertLinterRuleDiagnostics(ruleCode, bicepText, onCompileErrors, diags =>
{
diags.Select(d => d.Message).Should().BeEquivalentTo(expectedMessagesForCode);
});
}
protected void AssertLinterRuleDiagnostics(string ruleCode, string bicepText, int expectedDiagnosticCountForCode, OnCompileErrors onCompileErrors = OnCompileErrors.Fail)
{
AssertLinterRuleDiagnostics(ruleCode, bicepText, onCompileErrors, diags =>
{
diags.Should().HaveCount(expectedDiagnosticCountForCode);
});
}
protected void AssertLinterRuleDiagnostics(string ruleCode, string bicepText, Action<IEnumerable<IDiagnostic>> assertAction)
{
AssertLinterRuleDiagnostics(ruleCode, bicepText, OnCompileErrors.Fail, assertAction);
}
protected void AssertLinterRuleDiagnostics(string ruleCode, string bicepText, OnCompileErrors onCompileErrors, Action<IEnumerable<IDiagnostic>> assertAction)
{
RunWithDiagnosticAnnotations(
bicepText,
diag => diag.Code == ruleCode || (onCompileErrors == OnCompileErrors.Fail && diag.Level == DiagnosticLevel.Error),
onCompileErrors,
assertAction);
}
private void RunWithDiagnosticAnnotations(string bicepText, Func<IDiagnostic, bool> filterFunc, OnCompileErrors onCompileErrors, Action<IEnumerable<IDiagnostic>> assertAction)
{
using (AssertionScope scope = new AssertionScope())
{
scope.AddReportable("bicep code", bicepText);
var result = CompilationHelper.Compile(bicepText);
result.Should().NotHaveDiagnosticsWithCodes(new[] { LinterAnalyzer.FailedRuleCode }, "There should never be linter FailedRuleCode errors");
if (onCompileErrors == OnCompileErrors.Fail)
{
var compileErrors = result.Diagnostics.Where(d => d.Level == DiagnosticLevel.Error);
DiagnosticAssertions.DoWithDiagnosticAnnotations(
result.Compilation.SourceFileGrouping.EntryPoint,
compileErrors,
diags => diags.Should().HaveCount(0));
}
IDiagnostic[] diagnosticsMatchingCode = result.Diagnostics.Where(filterFunc).ToArray();
DiagnosticAssertions.DoWithDiagnosticAnnotations(
result.Compilation.SourceFileGrouping.EntryPoint,
result.Diagnostics.Where(filterFunc),
assertAction);
}
}
}
}
| 42.670732 | 183 | 0.658188 |
c97bdec12a07e89adc78f895a53732179f1c98dc | 1,480 | cs | C# | src/SignalRChat/SignalRChat/App_Start/IoCMvcConfig.cs | jasonliaocn/SignalRChat | 77c37b61a9a7d153330b4c218b8cc82bf0982859 | [
"Apache-2.0"
] | null | null | null | src/SignalRChat/SignalRChat/App_Start/IoCMvcConfig.cs | jasonliaocn/SignalRChat | 77c37b61a9a7d153330b4c218b8cc82bf0982859 | [
"Apache-2.0"
] | null | null | null | src/SignalRChat/SignalRChat/App_Start/IoCMvcConfig.cs | jasonliaocn/SignalRChat | 77c37b61a9a7d153330b4c218b8cc82bf0982859 | [
"Apache-2.0"
] | null | null | null | using Autofac;
using Autofac.Integration.Mvc;
using Microsoft.AspNet.SignalR;
using SignalRChat.Common;
using System.Reflection;
using System.Web.Mvc;
namespace SignalRChat
{
public class IoCMvcConfig
{
public static void Initialize(HubConfiguration config)
{
var builder = new ContainerBuilder();
Register(builder);
var container = builder.Build();
var resolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(resolver);
//GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
config.Resolver = new AutofacDependencyResolverForSignalR(container);
}
private static void Register(ContainerBuilder builder)
{
//Register current AppDomain's components here.
var executingAssemblies = Assembly.GetExecutingAssembly();
builder.RegisterControllers(executingAssemblies);
// Enable property injection into action filters.
builder.RegisterFilterProvider();
builder.RegisterAssemblyTypes(executingAssemblies)
.Where(t => t.Name.EndsWith("Manager") || t.Name.EndsWith("Client"))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(executingAssemblies)
.Where(t => typeof(Microsoft.AspNet.SignalR.Hubs.IHub).IsAssignableFrom(t))
.ExternallyOwned();
}
}
} | 33.636364 | 87 | 0.663514 |
c4a10d111cbade53695cef1308885918b69fcc8c | 962 | cs | C# | Two.Persistance/Configurations/OrderFoodOperationConfiguration.cs | AmazingSuka/two-bros | 8cb667e14e1a73fba949537b7e7ec054d8ce668a | [
"MIT"
] | null | null | null | Two.Persistance/Configurations/OrderFoodOperationConfiguration.cs | AmazingSuka/two-bros | 8cb667e14e1a73fba949537b7e7ec054d8ce668a | [
"MIT"
] | 4 | 2021-09-28T05:37:13.000Z | 2022-03-02T09:54:34.000Z | Two.Persistance/Configurations/OrderFoodOperationConfiguration.cs | DulkinDmitriy/two-bros | 11a7236c1a92220161960213ef3c1f9ff71d1eab | [
"MIT"
] | null | null | null | using Boxters.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace Boxters.Persistance.Configurations
{
public class OrderFoodOperationConfiguration : IEntityTypeConfiguration<OrderFoodOperation>
{
public void Configure(EntityTypeBuilder<OrderFoodOperation> builder)
{
builder.HasOne(d => d.Order)
.WithMany(p => p.OrderFoodOperations)
.HasForeignKey(d => d.OrderId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("order_orderFoodOperation_fk");
builder.HasOne(d => d.Food)
.WithMany(p => p.OrderFoodOperations)
.HasForeignKey(d => d.FoodId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("food_orderFoodOperation_fk");
}
}
}
| 34.357143 | 95 | 0.659044 |
c4b9dff0def6dda9e9860ffc616e8147ae4d7628 | 2,042 | cs | C# | ClientFramework/HotFixLogic/HotFixLogic/FrameWork/DllFrameWork/GameScript/GameProject/ScriptProject/B_Rall/Msg/MsgDefine/BitProtocolClass/BaseDataAttribute/GameCoreData.cs | lantis-of-china/UnityFramework | 89d542ada786fff67559d82e78d7215efa6e7508 | [
"MIT"
] | 1 | 2022-03-24T06:36:34.000Z | 2022-03-24T06:36:34.000Z | ClientFramework/HotFixLogic/HotFixLogic/FrameWork/DllFrameWork/GameScript/GameProject/ScriptProject/B_Rall/Msg/MsgDefine/BitProtocolClass/BaseDataAttribute/GameCoreData.cs | lantis-of-china/UnityFramework | 89d542ada786fff67559d82e78d7215efa6e7508 | [
"MIT"
] | null | null | null | ClientFramework/HotFixLogic/HotFixLogic/FrameWork/DllFrameWork/GameScript/GameProject/ScriptProject/B_Rall/Msg/MsgDefine/BitProtocolClass/BaseDataAttribute/GameCoreData.cs | lantis-of-china/UnityFramework | 89d542ada786fff67559d82e78d7215efa6e7508 | [
"MIT"
] | 1 | 2022-03-24T06:36:40.000Z | 2022-03-24T06:36:40.000Z | // 此文件由协议导出插件自动生成
// ID : 10036]
//****游戏核心数据****
using System;
using System.Collections.Generic;
using System.IO;
using BaseDataAttribute;
using Server;
namespace BaseDataAttribute{
/// <summary>
///游戏核心数据
/// <\summary>
public class GameCoreData : LantisBitProtocolBase {
/// <summary>
///角色信息
/// <\summary>
public RoleInfor _roleInfor;
public GameCoreData(){}
public GameCoreData(RoleInfor __roleInfor){
this._roleInfor = __roleInfor;
}
private Byte[] get__roleInfor_encoding(){
Byte[] outBuf = null;
outBuf = ((LantisBitProtocolBase)_roleInfor).Serializer();
return outBuf;
}
private int set__roleInfor_fromBuf(Byte[] sourceBuf,int curIndex){
Byte tag = sourceBuf[curIndex];
curIndex += 1;
if(tag != 0){;
_roleInfor = new RoleInfor();
curIndex = _roleInfor.Deserializer(sourceBuf,curIndex);
}return curIndex;
}
public override Byte[] Serializer(){
MemoryStream memoryWrite = new MemoryStream();
Byte[] byteBuf = null;
if(_roleInfor != null){
memoryWrite.WriteByte(1);
byteBuf = get__roleInfor_encoding();
memoryWrite.Write(byteBuf,0,byteBuf.Length);
}
else {memoryWrite.WriteByte(0);
}Byte[] bufResult = memoryWrite.ToArray();memoryWrite.Dispose();
return bufResult;
}
public override int Deserializer(Byte[] sourceBuf,int startOffset){
startOffset = set__roleInfor_fromBuf(sourceBuf,startOffset);
return startOffset;}
public String get__roleInfor_json(){
if(_roleInfor==null){return "";}String resultJson = "\"_roleInfor\":";resultJson += ((LantisBitProtocolBase)_roleInfor).SerializerJson();return resultJson;
}
public void set__roleInfor_fromJson(LitJson.JsonData jsonObj){
_roleInfor= new RoleInfor();
_roleInfor.DeserializerJson(jsonObj.ToJson());}
public override String SerializerJson(){
String resultStr = "{";if(_roleInfor != null){
resultStr += get__roleInfor_json();
}
else {}resultStr += "}";return resultStr;
}
public override void DeserializerJson(String json){
LitJson.JsonData jsonObj = CSTools.JsonToData(json);
if(jsonObj["_roleInfor"] != null){
set__roleInfor_fromJson(jsonObj["_roleInfor"]);
}
}
}
}
| 25.209877 | 155 | 0.75857 |
f2338ee2ae161e0395e775c8da8aa6302e21e194 | 6,482 | cs | C# | TestKernelServiceDesktop/Form1.cs | DigitalPlatform/dp2core | 098e0ee4bc70f907ec8d763a9bc35ca355f7f738 | [
"Apache-2.0"
] | null | null | null | TestKernelServiceDesktop/Form1.cs | DigitalPlatform/dp2core | 098e0ee4bc70f907ec8d763a9bc35ca355f7f738 | [
"Apache-2.0"
] | null | null | null | TestKernelServiceDesktop/Form1.cs | DigitalPlatform/dp2core | 098e0ee4bc70f907ec8d763a9bc35ca355f7f738 | [
"Apache-2.0"
] | null | null | null | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using dp2Kernel;
using DigitalPlatform.rms;
using Microsoft.CodeAnalysis.CSharp;
using System.Reflection;
using Microsoft.CodeAnalysis;
using System.IO;
using Microsoft.CodeAnalysis.Emit;
using System.Runtime.Loader;
using DigitalPlatform.Text;
using System.Net.Http;
using JiebaNet.Segmenter;
using System.Speech.Synthesis;
using DigitalPlatform;
namespace TestKernelServiceDesktop
{
public partial class Form1 : Form
{
public KernelApplication _kernelApp = null;
public KernelService _service = null;
public Form1()
{
InitializeComponent();
this.toolStripMenuItem_test_speech.Click += ToolStripMenuItem_test_speech_Click;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
_service?.Dispose();
_kernelApp?.Close();
}
private void button_initialApplication_Click(object sender, EventArgs e)
{
string kernelDirectory = DataModel.GetKernelDataDirectory();
_kernelApp = KernelService.NewApplication(kernelDirectory);
_service = new KernelService(_kernelApp, new KernelSessionInfo(_kernelApp));
}
private void button_test_login_Click(object sender, EventArgs e)
{
var result = _service.Login("root", "");
MessageBox.Show(this, result.ToString());
}
private void button_test_search_Click(object sender, EventArgs e)
{
var result = _service.Search(@"
<target list='中文图书:题名'>
<item>
<word>中国</word>
<match>left</match>
<relation>=</relation>
<dataType>string</dataType>
</item>
<lang>zh</lang>
</target>",
"default",
"");
MessageBox.Show(this, result.ToString());
}
private void button_test_compile_Click(object sender, EventArgs e)
{
// https://docs.microsoft.com/en-us/archive/msdn-magazine/2017/may/net-core-cross-platform-code-generation-with-roslyn-and-net-core
const string code = @"using System;
using System.IO;
namespace RoslynCore
{
...
public static class Helper
{
public static double CalculateCircleArea(double radius)
{
return radius * radius * Math.PI;
}
}
}";
GenerateAssembly(code);
}
public void GenerateAssembly(string code)
{
List<string> errors = new List<string>();
var tree = SyntaxFactory.ParseSyntaxTree(code);
string fileName = "mylib.dll";
// Detect the file location for the library that defines the object type
var systemRefLocation = typeof(object).GetTypeInfo().Assembly.Location;
// Create a reference to the library
var systemReference = MetadataReference.CreateFromFile(systemRefLocation);
// A single, immutable invocation to the compiler
// to produce a library
var compilation = CSharpCompilation.Create(fileName)
.WithOptions(
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(systemReference)
.AddSyntaxTrees(tree);
string path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
EmitResult compilationResult = compilation.Emit(path);
if (compilationResult.Success)
{
// Load the assembly
Assembly asm =
AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
// Invoke the RoslynCore.Helper.CalculateCircleArea method passing an argument
double radius = 10;
object result =
asm.GetType("RoslynCore.Helper").GetMethod("CalculateCircleArea").
Invoke(null, new object[] { radius });
errors.Add($"Circle area with radius = {radius} is {result}");
}
else
{
foreach (Diagnostic codeIssue in compilationResult.Diagnostics)
{
string issue = $"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()},Location: { codeIssue.Location.GetLineSpan()},Severity: { codeIssue.Severity}";
errors.Add(issue);
}
}
MessageBox.Show(this, StringUtil.MakePathList(errors, "\r\n"));
}
private async void button_test_callTestServer_Click(object sender, EventArgs e)
{
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://localhost:59483/");
TestWebApiServerClient client = new TestWebApiServerClient(httpClient);
var res = await client.LoginAsync("supervisor", "test", "parameters", "instance1"); //consume a webApi get action
MessageBox.Show(this, res.ToString());
}
private void button_test_splitWord_Click(object sender, EventArgs e)
{
var segmenter = new JiebaSegmenter();
var segments = segmenter.Cut("我来到北京清华大学"); // 默认为精确模式
var result = string.Join("/ ", segments);
MessageBox.Show(this, result);
}
// https://www.nuget.org/packages/System.Speech
static SpeechSynthesizer m_speech = new SpeechSynthesizer();
// 测试语音
private void ToolStripMenuItem_test_speech_Click(object sender, EventArgs e)
{
this.BeginInvoke((Action)(() =>
{
bool cancel_before = true;
string strText = "测试语音";
try
{
if (cancel_before)
m_speech.SpeakAsyncCancelAll();
m_speech.SpeakAsync(strText);
}
catch (System.Runtime.InteropServices.COMException ex)
{
// ClientInfo.WriteErrorLog($"FormClientInfo::Speak() 出现异常: {ExceptionUtil.GetDebugText(ex)}");
}
}));
}
}
}
| 34.115789 | 170 | 0.603055 |
f2ba629054cb5ab93992ad3e1b68f6c56a5946b1 | 1,589 | cs | C# | src/RPGCore.Behaviour/Core/Nodes/Node.cs | yika-aixi/RPGCore | 27081b2d38463001d7680de70f7ce29c708c3f76 | [
"Apache-2.0"
] | 1 | 2019-11-26T09:29:11.000Z | 2019-11-26T09:29:11.000Z | src/RPGCore.Behaviour/Core/Nodes/Node.cs | yika-aixi/RPGCore | 27081b2d38463001d7680de70f7ce29c708c3f76 | [
"Apache-2.0"
] | null | null | null | src/RPGCore.Behaviour/Core/Nodes/Node.cs | yika-aixi/RPGCore | 27081b2d38463001d7680de70f7ce29c708c3f76 | [
"Apache-2.0"
] | 1 | 2019-12-11T03:42:44.000Z | 2019-12-11T03:42:44.000Z | using Newtonsoft.Json;
using System.Diagnostics;
namespace RPGCore.Behaviour
{
public abstract class Node
{
[JsonIgnore]
public LocalId Id { get; set; }
public abstract INodeInstance CreateInstance ();
public abstract void Setup (IGraphInstance graph, INodeInstance metadata);
internal abstract InputMap[] Inputs (IGraphConnections connections, INodeInstance instance);
internal abstract OutputMap[] Outputs (IGraphConnections connections, INodeInstance instance);
}
public abstract class Node<TNode> : Node
where TNode : Node<TNode>
{
public abstract class Instance : NodeInstanceBase
{
[JsonIgnore]
public TNode Node { get; internal set; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override Node NodeBase => Node;
}
public abstract Instance Create ();
public sealed override INodeInstance CreateInstance () => Create ();
internal sealed override InputMap[] Inputs (IGraphConnections connections, INodeInstance instance)
{
var castedInstance = (Instance)instance;
castedInstance.Node = (TNode)this;
return castedInstance.Inputs (connections);
}
internal sealed override OutputMap[] Outputs (IGraphConnections connections, INodeInstance instance)
{
var castedInstance = (Instance)instance;
castedInstance.Node = (TNode)this;
return castedInstance.Outputs (connections);
}
public sealed override void Setup (IGraphInstance graph, INodeInstance metadata)
{
var instance = (Instance)metadata;
instance.Node = (TNode)this;
instance.Graph = graph;
metadata.Setup ();
}
}
}
| 26.483333 | 102 | 0.748269 |
9366eaa767a6b409bbc4498f156098ad6daf84d7 | 1,157 | cs | C# | src/AdventureWorks.Application/DataEngine/Purchasing/ShipMethod/Queries/GetShipMethodDetail/GetShipMethodDetailQueryHandler.cs | CodeSwifterGit/adwenture-works | dfafadeb88102a31b9a7b028ea71d8781bb14352 | [
"Unlicense"
] | null | null | null | src/AdventureWorks.Application/DataEngine/Purchasing/ShipMethod/Queries/GetShipMethodDetail/GetShipMethodDetailQueryHandler.cs | CodeSwifterGit/adwenture-works | dfafadeb88102a31b9a7b028ea71d8781bb14352 | [
"Unlicense"
] | null | null | null | src/AdventureWorks.Application/DataEngine/Purchasing/ShipMethod/Queries/GetShipMethodDetail/GetShipMethodDetailQueryHandler.cs | CodeSwifterGit/adwenture-works | dfafadeb88102a31b9a7b028ea71d8781bb14352 | [
"Unlicense"
] | null | null | null | using System.Threading;
using System.Threading.Tasks;
using MediatR;
using AutoMapper;
using AdventureWorks.Application.DataEngine.Purchasing.ShipMethod.Queries.GetShipMethods;
using AdventureWorks.Application.Exceptions;
using AdventureWorks.Domain;
namespace AdventureWorks.Application.DataEngine.Purchasing.ShipMethod.Queries.GetShipMethodDetail
{
public partial class GetShipMethodDetailQueryHandler : IRequestHandler<GetShipMethodDetailQuery, ShipMethodLookupModel>
{
private readonly IAdventureWorksContext _context;
private readonly IMapper _mapper;
public GetShipMethodDetailQueryHandler(IAdventureWorksContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<ShipMethodLookupModel> Handle(GetShipMethodDetailQuery request, CancellationToken cancellationToken)
{
var entity = await _context.ShipMethods
.FindAsync(new object[] { request.ShipMethodID }, cancellationToken);
return _mapper.Map<Domain.Entities.Purchasing.ShipMethod, ShipMethodLookupModel>(entity);
}
}
}
| 37.322581 | 126 | 0.75108 |
f43d5b480548c84ed4bac182de34498725849775 | 232 | cs | C# | src/Codeworx.Identity.Primitives/Login/ILoginRegistrationGroup.cs | steffibreuer/identity | 0ef2d353439bf409dc4b4bc2600c72e1491f8bb3 | [
"MIT"
] | null | null | null | src/Codeworx.Identity.Primitives/Login/ILoginRegistrationGroup.cs | steffibreuer/identity | 0ef2d353439bf409dc4b4bc2600c72e1491f8bb3 | [
"MIT"
] | 9 | 2021-11-08T16:19:02.000Z | 2022-03-10T12:16:14.000Z | src/Codeworx.Identity.Primitives/Login/ILoginRegistrationGroup.cs | steffibreuer/identity | 0ef2d353439bf409dc4b4bc2600c72e1491f8bb3 | [
"MIT"
] | 5 | 2021-08-16T11:16:39.000Z | 2022-02-03T15:31:01.000Z | using System.Collections.Generic;
namespace Codeworx.Identity.Login
{
public interface ILoginRegistrationGroup
{
string Template { get; }
IEnumerable<ILoginRegistrationInfo> Registrations { get; }
}
}
| 19.333333 | 66 | 0.702586 |
6b94b9a5af327e5c456e5ef62d18926a72f3c6fe | 456 | cs | C# | PkMn.Game/Enums/SpriteTransformation.cs | mblaine/PkMn.Game | 95937dce4f7d15cf27180f0508fd077429037b7e | [
"MIT"
] | 1 | 2016-06-28T02:18:50.000Z | 2016-06-28T02:18:50.000Z | PkMn.Game/Enums/SpriteTransformation.cs | mblaine/PkMn.Game | 95937dce4f7d15cf27180f0508fd077429037b7e | [
"MIT"
] | null | null | null | PkMn.Game/Enums/SpriteTransformation.cs | mblaine/PkMn.Game | 95937dce4f7d15cf27180f0508fd077429037b7e | [
"MIT"
] | null | null | null |
namespace PkMn.Game.Enums
{
public enum SpriteTransformation
{
SlideDown,
SlideUp,
Shrink,
Stretch,
Blink,
Show,
Hide,
ShiftForward,
ShiftBackward,
SlideOff,
Flatten,
ShowAsBall,
ShowAsNormal,
ShowAsMinimized,
ShowAsSubstitute,
SlideOffTop,
SlideBackDown,
ShakeInPlace
}
}
| 17.538462 | 37 | 0.489035 |
dcff513b7ced9beb0bdfa19b1e470ffce1b0cf6c | 1,052 | cs | C# | src/DND.Bot/Controllers/DialogflowController.cs | davidikin45/DigitalNomadDaveAspNetCore | 99be5389605223aaa7be87d778eb1a66c0c08340 | [
"MIT"
] | null | null | null | src/DND.Bot/Controllers/DialogflowController.cs | davidikin45/DigitalNomadDaveAspNetCore | 99be5389605223aaa7be87d778eb1a66c0c08340 | [
"MIT"
] | null | null | null | src/DND.Bot/Controllers/DialogflowController.cs | davidikin45/DigitalNomadDaveAspNetCore | 99be5389605223aaa7be87d778eb1a66c0c08340 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using DND.Bot.Helpers;
using Google.Cloud.Dialogflow.V2;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DND.Bot.Controllers
{
//Google
public class DialogflowController : ApiController
{
[HttpPost]
public async Task<dynamic> Post()
{
var json = await Request.Content.ReadAsStringAsync();
WebhookRequest request = CommonModelMapper.JsonToDialogflow(json);
var commonModel = CommonModelMapper.DialogflowToCommonModel(request);
if (commonModel == null)
return null;
commonModel = IntentRouter.Process(commonModel);
return CommonModelMapper.CommonModelToDialogflow(commonModel);
}
public string Get()
{
return "Hello Dialogflow!";
}
}
}
| 24.465116 | 81 | 0.658745 |
73658b514c2709146067a96c69b8cd995f6423d9 | 2,629 | cs | C# | test/Microsoft.AspNetCore.Mvc.FunctionalTests/MvcTestFixture.cs | davidsagang/Mvc | 1ab5bb3496056fbe64165b9e6f3038efba4d10cd | [
"Apache-2.0"
] | 23 | 2016-06-11T00:13:07.000Z | 2021-12-24T13:38:24.000Z | test/Microsoft.AspNetCore.Mvc.FunctionalTests/MvcTestFixture.cs | davidsagang/Mvc | 1ab5bb3496056fbe64165b9e6f3038efba4d10cd | [
"Apache-2.0"
] | 6 | 2020-12-02T23:32:55.000Z | 2021-06-25T15:46:32.000Z | test/Microsoft.AspNetCore.Mvc.FunctionalTests/MvcTestFixture.cs | davidsagang/Mvc | 1ab5bb3496056fbe64165b9e6f3038efba4d10cd | [
"Apache-2.0"
] | 1 | 2016-06-15T11:44:22.000Z | 2016-06-15T11:44:22.000Z | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Net.Http;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class MvcTestFixture<TStartup> : IDisposable
{
private readonly TestServer _server;
public MvcTestFixture()
: this(Path.Combine("test", "WebSites"))
{
}
protected MvcTestFixture(string solutionRelativePath)
{
// RequestLocalizationOptions saves the current culture when constructed, potentially changing response
// localization i.e. RequestLocalizationMiddleware behavior. Ensure the saved culture
// (DefaultRequestCulture) is consistent regardless of system configuration or personal preferences.
using (new CultureReplacer())
{
var startupAssembly = typeof(TStartup).GetTypeInfo().Assembly;
var contentRoot = SolutionPathUtility.GetProjectPath(solutionRelativePath, startupAssembly);
var builder = new WebHostBuilder()
.UseContentRoot(contentRoot)
.ConfigureServices(InitializeServices)
.UseStartup(typeof(TStartup));
_server = new TestServer(builder);
}
Client = _server.CreateClient();
Client.BaseAddress = new Uri("http://localhost");
}
public HttpClient Client { get; }
public void Dispose()
{
Client.Dispose();
_server.Dispose();
}
protected virtual void InitializeServices(IServiceCollection services)
{
var startupAssembly = typeof(TStartup).GetTypeInfo().Assembly;
// Inject a custom application part manager. Overrides AddMvcCore() because that uses TryAdd().
var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new AssemblyPart(startupAssembly));
manager.FeatureProviders.Add(new ControllerFeatureProvider());
manager.FeatureProviders.Add(new ViewComponentFeatureProvider());
services.AddSingleton(manager);
}
}
}
| 36.513889 | 115 | 0.668695 |
738d324a95b8dcea52b529d5680e996bfed0822d | 4,109 | cs | C# | WLib.ArcGis/GeoDatabase/WorkSpace/EWorkspaceType.cs | Windr07/WLib | d6d2618401887d9b972fb983785d8d9080c837a8 | [
"DOC"
] | 21 | 2019-01-02T12:42:46.000Z | 2021-11-04T07:48:21.000Z | WLib.ArcGis/GeoDatabase/WorkSpace/EWorkspaceType.cs | Windr07/WLib | d6d2618401887d9b972fb983785d8d9080c837a8 | [
"DOC"
] | null | null | null | WLib.ArcGis/GeoDatabase/WorkSpace/EWorkspaceType.cs | Windr07/WLib | d6d2618401887d9b972fb983785d8d9080c837a8 | [
"DOC"
] | 10 | 2019-10-10T01:26:56.000Z | 2021-11-06T13:47:48.000Z | /*----------------------------------------------------------------
// auth: Windragon
// date: 2018
// desc: None
// mdfy: None
//----------------------------------------------------------------*/
using WLib.Attributes.Description;
namespace WLib.ArcGis.GeoDatabase.WorkSpace
{
/// <summary>
/// ESRI ArcGIS常用工作空间(IWorkspace)类别
/// </summary>
public enum EWorkspaceType
{
/// <summary>
/// 默认,指ShapeFile,FileGDB,Access三种工作空间之一
/// </summary>
[DescriptionEx("shp/gdb,或mdb数据库")]
[DescriptionEx("default",2)]
[DescriptionEx("", 1)]
Default = 0,
/// <summary>
/// ShapeFile文件夹
/// </summary>
[DescriptionEx("ShapeFile文件夹")]
[DescriptionEx("shp", 2)]
[DescriptionEx("esriDataSourcesFile.ShapefileWorkspaceFactory", 1)]
ShapeFile = 1,
/// <summary>
/// 文件地理数据库(*.gdb)
/// </summary>
[DescriptionEx("文件地理数据库")]
[DescriptionEx("gdb", 2)]
[DescriptionEx("esriDataSourcesGDB.FileGDBWorkspaceFactory", 1)]
FileGDB = 2,
/// <summary>
/// Access数据库
/// </summary>
[DescriptionEx("Access数据库")]
[DescriptionEx("mdb", 2)]
[DescriptionEx("esriDataSourcesGDB.AccessWorkspaceFactory", 1)]
Access = 3,
/// <summary>
/// SDE数据库
/// </summary>
[DescriptionEx("SDE数据库")]
[DescriptionEx("sde", 2)]
[DescriptionEx("esriDataSourcesGDB.SdeWorkspaceFactory", 1)]
Sde = 4,
/// <summary>
/// Excel文件
/// </summary>
[DescriptionEx("Excel文件")]
[DescriptionEx("excel", 2)]
[DescriptionEx("esriDataSourcesOleDB.ExcelWorkspaceFactory", 1)]
Excel = 5,
/// <summary>
/// 文本文件夹
/// </summary>
[DescriptionEx("文本文件夹")]
[DescriptionEx("txt", 2)]
[DescriptionEx("esriDataSourcesOleDB.TextFileWorkspaceFactory", 1)]
TextFile = 6,
/// <summary>
/// OleDb数据库(Access/Excel/dbf/Oracle/SQLServer等)
/// </summary>
[DescriptionEx("OleDb数据库")]
[DescriptionEx("oledb", 2)]
[DescriptionEx("esriDataSourcesOleDB.OLEDBWorkspaceFactory", 1)]
OleDb = 7,
/// <summary>
/// 栅格数据
/// </summary>
[DescriptionEx("栅格数据文件夹")]
[DescriptionEx("raster", 2)]
[DescriptionEx("esriDataSourcesRaster.RasterWorkspaceFactory", 1)]
Raster = 8,
/// <summary>
/// Sql数据库
/// </summary>
[DescriptionEx("Sql数据库")]
[DescriptionEx("sql", 2)]
[DescriptionEx("esriDataSourcesGDB.SqlWorkspaceFactory", 1)]
Sql = 10,
/// <summary>
/// CAD数据文件夹
/// </summary>
[DescriptionEx("CAD数据文件夹")]
[DescriptionEx("cad", 2)]
[DescriptionEx("esriDataSourcesFile.CadWorkspaceFactory", 1)]
CAD = 11,
/// <summary>
/// 内存工作空间
/// </summary>
[DescriptionEx("内存工作空间")]
[DescriptionEx("InMemory", 2)]
[DescriptionEx("esriDataSourcesGDB.InMemoryWorkspaceFactory", 1)]
InMemory = 12,
//关于UID:https://blog.csdn.net/yulongguiziyao/article/details/16119633
//关于WorkspaceFactoryProgID:http://edndoc.esri.com/arcobjects/9.2/ComponentHelp/esriGeodatabase/IWorkspaceName_WorkspaceFactoryProgID.htm
// esriDataSourcesGDB.AccessWorkspaceFactory
// esriDataSourcesFile.ArcInfoWorkspaceFactory
// esriDataSourcesFile.CadWorkspaceFactory
// esriDataSourcesGDB.FileGDBWorkspaceFactory
// esriDataSourcesOleDB.OLEDBWorkspaceFactory
// esriDataSourcesFile.PCCoverageWorkspaceFactory
// esriDataSourcesRaster.RasterWorkspaceFactory
// esriDataSourcesGDB.SdeWorkspaceFactory
// esriDataSourcesFile.ShapefileWorkspaceFactory
// esriDataSourcesOleDB.TextFileWorkspaceFactory
// esriDataSourcesFile.TinWorkspaceFactory
// esriDataSourcesFile.VpfWorkspaceFactory
}
}
| 34.822034 | 144 | 0.565588 |
dc1c48ae1e268ab3827a0f6b45f034ab5d4861d6 | 4,403 | cs | C# | R.Test/RNetTest.cs | brunoocostaa/R.Activities | 8aa147f0a8e177e602cd4d0b998f5b3ee77cec67 | [
"MIT"
] | 1 | 2020-02-26T10:15:11.000Z | 2020-02-26T10:15:11.000Z | R.Test/RNetTest.cs | brunoocostaa/R.Activities | 8aa147f0a8e177e602cd4d0b998f5b3ee77cec67 | [
"MIT"
] | null | null | null | R.Test/RNetTest.cs | brunoocostaa/R.Activities | 8aa147f0a8e177e602cd4d0b998f5b3ee77cec67 | [
"MIT"
] | null | null | null | using System;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Statements;
using System.Activities.XamlIntegration;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xaml;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RDotNet;
namespace Statistical.R.Test
{
[TestClass]
public class RNetTest
{
static string pathR = @"C:\Program Files\R\R-3.4.3\bin\i386\R.dll";
#region . Test Methods .
[TestMethod]
public void GetWd_ReturnPath_Success()
{
REngine engine = REngine.GetInstance(pathR);
RNet rApp = new RNet(engine);
Assert.IsNotNull(rApp.GetWd());
}
#endregion
#region . Workflow Samples .
public static DynamicActivity GetActivity_RunScript(string rsrcName)
{
string scriptFile = GetScriptPath_Resources(rsrcName);
Variable<SymbolicExpression> result = new Variable<SymbolicExpression>("rScriptResult");
OutArgument<RDotNet.SymbolicExpression> out_ScriptResult = new OutArgument<RDotNet.SymbolicExpression>();
DynamicActivity wfRScriptTester;
try
{
wfRScriptTester = new DynamicActivity()
{
Properties = {
new DynamicActivityProperty{
Name="OutRResult",
Type=typeof(OutArgument<RDotNet.SymbolicExpression>),
Value = out_ScriptResult
},
},
Implementation = () => new Sequence
{
Variables =
{
result
},
Activities =
{
new RScope
{
Path = pathR,
Body = {
Handler = new RunRScript()
{
File = scriptFile,
Output = result
}
}
},
new Assign<RDotNet.SymbolicExpression>{
To = new ArgumentReference<RDotNet.SymbolicExpression>{ ArgumentName = "OutRResult" },
Value = new InArgument<RDotNet.SymbolicExpression>((env)=>(result.Get(env)))
},
new WriteLine()
{
Text = "Completed RunRScript activity test."
}
}
}
};
}
catch (Exception e)
{
throw e;
}
return wfRScriptTester;
}
private static string GetScriptPath_Resources(string resourceName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceNameSpace = "Statistical.R.Test.Sample";
string tempFile = string.Empty;
string resourceContents = string.Empty;
try
{
tempFile = Path.Combine(Path.GetTempPath(), resourceName);
using (Stream stream = assembly.GetManifestResourceStream(resourceNameSpace + "." + resourceName))
using (StreamReader reader = new StreamReader(stream))
{
resourceContents = reader.ReadToEnd();
}
if (File.Exists(tempFile))
File.Delete(tempFile);
}
catch (Exception e)
{
throw e;
}
File.WriteAllText(tempFile, resourceContents);
return tempFile;
}
#endregion
}
}
| 34.944444 | 123 | 0.430388 |
ec4c40afe45c16ce7743dd31d7a0e3d76aa96935 | 1,368 | cs | C# | Client/DataStructure/TransportationMode.cs | HaaLeo/mvg-sharp | 30718f8d6bd3da86190f146b236dd703c136bd0d | [
"MIT"
] | null | null | null | Client/DataStructure/TransportationMode.cs | HaaLeo/mvg-sharp | 30718f8d6bd3da86190f146b236dd703c136bd0d | [
"MIT"
] | null | null | null | Client/DataStructure/TransportationMode.cs | HaaLeo/mvg-sharp | 30718f8d6bd3da86190f146b236dd703c136bd0d | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------------
// <copyright file="TransportationMode.cs">
// Copyright (c) Leo Hanisch
// </copyright>
// <author>Leo Hanisch</author>
// <summary>
// Defines the TransportationMode enum.
// </summary>
// ----------------------------------------------------------------------------
namespace Client.DataStructure
{
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// The transportation mode enum.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum TransportationMode
{
/// <summary>
/// The S-Bahn.
/// </summary>
[EnumMember(Value = "s")]
SBahn,
/// <summary>
/// The U-Bahn.
/// </summary>
[EnumMember(Value = "u")]
UBahn,
/// <summary>
/// The tram.
/// </summary>
[EnumMember(Value = "t")]
Tram,
/// <summary>
/// The bus.
/// </summary>
[EnumMember(Value = "b")]
Bus,
/// <summary>
/// The train.
/// </summary>
[EnumMember(Value = "z")]
Train,
/// <summary>
/// The ferry.
/// </summary>
[EnumMember(Value = "f")]
Ferry
}
}
| 22.8 | 80 | 0.434211 |
a64cfc2f13b57f101e8899ca7cda95338a9b7d1e | 526 | cs | C# | src/P23.MetaTrader4.Manager.Contracts/Configuration/PluginWithParameters.cs | nerzhul250/MetaTrader4.Manager.Wrapper | 8bbe44174a74f703f60255c06cde8905360f2ae9 | [
"MIT"
] | 6 | 2020-05-18T19:53:37.000Z | 2022-01-21T17:20:38.000Z | src/P23.MetaTrader4.Manager.Contracts/Configuration/PluginWithParameters.cs | nerzhul250/MetaTrader4.Manager.Wrapper | 8bbe44174a74f703f60255c06cde8905360f2ae9 | [
"MIT"
] | null | null | null | src/P23.MetaTrader4.Manager.Contracts/Configuration/PluginWithParameters.cs | nerzhul250/MetaTrader4.Manager.Wrapper | 8bbe44174a74f703f60255c06cde8905360f2ae9 | [
"MIT"
] | 11 | 2020-06-03T10:31:21.000Z | 2021-12-17T15:03:15.000Z | using System.Collections.Generic;
namespace P23.MetaTrader4.Manager.Contracts.Configuration
{
/// <summary>
/// Object that represents plugin with parameters configuration
/// </summary>
public class PluginWithParameters
{
/// <summary>
/// Plugin configuration
/// </summary>
public Plugin Plugin { get; set; }
/// <summary>
/// Plugin parameters
/// </summary>
public IList<PluginConfigurationParameter> Parameters { get; set; }
};
} | 26.3 | 75 | 0.610266 |
047795cd4da860fe81961c68b68e737e5412d206 | 874 | cs | C# | Assets/Scripts/MenuManager.cs | MihaylovArtem/StillWaters | d849ca9029a708e243ca8e2c9c3587613fadfba1 | [
"Apache-2.0"
] | null | null | null | Assets/Scripts/MenuManager.cs | MihaylovArtem/StillWaters | d849ca9029a708e243ca8e2c9c3587613fadfba1 | [
"Apache-2.0"
] | null | null | null | Assets/Scripts/MenuManager.cs | MihaylovArtem/StillWaters | d849ca9029a708e243ca8e2c9c3587613fadfba1 | [
"Apache-2.0"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class MenuManager : MonoBehaviour {
public Text highscore;
// Use this for initialization
void Start () {
if (!PlayerPrefs.HasKey ("HighscoreCompleted")) {
highscore.text = "";
} else {
highscore.text = "Highscore: " + PlayerPrefs.GetInt ("HighscoreCompleted") + "%";
}
if (PlayerPrefs.HasKey ("PeopleAlive")) {
highscore.text = "Highscore: " + PlayerPrefs.GetInt ("PeopleAlive") + " people alive";
}
}
// Update is called once per frame
void Update () {
UnityEngine.Cursor.lockState = CursorLockMode.Confined;
UnityEngine.Cursor.visible = true;
}
public void StartGame() {
Invoke ("LoadLevel", 0.5f);
}
private void LoadLevel() {
Application.LoadLevel ("main");
}
public void ExitGame() {
Application.Quit ();
}
}
| 21.85 | 89 | 0.686499 |
c2f0019347001359a161b19f2984ecb7d662dd99 | 410 | cs | C# | MarketBoardPlugin.Tests/UnitTest1.cs | Caraxi/MarketBoardPlugin | 4d7198b44c071ee9976963d324e3d1a3ad595aaf | [
"MIT"
] | 24 | 2020-07-01T07:06:47.000Z | 2022-03-24T10:29:00.000Z | MarketBoardPlugin.Tests/UnitTest1.cs | Caraxi/MarketBoardPlugin | 4d7198b44c071ee9976963d324e3d1a3ad595aaf | [
"MIT"
] | 21 | 2020-05-28T11:47:02.000Z | 2022-02-26T17:39:27.000Z | MarketBoardPlugin.Tests/UnitTest1.cs | Caraxi/MarketBoardPlugin | 4d7198b44c071ee9976963d324e3d1a3ad595aaf | [
"MIT"
] | 19 | 2020-05-25T13:38:19.000Z | 2022-01-29T09:07:33.000Z | // <copyright file="UnitTest1.cs" company="Florian Maunier">
// Copyright (c) Florian Maunier. All rights reserved.
// </copyright>
namespace MarketBoardPlugin.Tests
{
using System;
using Xunit;
/// <summary>
/// UnitTest1.
/// </summary>
public class UnitTest1
{
/// <summary>
/// Test1.
/// </summary>
[Fact]
public void Test1()
{
Assert.True(true);
}
}
}
| 16.4 | 60 | 0.590244 |
6c1ebdc7a3c0a97c7af5f74296818e6bda55aa05 | 1,505 | cs | C# | functions/helloworld/HelloPubSub/Function.cs | karthiktoyou/dotnet-docs-samples | a48c1550021436fb9a33ef5d670d23828560feda | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | functions/helloworld/HelloPubSub/Function.cs | karthiktoyou/dotnet-docs-samples | a48c1550021436fb9a33ef5d670d23828560feda | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-08-21T05:39:02.000Z | 2020-08-25T16:56:53.000Z | functions/helloworld/HelloPubSub/Function.cs | karthiktoyou/dotnet-docs-samples | a48c1550021436fb9a33ef5d670d23828560feda | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright 2020 Google LLC
//
// 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
//
// https://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.
// [START functions_helloworld_pubsub]
using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.SystemTextJson.Cloud.PubSub.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
namespace HelloPubSub
{
public class Function : ICloudEventFunction<MessagePublishedData>
{
private readonly ILogger _logger;
public Function(ILogger<Function> logger) =>
_logger = logger;
public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
{
string nameFromMessage = data.Message?.TextData;
string name = string.IsNullOrEmpty(nameFromMessage) ? "world" : nameFromMessage;
_logger.LogInformation("Hello {name}", name);
return Task.CompletedTask;
}
}
}
// [END functions_helloworld_pubsub]
| 35.833333 | 118 | 0.728904 |
1372ac5926490f2e0f9459dc1f8f130b6075e6c6 | 7,672 | cs | C# | Assets/Scripts/GameOfLife.cs | Peter226/GPUGameOfLife | 058482130beadcca2fd21836be59884abb64650c | [
"MIT"
] | null | null | null | Assets/Scripts/GameOfLife.cs | Peter226/GPUGameOfLife | 058482130beadcca2fd21836be59884abb64650c | [
"MIT"
] | null | null | null | Assets/Scripts/GameOfLife.cs | Peter226/GPUGameOfLife | 058482130beadcca2fd21836be59884abb64650c | [
"MIT"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;
[RequireComponent(typeof(MeshRenderer))]
public class GameOfLife : MonoBehaviour
{
//display material
Material _material;
//Simulation buffers
[HideInInspector]
public RenderTexture buffer_A;
[HideInInspector]
public RenderTexture buffer_B;
//Simulation settings
public GameOfLifeSettings settings;
//compute shaders
public ComputeShader clearCompute;
public ComputeShader lifeCompute;
public ComputeShader drawCompute;
public ComputeShader copyCompute;
//compute kernels
private int clearKernel;
private int lifeKernel;
private int drawKernel;
private int copyKernel;
//pre-calculated property IDs
private int resultPropertyName = Shader.PropertyToID("Result");
private int inputPropertyName = Shader.PropertyToID("Input");
private int pointAPropertyName = Shader.PropertyToID("PointA");
private int pointBPropertyName = Shader.PropertyToID("PointB");
private int colorPropertyName = Shader.PropertyToID("IColor");
private int mainTexturePropertyName = Shader.PropertyToID("MainTex");
//Simulation variables
private float _simulationTimer;
private int _previousResolution;
System.Diagnostics.Stopwatch _simulationWatcher = new System.Diagnostics.Stopwatch();
/// <summary>
/// Init
/// </summary>
void Start()
{
_material = GetComponent<MeshRenderer>().material;
buffer_A = CreateBufferTexture(settings);
buffer_B = CreateBufferTexture(settings);
_material.SetTexture(mainTexturePropertyName,buffer_A);
try
{
clearKernel = clearCompute.FindKernel("CSMain");
lifeKernel = lifeCompute.FindKernel("CSMain");
drawKernel = drawCompute.FindKernel("CSMain");
copyKernel = copyCompute.FindKernel("CSMain");
}
catch
{
Debug.LogError("Missing a compute shader! Please fill all references!");
}
ClearBuffer(buffer_A);
_simulationWatcher.Start();
}
/// <summary>
/// Simulate Game Of Life every frame, as many times needed, and check updated settings
/// </summary>
void Update()
{
if (_previousResolution != settings.resolution)
{
ResizeCanvas();
_previousResolution = settings.resolution;
}
if (settings.running) {
double simStartTime = _simulationWatcher.Elapsed.TotalMilliseconds;
double simEndTime = simStartTime;
int simCount = 0;
while (_simulationTimer > 1)
{
simCount++;
if (simEndTime - simStartTime < 0.04)
{
Simulate();
}
simEndTime = _simulationWatcher.Elapsed.TotalMilliseconds;
_simulationTimer -= 1;
}
_simulationTimer += Time.deltaTime * settings.simulationSpeed;
}
}
/// <summary>
/// Resize the canvas according to the settings
/// </summary>
private void ResizeCanvas() {
buffer_A.Release();
buffer_B.Release();
buffer_A.width = settings.resolution;
buffer_A.height = settings.resolution;
buffer_B.width = settings.resolution;
buffer_B.height = settings.resolution;
buffer_A.Create();
buffer_B.Create();
}
/// <summary>
/// Simulate a generation of Game Of Life
/// </summary>
public void Simulate()
{
lifeCompute.SetTexture(lifeKernel,inputPropertyName,buffer_A);
lifeCompute.SetTexture(lifeKernel,resultPropertyName,buffer_B);
int threadGroups = GetThreadGroupSize();
lifeCompute.Dispatch(lifeKernel,threadGroups,threadGroups,1);
SwapBuffers();
}
/// <summary>
/// Switch out buffer A and buffer B as render targets
/// </summary>
private void SwapBuffers()
{
RenderTexture buff1 = buffer_A;
buffer_A = buffer_B;
buffer_B = buff1;
_material.SetTexture(mainTexturePropertyName, buffer_A);
}
/// <summary>
/// Draw a point in Game Of Life
/// </summary>
/// <param name="point">Coordinate on the canvas</param>
/// <param name="color">Color to draw (0 = dead cell; 1 = live cell)</param>
public void DrawPoint(int2 point, int color)
{
drawCompute.SetVector(pointAPropertyName,(Vector2)(float2)point);
drawCompute.SetVector(pointBPropertyName,(Vector2)(float2)point);
drawCompute.SetInt(colorPropertyName, color);
drawCompute.SetTexture(drawKernel,inputPropertyName,buffer_A);
drawCompute.SetTexture(drawKernel, resultPropertyName, buffer_B);
int threadGroups = GetThreadGroupSize();
drawCompute.Dispatch(drawKernel,threadGroups,threadGroups,1);
SwapBuffers();
}
/// <summary>
/// Fill an area in Game of Life
/// </summary>
/// <param name="pointA">First coordinate on the canvas</param>
/// <param name="pointB">Second coordinate on the canvas</param>
/// <param name="color">Color to draw (0 = dead cell; 1 = live cell)</param>
public void DrawArea(int2 pointA, int2 pointB, int color)
{
if (pointA.x > pointB.x)
{
int x = pointA.x;
pointA.x = pointB.x;
pointB.x = x;
}
if (pointA.y > pointB.y)
{
int y = pointA.y;
pointA.y = pointB.y;
pointB.y = y;
}
drawCompute.SetVector(pointAPropertyName, (Vector2)(float2)pointA);
drawCompute.SetVector(pointBPropertyName, (Vector2)(float2)pointB);
drawCompute.SetInt(colorPropertyName,color);
drawCompute.SetTexture(drawKernel, inputPropertyName, buffer_A);
drawCompute.SetTexture(drawKernel, resultPropertyName, buffer_B);
int threadGroups = GetThreadGroupSize();
drawCompute.Dispatch(drawKernel, threadGroups, threadGroups, 1);
SwapBuffers();
}
/// <summary>
/// Utility for clearing a buffer texture
/// </summary>
/// <param name="buffer"></param>
private void ClearBuffer(RenderTexture buffer)
{
int threadGroupSize = GetThreadGroupSize();
clearCompute.SetTexture(clearKernel,resultPropertyName,buffer);
clearCompute.Dispatch(clearKernel, threadGroupSize, threadGroupSize, 1);
}
/// <summary>
/// Utility to get the needed thread group size for the given resolution
/// </summary>
/// <returns></returns>
private int GetThreadGroupSize()
{
return Mathf.CeilToInt(settings.resolution / 8.0f);
}
/// <summary>
/// Create a new buffer texture based on resolution
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
private static RenderTexture CreateBufferTexture(GameOfLifeSettings settings)
{
RenderTexture rt = new RenderTexture(settings.resolution,settings.resolution,1,RenderTextureFormat.R8);
rt.enableRandomWrite = true;
rt.filterMode = FilterMode.Point;
return rt;
}
/// <summary>
/// Release buffers when the application quits
/// </summary>
private void OnApplicationQuit()
{
buffer_A.Release();
buffer_B.Release();
_simulationWatcher.Stop();
}
}
/// <summary>
/// Stored settings of Game Of Life
/// </summary>
[System.Serializable]
public struct GameOfLifeSettings
{
public int resolution;
public float simulationSpeed;
public bool running;
}
| 32.786325 | 111 | 0.64012 |
92883338b4f59544384d29f718bb0c00e212fd5e | 6,093 | cs | C# | src/_Report/Framework.CustomReports.Generation/Facade/GetCustomReportStreamMethodGenerator.cs | Luxoft/BSSFramework | e060a42db5b1a96cc915b30c09e4e5751543e8af | [
"MIT"
] | 18 | 2021-12-22T09:28:06.000Z | 2022-01-20T19:48:41.000Z | src/_Report/Framework.CustomReports.Generation/Facade/GetCustomReportStreamMethodGenerator.cs | Luxoft/BSSFramework | e060a42db5b1a96cc915b30c09e4e5751543e8af | [
"MIT"
] | 44 | 2021-12-28T08:36:17.000Z | 2022-03-22T09:17:28.000Z | src/_Report/Framework.CustomReports.Generation/Facade/GetCustomReportStreamMethodGenerator.cs | Luxoft/BSSFramework | e060a42db5b1a96cc915b30c09e4e5751543e8af | [
"MIT"
] | 2 | 2021-12-23T15:30:01.000Z | 2021-12-28T01:26:36.000Z | using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using System.Linq;
using System.Linq.Expressions;
using Framework.CodeDom;
using Framework.Core;
using Framework.DomainDriven.BLL;
using Framework.DomainDriven.Generation.Domain;
using Framework.DomainDriven.ServiceModelGenerator;
using Framework.CustomReports.Domain;
using FileType = Framework.CustomReports.Generation.BLL.FileType;
namespace Framework.CustomReports.Generation.Facade
{
public class GetCustomReportStreamMethodGenerator<TConfiguration> : GeneratorConfigurationContainer<TConfiguration>, IServiceMethodGenerator, IDomainTypeContainer
where TConfiguration : class, ICustomReportServiceGeneratorConfiguration<ICustomReportServiceGenerationEnvironmentBase>
{
public GetCustomReportStreamMethodGenerator(TConfiguration configuration, Type customReportType, Type parameterType) : base(configuration)
{
this.DomainType = customReportType;
this.CustomReportParameterType = parameterType;
}
public virtual string MethodName => $"Get{this.DomainType.Name}";
public virtual MethodIdentity Identity => CustomReportMethodIdentityType.GetCustomReport;
public virtual CodeMemberMethod GetContractMethod()
{
return new CodeMemberMethod
{
Name = this.MethodName,
ReturnType = this.ResultType
}.WithParameters(new[] { this.FacadeMethodParameterDeclaration })
.WithComment(this.GetComment());
}
protected virtual string GetComment()
{
return $"Get {this.DomainType.Name} custom report";
}
protected virtual CodeParameterDeclarationExpression FacadeMethodParameterDeclaration
{
get
{
var configuration = this.Configuration.Environment.ServerDTO;
var dtoTypeRef = configuration.GetCodeTypeReference(this.CustomReportParameterType, Framework.DomainDriven.DTOGenerator.FileType.StrictDTO);
return dtoTypeRef.ToParameterDeclarationExpression("modelDTO");
}
}
public virtual IEnumerable<CodeMemberMethod> GetFacadeMethods()
{
yield return new CodeMemberMethod
{
Name = this.MethodName,
ReturnType = this.ResultType,
Attributes = MemberAttributes.Public,
}
.WithParameters(new[] { this.FacadeMethodParameterDeclaration })
.WithComment(this.GetComment())
.WithStatements(this.GetFacadeMethodStatements());
}
private IEnumerable<CodeStatement> GetFacadeMethodStatements()
{
var evaluateDataParameterExpr = new CodeParameterDeclarationExpression(this.Configuration.EvaluateDataTypeReference, "evaluateData");
var evaluateMethod = new CodeThisReferenceExpression().ToMethodInvokeExpression(
"Evaluate",
DBSessionMode.Read.ToPrimitiveExpression(),
new CodeLambdaExpression
{
Parameters = { new CodeParameterDeclarationExpression { Name = evaluateDataParameterExpr.Name } },
Statements = new CodeStatementCollection(this.GetEvaluateStatements(evaluateDataParameterExpr).ToArray())
}).ToResultStatement(this.ResultType);
yield return evaluateMethod;
}
private IEnumerable<CodeStatement> GetEvaluateStatements(CodeParameterDeclarationExpression evaluateDataParameterExpr)
{
var customReportParameter = new CodeParameterDeclarationExpression(this.CustomReportParameterType, "customReportParameter");
var customReportParameterAssign = new CodeAssignStatement(customReportParameter, new CodeObjectCreateExpression(this.CustomReportParameterType));
yield return customReportParameterAssign;
var evaluateDataRef = evaluateDataParameterExpr.ToVariableReferenceExpression();
yield return this.FacadeMethodParameterDeclaration
.ToVariableReferenceExpression()
.ToMethodInvokeExpression(this.Configuration.Environment.ServerDTO.MapToDomainObjectMethodName, evaluateDataRef.GetMappingService(), customReportParameter.ToVariableReferenceExpression())
.ToExpressionStatement();
var reportBLLType = this.Configuration.Environment.ReportBLL.GetCodeTypeReference(this.DomainType, FileType.CustomReportBLL);
var customReport = reportBLLType.ToParameterDeclarationExpression("customReport");
var customReportAssign = reportBLLType.ToObjectCreateExpression(evaluateDataRef.GetContext())
.ToAssignStatement(customReport);
yield return customReportAssign;
var customReportStreamResult = new CodeParameterDeclarationExpression(typeof(IReportStream).ToTypeReference(), "reportStreamResult");
//TODO: MethodName from Expressin<Func....
var getReportStreamMethod = customReport.ToVariableReferenceExpression().ToMethodInvokeExpression("GetReportStream", customReportParameter.ToVariableReferenceExpression());
var customReportStreamResultAssign = new CodeAssignStatement(customReportStreamResult, getReportStreamMethod);
yield return customReportStreamResultAssign;
yield return new CodeThisReferenceExpression().ToMethodInvokeExpression("GetReportResult", customReportStreamResult.ToVariableReferenceExpression()).ToMethodReturnStatement();
}
public CodeTypeReference ResultType => typeof(Microsoft.AspNetCore.Mvc.FileStreamResult).ToTypeReference();
public Type CustomReportParameterType { get; }
public Type DomainType { get; }
}
}
| 46.51145 | 217 | 0.69309 |
9a53022dd5068611e95360c511ac18ada31cf6eb | 7,607 | cs | C# | Dashboard/va.gov.artemis.ui.data/Brokers/Observations/ObservationsFactory.cs | Veratics/Maternity-Tracker | bc28178d832960ca2f543b0667c075e33f45a93e | [
"Apache-2.0"
] | 2 | 2016-05-20T22:11:42.000Z | 2021-02-21T17:31:05.000Z | Dashboard/va.gov.artemis.ui.data/Brokers/Observations/ObservationsFactory.cs | Veratics/Maternity-Tracker | bc28178d832960ca2f543b0667c075e33f45a93e | [
"Apache-2.0"
] | 43 | 2015-05-15T22:21:21.000Z | 2017-01-06T17:39:09.000Z | Dashboard/va.gov.artemis.ui.data/Brokers/Observations/ObservationsFactory.cs | VHAINNOVATIONS/Maternity-Tracker | fca505195c458ca1e5f08fbfe40f7303cd1c25bb | [
"Apache-2.0"
] | 11 | 2015-05-20T15:15:40.000Z | 2017-09-05T13:43:15.000Z | // Originally submitted to OSEHRA 2/21/2017 by DSS, Inc.
// Authored by DSS, Inc. 2014-2017
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using VA.Gov.Artemis.CDA.Common;
using VA.Gov.Artemis.Commands.Dsio.Observation;
using VA.Gov.Artemis.UI.Data.Models.Edd;
using VA.Gov.Artemis.UI.Data.Models.Observations;
using VA.Gov.Artemis.UI.Data.Models.Pregnancy;
using VA.Gov.Artemis.Vista.Utility;
namespace VA.Gov.Artemis.UI.Data.Brokers.Observations
{
public static class ObservationsFactory
{
public static string NextContactCode { get { return "NextContactDate"; } }
public static string LastContactCode { get { return "LastContactDate"; } }
public static string NextChecklistCode { get { return "NextChecklistDate"; } }
public static string ContactCategory { get { return "Contact"; } }
public static string ChecklistCategory { get { return "Checklist"; } }
public static string OutcomeCategory { get { return "Outcome"; } }
public static string OutcomeTypeCode { get { return "OutcomeType"; } }
public static string PregnancyCategory { get { return "Pregnancy"; } }
public static string FetusBabyCountCode { get { return "FetusBabyCount"; } }
public static Observation CreateNextContactObservation(string patientDfn, DateTime nextContactDue)
{
return CreateObservation(patientDfn, nextContactDue, NextContactCode, "Contact", "The patient is due to be contacted on {0}");
}
public static Observation CreateLastContactObservation(string patientDfn, DateTime lastContactDate)
{
return CreateObservation(patientDfn, lastContactDate, LastContactCode, "Contact", "The last contact with the patient occurred on {0}");
}
public static Observation CreateNextChecklistObservation(string patientDfn, DateTime nextChecklistDate)
{
return CreateObservation(patientDfn, nextChecklistDate, NextChecklistCode, "Checklist", "The next checklist item is due on {0}");
}
public static List<Observation> CreateOutcomeObservations(string patientDfn, PregnancyOutcomeType outcomeType, string outcomeDate, string pregIen)
{
List<Observation> returnList = new List<Observation>();
Observation obs = new Observation()
{
PatientDfn = patientDfn,
Category = OutcomeCategory,
PregnancyIen = pregIen,
Code = OutcomeTypeCode,
CodeSystem = CDA.Common.CodingSystem.Other, //Observation.OtherCodeSystem,
EntryDate = DateTime.Now, //.ToString(VistaDates.VistADateFormatFour),
Description = "Pregnancy Outcome",
Value = outcomeType.ToString()
};
returnList.Add(obs);
if ((outcomeType == PregnancyOutcomeType.FullTermDelivery) || (outcomeType == PregnancyOutcomeType.PretermDelivery))
{
obs = new Observation()
{
PatientDfn = patientDfn,
Category = OutcomeCategory,
PregnancyIen = pregIen,
Code = "75092-7",
CodeSystem = CodingSystem.Loinc, //Observation.LoincCodeSystem,
EntryDate = DateTime.Now, //.ToString(VistaDates.VistADateFormatFour),
Description = "Birth Date of Fetus",
Value = outcomeDate
};
returnList.Add(obs);
}
return returnList;
}
private static Observation CreateObservation(string patientDfn, DateTime nextContactDue, string code, string category, string descriptionFormat)
{
// *** Create the observation ***
Observation obs = new Observation();
obs.PatientDfn = patientDfn;
obs.Ien = "";
obs.EntryDate = DateTime.Now; //.ToString(VistaDates.VistADateFormatFour);
obs.PregnancyIen = "";
obs.BabyIen = "";
obs.Category = category;
obs.CodeSystem = CodingSystem.Other; //Observation.OtherCodeSystem;
obs.Code = code;
obs.Description = string.Format(descriptionFormat, nextContactDue.ToString(VistaDates.VistADateOnlyFormat));
obs.Value = nextContactDue.ToString(VistaDates.VistADateOnlyFormat);
return obs;
}
//public static List<Observation> GetObservations(object obj, string patientDfn, string pregnancyIen, string babyIen)
//{
// List<Observation> returnList = new List<Observation>();
// PropertyInfo[] props = obj.GetType().GetProperties();
// foreach (PropertyInfo pi in props)
// {
// object orig = pi.GetValue(obj);
// if (pi.CanWrite)
// {
// var tempVal = pi.GetValue(obj);
// if (tempVal != null)
// {
// Observation obs = GetObservationPrototype(obj, patientDfn, pregnancyIen, babyIen);
// obs.Code = pi.Name;
// obs.Value = tempVal.ToString();
// returnList.Add(obs);
// }
// }
// }
// return returnList;
//}
//public static Observation GetObservationPrototype(object obj, string patientDfn, string pregnancyIen, string babyIen)
//{
// Observation returnVal = new Observation();
// returnVal.PatientDfn = patientDfn;
// returnVal.PregnancyIen = pregnancyIen;
// returnVal.BabyIen = babyIen;
// returnVal.Category = obj.GetType().Name;
// returnVal.Date = DateTime.Now.ToString(VistaDates.VistADateFormatFour);
// returnVal.CodeSystem = Observation.OtherCodeSystem;
// return returnVal;
//}
public static Observation CreateFetusBabyCountObservation(string patientDfn, string pregIen, int fetusBabyCount)
{
Observation obs = new Observation()
{
PatientDfn = patientDfn,
Category = PregnancyCategory,
PregnancyIen = pregIen,
Code = FetusBabyCountCode,
CodeSystem = CodingSystem.Other, //Observation.OtherCodeSystem,
EntryDate = DateTime.Now, //.ToString(VistaDates.VistADateFormatFour),
Description = "Fetus/Baby Count",
Value = fetusBabyCount.ToString()
};
return obs;
}
public static Observation CreateLmpObservation(string patientDfn, string pregIen, string lmp, bool approximate)
{
Observation obs = new Observation()
{
PatientDfn = patientDfn,
Category = PregnancyCategory,
PregnancyIen = pregIen,
Code = EddUtility.LmpDateCode,
CodeSystem = CodingSystem.Loinc, //Observation.LoincCodeSystem,
EntryDate = DateTime.Now, //.ToString(VistaDates.VistADateFormatFour),
Description = "Last Menstrual Period",
};
if (approximate)
obs.Value = string.Format("{0}|{1}", lmp, "A");
else
obs.Value = lmp;
return obs;
}
}
}
| 40.679144 | 154 | 0.592875 |
475b2bbae9bd6ad7622f1600b49e0c6e2dc19efb | 258 | cs | C# | FullStackTestBed.Web/BroadbandChoices/Api/Results/BundleApiResult.cs | sepharg/FullStackTestBed | ea5259d8eefcdd9089db74937c77a388b2d5e864 | [
"Apache-2.0"
] | null | null | null | FullStackTestBed.Web/BroadbandChoices/Api/Results/BundleApiResult.cs | sepharg/FullStackTestBed | ea5259d8eefcdd9089db74937c77a388b2d5e864 | [
"Apache-2.0"
] | null | null | null | FullStackTestBed.Web/BroadbandChoices/Api/Results/BundleApiResult.cs | sepharg/FullStackTestBed | ea5259d8eefcdd9089db74937c77a388b2d5e864 | [
"Apache-2.0"
] | null | null | null | using System.Collections.Generic;
using FullStackTestBed.Web.BroadbandChoices.Model;
namespace FullStackTestBed.Web.BroadbandChoices.Api.Results
{
public class BundleApiResult : ApiResult
{
public IList<Bundle> Bundles { get; set; }
}
} | 25.8 | 59 | 0.748062 |
f80c5039fdb8a3524dbb2d9419b36d6eab1519b1 | 5,051 | cs | C# | src/ACME.Protocol/RequestServices/DefaultRequestValidationService.cs | unix68/ACME-Server | 42cde2ec957a502911d39022502e0026be262190 | [
"MIT"
] | 5 | 2020-07-03T05:10:55.000Z | 2021-09-16T03:52:25.000Z | src/ACME.Protocol/RequestServices/DefaultRequestValidationService.cs | unix68/ACME-Server | 42cde2ec957a502911d39022502e0026be262190 | [
"MIT"
] | 2 | 2020-06-26T01:41:21.000Z | 2020-07-09T08:13:13.000Z | src/ACME.Protocol/RequestServices/DefaultRequestValidationService.cs | unix68/ACME-Server | 42cde2ec957a502911d39022502e0026be262190 | [
"MIT"
] | 4 | 2020-09-18T08:05:03.000Z | 2022-02-20T05:41:32.000Z | using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using TGIT.ACME.Protocol.HttpModel.Requests;
using TGIT.ACME.Protocol.Model;
using TGIT.ACME.Protocol.Model.Exceptions;
using TGIT.ACME.Protocol.Services;
using TGIT.ACME.Protocol.Storage;
namespace TGIT.ACME.Protocol.RequestServices
{
public class DefaultRequestValidationService : IRequestValidationService
{
private readonly IAccountService _accountService;
private readonly INonceStore _nonceStore;
private readonly ILogger<DefaultRequestValidationService> _logger;
private readonly string[] _supportedAlgs = new[] { "RS256" };
public DefaultRequestValidationService(IAccountService accountService, INonceStore nonceStore,
ILogger<DefaultRequestValidationService> logger)
{
_accountService = accountService;
_nonceStore = nonceStore;
_logger = logger;
}
public async Task ValidateRequestAsync(AcmeRawPostRequest request, AcmeHeader header,
string requestUrl, CancellationToken cancellationToken)
{
if (request is null)
throw new ArgumentNullException(nameof(request));
if (header is null)
throw new ArgumentNullException(nameof(header));
if (string.IsNullOrWhiteSpace(requestUrl))
throw new ArgumentNullException(nameof(requestUrl));
ValidateRequestHeader(header, requestUrl);
await ValidateNonceAsync(header.Nonce, cancellationToken);
await ValidateSignatureAsync(request, header, cancellationToken);
}
private void ValidateRequestHeader(AcmeHeader header, string requestUrl)
{
if (header is null)
throw new ArgumentNullException(nameof(header));
_logger.LogDebug("Attempting to validate AcmeHeader ...");
if (!Uri.IsWellFormedUriString(header.Url, UriKind.RelativeOrAbsolute))
throw new MalformedRequestException("Header Url is not well-formed.");
if (header.Url != requestUrl)
throw new NotAuthorizedException();
if (!_supportedAlgs.Contains(header.Alg))
throw new BadSignatureAlgorithmException();
if (header.Jwk != null && header.Kid != null)
throw new MalformedRequestException("Do not provide both Jwk and Kid.");
if (header.Jwk == null && header.Kid == null)
throw new MalformedRequestException("Provide either Jwk or Kid.");
_logger.LogDebug("successfully validated AcmeHeader.");
}
private async Task ValidateNonceAsync(string? nonce, CancellationToken cancellationToken)
{
_logger.LogDebug("Attempting to validate replay nonce ...");
if (string.IsNullOrWhiteSpace(nonce))
{
_logger.LogDebug($"Nonce was empty.");
throw new BadNonceException();
}
if (!await _nonceStore.TryRemoveNonceAsync(new Nonce(nonce), cancellationToken))
{
_logger.LogDebug($"Nonce was invalid.");
throw new BadNonceException();
}
_logger.LogDebug("successfully validated replay nonce.");
}
private async Task ValidateSignatureAsync(AcmeRawPostRequest request, AcmeHeader header, CancellationToken cancellationToken)
{
if (request is null)
throw new ArgumentNullException(nameof(request));
if (header is null)
throw new ArgumentNullException(nameof(header));
_logger.LogDebug("Attempting to validate signature ...");
var jwk = header.Jwk;
if(jwk == null)
{
try
{
var accountId = header.GetAccountId();
var account = await _accountService.LoadAcountAsync(accountId, cancellationToken);
jwk = account?.Jwk;
}
catch (InvalidOperationException)
{
throw new MalformedRequestException("KID could not be found.");
}
}
if(jwk == null)
throw new MalformedRequestException("Could not load JWK.");
var securityKey = jwk.SecurityKey;
using var signatureProvider = new AsymmetricSignatureProvider(securityKey, header.Alg);
var plainText = System.Text.Encoding.UTF8.GetBytes($"{request.Header}.{request.Payload ?? ""}");
var signature = Base64UrlEncoder.DecodeBytes(request.Signature);
if (!signatureProvider.Verify(plainText, signature))
throw new MalformedRequestException("The signature could not be verified");
_logger.LogDebug("successfully validated signature.");
}
}
}
| 39.155039 | 133 | 0.626213 |
f829e4491e07be60b0c6852609baa2c4d6a4a18f | 1,457 | cs | C# | EDDNResponder/EDDNCommodity.cs | Juggernaut93/EDDI | 6af42ee4b8b1f5f172d267c3f84bcc1f8201516b | [
"Apache-2.0"
] | null | null | null | EDDNResponder/EDDNCommodity.cs | Juggernaut93/EDDI | 6af42ee4b8b1f5f172d267c3f84bcc1f8201516b | [
"Apache-2.0"
] | null | null | null | EDDNResponder/EDDNCommodity.cs | Juggernaut93/EDDI | 6af42ee4b8b1f5f172d267c3f84bcc1f8201516b | [
"Apache-2.0"
] | null | null | null | using EddiDataDefinitions;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace EDDNResponder
{
public class EDDNCommodity
{
// Schema reference: https://github.com/EDSM-NET/EDDN/blob/master/schemas/commodity-v3.0.json
public string name;
public int meanPrice;
public int buyPrice;
public int stock;
public dynamic stockBracket; // Possible values are 0, 1, 2, 3, or ""
public int sellPrice;
public int demand;
public dynamic demandBracket; // Possible values are 0, 1, 2, 3, or ""
public List<string> statusFlags = new List<string>();
public bool ShouldSerializestatusFlags()
{
// Don't serialize status flags if they are empty as the schema requires that if present they contain at least 1 element
return (statusFlags != null && statusFlags.Count > 0);
}
public EDDNCommodity(CommodityMarketQuote quote)
{
name = quote.definition.edname;
meanPrice = quote.definition.avgprice;
buyPrice = quote.buyprice;
stock = quote.stock;
stockBracket = quote.stockbracket;
sellPrice = quote.sellprice;
demand = quote.demand;
demandBracket = quote.demandbracket;
if (quote.StatusFlags.Count > 0)
{
statusFlags = quote.StatusFlags;
}
}
}
}
| 33.883721 | 132 | 0.606726 |
b0970b58d7e7c5ffaea8fbc6723db462962cba31 | 329 | cs | C# | src/sabatex.V1C8.Models/Metadata/DateQualifiersType.cs | sabatex/1C8 | f3dc916d3a3881585452e70ed3e2fb4c299262b1 | [
"MIT"
] | 1 | 2020-08-31T15:08:27.000Z | 2020-08-31T15:08:27.000Z | src/sabatex.V1C8.Models/Metadata/DateQualifiersType.cs | sabatex/V1C8 | f3dc916d3a3881585452e70ed3e2fb4c299262b1 | [
"MIT"
] | null | null | null | src/sabatex.V1C8.Models/Metadata/DateQualifiersType.cs | sabatex/V1C8 | f3dc916d3a3881585452e70ed3e2fb4c299262b1 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Text;
namespace sabatex.V1C8.Models.Metadata
{
public class DateQualifiersType
{
public string DateFractions { get; set; }
public DateQualifiersType(string dateFractions)
{
DateFractions = dateFractions;
}
}
}
| 20.5625 | 55 | 0.662614 |
83ac5ce9a390132953a151a6357cd9bf02b7eb54 | 107 | cs | C# | System.Speech/System.Speech.Synthesis.TtsEngine/ProsodyUnit.cs | aaasoft/Unoffical.System.Speech | 708fcd4527d6093ff29ba39d1d14d406e59f7d44 | [
"MIT"
] | 1 | 2021-01-17T16:03:36.000Z | 2021-01-17T16:03:36.000Z | System.Speech/System.Speech.Synthesis.TtsEngine/ProsodyUnit.cs | aaasoft/Unoffical.System.Speech | 708fcd4527d6093ff29ba39d1d14d406e59f7d44 | [
"MIT"
] | null | null | null | System.Speech/System.Speech.Synthesis.TtsEngine/ProsodyUnit.cs | aaasoft/Unoffical.System.Speech | 708fcd4527d6093ff29ba39d1d14d406e59f7d44 | [
"MIT"
] | null | null | null | namespace System.Speech.Synthesis.TtsEngine
{
public enum ProsodyUnit
{
Default,
Hz,
Semitone
}
}
| 10.7 | 43 | 0.719626 |
becfe3ff2defb955df349799be231b19d30b8542 | 2,557 | cs | C# | RZ.Server/RZ.Plugin.Feedback.Proxy/RZ.Plugin.Feedback.Proxy.cs | stijni/ruckzuck | bb3f7c85e225a96a8ebd278c0e55ad7f609cf0d1 | [
"MS-PL"
] | 145 | 2017-04-07T21:18:11.000Z | 2022-03-22T21:36:58.000Z | RZ.Server/RZ.Plugin.Feedback.Proxy/RZ.Plugin.Feedback.Proxy.cs | stijni/ruckzuck | bb3f7c85e225a96a8ebd278c0e55ad7f609cf0d1 | [
"MS-PL"
] | 168 | 2017-04-07T18:11:59.000Z | 2022-03-15T14:31:58.000Z | RZ.Server/RZ.Plugin.Feedback.Proxy/RZ.Plugin.Feedback.Proxy.cs | stijni/ruckzuck | bb3f7c85e225a96a8ebd278c0e55ad7f609cf0d1 | [
"MS-PL"
] | 19 | 2017-11-05T05:01:35.000Z | 2022-01-30T05:56:49.000Z | using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using RZ.Server;
using RZ.Server.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace RZ.Plugin.Feedback.Azure
{
public class Plugin_Feedback : IFeedback
{
private IMemoryCache _cache;
public string Name
{
get
{
return Assembly.GetExecutingAssembly().ManifestModule.Name;
}
}
public Dictionary<string, string> Settings { get; set; }
public void Init(string PluginPath)
{
//Check if MemoryCache is initialized
if (_cache != null)
{
_cache.Dispose();
}
_cache = new MemoryCache(new MemoryCacheOptions());
if (Settings == null)
Settings = new Dictionary<string, string>();
}
public Task<bool> StoreFeedback(string name = "", string ver = "", string man = "", string shortname = "", string feedback = "", string user = "", bool? failure = null, string ip = "", string customerid = "rzproxy")
{
var tFeedback = Task.Run(() =>
{
try
{
string ok = "false";
if (failure == false)
ok = "true";
if (failure == true)
{
Console.WriteLine("Failure: " + name + " " + ver + " Error:" + feedback);
}
else
{
Console.WriteLine("Success: " + name + " " + ver);
}
RZRestAPIv2.StoreFeedback(name, ver, man, ok, user, feedback, customerid);
return true;
}
catch
{
return false;
}
});
return tFeedback;
}
public void PushBullet(string Message, string Body)
{
}
public Task<bool> SendNotification(string message = "", string body = "", string customerid = "")
{
Task<bool> t = Task<bool>.Run(() =>
{
PushBullet(message, body);
return true;
});
return t;
}
}
}
| 27.202128 | 223 | 0.479859 |
4bd6f96f3865e7780d3e2b35b56983bb2c2d89ef | 586 | cs | C# | BTCPayServer/AtomicSwaps/Preimage.cs | queilawithaQ/btcpayserver | 8c8cdc232a88f307a8918f273e459b4f7f9af1f8 | [
"MIT"
] | null | null | null | BTCPayServer/AtomicSwaps/Preimage.cs | queilawithaQ/btcpayserver | 8c8cdc232a88f307a8918f273e459b4f7f9af1f8 | [
"MIT"
] | null | null | null | BTCPayServer/AtomicSwaps/Preimage.cs | queilawithaQ/btcpayserver | 8c8cdc232a88f307a8918f273e459b4f7f9af1f8 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NBitcoin;
using NBitcoin.Crypto;
namespace BTCPayServer.AtomicSwaps
{
public class Preimage
{
public Preimage()
{
Bytes = RandomUtils.GetBytes(32);
}
public Preimage(byte[] bytes)
{
Bytes = bytes;
}
public byte[] Bytes
{
get; set;
}
public uint160 GetHash()
{
return new uint160(Hashes.Hash160(Bytes, Bytes.Length));
}
}
}
| 18.3125 | 68 | 0.549488 |
07ed4e225b2e38d84d4d8c1ed04507650a4f13bf | 655 | cs | C# | HowTo/DataAccess/SelectByKeySql.cs | igor-tkachev/bltoolkit | b9149ffa5c9826a01e93de81907a3eae56cbe051 | [
"MIT"
] | 152 | 2015-01-09T14:10:22.000Z | 2022-02-12T08:50:45.000Z | HowTo/DataAccess/SelectByKeySql.cs | igor-tkachev/bltoolkit | b9149ffa5c9826a01e93de81907a3eae56cbe051 | [
"MIT"
] | 97 | 2015-01-28T15:38:45.000Z | 2021-07-23T07:24:38.000Z | HowTo/DataAccess/SelectByKeySql.cs | igor-tkachev/bltoolkit | b9149ffa5c9826a01e93de81907a3eae56cbe051 | [
"MIT"
] | 70 | 2015-01-16T14:02:18.000Z | 2022-02-12T08:50:53.000Z | using System;
using NUnit.Framework;
using BLToolkit.Data;
using BLToolkit.DataAccess;
namespace HowTo.DataAccess
{
[TestFixture]
public class SelectByKeySql
{
[Test]
public void Test1()
{
/*[a]*/SqlQuery<Person> query = new SqlQuery<Person>()/*[/a]*/;
Person person = query./*[a]*/SelectByKey(1)/*[/a]*/;
Assert.IsNotNull(person);
}
[Test]
public void Test2()
{
using (DbManager db = new DbManager())
{
/*[a]*/SqlQuery<Person> query = new SqlQuery<Person>()/*[/a]*/;
Person person = query./*[a]*/SelectByKey(db, 1)/*[/a]*/;
Assert.IsNotNull(person);
}
}
}
}
| 17.236842 | 68 | 0.580153 |
751ca8c7e11277698ef805b2fa2e27250a7b33e7 | 291 | cs | C# | src/Keyvalet/ViewModels/WelcomeViewModel.cs | mitchdenny/keyvalet | 2ab03b5a92440a3991aba63a3e9ba212215d9dc9 | [
"MIT"
] | null | null | null | src/Keyvalet/ViewModels/WelcomeViewModel.cs | mitchdenny/keyvalet | 2ab03b5a92440a3991aba63a3e9ba212215d9dc9 | [
"MIT"
] | null | null | null | src/Keyvalet/ViewModels/WelcomeViewModel.cs | mitchdenny/keyvalet | 2ab03b5a92440a3991aba63a3e9ba212215d9dc9 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Keyvalet.ViewModels
{
public class WelcomeViewModel : KeyvaletViewModel
{
public WelcomeViewModel(Uri uri) : base(uri)
{
}
}
}
| 18.1875 | 53 | 0.690722 |
8d57dc9e7ebe3fbd4dce8336bd94ed47f393d9fe | 5,745 | cs | C# | MaasOne.Yahoo/Finance/YahooFinance/QuoteOptionsDownload_DesktopSpecific.cs | kflu/yahoo-finance-managed | 014bd22a29713ee6576881de883eb79a9d883f9e | [
"Apache-2.0"
] | null | null | null | MaasOne.Yahoo/Finance/YahooFinance/QuoteOptionsDownload_DesktopSpecific.cs | kflu/yahoo-finance-managed | 014bd22a29713ee6576881de883eb79a9d883f9e | [
"Apache-2.0"
] | null | null | null | MaasOne.Yahoo/Finance/YahooFinance/QuoteOptionsDownload_DesktopSpecific.cs | kflu/yahoo-finance-managed | 014bd22a29713ee6576881de883eb79a9d883f9e | [
"Apache-2.0"
] | null | null | null | // ******************************************************************************
// **
// ** Yahoo! Managed
// ** Written by Marius Häusler 2012
// ** It would be pleasant, if you contact me when you are using this code.
// ** Contact: YahooFinanceManaged@gmail.com
// ** Project Home: http://code.google.com/p/yahoo-finance-managed/
// **
// ******************************************************************************
// **
// ** Copyright 2012 Marius Häusler
// **
// ** Licensed under the Apache License, Version 2.0 (the "License");
// ** you may not use this file except in compliance with the License.
// ** You may obtain a copy of the License at
// **
// ** http://www.apache.org/licenses/LICENSE-2.0
// **
// ** Unless required by applicable law or agreed to in writing, software
// ** distributed under the License is distributed on an "AS IS" BASIS,
// ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// ** See the License for the specific language governing permissions and
// ** limitations under the License.
// **
// ******************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
namespace MaasOne.Finance.YahooFinance
{
public partial class QuoteOptionsDownload
{
public Base.Response<QuoteOptionsResult> Download(IID managedID)
{
if (managedID == null)
{
throw new ArgumentNullException("managedID", "The passed ID is null.");
}
else
{
return this.Download(managedID.ID);
}
}
public Base.Response<QuoteOptionsResult> Download(IEnumerable<IID> managedIDs)
{
if (managedIDs == null)
{
throw new ArgumentNullException("managedIDs", "The passed list is null.");
}
else
{
return this.Download(FinanceHelper.IIDsToStrings(managedIDs));
}
}
public Base.Response<QuoteOptionsResult> Download(IID managedID, System.DateTime expirationDate)
{
if (managedID == null)
{
throw new ArgumentNullException("managedID", "The passed ID is null.");
}
else
{
return this.Download(managedID.ID, expirationDate);
}
}
public Base.Response<QuoteOptionsResult> Download(IEnumerable<IID> managedIDs, System.DateTime expirationDate)
{
if (managedIDs == null)
{
throw new ArgumentNullException("managedIDs", "The passed list is null.");
}
else
{
return this.Download(FinanceHelper.IIDsToStrings(managedIDs), expirationDate);
}
}
public Base.Response<QuoteOptionsResult> Download(IID managedID, IEnumerable<System.DateTime> expirationDates)
{
if (managedID == null)
{
throw new ArgumentNullException("managedID", "The passed ID is null.");
}
else
{
return this.Download(managedID.ID, expirationDates);
}
}
public Base.Response<QuoteOptionsResult> Download(string unmanagedID)
{
if (unmanagedID == string.Empty)
{
throw new ArgumentNullException("unmanagedID", "The passed ID is empty.");
}
else
{
return this.Download(new string[] { unmanagedID });
}
}
public Base.Response<QuoteOptionsResult> Download(IEnumerable<string> unmanagedIDs)
{
if (unmanagedIDs == null)
{
throw new ArgumentNullException("unmanagedIDs", "The passed list is null.");
}
else
{
return this.Download(new QuoteOptionsDownloadSettings() { IDs = MyHelper.EnumToArray(unmanagedIDs) });
}
}
public Base.Response<QuoteOptionsResult> Download(string unmanagedID, System.DateTime expirationDate)
{
if (unmanagedID == string.Empty)
{
throw new ArgumentNullException("unmanagedID", "The passed ID is empty.");
}
else
{
return this.Download(new string[] { unmanagedID }, expirationDate);
}
}
public Base.Response<QuoteOptionsResult> Download(IEnumerable<string> unmanagedIDs, System.DateTime expirationDate)
{
if (unmanagedIDs == null)
{
throw new ArgumentNullException("unmanagedIDs", "The passed list is null.");
}
else
{
return this.Download(new QuoteOptionsDownloadSettings() { IDs = MyHelper.EnumToArray(unmanagedIDs), ExpirationDates = new System.DateTime[] { expirationDate } });
}
}
public Base.Response<QuoteOptionsResult> Download(string unmanagedID, IEnumerable<System.DateTime> expirationDates)
{
if (unmanagedID == string.Empty)
{
throw new ArgumentNullException("unmanagedID", "The passed ID is empty.");
}
else
{
return this.Download(new QuoteOptionsDownloadSettings() { IDs = new string[] { unmanagedID }, ExpirationDates = MyHelper.EnumToArray(expirationDates) });
}
}
public Base.Response<QuoteOptionsResult> Download(QuoteOptionsDownloadSettings settings)
{
return base.Download(settings);
}
}
}
| 37.064516 | 178 | 0.545866 |
22ccb6df1aedc3b8527a031b7e04af50fcaf69e9 | 2,372 | cs | C# | src/Web/Pages/Data/ListenLaterService.cs | Glepooek/dotnet-podcasts | 0e0c708c032e07e4a130c9d219f3ac37eb5e4458 | [
"MIT"
] | 869 | 2021-12-02T17:55:54.000Z | 2022-03-31T13:14:35.000Z | src/Web/Pages/Data/ListenLaterService.cs | Glepooek/dotnet-podcasts | 0e0c708c032e07e4a130c9d219f3ac37eb5e4458 | [
"MIT"
] | 29 | 2021-12-03T18:04:28.000Z | 2022-03-26T09:42:44.000Z | src/Web/Pages/Data/ListenLaterService.cs | Glepooek/dotnet-podcasts | 0e0c708c032e07e4a130c9d219f3ac37eb5e4458 | [
"MIT"
] | 251 | 2021-12-02T18:15:56.000Z | 2022-03-31T17:32:40.000Z | using Podcast.Components;
using Podcast.Pages.Models;
namespace Podcast.Pages.Data;
public class ListenLaterService
{
private const string ListenLaterKey = "ListenLater";
private readonly LocalStorageInterop _localStorage;
private readonly SemaphoreSlim _semaphore = new(1);
private HashSet<EpisodeInfo> _episodes = default!;
private bool _isInitialized = false;
public event Action<ICollection<EpisodeInfo>>? EpisodesChanged;
public ListenLaterService(LocalStorageInterop localStorage)
{
_localStorage = localStorage;
}
public async Task InitializeAsync()
{
if (!_isInitialized)
{
try
{
await _semaphore.WaitAsync();
if (!_isInitialized)
{
var episodes = await _localStorage.GetItem<EpisodeInfo[]>(ListenLaterKey);
_episodes = episodes?.ToHashSet() ?? new();
_isInitialized = true;
}
}
finally
{
_semaphore.Release();
}
}
}
public async Task<ICollection<EpisodeInfo>> GetEpisodesAsync()
{
await InitializeAsync();
return _episodes;
}
public async Task<bool> IsListenLaterEpisodeAsync(Guid episodeId)
{
await InitializeAsync();
return _episodes?.Any(s => s.Id == episodeId) ?? false;
}
public Task ToggleListenLaterEpisodeAsync(EpisodeInfo episode, bool isListenLater) =>
isListenLater ? AddListenLaterEpisodeAsync(episode) : RemoveListenLaterEpisodeAsync(episode.Id);
public async Task AddListenLaterEpisodeAsync(EpisodeInfo episode)
{
await InitializeAsync();
if (!_episodes.Any(s => s.Id == episode.Id))
{
_episodes.Add(episode);
await _localStorage.SetItem(ListenLaterKey, _episodes);
EpisodesChanged?.Invoke(_episodes);
}
}
public async Task RemoveListenLaterEpisodeAsync(Guid episodeId)
{
await InitializeAsync();
var episode = _episodes.FirstOrDefault(s => s.Id == episodeId);
if (episode != null)
{
_episodes.Remove(episode);
await _localStorage.SetItem(ListenLaterKey, _episodes);
EpisodesChanged?.Invoke(_episodes);
}
}
}
| 29.283951 | 104 | 0.613406 |
cac3c7f4ed6a2da0ee2a1dbecd667377a0ca3c70 | 13,470 | cs | C# | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs | bbarry/roslyn | 53f2a8744e08c70cd42e38e3d5571a957ddaaf69 | [
"Apache-2.0"
] | 1 | 2020-03-14T21:50:33.000Z | 2020-03-14T21:50:33.000Z | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs | bbarry/roslyn | 53f2a8744e08c70cd42e38e3d5571a957ddaaf69 | [
"Apache-2.0"
] | null | null | null | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs | bbarry/roslyn | 53f2a8744e08c70cd42e38e3d5571a957ddaaf69 | [
"Apache-2.0"
] | 1 | 2020-07-09T09:42:18.000Z | 2020-07-09T09:42:18.000Z | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpAutomaticBraceCompletion : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpAutomaticBraceCompletion(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpAutomaticBraceCompletion))
{
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Braces_InsertionAndTabCompleting()
{
SetUpEditor(@"
class C {
void Foo() {
$$
}
}");
SendKeys("if (true) {");
VerifyCurrentLineText("if (true) { $$}", assertCaretPosition: true);
SendKeys(VirtualKey.Tab);
VerifyCurrentLineText("if (true) { }$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Braces_Overtyping()
{
SetUpEditor(@"
class C {
void Foo() {
$$
}
}");
SendKeys("if (true) {");
VerifyCurrentLineText("if (true) { $$}", assertCaretPosition: true);
SendKeys("}");
VerifyCurrentLineText("if (true) { }$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Braces_OnReturnNoFormattingOnlyIndentationBeforeCloseBrace()
{
SetUpEditor(@"
class C {
void Foo() {
$$
}
}");
SendKeys(
"if (true) {",
VirtualKey.Enter,
"var a = 1;");
VerifyTextContains(@"
class C {
void Foo() {
if (true)
{
var a = 1;$$
}
}
}",
assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Braces_OnReturnOvertypingTheClosingBrace()
{
SetUpEditor(@"
class C {
void Foo() {
$$
}
}");
SendKeys(
"if (true) {",
VirtualKey.Enter,
"var a = 1;",
'}');
VerifyTextContains(@"
class C {
void Foo() {
if (true)
{
var a = 1;
}$$
}
}",
assertCaretPosition: true);
}
[WorkItem(653540, "DevDiv")]
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Braces_OnReturnWithNonWhitespaceSpanInside()
{
SendKeys(
"class A { int i;",
VirtualKey.Enter);
VerifyTextContains(@"class A { int i;
$$}",
assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Paren_InsertionAndTabCompleting()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys("void Foo(");
VerifyCurrentLineText("void Foo($$)", assertCaretPosition: true);
SendKeys("int x", VirtualKey.Tab);
VerifyCurrentLineText("void Foo(int x)$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Paren_Overtyping()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys(
"void Foo(",
VirtualKey.Escape,
")");
VerifyCurrentLineText("void Foo()$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void SquareBracket_Insertion()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys("int [");
VerifyCurrentLineText("int [$$]", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void SquareBracket_Overtyping()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys("int [", ']');
VerifyCurrentLineText("int []$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void DoubleQuote_InsertionAndTabCompletion()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys("string str = \"", VirtualKey.Tab);
VerifyCurrentLineText("string str = \"\"$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void DoubleQuote_InsertionAndOvertyping()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys("string str = \"Hi Roslyn!", '"');
VerifyCurrentLineText("string str = \"Hi Roslyn!\"$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void AngleBracket_PossibleGenerics_InsertionAndCompletion()
{
SetUpEditor(@"
class C {
//field
$$
}");
SendKeys("System.Action<", VirtualKey.Tab);
VerifyCurrentLineText("System.Action<>$$", assertCaretPosition: true);
SetUpEditor(@"
class C {
//method decl
$$
}");
SendKeys("void GenericMethod<", VirtualKey.Tab);
VerifyCurrentLineText("void GenericMethod<>$$", assertCaretPosition: true);
SetUpEditor(@"
class C {
//delegate
$$
}");
SendKeys("delegate void Del<");
VerifyCurrentLineText("delegate void Del<$$>", assertCaretPosition: true);
SetUpEditor(@"
//using directive
$$
");
SendKeys("using ActionOfT = System.Action<");
VerifyCurrentLineText("using ActionOfT = System.Action<$$>", assertCaretPosition: true);
SetUpEditor(@"
//class
$$
");
SendKeys("class GenericClass<", '>');
VerifyCurrentLineText("class GenericClass<>$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void SingleQuote_InsertionAndCompletion()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys("char c = '");
VerifyCurrentLineText("char c = '$$'", assertCaretPosition: true);
SendKeys(VirtualKey.Delete, VirtualKey.Backspace);
SendKeys("'\u6666", "'");
VerifyCurrentLineText("char c = '\u6666'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Nested_AllKinds()
{
SetUpEditor(@"
class Bar<U>
{
T Foo<T>(T t) { return t; }
void M()
{
$$
}
}");
SendKeys(
"var arr=new object[,]{{Foo(0",
VirtualKey.Tab,
VirtualKey.Tab,
",{Foo(Foo(\"hello",
VirtualKey.Tab,
VirtualKey.Tab,
VirtualKey.Tab,
VirtualKey.Tab,
VirtualKey.Tab,
';');
VerifyCurrentLineText("var arr = new object[,] { { Foo(0) }, { Foo(Foo(\"hello\")) } };$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionInSingleLineComments()
{
SetUpEditor(@"
class C {
// $$
}");
SendKeys("{([\"'");
VerifyCurrentLineText("// {([\"'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionInMultiLineComments()
{
SetUpEditor(@"
class C {
/*
$$
*/
}");
SendKeys("{([\"'");
VerifyCurrentLineText("{([\"'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionStringVerbatimStringOrCharLiterals()
{
SetUpEditor(@"
class C {
$$
}");
SendKeys("string s = \"{([<'");
VerifyCurrentLineText("string s = \"{([<'\"$$", assertCaretPosition: true);
SendKeys(VirtualKey.End, ';', VirtualKey.Enter);
SendKeys("string y = @\"{([<'");
VerifyCurrentLineText("string y = @\"{([<'\"$$", assertCaretPosition: true);
SendKeys(VirtualKey.End, ';', VirtualKey.Enter);
SendKeys("char ch = '{([<\"");
VerifyCurrentLineText("char ch = '{([<\"'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionInXmlDocComments()
{
SetUpEditor(@"
$$
class C { }");
SendKeys(
"///",
"{([<\"'");
VerifyCurrentLineText("/// {([<\"'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionInDisabledPreprocesser()
{
SetUpEditor(@"
class C {
#if false
$$
#endif
}");
SendKeys("void Foo(");
VerifyCurrentLineText("void Foo($$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionAfterRegionPreprocesser()
{
SetUpEditor(@"
#region $$
#endregion
");
SendKeys("{([<\"'");
VerifyCurrentLineText("#region {([<\"'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionAfterEndregionPreprocesser()
{
SetUpEditor(@"
#region
#endregion $$
");
SendKeys("{([<\"'");
VerifyCurrentLineText("#endregion {([<\"'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionAfterIfPreprocesser()
{
SetUpEditor(@"
#if $$
");
SendKeys("{([<\"'");
VerifyCurrentLineText("#if {([<\"'$$", assertCaretPosition: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Negative_NoCompletionAfterPragmaPreprocesser()
{
SetUpEditor(@"
#pragma $$
");
SendKeys("{([<\"'");
VerifyCurrentLineText("#pragma {([<\"'$$", assertCaretPosition: true);
}
[WorkItem(651954, "DevDiv")]
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void InteractionWithOverrideStubGeneration()
{
SetUpEditor(@"
class A
{
public virtual void Foo() { }
}
class B : A
{
// type ""override Foo(""
$$
}
");
SendKeys("override Foo(");
VerifyTextContains(@"
class B : A
{
// type ""override Foo(""
public override void Foo()
{
base.Foo();
}
}");
}
[WorkItem(531107, "DevDiv")]
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void InteractionWithCompletionList()
{
SetUpEditor(@"
using System.Collections.Generic;
class C
{
void M()
{
List<int> li = $$
}
}
");
SendKeys("new Li(", VirtualKey.Tab);
VerifyCurrentLineText("List<int> li = new List<int>($$)", assertCaretPosition: true);
}
[WorkItem(823958, "DevDiv")]
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void AutoBraceCompleteDoesNotFormatBracePairInInitializers()
{
SetUpEditor(@"
class C
{
void M()
{
var x = $$
}
}
");
SendKeys("new int[]{");
VerifyCurrentLineText("var x = new int[] {$$}", assertCaretPosition: true);
}
[WorkItem(823958, "DevDiv")]
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void AutoBraceCompleteDoesNotFormatBracePairInObjectCreationExpression()
{
SetUpEditor(@"
class C
{
void M()
{
var x = $$
}
}
");
SendKeys("new {");
VerifyCurrentLineText("var x = new {$$}", assertCaretPosition: true);
}
[WorkItem(823958, "DevDiv")]
[Fact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void AutoBraceCompleteFormatsBracePairInClassDeclarationAndAutoProperty()
{
SetUpEditor(@"
class $$
");
SendKeys("C{");
VerifyCurrentLineText("class C { $$}", assertCaretPosition: true);
SendKeys(
VirtualKey.Enter,
"int Prop {");
VerifyTextContains(@"
class C
{
int Prop { $$}
}",
assertCaretPosition: true);
}
}
} | 25.657143 | 161 | 0.553526 |
889ccc2dacb10421a2402d3631d227dfecc6699e | 351 | cs | C# | src/TRuDI.Backend/Models/ContractContainer.cs | flobecker/trudi-koala | 924f5b620708a94a977b0bfc34140d969a4d5de8 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/TRuDI.Backend/Models/ContractContainer.cs | flobecker/trudi-koala | 924f5b620708a94a977b0bfc34140d969a4d5de8 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/TRuDI.Backend/Models/ContractContainer.cs | flobecker/trudi-koala | 924f5b620708a94a977b0bfc34140d969a4d5de8 | [
"Apache-2.0",
"MIT"
] | null | null | null | namespace TRuDI.Backend.Models
{
using TRuDI.HanAdapter.Interface;
/// <summary>
/// Container class used to group TAF-6 to the corresponding TAF-x contract.
/// </summary>
public class ContractContainer
{
public ContractInfo Contract { get; set; }
public ContractInfo Taf6 { get; set; }
}
}
| 25.071429 | 81 | 0.618234 |
2a107bc22490ceab67402d04c6b298b580259b3b | 14,092 | cs | C# | Source/Krypton Toolkit Suite Extended/Applications/Palette Explorer/UX/PaletteColourExporter.cs | Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461 | a03bbfc132e6f56775d5f3044f676b4dfdc365f7 | [
"BSD-3-Clause"
] | 43 | 2019-01-16T21:08:36.000Z | 2020-03-02T06:14:28.000Z | Source/Krypton Toolkit Suite Extended/Applications/Palette Explorer/UX/PaletteColourExporter.cs | Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461 | a03bbfc132e6f56775d5f3044f676b4dfdc365f7 | [
"BSD-3-Clause"
] | 82 | 2018-09-29T09:56:33.000Z | 2020-02-14T23:03:16.000Z | Source/Krypton Toolkit Suite Extended/Applications/Palette Explorer/UX/PaletteColourExporter.cs | Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461 | a03bbfc132e6f56775d5f3044f676b4dfdc365f7 | [
"BSD-3-Clause"
] | 7 | 2019-02-06T05:41:54.000Z | 2019-10-28T08:33:36.000Z | using ComponentFactory.Krypton.Toolkit;
using Microsoft.WindowsAPICodePack.Dialogs;
using PaletteExplorer.Classes;
using PaletteExplorer.Enumerations;
using System;
using System.IO;
namespace PaletteExplorer.UX
{
public class PaletteColourExporter : KryptonForm
{
#region Designer Code
private KryptonPanel kryptonPanel2;
private KryptonButton kbtnClose;
private KryptonLabel lblColourOutput;
private KryptonPanel kryptonPanel1;
private KryptonButton kbtnExport;
private KryptonButton kbtnBrowse;
private KryptonTextBox ktxtConfigurationPath;
private KryptonLabel kryptonLabel2;
private KryptonComboBox kcmbConfigurationType;
private KryptonLabel kryptonLabel1;
private System.Windows.Forms.Panel panel1;
private void InitializeComponent()
{
this.kryptonPanel2 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kbtnExport = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kbtnClose = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.lblColourOutput = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.panel1 = new System.Windows.Forms.Panel();
this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kbtnBrowse = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.ktxtConfigurationPath = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kcmbConfigurationType = new ComponentFactory.Krypton.Toolkit.KryptonComboBox();
this.kryptonLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).BeginInit();
this.kryptonPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit();
this.kryptonPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kcmbConfigurationType)).BeginInit();
this.SuspendLayout();
//
// kryptonPanel2
//
this.kryptonPanel2.Controls.Add(this.kbtnExport);
this.kryptonPanel2.Controls.Add(this.kbtnClose);
this.kryptonPanel2.Controls.Add(this.lblColourOutput);
this.kryptonPanel2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.kryptonPanel2.Location = new System.Drawing.Point(0, 130);
this.kryptonPanel2.Name = "kryptonPanel2";
this.kryptonPanel2.Size = new System.Drawing.Size(684, 54);
this.kryptonPanel2.TabIndex = 5;
//
// kbtnExport
//
this.kbtnExport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.kbtnExport.AutoSize = true;
this.kbtnExport.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnExport.Enabled = false;
this.kbtnExport.Location = new System.Drawing.Point(557, 12);
this.kbtnExport.Name = "kbtnExport";
this.kbtnExport.Size = new System.Drawing.Size(58, 30);
this.kbtnExport.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnExport.TabIndex = 65;
this.kbtnExport.Values.Text = "E&xport";
this.kbtnExport.Click += new System.EventHandler(this.KbtnExport_Click);
//
// kbtnClose
//
this.kbtnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.kbtnClose.AutoSize = true;
this.kbtnClose.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnClose.Location = new System.Drawing.Point(621, 12);
this.kbtnClose.Name = "kbtnClose";
this.kbtnClose.Size = new System.Drawing.Size(51, 30);
this.kbtnClose.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnClose.TabIndex = 64;
this.kbtnClose.Values.Text = "&Close";
//
// lblColourOutput
//
this.lblColourOutput.Location = new System.Drawing.Point(12, 13);
this.lblColourOutput.Name = "lblColourOutput";
this.lblColourOutput.Size = new System.Drawing.Size(6, 2);
this.lblColourOutput.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblColourOutput.TabIndex = 63;
this.lblColourOutput.Values.Text = "";
//
// panel1
//
this.panel1.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 127);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(684, 3);
this.panel1.TabIndex = 6;
//
// kryptonPanel1
//
this.kryptonPanel1.Controls.Add(this.kbtnBrowse);
this.kryptonPanel1.Controls.Add(this.ktxtConfigurationPath);
this.kryptonPanel1.Controls.Add(this.kryptonLabel2);
this.kryptonPanel1.Controls.Add(this.kcmbConfigurationType);
this.kryptonPanel1.Controls.Add(this.kryptonLabel1);
this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanel1.Location = new System.Drawing.Point(0, 0);
this.kryptonPanel1.Name = "kryptonPanel1";
this.kryptonPanel1.Size = new System.Drawing.Size(684, 127);
this.kryptonPanel1.TabIndex = 7;
//
// kbtnBrowse
//
this.kbtnBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.kbtnBrowse.AutoSize = true;
this.kbtnBrowse.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.kbtnBrowse.Location = new System.Drawing.Point(648, 72);
this.kbtnBrowse.Name = "kbtnBrowse";
this.kbtnBrowse.Size = new System.Drawing.Size(23, 30);
this.kbtnBrowse.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kbtnBrowse.TabIndex = 65;
this.kbtnBrowse.Values.Text = ".&..";
this.kbtnBrowse.Click += new System.EventHandler(this.KbtnBrowse_Click);
//
// ktxtConfigurationPath
//
this.ktxtConfigurationPath.Location = new System.Drawing.Point(187, 73);
this.ktxtConfigurationPath.Name = "ktxtConfigurationPath";
this.ktxtConfigurationPath.Size = new System.Drawing.Size(455, 29);
this.ktxtConfigurationPath.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ktxtConfigurationPath.StateCommon.Content.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Inherit;
this.ktxtConfigurationPath.TabIndex = 3;
this.ktxtConfigurationPath.TextChanged += new System.EventHandler(this.KtxtConfigurationPath_TextChanged);
//
// kryptonLabel2
//
this.kryptonLabel2.Location = new System.Drawing.Point(13, 73);
this.kryptonLabel2.Name = "kryptonLabel2";
this.kryptonLabel2.Size = new System.Drawing.Size(164, 26);
this.kryptonLabel2.StateCommon.LongText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel2.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel2.TabIndex = 2;
this.kryptonLabel2.Values.Text = "Configuration Path:";
//
// kcmbConfigurationType
//
this.kcmbConfigurationType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.kcmbConfigurationType.DropDownWidth = 484;
this.kcmbConfigurationType.Location = new System.Drawing.Point(187, 13);
this.kcmbConfigurationType.Name = "kcmbConfigurationType";
this.kcmbConfigurationType.Size = new System.Drawing.Size(484, 27);
this.kcmbConfigurationType.StateCommon.ComboBox.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kcmbConfigurationType.StateCommon.ComboBox.Content.TextH = ComponentFactory.Krypton.Toolkit.PaletteRelativeAlign.Near;
this.kcmbConfigurationType.StateCommon.Item.Content.LongText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kcmbConfigurationType.StateCommon.Item.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kcmbConfigurationType.TabIndex = 1;
//
// kryptonLabel1
//
this.kryptonLabel1.Location = new System.Drawing.Point(13, 13);
this.kryptonLabel1.Name = "kryptonLabel1";
this.kryptonLabel1.Size = new System.Drawing.Size(167, 26);
this.kryptonLabel1.StateCommon.LongText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel1.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonLabel1.TabIndex = 0;
this.kryptonLabel1.Values.Text = "Configuration Type:";
//
// PaletteColourExporter
//
this.ClientSize = new System.Drawing.Size(684, 184);
this.Controls.Add(this.kryptonPanel1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.kryptonPanel2);
this.Name = "PaletteColourExporter";
this.Load += new System.EventHandler(this.PaletteColourExporter_Load);
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).EndInit();
this.kryptonPanel2.ResumeLayout(false);
this.kryptonPanel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit();
this.kryptonPanel1.ResumeLayout(false);
this.kryptonPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kcmbConfigurationType)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region Variables
private string[] _configurationTypes = { "All Colours", "Basic Colours", "Custom Colours", "Custom Text Colours", "Link Text Colours", "Miscellaneous Colours", "Standard Control Text Colours", "Text Colours" };
#endregion
public PaletteColourExporter()
{
InitializeComponent();
}
private void PaletteColourExporter_Load(object sender, EventArgs e)
{
foreach (string item in _configurationTypes)
{
kcmbConfigurationType.Items.Add(item);
}
}
private void KbtnExport_Click(object sender, EventArgs e)
{
if (kcmbConfigurationType.Text == "All Colours")
{
ColourConfigurationFileManager.SaveColourConfigurationFile(ColourSettingsType.ALLCOLOURSETTINGS, ktxtConfigurationPath.Text);
}
else if (kcmbConfigurationType.Text == "Basic Colours")
{
ColourConfigurationFileManager.SaveColourConfigurationFile(ColourSettingsType.BASICCOLOURSETTINGS, ktxtConfigurationPath.Text);
}
else if (kcmbConfigurationType.Text == "Custom Colours")
{
ColourConfigurationFileManager.SaveColourConfigurationFile(ColourSettingsType.CUSTOMCOLOURSETTINGS, ktxtConfigurationPath.Text);
}
else if (kcmbConfigurationType.Text == "Custom Text Colours")
{
ColourConfigurationFileManager.SaveColourConfigurationFile(ColourSettingsType.CUSTOMTEXTCOLOURSETTINGS, ktxtConfigurationPath.Text);
}
}
private void KbtnBrowse_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.Title = "Select Where to Save Your Configuation Files:";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
ktxtConfigurationPath.Text = Path.GetFullPath(dialog.FileName);
}
}
private void KtxtConfigurationPath_TextChanged(object sender, EventArgs e)
{
if (ktxtConfigurationPath.Text.Length > 0)
{
kbtnExport.Enabled = true;
}
else
{
kbtnExport.Enabled = false;
}
}
}
} | 55.920635 | 218 | 0.652569 |
8830aca290fd3af97a46dc9f99d98a85f24f18d5 | 9,286 | cs | C# | src/System.IO.FileSystem/tests/DirectoryInfo/GetDirectories_str_so.cs | sharwell/corefx | 64f58e21c55f80db465aa9ccf8c0fab6f9fc36a5 | [
"MIT"
] | null | null | null | src/System.IO.FileSystem/tests/DirectoryInfo/GetDirectories_str_so.cs | sharwell/corefx | 64f58e21c55f80db465aa9ccf8c0fab6f9fc36a5 | [
"MIT"
] | null | null | null | src/System.IO.FileSystem/tests/DirectoryInfo/GetDirectories_str_so.cs | sharwell/corefx | 64f58e21c55f80db465aa9ccf8c0fab6f9fc36a5 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/**
We test this API's functionality comprehensively via Directory.GetDirectories(String, String, SearchOption). Here, we concentrate on the following
- vanilla
- parm validation, including non existent dir
- security
**/
using System;
using System.Runtime.CompilerServices;
using System.IO;
using System.Collections.Generic;
using System.Security;
using System.Globalization;
using Xunit;
public class DirectoryInfo_GetDirectories_str_so
{
private delegate void ExceptionCode();
private static bool s_pass = true;
[Fact]
public static void RunTest()
{
try
{
String dirName;
DirectoryInfo dirInfo;
String[] expectedDirs;
DirectoryInfo[] dirs;
List<String> list;
//Scenario 1: Vanilla
try
{
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirInfo = new DirectoryInfo(dirName);
expectedDirs = fileManager.GetAllDirectories();
list = new List<String>(expectedDirs);
dirs = dirInfo.GetDirectories("*", SearchOption.AllDirectories);
Eval(dirs.Length == list.Count, "Err_415mbz! wrong count {0} {1}", dirs.Length, list.Count);
for (int i = 0; i < expectedDirs.Length; i++)
{
if (Eval(list.Contains(dirs[i].FullName), "Err_287kkm! No file found: {0}", dirs[i].FullName))
list.Remove(dirs[i].FullName);
}
if (!Eval(list.Count == 0, "Err_921mhs! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_349t7g! Exception caught in scenario: {0}", ex);
}
//Scenario 3: Parm Validation
try
{
// dir not present and then after creating
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
dirInfo = new DirectoryInfo(dirName);
CheckException<DirectoryNotFoundException>(delegate { dirs = dirInfo.GetDirectories("*", SearchOption.AllDirectories); }, "Err_326pgt! worng exception thrown");
// create the dir and then check that we dont cache this info
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirInfo = new DirectoryInfo(dirName);
expectedDirs = fileManager.GetAllDirectories();
list = new List<String>(expectedDirs);
dirs = dirInfo.GetDirectories("*", SearchOption.AllDirectories);
Eval(dirs.Length == list.Count, "Err_948kxt! wrong count");
for (int i = 0; i < expectedDirs.Length; i++)
{
if (Eval(list.Contains(dirs[i].FullName), "Err_535xaj! No file found: {0}", dirs[i].FullName))
list.Remove(dirs[i].FullName);
}
if (!Eval(list.Count == 0, "Err_370pjl! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
CheckException<ArgumentNullException>(delegate { dirs = dirInfo.GetDirectories(null, SearchOption.TopDirectoryOnly); }, "Err_751mwu! worng exception thrown");
CheckException<ArgumentOutOfRangeException>(delegate { dirs = dirInfo.GetDirectories("*", (SearchOption)100); }, "Err_589kvu! worng exception thrown - see bug #386545");
CheckException<ArgumentOutOfRangeException>(delegate { dirs = dirInfo.GetDirectories("*", (SearchOption)(-1)); }, "Err_359vcj! worng exception thrown - see bug #386545");
String[] invalidValuesForSearch = { "..", @".." + Path.DirectorySeparatorChar };
for (int i = 0; i < invalidValuesForSearch.Length; i++)
{
CheckException<ArgumentException>(delegate { dirs = dirInfo.GetDirectories(invalidValuesForSearch[i], SearchOption.TopDirectoryOnly); }, String.Format("Err_631bwy! worng exception thrown: {1}", i, invalidValuesForSearch[i]));
}
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_006dwq! Exception caught in scenario: {0}", ex);
}
//Scenario for bug #461014 - Getting files/directories of CurrentDirectory of drives are broken
/* Scenario disabled when porting because it relies on the contents of the current directory not changing during execution
try
{
string anotherDrive = IOServices.GetNtfsDriveOtherThanCurrent();
String[] paths = null == anotherDrive ? new String[] { Directory.GetCurrentDirectory() } : new String[] { anotherDrive, Directory.GetCurrentDirectory() };
String path;
for (int i = 0; i < paths.Length; i++)
{
path = paths[i];
if (path.Length > 1)
{
path = path.Substring(0, 2);
DirectoryInfo[] f1 = new DirectoryInfo(Path.GetFullPath(path)).GetDirectories();
DirectoryInfo[] f2 = new DirectoryInfo(path).GetDirectories();
Eval<int>(f1.Length, f2.Length, "Err_2497gds! wrong value");
for (int j = 0; j < f1.Length; j++)
{
Eval<String>(f1[j].FullName, f2[j].FullName, "Err_03284t! wrong value");
Eval<String>(f1[j].Name, f2[j].Name, "Err_03284t! wrong value");
}
}
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_349t7g! Exception caught in scenario: {0}", ex);
}
*/
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_234rsgf! Uncaught exception in RunTest: {0}", ex);
}
Assert.True(s_pass);
}
private void DeleteFile(String fileName)
{
if (File.Exists(fileName))
File.Delete(fileName);
}
private void DeleteDir(String dirName)
{
if (Directory.Exists(dirName))
Directory.Delete(dirName);
}
//Checks for error
private static bool Eval(bool expression, String msg, params Object[] values)
{
return Eval(expression, String.Format(msg, values));
}
private static bool Eval<T>(T actual, T expected, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return retValue;
}
private static bool Eval(bool expression, String msg)
{
if (!expression)
{
s_pass = false;
Console.WriteLine(msg);
}
return expression;
}
//Checks for a particular type of exception
private static void CheckException<E>(ExceptionCode test, string error)
{
CheckException<E>(test, error, null);
}
//Checks for a particular type of exception and an Exception msg in the English locale
private static void CheckException<E>(ExceptionCode test, string error, String msgExpected)
{
bool exception = false;
try
{
test();
error = String.Format("{0} Exception NOT thrown ", error);
}
catch (Exception e)
{
if (e.GetType() == typeof(E))
{
exception = true;
if (msgExpected != null && System.Globalization.CultureInfo.CurrentUICulture.Name == "en-US" && e.Message != msgExpected)
{
exception = false;
error = String.Format("{0} Message Different: <{1}>", error, e.Message);
}
}
else
error = String.Format("{0} Exception type: {1}", error, e.GetType().Name);
}
Eval(exception, error);
}
}
| 40.907489 | 249 | 0.540491 |
421bbf34c6156a59e18f53bb30eb13eff03a71cb | 10,330 | cs | C# | src/prod/src/managed/Microsoft.ServiceFabric.Data.Impl/Collections/ReliableConcurrentQueue/CheckpointFileHelper.cs | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/managed/Microsoft.ServiceFabric.Data.Impl/Collections/ReliableConcurrentQueue/CheckpointFileHelper.cs | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/managed/Microsoft.ServiceFabric.Data.Impl/Collections/ReliableConcurrentQueue/CheckpointFileHelper.cs | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Data.Collections.ReliableConcurrentQueue
{
using System;
using System.Collections.Generic;
using System.Fabric.Common;
using System.Fabric.Common.Tracing;
using System.IO;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Replicator;
// todo: comment on disk and memory overhead
internal static class CheckpointFileHelper
{
/// <summary>
/// The currently supported key checkpoint file version.
/// </summary>
public const string CheckpointFileExtension = ".sfc";
internal const string CopyFileName = "copy" + CheckpointFileExtension;
// Once a chunk has exceeded this size, it will be written
internal const int ChunkWriteThreshold = 32 * 1024; // 32KB
internal const int MetadataMarker = 541;
internal static readonly ArraySegment<byte> MetadataMarkerSegment = new ArraySegment<byte>(BitConverter.GetBytes(MetadataMarker));
internal const int BeginFrameMarker = 17;
internal static readonly ArraySegment<byte> BeginChunkMarkerSegment = new ArraySegment<byte>(BitConverter.GetBytes(BeginFrameMarker));
internal const int EndFramesMarker = 293;
internal static readonly ArraySegment<byte> EndFramesMarkerSegment = new ArraySegment<byte>(BitConverter.GetBytes(EndFramesMarker));
internal static string GetCopyFilePath(string directory)
{
return Path.Combine(directory, CopyFileName);
}
internal static IEnumerable<string> GetCheckpointFiles(string workDirectory)
{
return FabricDirectory.GetFiles(workDirectory, "*" + CheckpointFileExtension, SearchOption.TopDirectoryOnly);
}
public static bool TryDeleteCopyFile(string directory, string traceType)
{
var filePath = GetCopyFilePath(directory);
if (!FabricFile.Exists(filePath))
{
return false;
}
FabricFile.Delete(filePath);
if (FabricFile.Exists(filePath))
{
TestableAssertHelper.FailInvalidData(traceType, "CheckpointFileHelper.TryDeleteCopyFile", "!FabricFile.Exists(filePath). filePath: {0}", filePath);
}
return true;
}
public static async Task<DataStore<T>> ReadCopyFileAsync<T>(string directory, IStateSerializer<T> valueSerializer, RCQMode queueMode, string traceType)
{
var copy = new Checkpoint<T>(directory, CopyFileName, valueSerializer, traceType);
await copy.ReadAsync().ConfigureAwait(false);
// do not ReleaseRef on the copy file; it will be deleted later. Keeping the file around may enable
// a DR scenario where the primary copies the last copy of its state to a secondary and is then lost,
// and the new secondary crashes in between deleting the copy file and making the copied state the new
// checkpoint.
return new DataStore<T>(copy.ListElements, queueMode, traceType);
}
public static async Task<bool> WriteFrameAsync(ArraySegment<byte> frame, Stream stream, string traceType)
{
bool complete;
var marker = BitConverter.ToInt32(frame.Array, frame.Offset);
if (marker == BeginFrameMarker)
{
complete = false;
}
else if (marker == EndFramesMarker)
{
complete = true;
}
else
{
var exc = new InvalidDataException(string.Format("CheckpointFileHelper.WriteFrameAsync : marker = {0}", marker));
FabricEvents.Events.ReliableConcurrentQueue_ExceptionError(traceType, exc.ToString());
throw exc;
}
await stream.WriteAsync(frame.Array, frame.Offset, frame.Count).ConfigureAwait(false);
return complete;
}
private static async Task CopyListElementsFrameAsync(Stream inputStream, Stream outputStream, string traceType)
{
var listElementsCountSegment = new ArraySegment<byte>(new byte[sizeof(int)]);
var listElementsBytesSegment = new ArraySegment<byte>(new byte[sizeof(int)]);
var crcSegment = new ArraySegment<byte>(new byte[sizeof(ulong)]);
var listElementsCount = await SerializationHelper.ReadIntAsync(listElementsCountSegment, inputStream).ConfigureAwait(false);
if (listElementsCount < 0)
{
var exc = new InvalidDataException(string.Format("CheckpointFileHelper.CopyListElementsFrameAsync : Unexpected listElementsCount: {0}", listElementsCount));
FabricEvents.Events.ReliableConcurrentQueue_ExceptionError(traceType, exc.ToString());
throw exc;
}
var listElementsBytes = await SerializationHelper.ReadIntAsync(listElementsBytesSegment, inputStream).ConfigureAwait(false);
if (listElementsBytes < 0)
{
var exc = new InvalidDataException(string.Format("CheckpointFileHelper.CopyListElementsFrameAsync : Unexpected listElementsBytes: {0}", listElementsBytes));
FabricEvents.Events.ReliableConcurrentQueue_ExceptionError(traceType, exc.ToString());
throw exc;
}
var listElementsSegment = new ArraySegment<byte>(new byte[listElementsBytes]);
await SerializationHelper.ReadBytesAsync(listElementsSegment, listElementsBytes, inputStream).ConfigureAwait(false);
await SerializationHelper.ReadBytesAsync(crcSegment, sizeof(ulong), inputStream).ConfigureAwait(false);
var readCRC = BitConverter.ToUInt64(crcSegment.Array, crcSegment.Offset);
var calcCrc = CRC64.ToCRC64(new[] { listElementsCountSegment, listElementsBytesSegment, listElementsSegment });
if (calcCrc != readCRC)
{
var exc = new InvalidDataException(string.Format("CheckpointFileHelper.CopyListElementsFrameAsync => CRC mismatch. Read: {0} Calculated: {1}", readCRC, calcCrc));
FabricEvents.Events.ReliableConcurrentQueue_ExceptionError(traceType, exc.ToString());
throw exc;
}
await outputStream.WriteAsync(listElementsCountSegment.Array, listElementsCountSegment.Offset, listElementsCountSegment.Count).ConfigureAwait(false);
await outputStream.WriteAsync(listElementsBytesSegment.Array, listElementsBytesSegment.Offset, listElementsBytesSegment.Count).ConfigureAwait(false);
await outputStream.WriteAsync(listElementsSegment.Array, listElementsSegment.Offset, listElementsSegment.Count).ConfigureAwait(false);
await outputStream.WriteAsync(crcSegment.Array, crcSegment.Offset, crcSegment.Count).ConfigureAwait(false);
}
// return true if there will be no more frames to copy (complete)
public static async Task<bool> CopyNextFrameAsync(Stream inputStream, Stream outputStream, string traceType)
{
try
{
var intSegment = new ArraySegment<byte>(new byte[sizeof(int)]);
var marker = await SerializationHelper.ReadIntAsync(intSegment, inputStream).ConfigureAwait(false);
if (marker == BeginFrameMarker)
{
// write the marker
await outputStream.WriteAsync(intSegment.Array, intSegment.Offset, intSegment.Count).ConfigureAwait(false);
// copy the bytes for this frame
await CopyListElementsFrameAsync(inputStream, outputStream, traceType).ConfigureAwait(false);
return false;
}
else if (marker == EndFramesMarker)
{
// write the end marker, and the copy is complete
await outputStream.WriteAsync(intSegment.Array, intSegment.Offset, intSegment.Count).ConfigureAwait(false);
return true;
}
else
{
var exc = new InvalidDataException(string.Format("CheckpointFileHelper.CopyNextFrameAsync => Marker : {0}", marker));
FabricEvents.Events.ReliableConcurrentQueue_ExceptionError(traceType, exc.ToString());
throw exc;
}
}
catch (Exception ex)
{
FabricEvents.Events.ReliableConcurrentQueue_CopyNextFrameError("ReliableConcurrentQueueCheckpointFile.CopyNextFrameAsync@", ex.ToString());
throw;
}
}
public static void SafeFileReplace(string currentFilePath, string newFilePath, string backupFilePath, string traceType)
{
if (FabricFile.Exists(backupFilePath))
{
FabricFile.Delete(backupFilePath);
}
if (FabricFile.Exists(backupFilePath))
{
TestableAssertHelper.FailInvalidData(traceType, "CheckpointFileHelper.SafeFileReplace", "!FabricFile.Exists(backupFilePath) : {0}", backupFilePath);
}
// Previous replace could have failed in the middle before the next metadata table file got renamed to current.
if (!FabricFile.Exists(currentFilePath))
{
FabricFile.Move(newFilePath, currentFilePath);
}
else
{
FabricFile.Replace(newFilePath, currentFilePath, backupFilePath, ignoreMetadataErrors: false);
}
if (FabricFile.Exists(backupFilePath))
{
FabricFile.Delete(backupFilePath);
}
if (FabricFile.Exists(backupFilePath))
{
TestableAssertHelper.FailInvalidData(traceType, "CheckpointFileHelper.SafeFileReplace", "!FabricFile.Exists(backupFilePath) : {0}", backupFilePath);
}
}
}
} | 48.497653 | 179 | 0.638529 |
b7b8b064756e8d9348b118372cef52e4a1803b4e | 1,774 | cs | C# | Tools System/Concrete Tools/OvertimeTool.cs | linusesbjornsson/GameDevClickers | 0a85c4cbc324da0cfa7aeda0affeb7a5b913eb2a | [
"MIT"
] | 4 | 2020-12-08T05:58:43.000Z | 2021-06-07T04:54:20.000Z | Tools System/Concrete Tools/OvertimeTool.cs | linusesbjornsson/GameDevClickers | 0a85c4cbc324da0cfa7aeda0affeb7a5b913eb2a | [
"MIT"
] | null | null | null | Tools System/Concrete Tools/OvertimeTool.cs | linusesbjornsson/GameDevClickers | 0a85c4cbc324da0cfa7aeda0affeb7a5b913eb2a | [
"MIT"
] | 4 | 2020-12-08T04:26:48.000Z | 2020-12-09T07:45:42.000Z | using System;
using System.Collections.Generic;
using System.Numerics;
public class OvertimeTool : ConcreteTool
{
public OvertimeTool(int level, Entity player) : base("Overtime", level, player)
{
}
public OvertimeTool(int level, Entity player, Queue<ToolUpgrade> nextUpgrades, Dictionary<ToolID, ToolUpgrade> upgrades, int numberOfUpgrades) : base("Overtime", level, player, nextUpgrades, upgrades, numberOfUpgrades)
{
}
public override BigInteger GetCost()
{
if (_cost == BigInteger.Zero)
{
BigInteger cost = new BigInteger(10);
_cost = cost * Level * new BigRational(Math.Pow(Level + 1, 0.75)).WholePart;
}
return _cost;
}
public override string GetDescription()
{
return FormatDescription("Every 60 seconds, there is a <TOOL_VALUE>% chance to instantly complete an active job");
}
public override int MaxLevel()
{
return 100;
}
public override BigRational GetModifier()
{
if (_modifier == BigRational.Zero)
{
_modifier = new BigRational(1) * new BigRational(Math.Pow(Level, 0.35f));
}
return _modifier;
}
public override bool IsUnlocked()
{
Tool pairCoder = _entity.Tools.GetTool(ToolID.PAIR_PROGRAMMER);
return pairCoder != null;
}
public override object Clone()
{
OvertimeTool tool = new OvertimeTool(Level, _entity, _nextUpgrades, _upgrades, _numberOfUpgrades);
tool.CloneUpgrades(this);
return tool;
}
public override ToolID GetID()
{
return ToolID.OVERTIME;
}
protected override void SetupUpgrades()
{
}
}
| 26.878788 | 223 | 0.612176 |
35e5a94302d094cc957ef10fee7b40f842517be1 | 673 | cs | C# | OnLineVideotech/OnLineVideotech.Services/Admin/Interfaces/IGenreService.cs | kockata/OnlineVideotech | 9a19d09d5afb1f631b55e7a42b2aff6b10f43b2f | [
"MIT"
] | null | null | null | OnLineVideotech/OnLineVideotech.Services/Admin/Interfaces/IGenreService.cs | kockata/OnlineVideotech | 9a19d09d5afb1f631b55e7a42b2aff6b10f43b2f | [
"MIT"
] | null | null | null | OnLineVideotech/OnLineVideotech.Services/Admin/Interfaces/IGenreService.cs | kockata/OnlineVideotech | 9a19d09d5afb1f631b55e7a42b2aff6b10f43b2f | [
"MIT"
] | null | null | null | using OnLineVideotech.Data.Models;
using OnLineVideotech.Services.Admin.ServiceModels;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace OnLineVideotech.Services.Admin.Interfaces
{
public interface IGenreService : IBaseService
{
Task Create(string name);
Task<List<GenreServiceModel>> GetAllGenres();
Task<GenreServiceModel> FindGenre(Guid id);
Task UpdateGenre(GenreServiceModel genreServiceModel);
Task Delete(GenreServiceModel genreServiceModel);
Task<List<Genre>> GetAllGenreForMovie(Guid MovieId);
Task<List<Guid>> GetAllMoviesForGenre(Guid genreId);
}
} | 26.92 | 62 | 0.742942 |
7e31ab13472ce61f793dc1637c28a1e52f07364e | 102 | cs | C# | Goodbye.cs | ElreyB/hello_world | ad09ad200a075fb373e0b1b5b29e97df789d8645 | [
"MIT"
] | null | null | null | Goodbye.cs | ElreyB/hello_world | ad09ad200a075fb373e0b1b5b29e97df789d8645 | [
"MIT"
] | null | null | null | Goodbye.cs | ElreyB/hello_world | ad09ad200a075fb373e0b1b5b29e97df789d8645 | [
"MIT"
] | null | null | null | using System;
class Goodbye
{
static void Main()
{
Console.WriteLine("Goodbye World");
}
}
| 10.2 | 39 | 0.637255 |
c633c4362fa8aeacaf4da16597986c486cd34705 | 287 | cs | C# | Assets/Sample/Editor/MyOtherEffectEditor.cs | Coreo7/Unity-Visual-Experiments | 4bbe96f0ab7767282a50a3aaa2a6e017f52dab73 | [
"MIT"
] | null | null | null | Assets/Sample/Editor/MyOtherEffectEditor.cs | Coreo7/Unity-Visual-Experiments | 4bbe96f0ab7767282a50a3aaa2a6e017f52dab73 | [
"MIT"
] | null | null | null | Assets/Sample/Editor/MyOtherEffectEditor.cs | Coreo7/Unity-Visual-Experiments | 4bbe96f0ab7767282a50a3aaa2a6e017f52dab73 | [
"MIT"
] | null | null | null | using ImageEffectGraph.Demo;
using ImageEffectGraph.Editor.PostProcessing;
using UnityEditor.Rendering.PostProcessing;
namespace ImageEffectGraph.Editor.Demo
{
[PostProcessEditor(typeof(MyOtherEffect))]
public class MyOtherEffectEditor : RenderWithMaterialEditor
{
}
}
| 23.916667 | 63 | 0.801394 |
ff42f2bfafac75fcb945c6a6930669bf32990bc0 | 3,907 | cs | C# | TixFactory.Serialization/TixFactory.Serialization.Json/Converters/KindAwareDateTimeConverter.cs | tix-factory/nuget | 8dec84757a9009edebfe495b21bbe6e5fad32142 | [
"MIT"
] | null | null | null | TixFactory.Serialization/TixFactory.Serialization.Json/Converters/KindAwareDateTimeConverter.cs | tix-factory/nuget | 8dec84757a9009edebfe495b21bbe6e5fad32142 | [
"MIT"
] | 1 | 2019-11-29T18:18:16.000Z | 2019-11-29T18:18:16.000Z | TixFactory.Serialization/TixFactory.Serialization.Json/Converters/KindAwareDateTimeConverter.cs | tix-factory/nuget | 8dec84757a9009edebfe495b21bbe6e5fad32142 | [
"MIT"
] | null | null | null | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace TixFactory.Serialization.Json
{
/// <summary>
/// Extended IsoDateTimeConverter which handles converting <see cref="DateTime"/>s to specified <see cref="DateTimeKind"/>.
/// </summary>
public class KindAwareDateTimeConverter : IsoDateTimeConverter
{
private const string _NotSupportedKindExceptionMessage = "DateTimeKind Unspecified is not supported.";
private readonly DateTimeKind _TargetReadDateTimeKind;
private readonly DateTimeKind _TargetWriteDateTimeKind;
/// <summary>
/// Initializes a new <see cref="KindAwareDateTimeConverter"/>.
/// </summary>
/// <remarks>
/// Json reads and writes will be <see cref="DateTimeKind.Utc"/>.
/// </remarks>
public KindAwareDateTimeConverter()
: this(DateTimeKind.Utc, DateTimeKind.Utc)
{
}
/// <summary>
/// Initializes a new <see cref="KindAwareDateTimeConverter"/>.
/// </summary>
/// <param name="targetReadDateTimeKind">The <see cref="DateTimeKind"/> to parse (read) the Json <see cref="DateTime"/> as.</param>
/// <param name="targetWriteDateTimeKind">The <see cref="DateTimeKind"/> to write the Json <see cref="DateTime"/> as.</param>
/// <exception cref="ArgumentException">
/// - <paramref name="targetReadDateTimeKind"/> is <see cref="DateTimeKind.Unspecified"/>.
/// - <paramref name="targetWriteDateTimeKind"/> is <see cref="DateTimeKind.Unspecified"/>.
/// </exception>
public KindAwareDateTimeConverter(DateTimeKind targetReadDateTimeKind, DateTimeKind targetWriteDateTimeKind)
{
if (targetReadDateTimeKind == DateTimeKind.Unspecified)
{
throw new ArgumentException(_NotSupportedKindExceptionMessage, nameof(targetReadDateTimeKind));
}
if (targetWriteDateTimeKind == DateTimeKind.Unspecified)
{
throw new ArgumentException(_NotSupportedKindExceptionMessage, nameof(targetWriteDateTimeKind));
}
_TargetReadDateTimeKind = targetReadDateTimeKind;
_TargetWriteDateTimeKind = targetWriteDateTimeKind;
}
/// <inheritdoc cref="IsoDateTimeConverter.ReadJson"/>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var result = base.ReadJson(reader, objectType, existingValue, serializer);
if (result != null && result is DateTime resultDateTime)
{
return _TargetReadDateTimeKind == DateTimeKind.Utc
? TranslateToUtc(resultDateTime)
: TranslateToLocal(resultDateTime);
}
return result;
}
/// <inheritdoc cref="IsoDateTimeConverter.WriteJson"/>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value != null && value is DateTime dateTimeToWrite)
{
dateTimeToWrite = _TargetWriteDateTimeKind == DateTimeKind.Utc ? TranslateToUtc(dateTimeToWrite) : TranslateToLocal(dateTimeToWrite);
base.WriteJson(writer, dateTimeToWrite, serializer);
}
else
{
base.WriteJson(writer, value, serializer);
}
}
private DateTime TranslateToUtc(DateTime dateTime)
{
switch (dateTime.Kind)
{
case DateTimeKind.Utc:
return dateTime;
case DateTimeKind.Unspecified:
return TimeZoneInfo.ConvertTimeToUtc(dateTime, TimeZoneInfo.Local);
default:
return dateTime.ToUniversalTime();
}
}
private DateTime TranslateToLocal(DateTime dateTime)
{
switch (dateTime.Kind)
{
case DateTimeKind.Local:
return dateTime;
case DateTimeKind.Unspecified:
return DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
default:
return dateTime.ToLocalTime();
}
}
}
}
| 35.844037 | 149 | 0.681085 |
5f1153a90ed68ce5bec8133b6aadb400a95e95c9 | 348 | cs | C# | OnLineShop/Services/OnLineShop.Services.Data/Contracts/IsizeService.cs | dushka-dragoeva/OnLineShopMVC | db13c869b83c2c433a274e6eeed6fc710694eff7 | [
"MIT"
] | null | null | null | OnLineShop/Services/OnLineShop.Services.Data/Contracts/IsizeService.cs | dushka-dragoeva/OnLineShopMVC | db13c869b83c2c433a274e6eeed6fc710694eff7 | [
"MIT"
] | null | null | null | OnLineShop/Services/OnLineShop.Services.Data/Contracts/IsizeService.cs | dushka-dragoeva/OnLineShopMVC | db13c869b83c2c433a274e6eeed6fc710694eff7 | [
"MIT"
] | null | null | null | using OnLineShop.Data.Models;
using System.Collections.Generic;
using System.Linq;
namespace OnLineShop.Services.Data.Contracts
{
public interface ISizeService
{
IEnumerable<Size> GetAll();
Size GetById(int? id);
//int Update(Size size);
//int Delete(int? id);
//int Insert(Size size);
}
}
| 17.4 | 44 | 0.635057 |
c6ed9fef101da7f9cf1fc81947a79540b2254ba3 | 6,238 | cs | C# | src/EFCore.PG/Query/Internal/NpgsqlSetOperationTypeResolutionCompensatingExpressionVisitor.cs | npgsql/Npgsql.EntityFrameworkCore.PostgreSQL | 46782f0c9c85a92a6f1d715515a5249f72fd4d43 | [
"PostgreSQL"
] | 602 | 2016-04-14T14:13:34.000Z | 2019-10-10T13:42:15.000Z | src/EFCore.PG/Query/Internal/NpgsqlSetOperationTypeResolutionCompensatingExpressionVisitor.cs | npgsql/Npgsql.EntityFrameworkCore.PostgreSQL | 46782f0c9c85a92a6f1d715515a5249f72fd4d43 | [
"PostgreSQL"
] | 991 | 2016-04-14T12:55:50.000Z | 2019-10-14T09:38:50.000Z | src/EFCore.PG/Query/Internal/NpgsqlSetOperationTypeResolutionCompensatingExpressionVisitor.cs | npgsql/Npgsql.EntityFrameworkCore.PostgreSQL | 46782f0c9c85a92a6f1d715515a5249f72fd4d43 | [
"PostgreSQL"
] | 123 | 2016-04-29T08:53:25.000Z | 2019-10-08T17:55:38.000Z | using Microsoft.EntityFrameworkCore.Query.Internal;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal;
public class NpgsqlSetOperationTypeResolutionCompensatingExpressionVisitor : ExpressionVisitor
{
private State _state;
protected override Expression VisitExtension(Expression extensionExpression)
=> extensionExpression switch
{
ShapedQueryExpression shapedQueryExpression
=> shapedQueryExpression.Update(
Visit(shapedQueryExpression.QueryExpression),
Visit(shapedQueryExpression.ShaperExpression)),
SetOperationBase setOperationExpression => VisitSetOperation(setOperationExpression),
SelectExpression selectExpression => VisitSelect(selectExpression),
TpcTablesExpression tpcTablesExpression => VisitTpcTablesExpression(tpcTablesExpression),
_ => base.VisitExtension(extensionExpression)
};
private Expression VisitSetOperation(SetOperationBase setOperationExpression)
{
switch (_state)
{
case State.Nothing:
_state = State.InSingleSetOperation;
var visited = base.VisitExtension(setOperationExpression);
_state = State.Nothing;
return visited;
case State.InSingleSetOperation:
_state = State.InNestedSetOperation;
visited = base.VisitExtension(setOperationExpression);
_state = State.InSingleSetOperation;
return visited;
default:
return base.VisitExtension(setOperationExpression);
}
}
#pragma warning disable EF1001
private Expression VisitTpcTablesExpression(TpcTablesExpression tpcTablesExpression)
{
var parentState = _state;
if (tpcTablesExpression.SelectExpressions.Count < 3)
{
return base.VisitExtension(tpcTablesExpression);
}
var changed = false;
var visitedSelectExpressions = new SelectExpression[tpcTablesExpression.SelectExpressions.Count];
_state = State.InNestedSetOperation;
visitedSelectExpressions[0] = (SelectExpression)Visit(tpcTablesExpression.SelectExpressions[0]);
changed |= visitedSelectExpressions[0] != tpcTablesExpression.SelectExpressions[0];
_state = State.AlreadyCompensated;
for (var i = 1; i < tpcTablesExpression.SelectExpressions.Count; i++)
{
var selectExpression = tpcTablesExpression.SelectExpressions[i];
var visitedSelectExpression = (SelectExpression)Visit(tpcTablesExpression.SelectExpressions[i]);
visitedSelectExpressions[i] = visitedSelectExpression;
changed |= selectExpression != visitedSelectExpression;
}
_state = parentState;
return changed
? new TpcTablesExpression(tpcTablesExpression.Alias, tpcTablesExpression.EntityType, visitedSelectExpressions)
: tpcTablesExpression;
}
#pragma warning restore EF1001
private Expression VisitSelect(SelectExpression selectExpression)
{
var changed = false;
var tables = new List<TableExpressionBase>();
foreach (var table in selectExpression.Tables)
{
var newTable = (TableExpressionBase)Visit(table);
changed |= newTable != table;
tables.Add(newTable);
}
// Above we visited the tables, which may contain nested set operations - so we retained our state.
// When visiting the below elements, reset to state to properly handle nested unions inside e.g. the predicate.
var parentState = _state;
_state = State.Nothing;
var projections = new List<ProjectionExpression>();
foreach (var item in selectExpression.Projection)
{
// Inject an explicit cast node around null literals
var updatedProjection = parentState == State.InNestedSetOperation && item.Expression is SqlConstantExpression { Value : null }
? item.Update(
new SqlUnaryExpression(ExpressionType.Convert, item.Expression, item.Expression.Type, item.Expression.TypeMapping))
: (ProjectionExpression)Visit(item);
projections.Add(updatedProjection);
changed |= updatedProjection != item;
}
var predicate = (SqlExpression?)Visit(selectExpression.Predicate);
changed |= predicate != selectExpression.Predicate;
var groupBy = new List<SqlExpression>();
foreach (var groupingKey in selectExpression.GroupBy)
{
var newGroupingKey = (SqlExpression)Visit(groupingKey);
changed |= newGroupingKey != groupingKey;
groupBy.Add(newGroupingKey);
}
var havingExpression = (SqlExpression?)Visit(selectExpression.Having);
changed |= havingExpression != selectExpression.Having;
var orderings = new List<OrderingExpression>();
foreach (var ordering in selectExpression.Orderings)
{
var orderingExpression = (SqlExpression)Visit(ordering.Expression);
changed |= orderingExpression != ordering.Expression;
orderings.Add(ordering.Update(orderingExpression));
}
var offset = (SqlExpression?)Visit(selectExpression.Offset);
changed |= offset != selectExpression.Offset;
var limit = (SqlExpression?)Visit(selectExpression.Limit);
changed |= limit != selectExpression.Limit;
// If we were in the InNestedSetOperation state, we've applied all explicit type mappings when visiting the ProjectionExpressions
// above; change the state to prevent unnecessarily continuing to compensate
_state = parentState == State.InNestedSetOperation ? State.AlreadyCompensated : parentState;
return changed
? selectExpression.Update(
projections, tables, predicate, groupBy, havingExpression, orderings, limit, offset)
: selectExpression;
}
private enum State
{
Nothing,
InSingleSetOperation,
InNestedSetOperation,
AlreadyCompensated
}
}
| 40.771242 | 138 | 0.670407 |
b812cf5309ed890fc09bc8c6139027bd5d1b7c11 | 1,219 | cs | C# | framework/Svt.Network/ConnectionEventArgs.cs | OssiPesonen/Eilium | b465e43d82abb4cc0ef21146f1506d95f7a7b921 | [
"MIT"
] | 9 | 2015-10-28T00:36:22.000Z | 2021-08-09T18:41:04.000Z | framework/Svt.Network/ConnectionEventArgs.cs | OssiPesonen/Eilium | b465e43d82abb4cc0ef21146f1506d95f7a7b921 | [
"MIT"
] | null | null | null | framework/Svt.Network/ConnectionEventArgs.cs | OssiPesonen/Eilium | b465e43d82abb4cc0ef21146f1506d95f7a7b921 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Svt.Network
{
public class ConnectionEventArgs : EventArgs
{
internal ConnectionEventArgs(string host, int port, bool connected)
{
Hostname = host;
Port = port;
Connected = connected;
Exception = null;
}
internal ConnectionEventArgs(string host, int port, bool connected, Exception exception)
{
Hostname = host;
Port = port;
Connected = connected;
Exception = exception;
}
public string Hostname { get; private set; }
public int Port { get; private set; }
public bool Connected { get; private set; }
public Exception Exception { get; private set; }
}
public class ClientConnectionEventArgs : ConnectionEventArgs
{
public RemoteHostState Client { get; set; }
internal ClientConnectionEventArgs(string host, int port, bool connected, Exception ex, bool remote)
: base(host, port, connected, ex)
{
Remote = remote;
}
public bool Remote { get; private set; }
}
}
| 27.704545 | 108 | 0.599672 |
d4d4e327fe32b5a877326c824f973ff27057400a | 10,201 | cs | C# | src/StudentsAbstraction/Services/StudentStore.cs | namofun/tenant | c3408c4a1de2c6e03ab39b235e088c2c92929d0c | [
"MIT"
] | null | null | null | src/StudentsAbstraction/Services/StudentStore.cs | namofun/tenant | c3408c4a1de2c6e03ab39b235e088c2c92929d0c | [
"MIT"
] | 1 | 2021-07-29T07:39:04.000Z | 2021-07-29T07:39:04.000Z | src/StudentsAbstraction/Services/StudentStore.cs | namofun/tenant | c3408c4a1de2c6e03ab39b235e088c2c92929d0c | [
"MIT"
] | null | null | null | using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Tenant.Entities;
namespace Tenant.Services
{
/// <summary>
/// The store interface for <see cref="Student"/>.
/// </summary>
public interface IStudentStore
{
/// <summary>
/// List students via affiliation.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="page">The current page.</param>
/// <param name="pageCount">The count per page.</param>
/// <returns>The task for fetching students.</returns>
Task<IPagedList<Student>> ListStudentsAsync(Affiliation affiliation, int page, int pageCount);
/// <summary>
/// List students via teaching class.
/// </summary>
/// <param name="class">The teaching class.</param>
/// <param name="page">The current page.</param>
/// <param name="pageCount">The count per page.</param>
/// <returns>The task for fetching students.</returns>
Task<IPagedList<Student>> ListStudentsAsync(Class @class, int page, int pageCount);
/// <summary>
/// List teaching classes via affiliation.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="filters">The filters on classes.</param>
/// <returns>The task for fetching teaching classes.</returns>
Task<List<Class>> ListClassesAsync(Affiliation affiliation, Expression<Func<Class, bool>>? filters = null);
/// <summary>
/// List teaching classes via affiliation IDs.
/// </summary>
/// <param name="affiliationIds">The affiliation IDs.</param>
/// <param name="filters">The filters on classes.</param>
/// <returns>The task for fetching teaching classes.</returns>
Task<List<Class>> ListClassesAsync(IEnumerable<int> affiliationIds, Expression<Func<Class, bool>>? filters = null);
/// <summary>
/// List teaching classes via affiliation.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="page">The current page.</param>
/// <param name="pageCount">The count per page.</param>
/// <param name="filters">The filters on classes.</param>
/// <returns>The task for fetching teaching classes.</returns>
Task<IPagedList<Class>> ListClassesAsync(Affiliation affiliation, int page, int pageCount, Expression<Func<Class, bool>>? filters = null);
/// <summary>
/// List teaching classes via affiliation IDs.
/// </summary>
/// <param name="affiliationIds">The affiliation IDs.</param>
/// <param name="page">The current page.</param>
/// <param name="pageCount">The count per page.</param>
/// <param name="filters">The filters on classes.</param>
/// <returns>The task for fetching teaching classes.</returns>
Task<IPagedList<Class>> ListClassesAsync(IEnumerable<int> affiliationIds, int page, int pageCount, Expression<Func<Class, bool>>? filters = null);
/// <summary>
/// List all students from teaching class.
/// </summary>
/// <param name="class">The teaching class.</param>
/// <returns>The task for fetching students.</returns>
Task<List<Student>> ListStudentsAsync(Class @class);
/// <summary>
/// List all users from student.
/// </summary>
/// <param name="student">The student.</param>
/// <returns>The task for fetching users.</returns>
Task<IReadOnlyList<IUser>> FindUserByStudentAsync(Student student);
/// <summary>
/// Find the teaching class.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="id">The teaching class ID.</param>
/// <returns>The teaching class.</returns>
Task<Class?> FindClassAsync(Affiliation affiliation, int id);
/// <summary>
/// Find the student.
/// </summary>
/// <param name="combinedId">The combined student ID.</param>
/// <returns>The task for finding student.</returns>
Task<(Affiliation, Student)?> FindStudentAsync(string combinedId);
/// <summary>
/// Find the student.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="rawId">The raw student ID.</param>
/// <returns>The task for finding student.</returns>
Task<Student?> FindStudentAsync(Affiliation affiliation, string rawId);
/// <summary>
/// Batch create or update a student entity.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="students">The dictionary for raw ID to name.</param>
/// <returns>The task for batch creating student.</returns>
Task<int> MergeAsync(Affiliation affiliation, Dictionary<string, string> students);
/// <summary>
/// Delete one student from store.
/// </summary>
/// <param name="student">The student.</param>
/// <returns>The task for deleting students.</returns>
Task DeleteAsync(Student student);
/// <summary>
/// Delete one class from store.
/// </summary>
/// <param name="class">The class.</param>
/// <returns>The task for deleting classes.</returns>
Task DeleteAsync(Class @class);
/// <summary>
/// Clone one class from store.
/// </summary>
/// <param name="class">The source class.</param>
/// <param name="className">The destination class name.</param>
/// <param name="userId">The creator user ID.</param>
/// <param name="userName">The creator user name.</param>
/// <returns>The task for cloning classes.</returns>
Task<Class> CloneAsync(Class @class, string className, int? userId, string? userName);
/// <summary>
/// Create a teaching class.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="className">The class name.</param>
/// <param name="userId">The creator user ID.</param>
/// <param name="userName">The creator user name.</param>
/// <returns>The task for creating class.</returns>
Task<Class> CreateAsync(Affiliation affiliation, string className, int? userId, string? userName);
/// <summary>
/// Batch add students to the class.
/// </summary>
/// <param name="class">The class.</param>
/// <param name="students">The student IDs.</param>
/// <returns>The task for merging.</returns>
Task<int> MergeAsync(Class @class, List<string> students);
/// <summary>
/// Check those existing students in store.
/// </summary>
/// <param name="affiliation">The affiliation.</param>
/// <param name="students">The student IDs.</param>
/// <returns>The task for fetching existing ones.</returns>
Task<List<string>> CheckExistingStudentsAsync(Affiliation affiliation, List<string> students);
/// <summary>
/// Remove the certain student from the certain class.
/// </summary>
/// <param name="class">The class.</param>
/// <param name="student">The student.</param>
/// <returns>Task for checking whether kick succeeded.</returns>
Task<bool> KickAsync(Class @class, Student student);
/// <summary>
/// Lists the administrators by affiliation.
/// </summary>
/// <param name="affiliation">The affiliation entity.</param>
/// <returns>The user list.</returns>
Task<IReadOnlyList<IUser>> GetAdministratorsAsync(Affiliation affiliation);
/// <summary>
/// Lists the tenants administrated by user.
/// </summary>
/// <param name="user">The user.</param>
/// <returns>The affiliation list</returns>
Task<IReadOnlyList<Affiliation>> GetAffiliationsForUserAsync(IUser user);
/// <summary>
/// Lists the roles of administrators by affiliation.
/// </summary>
/// <param name="affiliation">The affiliation entity.</param>
/// <returns>The role lookup.</returns>
Task<ILookup<int, string>> GetAdministratorRolesAsync(Affiliation affiliation);
/// <summary>
/// Creates a verify code for inviting students.
/// </summary>
/// <param name="affiliation">The affiliation entity.</param>
/// <param name="userId">The user ID of creator.</param>
/// <returns>The created verify code entity.</returns>
Task<VerifyCode> CreateVerifyCodeAsync(Affiliation affiliation, int userId);
/// <summary>
/// Gets all of the verify codes for this affiliations.
/// </summary>
/// <param name="affiliation">The affiliation entity.</param>
/// <param name="userId">The creator user ID.</param>
/// <param name="validOnly">Whether to include valid codes only.</param>
/// <returns>The list of verify codes.</returns>
Task<IReadOnlyList<VerifyCode>> GetVerifyCodesAsync(Affiliation affiliation, int? userId = null, bool validOnly = true);
/// <summary>
/// Redeems the verify code and check whether this is a valid code.
/// </summary>
/// <param name="affiliation">The affiliation entity.</param>
/// <param name="code">The verify code.</param>
/// <returns>Whether the code exists.</returns>
Task<bool> RedeemCodeAsync(Affiliation affiliation, string code);
/// <summary>
/// Marks the verify code as invalid.
/// </summary>
/// <param name="affiliation">The affiliation entity.</param>
/// <param name="code">The verify code.</param>
/// <returns>Whether the code exists.</returns>
Task<bool> InvalidateCodeAsync(Affiliation affiliation, string code);
}
}
| 44.741228 | 154 | 0.607489 |
236904748ba6126b8977eb28490ba8f79e6bf43f | 1,663 | cs | C# | src/NQuery/Text/TextChangeSet.cs | dallmair/nquery-vnext | cd32119a719391ecc58bdfdd65bafe08f4cad435 | [
"MIT"
] | 63 | 2015-01-20T19:31:34.000Z | 2022-03-15T19:15:36.000Z | src/NQuery/Text/TextChangeSet.cs | dallmair/nquery-vnext | cd32119a719391ecc58bdfdd65bafe08f4cad435 | [
"MIT"
] | 24 | 2017-09-21T00:25:10.000Z | 2022-03-29T17:32:19.000Z | src/NQuery/Text/TextChangeSet.cs | dallmair/nquery-vnext | cd32119a719391ecc58bdfdd65bafe08f4cad435 | [
"MIT"
] | 16 | 2015-02-20T10:35:16.000Z | 2021-02-10T05:51:24.000Z | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NQuery.Text
{
public sealed class TextChangeSet : IEnumerable<TextChange>
{
private readonly List<TextChange> _changes = new List<TextChange>();
public void ReplaceText(TextSpan span, string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
var change = TextChange.ForReplacement(span, newText);
RegisterChange(change);
}
public void InsertText(int position, string text)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
var change = TextChange.ForInsertion(position, text);
RegisterChange(change);
}
public void DeleteText(TextSpan span)
{
var change = TextChange.ForDeletion(span);
RegisterChange(change);
}
private void RegisterChange(TextChange newChange)
{
var conflicts = _changes.Any(existingChange => existingChange.Span.IntersectsWith(newChange.Span));
if (conflicts)
{
var message = string.Format(Resources.CannotRegisterOverlappingChange, newChange);
throw new InvalidOperationException(message);
}
_changes.Add(newChange);
}
public IEnumerator<TextChange> GetEnumerator()
{
return _changes.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | 28.672414 | 111 | 0.597715 |
3ee8be9a8e54a78be0a17a4b91ba3b7269f73abe | 4,911 | cs | C# | Unity/Assets/JCMG/AssetValidator/Editor/Validators/CrossSceneValidators/EnsureComponentIsUniqueValidator.cs | jeffcampbellmakesgames/unity-asset-validator | 5015ee510fe9d5e096b0ecd961b1cf16d646111e | [
"MIT"
] | 33 | 2017-11-06T08:48:19.000Z | 2021-11-24T13:49:05.000Z | Unity/Assets/JCMG/AssetValidator/Editor/Validators/CrossSceneValidators/EnsureComponentIsUniqueValidator.cs | jeffcampbellmakesgames/unity-asset-validator | 5015ee510fe9d5e096b0ecd961b1cf16d646111e | [
"MIT"
] | 1 | 2018-05-03T19:59:14.000Z | 2019-03-22T07:15:46.000Z | Unity/Assets/JCMG/AssetValidator/Editor/Validators/CrossSceneValidators/EnsureComponentIsUniqueValidator.cs | jeffcampbellmakesgames/unity-asset-validator | 5015ee510fe9d5e096b0ecd961b1cf16d646111e | [
"MIT"
] | 6 | 2018-05-01T21:17:01.000Z | 2021-09-25T16:38:05.000Z | /*
MIT License
Copyright (c) 2019 Jeff Campbell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace JCMG.AssetValidator.Editor
{
/// <summary>
/// <see cref="EnsureComponentIsUniqueValidator{T}"/> is an abstract validator that should be derived
/// from where there should only ever be one instance of a component present in one or more scene(s)
/// searched.
/// </summary>
/// <typeparam name="T"></typeparam>
[ValidatorDescription("This validator should be derived from where there should only ever be " +
"one instance of a component present in the scenes searched.")]
[ValidatorExample(@"
/// <summary>
/// FooComponent is a MonoBehavior derived component. There should only be
/// one FooComponent for any of the scenes searched.
/// </summary>
public class FooComponent : MonoBehaviour
{
}
/// <summary>
/// This is a subclass of EnsureComponentIsUniqueValidator; as the generic type is of FooComponent,
/// when this validator searches across one or more scenes, if it finds more than one instance of
/// FooComponent a validation warning will be dispatched per instance and an error noting that there
/// should only be one instance.
/// </summary>
public class EnsureFooComponentIsUniqueValidator : EnsureComponentIsUniqueValidator<FooComponent>
{
}
")]
public abstract class EnsureComponentIsUniqueValidator<T> : CrossSceneValidatorBase
where T : Component
{
/// <summary>
/// The name of the <see cref="Component"/> <see cref="Type"/> that should be a unique instance
/// across all scenes.
/// </summary>
public virtual string TargetTypeName
{
get { return _typeToTrack.Name; }
}
private readonly List<ValidationLog> _logs;
private readonly Type _typeToTrack;
private const string WarningFormat =
"Scene at path [{0}] is not the only Scene to contain an [{1}]...";
private const string FinalWarningFormat =
"More than one Scene of the Scene(s) validated has an [{0}] present";
protected EnsureComponentIsUniqueValidator()
{
_typeToTrack = typeof(T);
_logs = new List<ValidationLog>();
}
public sealed override void Search()
{
var scenePath = SceneManager.GetActiveScene().path;
var components = Object.FindObjectsOfType(_typeToTrack);
if (components.Length <= 1)
{
return;
}
// Create a warning log for each T component found. These are
// only used if more than one is found across all scenes
for (var i = 0; i < components.Length; i++)
{
if (!ShouldAddComponent(components[i] as T))
{
continue;
}
var vLog = CreateVLog(
components[i],
LogType.Warning,
string.Format(WarningFormat, scenePath, TargetTypeName),
scenePath,
LogSource.Scene);
_logs.Add(vLog);
}
}
/// <summary>
/// Should <typeparamref name="T"/> <paramref name="obj"/> be included as a component instance
/// that we want to track for uniqueness across one or more scene(s).
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public virtual bool ShouldAddComponent(T obj)
{
return true;
}
public sealed override bool Validate()
{
// If there is only one instance of a log for this type of component across all scenes,
// return true as validation is successful.
if (_logs.Count <= 1)
{
return true;
}
// Otherwise dispatch logs for all found non-unique components and return false.
for (var i = 0; i < _logs.Count; i++)
{
DispatchVLogEvent(_logs[i]);
}
DispatchVLogEvent(new ValidationLog
{
logType = LogType.Error,
source = LogSource.None,
validatorName = TypeName,
scenePath = string.Empty,
objectPath = string.Empty,
message = string.Format(FinalWarningFormat, _typeToTrack.Name)
});
return false;
}
}
}
| 31.480769 | 102 | 0.71798 |
41604b6f774aa154f6f8b7e9ee451aba12086f22 | 1,148 | cs | C# | Lxdn.Core.Expressions/Verbs/VerbFactory.cs | lxdotnet/lxd-core | 5529dd084ae6bfa23a9dc35f6795e6423249dc55 | [
"MIT"
] | null | null | null | Lxdn.Core.Expressions/Verbs/VerbFactory.cs | lxdotnet/lxd-core | 5529dd084ae6bfa23a9dc35f6795e6423249dc55 | [
"MIT"
] | null | null | null | Lxdn.Core.Expressions/Verbs/VerbFactory.cs | lxdotnet/lxd-core | 5529dd084ae6bfa23a9dc35f6795e6423249dc55 | [
"MIT"
] | null | null | null |
using System;
using System.Linq;
using Lxdn.Core.Expressions.Operators;
using Lxdn.Core.Expressions.Operators.Models.Domain;
namespace Lxdn.Core.Expressions.Verbs
{
public class VerbFactory
{
private readonly ExecutionEngine execution;
public VerbFactory(ExecutionEngine execution)
{
this.execution = execution;
}
public object Create(VerbModel model, BinaryStatement statement)
{
var verb = this.execution.Operators.Models.Sources
.Select(source => source.Assembly)
.SelectMany(assembly => assembly.GetTypes())
.Where(type => type.GetInterfaces().Any(i => i.IsGenericType && typeof(IVerb<>) == i.GetGenericTypeDefinition()) && !type.IsAbstract)
.SingleOrDefault(type => type.GetConstructors().Any(ctor => ctor.GetParameters().Any(p => p.ParameterType.IsInstanceOfType(model))));
if (verb == null)
throw new Exception("Cannot find verb for the model " + model.GetType().FullName);
return Activator.CreateInstance(verb, model, statement);
}
}
}
| 33.764706 | 149 | 0.638502 |
f01e5c059f944259e4b176ea0202807768982c1c | 1,677 | cs | C# | test/Sentry.AspNet.Tests/HttpContextExtensionsTests.cs | olegbreev/sentry-dotnet | 782bdfd5b6f306886d4162a1eba23848dc9bc07e | [
"MIT"
] | null | null | null | test/Sentry.AspNet.Tests/HttpContextExtensionsTests.cs | olegbreev/sentry-dotnet | 782bdfd5b6f306886d4162a1eba23848dc9bc07e | [
"MIT"
] | null | null | null | test/Sentry.AspNet.Tests/HttpContextExtensionsTests.cs | olegbreev/sentry-dotnet | 782bdfd5b6f306886d4162a1eba23848dc9bc07e | [
"MIT"
] | 1 | 2022-01-26T09:05:21.000Z | 2022-01-26T09:05:21.000Z | using Sentry.AspNet;
public class HttpContextExtensionsTests
{
[Fact]
public void StartSentryTransaction_CreatesValidTransaction()
{
// Arrange
var context = HttpContextBuilder.Build();
// Act
var transaction = context.StartSentryTransaction();
// Assert
transaction.Name.Should().Be("GET /the/path");
transaction.Operation.Should().Be("http.server");
}
[Fact]
public void StartSentryTransaction_BindsToScope()
{
// Arrange
using var _ = SentrySdk.UseHub(new Hub(
new SentryOptions { Dsn = "https://d4d82fc1c2c4032a83f3a29aa3a3aff@fake-sentry.io:65535/2147483647" },
Substitute.For<ISentryClient>()
));
var context = HttpContextBuilder.Build();
// Act
var transaction = context.StartSentryTransaction();
var transactionFromScope = SentrySdk.GetSpan();
// Assert
transactionFromScope.Should().BeSameAs(transaction);
}
[Fact]
public void FinishSentryTransaction_FinishesTransaction()
{
// Arrange
using var _ = SentrySdk.UseHub(new Hub(
new SentryOptions
{
Dsn = "https://d4d82fc1c2c4032a83f3a29aa3a3aff@fake-sentry.io:65535/2147483647"
},
Substitute.For<ISentryClient>()
));
var context = HttpContextBuilder.Build(404);
// Act
var transaction = context.StartSentryTransaction();
context.FinishSentryTransaction();
// Assert
transaction.IsFinished.Should().BeTrue();
transaction.Status.Should().Be(SpanStatus.NotFound);
}
}
| 27.491803 | 114 | 0.61777 |
f08df6f761e83689bb5e76ddb8b971df1828874a | 97 | cshtml | C# | src/Web/TattooShop.Web/Areas/Artists/Views/_ViewImports.cshtml | BojidarTonev/TattooShop | 845845c1b3b968b19f7256a9dd133e8b3b1294e3 | [
"MIT"
] | null | null | null | src/Web/TattooShop.Web/Areas/Artists/Views/_ViewImports.cshtml | BojidarTonev/TattooShop | 845845c1b3b968b19f7256a9dd133e8b3b1294e3 | [
"MIT"
] | null | null | null | src/Web/TattooShop.Web/Areas/Artists/Views/_ViewImports.cshtml | BojidarTonev/TattooShop | 845845c1b3b968b19f7256a9dd133e8b3b1294e3 | [
"MIT"
] | null | null | null | @using TattooShop.Web.Areas.Artists.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
| 32.333333 | 52 | 0.824742 |
ad74610bca3a04eaf09dd645ab637747c0a12466 | 3,322 | cs | C# | Sets and Dictionaries Advanced - Exercise/Ranking/Program.cs | IvanBerov/CSharp-Advanced | ac1539e025eb2a0eb5b0e95c4cf09b2e8ed8ef71 | [
"MIT"
] | null | null | null | Sets and Dictionaries Advanced - Exercise/Ranking/Program.cs | IvanBerov/CSharp-Advanced | ac1539e025eb2a0eb5b0e95c4cf09b2e8ed8ef71 | [
"MIT"
] | null | null | null | Sets and Dictionaries Advanced - Exercise/Ranking/Program.cs | IvanBerov/CSharp-Advanced | ac1539e025eb2a0eb5b0e95c4cf09b2e8ed8ef71 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
namespace Ranking
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> contestPass = new Dictionary<string, string>();
SortedDictionary<string, Dictionary<string, int>> nameContestPoints = new SortedDictionary<string, Dictionary<string, int>>();
string input = string.Empty;
while ((input = Console.ReadLine()) != "end of contests")
{
string[] commandArgs = input.Split(':');
string contest = commandArgs[0];
string password = commandArgs[1];
contestPass.Add(contest, password);
}
string command = string.Empty;
string[] separator = { "=>" };
while ((command = Console.ReadLine()) != "end of submissions")
{
string[] commArgs = command.Split(separator, StringSplitOptions.None);
string contestCheck = commArgs[0];
string passCheck = commArgs[1];
string nameCheck = commArgs[2];
int points = int.Parse(commArgs[3]);
if (contestPass.ContainsKey(contestCheck)
&& contestPass.ContainsValue(passCheck))
{
if (nameContestPoints.ContainsKey(nameCheck) == false)
{
nameContestPoints.Add(nameCheck, new Dictionary<string, int>());
nameContestPoints[nameCheck].Add(contestCheck, points);
}
if (nameContestPoints[nameCheck].ContainsKey(contestCheck))
{
if (nameContestPoints[nameCheck][contestCheck] < points)
{
nameContestPoints[nameCheck][contestCheck] = points;
}
}
else
{
nameContestPoints[nameCheck].Add(contestCheck, points);
}
}
}
Dictionary<string, int> usernameTotalPoints = new Dictionary<string, int>();
foreach (var kvp in nameContestPoints)
{
usernameTotalPoints[kvp.Key] = kvp.Value.Values.Sum();
}
string bestName = usernameTotalPoints.Keys.Max();
int bestPoints = usernameTotalPoints.Values.Max();
foreach (var pair in usernameTotalPoints)
{
if (pair.Value == bestPoints)
{
Console.WriteLine($"Best candidate is {pair.Key} with total {pair.Value} points.");
}
}
Console.WriteLine("Ranking: ");
foreach (var pair in nameContestPoints)
{
Dictionary<string, int> dictionary = pair.Value;
dictionary = dictionary.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
Console.WriteLine("{0}", pair.Key);
foreach (var kvp in dictionary)
{
Console.WriteLine("# {0} -> {1}", kvp.Key, kvp.Value);
}
}
}
}
}
| 34.604167 | 138 | 0.497592 |
481de31b34d15fd6b2e2d9117780351950462121 | 2,621 | cs | C# | Augury/DawgBuilder.cs | jeanbern/Augury | 6f13810d4c5d1b9fb38fad9c623b86a1f3a62847 | [
"MIT",
"Unlicense"
] | 2 | 2016-06-29T20:18:43.000Z | 2021-04-18T20:55:03.000Z | Augury/DawgBuilder.cs | jeanbern/Augury | 6f13810d4c5d1b9fb38fad9c623b86a1f3a62847 | [
"MIT",
"Unlicense"
] | 20 | 2016-07-12T21:08:17.000Z | 2016-10-28T19:03:46.000Z | Augury/DawgBuilder.cs | jeanbern/Augury | 6f13810d4c5d1b9fb38fad9c623b86a1f3a62847 | [
"MIT",
"Unlicense"
] | 1 | 2016-07-12T22:31:36.000Z | 2016-07-12T22:31:36.000Z | using System;
using System.Collections.Generic;
using System.Linq;
//http://stevehanov.ca/blog/index.php?id=115
//https://gist.github.com/smhanov/94230b422c2100ae4218
//No license
namespace Augury
{
internal class DawgBuilder
{
private string _previousWord = "";
public DawgNode Root = new DawgNode();
private readonly Dictionary<DawgNode, DawgNode> _minimizedNodes = new Dictionary<DawgNode, DawgNode>();
private readonly Stack<Tuple<DawgNode, char, DawgNode>> _uncheckedNodes = new Stack<Tuple<DawgNode, char, DawgNode>>();
public void Insert(string word)
{
if (string.Compare(word, _previousWord, StringComparison.OrdinalIgnoreCase) <= 0)
{
throw new Exception($"We expect the words to be sorted. But we received {_previousWord} followed by {word}");
}
int commonPrefix;
for (commonPrefix = 0; commonPrefix < Math.Min(word.Length, _previousWord.Length); commonPrefix++)
{
if (word[commonPrefix] != _previousWord[commonPrefix])
{
break;
}
}
Minimize(commonPrefix);
var node = _uncheckedNodes.Count == 0 ? Root : _uncheckedNodes.Peek().Item3;
foreach (var letter in word.Skip(commonPrefix))
{
var nextNode = new DawgNode();
node.Children[letter] = nextNode;
_uncheckedNodes.Push(new Tuple<DawgNode, char, DawgNode>(node, letter, nextNode));
node = nextNode;
}
node.TerminalNode = true;
_previousWord = word;
}
public DawgNode Finish()
{
Minimize(0);
_minimizedNodes.Clear();
_uncheckedNodes.Clear();
return Root;
}
private void Minimize(int downTo)
{
for (var i = _uncheckedNodes.Count - 1; i > downTo - 1; i--)
{
var unNode = _uncheckedNodes.Pop();
var parent = unNode.Item1;
var letter = unNode.Item2;
var child = unNode.Item3;
DawgNode newChild;
if (_minimizedNodes.TryGetValue(child, out newChild))
{
parent.Children[letter] = newChild;
}
else
{
_minimizedNodes.Add(child, child);
}
}
}
}
}
| 32.358025 | 128 | 0.516597 |
0e7700a32452b918763facc7dba53624d612d4b7 | 1,099 | cs | C# | WebSolutionTemplate/Web.Core.Frame/Dto/UseCaseResponses/General/Gen_ServicesResponse.cs | mroyon/CoreWebTemplate_V3.1 | 771831c6b7fb48b5f5ea24c193f5d8987bf02184 | [
"MIT"
] | null | null | null | WebSolutionTemplate/Web.Core.Frame/Dto/UseCaseResponses/General/Gen_ServicesResponse.cs | mroyon/CoreWebTemplate_V3.1 | 771831c6b7fb48b5f5ea24c193f5d8987bf02184 | [
"MIT"
] | null | null | null | WebSolutionTemplate/Web.Core.Frame/Dto/UseCaseResponses/General/Gen_ServicesResponse.cs | mroyon/CoreWebTemplate_V3.1 | 771831c6b7fb48b5f5ea24c193f5d8987bf02184 | [
"MIT"
] | null | null | null | using BDO.DataAccessObjects.Models;
using System.Collections.Generic;
using Web.Core.Frame.Dto;
using Web.Core.Frame.Interfaces;
using BDO.DataAccessObjects.ExtendedEntities;
namespace Web.Core.Frame.RequestResponse.UseCaseResponses
{
public class Gen_ServicesResponse : UseCaseResponseMessage
{
public gen_servicesEntity _gen_Services { get; }
public IEnumerable<gen_servicesEntity> _gen_ServicesList { get; }
public Error Errors { get; }
public Gen_ServicesResponse(bool success = false, string message = null, Error errors = null) : base(success, message)
{
Errors = errors;
}
public Gen_ServicesResponse(IEnumerable<gen_servicesEntity> gen_ServicesList, bool success = false, string message = null) : base(success, message)
{
_gen_ServicesList = gen_ServicesList;
}
public Gen_ServicesResponse(gen_servicesEntity gen_Services, bool success = false, string message = null) : base(success, message)
{
_gen_Services = gen_Services;
}
}
}
| 32.323529 | 155 | 0.690628 |
9c83ae2d609352d4aaac137736184668f33aee12 | 3,418 | cs | C# | DocuPanelSupport/MainWindowViewModel.cs | RHEAGROUP/docupanel | 901338530cbd628d36dcbb662c82dc32a29e4792 | [
"Apache-2.0"
] | 2 | 2017-03-17T09:14:51.000Z | 2021-12-27T19:55:41.000Z | DocuPanelSupport/MainWindowViewModel.cs | RHEAGROUP/docupanel | 901338530cbd628d36dcbb662c82dc32a29e4792 | [
"Apache-2.0"
] | 13 | 2020-11-27T20:15:35.000Z | 2022-02-26T01:21:32.000Z | DocuPanelSupport/MainWindowViewModel.cs | RHEAGROUP/docupanel | 901338530cbd628d36dcbb662c82dc32a29e4792 | [
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------------------------------
// <copyright file="MainWindowViewModel.cs" company="RHEA System S.A.">
//
// Copyright 2017 RHEA System S.A.
//
// 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.
//
// </copyright>
// --------------------------------------------------------------------------------------------------
namespace DocuPanelSupport
{
using System;
using System.IO;
using ReactiveUI;
using System.Reflection;
/// <summary>
/// The view-model for the main window.
/// </summary>
public class MainWindowViewModel : ReactiveObject
{
/// <summary>
/// Backing field for <see cref="PathDocumentationIndex"/>.
/// </summary>
private string pathDocumentationIndex;
/// <summary>
/// Backing field for <see cref="AppDataRoot"/>.
/// </summary>
private string appDataRoot;
/// <summary>
/// Path to the assembly.
/// </summary>
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
/// <summary>
/// Gets or sets the root directory of the documentation.
/// </summary>
public string PathDocumentationIndex
{
get { return this.pathDocumentationIndex; }
set { this.RaiseAndSetIfChanged(ref this.pathDocumentationIndex, value); }
}
/// <summary>
/// Gets or sets the path of the application data folder.
/// </summary>
public string AppDataRoot
{
get { return this.appDataRoot; }
set { this.RaiseAndSetIfChanged(ref this.appDataRoot, value); }
}
/// <summary>
/// Gets or sets the property which indicates whether the indexation of the documentation needs to be updated.
/// </summary>
public bool UpdateIndexation { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MainWindowViewModel"/> class.
/// </summary>
public MainWindowViewModel()
{
this.SetProperties();
}
/// <summary>
/// Sets the properties of this view-model.
/// </summary>
private void SetProperties()
{
this.PathDocumentationIndex = Path.Combine(AssemblyDirectory, @"Documentation\book.json");
this.AppDataRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RHEA_Group");
this.UpdateIndexation = true;
}
}
}
| 34.525253 | 133 | 0.562902 |
9cc9eb279bce98090bd33f711df4b5f09256c37a | 67,520 | cs | C# | OgcApi.Net.Features/OpenApi/OpenApiGenerator.cs | sam-is/OgcApi.Net | 7359848700f0cf0e7fe718c724cf3dd9883263bd | [
"MIT"
] | 4 | 2021-05-31T16:24:35.000Z | 2022-03-01T11:53:54.000Z | OgcApi.Net.Features/OpenApi/OpenApiGenerator.cs | sam-is/OgcApi.Net | 7359848700f0cf0e7fe718c724cf3dd9883263bd | [
"MIT"
] | 5 | 2021-09-08T10:41:50.000Z | 2022-03-28T15:13:49.000Z | OgcApi.Net.Features/OpenApi/OpenApiGenerator.cs | sam-is/OgcApi.Net | 7359848700f0cf0e7fe718c724cf3dd9883263bd | [
"MIT"
] | null | null | null | using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using OgcApi.Net.Features.Options;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OgcApi.Net.Features.OpenApi
{
public class OpenApiGenerator : IOpenApiGenerator
{
private readonly OgcApiOptions _apiOptions;
private readonly IServiceProvider _serviceProvider;
public OpenApiGenerator(IOptionsMonitor<OgcApiOptions> apiOptions, IServiceProvider serviceProvider)
{
_apiOptions = apiOptions?.CurrentValue ?? throw new ArgumentNullException(nameof(apiOptions));
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
public OpenApiDocument GetDocument(Uri baseUrl)
{
var openApiDocument = new OpenApiDocument
{
Info = new OpenApiInfo
{
Title = _apiOptions.LandingPage.Title,
Description = _apiOptions.LandingPage.Description,
Version = _apiOptions.LandingPage.Version,
Contact = new OpenApiContact()
{
Name = _apiOptions.LandingPage.ContactName,
Url = _apiOptions.LandingPage.ContactUrl
},
License = new OpenApiLicense()
{
Name = _apiOptions.LandingPage.LicenseName,
Url = _apiOptions.LandingPage.LicenseUrl
}
},
Servers = new List<OpenApiServer>
{
new() { Url = baseUrl.ToString() }
},
Paths = new OpenApiPaths
{
["/"] = new()
{
Operations = new Dictionary<OperationType, OpenApiOperation>
{
[OperationType.Get] = new()
{
Description = "The landing page provides links to the API definition, the conformance statements and to the feature collections in this dataset.",
Tags = new List<OpenApiTag>
{
new() { Name = "Capabilities" }
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["title"] = new() { Type = "string" },
["description"] = new() { Type = "string" },
["links"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "Link", Type = ReferenceType.Schema }
}
}
},
Required = new HashSet<string> { "links" }
}
}
}
}
}
}
}
},
["/conformance"] = new()
{
Operations = new Dictionary<OperationType, OpenApiOperation>
{
[OperationType.Get] = new()
{
Description = "Information about specifications that this API conforms to",
Tags = new List<OpenApiTag>
{
new() { Name = "Capabilities" }
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["conformsTo"] = new()
{
Type = "array",
Items = new OpenApiSchema { Type = "string" }
}
},
Required = new HashSet<string> { "conformsTo" }
}
}
}
}
}
}
}
},
["/collections"] = new()
{
Operations = new Dictionary<OperationType, OpenApiOperation>
{
[OperationType.Get] = new()
{
Description = "The feature collections in the dataset",
Tags = new List<OpenApiTag>
{
new() { Name = "Capabilities" }
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["links"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "Link", Type = ReferenceType.Schema }
}
},
["collections"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "Collection", Type = ReferenceType.Schema }
}
}
},
Required = new HashSet<string> { "links", "collections" }
}
}
}
}
}
}
}
}
},
Components = new OpenApiComponents
{
Schemas = new Dictionary<string, OpenApiSchema>
{
["Link"] = new()
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["href"] = new() { Type = "string" },
["rel"] = new() { Type = "string" },
["type"] = new() { Type = "string" },
["hreflang"] = new() { Type = "string" },
["title"] = new() { Type = "string" },
["length"] = new() { Type = "string" },
},
Required = new HashSet<string> { "href" }
},
["Collection"] = new()
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["id"] = new() { Type = "string", Description = "identifier of the collection used, for example, in URIs" },
["title"] = new() { Type = "string", Description = "human readable title of the collection" },
["description"] = new() { Type = "string", Description = "a description of the features in the collection" },
["links"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "Link", Type = ReferenceType.Schema }
}
},
["extent"] = new()
{
Type = "object",
Description = "The extent of the features in the collection",
Properties = new Dictionary<string, OpenApiSchema>
{
["spatial"] = new()
{
Type = "object",
Description = "The spatial extent of the features in the collection",
Properties = new Dictionary<string, OpenApiSchema>
{
["bbox"] = new()
{
Description = "One or more bounding boxes that describe the spatial extent of the dataset",
Type = "array",
MinItems = 1,
Items = new OpenApiSchema
{
Description = "Each bounding box is provided as four or six numbers, depending on\n" +
" whether the coordinate reference system includes a vertical axis\n" +
" (height or depth):\n\n" +
"* Lower left corner, coordinate axis 1\n" +
"* Lower left corner, coordinate axis 2\n" +
"* Upper right corner, coordinate axis 1\n" +
"* Upper right corner, coordinate axis 2\n\n" +
"The coordinate reference system of the values is WGS 84 longitude/latitude\n" +
"(http://www.opengis.net/def/crs/OGC/1.3/CRS84) unless a different ordinate\n" +
"reference system is specified in `crs`.\n" +
"For WGS 84 longitude/latitude the values are in most cases the sequence of\n" +
"minimum longitude, minimum latitude, maximum longitude and maximum latitude.\n" +
"However, in cases where the box spans the antimeridian the first value\n" +
"(west-most box edge) is larger than the third value (east-most box edge).\n" +
"If the vertical axis is included, the third and the sixth number are\n" +
"the bottom and the top of the 3-dimensional bounding box.\n" +
"If a feature has multiple spatial geometry properties, it is the decision of the\n" +
"server whether only a single spatial geometry property is used to determine\n" +
"the extent or all relevant geometries.",
Type = "array",
MinItems = 4,
MaxItems = 6,
Items = new OpenApiSchema
{
Type = "number"
},
Example = new OpenApiArray
{
new OpenApiDouble(-180),
new OpenApiDouble(-90),
new OpenApiDouble(180),
new OpenApiDouble(90)
}
}
},
["crs"] = new()
{
Description = "Coordinate reference system of the coordinates in the spatial extent\n" +
"(property `bbox`). The default reference system is WGS 84 longitude/latitude",
Type = "string",
Default = new OpenApiString("http://www.opengis.net/def/crs/OGC/1.3/CRS84")
}
}
},
["temporal"] = new()
{
Type = "object",
Description = "The temporal extent of the features in the collection",
Properties = new Dictionary<string, OpenApiSchema>
{
["interval"] = new()
{
Description = "One or more time intervals that describe the temporal extent of the dataset.\n" +
"The value `null` is supported and indicates an open time interval",
Type = "array",
MinItems = 1,
Items = new OpenApiSchema
{
Description = "Begin and end times of the time interval. The timestamps\n" +
"are in the coordinate reference system specified in `trs`. By default\n" +
"this is the Gregorian calendar.",
Type = "array",
MinItems = 2,
MaxItems = 2,
Items = new OpenApiSchema
{
Type = "string",
Format = "date-time",
Nullable = true,
Example = new OpenApiArray
{
new OpenApiString("2011-11-11T12:22:11Z"),
new OpenApiNull()
}
}
}
},
["trs"] = new()
{
Description = "Coordinate reference system of the coordinates in the temporal extent\n" +
"(property `interval`). The default reference system is the Gregorian calendar.\n" +
"In the Core this is the only supported temporal reference system.\n" +
"Extensions may support additional temporal reference systems and add\n" +
"additional enum values.",
Type = "string",
Default = new OpenApiString("http://www.opengis.net/def/uom/ISO-8601/0/Gregorian")
}
}
}
}
},
["itemType"] = new()
{
Type = "string",
Description = "indicator about the type of the items in the collection (the default value is 'feature')",
Default = new OpenApiString("feature")
},
["crs"] = new()
{
Description = "the list of coordinate reference systems supported by the service",
Type = "array",
Items = new OpenApiSchema { Type = "string" },
Default = new OpenApiString("http://www.opengis.net/def/crs/OGC/1.3/CRS84")
}
},
Required = new HashSet<string> { "id", "links" }
},
["ProblemDetails"] = new()
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new()
{
Type = "string",
Nullable = true
},
["title"] = new()
{
Type = "string",
Nullable = true
},
["status"] = new()
{
Type = "integer",
Format = "int32",
Nullable = true
},
["detail"] = new()
{
Type = "string",
Nullable = true
},
["instance"] = new()
{
Type = "string",
Nullable = true
}
}
},
}
}
};
foreach (var collection in _apiOptions.Collections.Items)
{
openApiDocument.Paths.Add($"/collections/{collection.Id}", new OpenApiPathItem
{
Operations = new Dictionary<OperationType, OpenApiOperation>
{
[OperationType.Get] = new()
{
Tags = new List<OpenApiTag>
{
new() { Name = collection.Title }
},
Summary = "Feature collection metadata",
Description = collection.Description,
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "Collection", Type = ReferenceType.Schema }
}
}
}
},
["404"] = new()
{
Description = "Not Found",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
}
}
}
}
});
openApiDocument.Paths.Add($"/collections/{collection.Id}/items", new OpenApiPathItem
{
Operations = GetFeatureCollectionOperations(collection)
});
openApiDocument.Paths.Add($"/collections/{collection.Id}/items/{{featureId}}", new OpenApiPathItem
{
Operations = GetFeatureOperations(collection)
});
}
if (_apiOptions.UseApiKeyAuthorization)
{
openApiDocument.SecurityRequirements = new List<OpenApiSecurityRequirement>
{
new()
{
[new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" }
}] = Array.Empty<string>()
}
};
openApiDocument.Components.SecuritySchemes = new Dictionary<string, OpenApiSecurityScheme>
{
["ApiKey"] = new()
{
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Query,
Name = "apiKey",
Description = "API key"
}
};
}
return openApiDocument;
}
private OpenApiSchema GetFeatureCollectionSchema(CollectionOptions collectionOptions)
{
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "features" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Enum = new List<IOpenApiAny> { new OpenApiString("FeatureCollection") } },
["features"] = new()
{
Type = "array",
Items = GetFeatureSchema(collectionOptions)
},
["links"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "Link", Type = ReferenceType.Schema }
}
},
["timeStamp"] = new()
{
Type = "string",
Format = "date-time"
},
["numberMatched"] = new()
{
Type = "integer",
Minimum = 0
},
["numberReturned"] = new()
{
Type = "integer",
Minimum = 0
}
}
};
}
private OpenApiSchema GetFeatureSchema(CollectionOptions collectionOptions)
{
var collectionSourceOptions = Utils.GetCollectionSourceOptions(_serviceProvider, collectionOptions.Id);
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "geometry", "properties" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Enum = new List<IOpenApiAny> { new OpenApiString("Feature") } },
["geometry"] = GetGeometrySchema(collectionSourceOptions?.GeometryGeoJsonType),
["properties"] = new()
{
Type = "object",
Nullable = true,
Properties = collectionSourceOptions?.Properties?.ToDictionary(key => key, _ => new OpenApiSchema())
},
["id"] = new()
{
OneOf = new List<OpenApiSchema>
{
new() { Type = "string" },
new() { Type = "integer" }
}
},
["links"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "Link", Type = ReferenceType.Schema }
}
}
}
};
}
private static OpenApiSchema GetGeometrySchema(string geometryType)
{
return geometryType switch
{
"Point" => GetPointSchema(),
"MultiPoint" => new OpenApiSchema
{
AnyOf = new List<OpenApiSchema>
{
GetPointSchema(),
GetMultiPointSchema()
}
},
"LineString" => GetLineStringSchema(),
"MultiLineString" => new OpenApiSchema
{
AnyOf = new List<OpenApiSchema>
{
GetLineStringSchema(),
GetMultiLineStringSchema()
}
},
"Polygon" => GetPolygonSchema(),
"MultiPolygon" => new OpenApiSchema
{
AnyOf = new List<OpenApiSchema>
{
GetPolygonSchema(),
GetMultiPolygonSchema()
}
},
_ => null
};
}
private static OpenApiSchema GetPointSchema()
{
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "coordinates" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Type = "string", Enum = { new OpenApiString("Point") } },
["coordinates"] = new()
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema { Type = "number" }
}
}
};
}
private static OpenApiSchema GetMultiPointSchema()
{
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "coordinates" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Type = "string", Enum = { new OpenApiString("MultiPoint") } },
["coordinates"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema { Type = "number" }
}
}
}
};
}
private static OpenApiSchema GetLineStringSchema()
{
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "coordinates" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Type = "string", Enum = { new OpenApiString("LineString") } },
["coordinates"] = new()
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema { Type = "number" }
}
}
}
};
}
private static OpenApiSchema GetMultiLineStringSchema()
{
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "coordinates" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Type = "string", Enum = { new OpenApiString("MultiLineString") } },
["coordinates"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema { Type = "number" }
}
}
}
}
};
}
private static OpenApiSchema GetPolygonSchema()
{
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "coordinates" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Type = "string", Enum = { new OpenApiString("Polygon") } },
["coordinates"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Type = "array",
MinItems = 4,
Items = new OpenApiSchema
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema { Type = "number" }
}
}
}
}
};
}
private static OpenApiSchema GetMultiPolygonSchema()
{
return new OpenApiSchema
{
Type = "object",
Required = new HashSet<string> { "type", "coordinates" },
Properties = new Dictionary<string, OpenApiSchema>
{
["type"] = new() { Type = "string", Enum = { new OpenApiString("MultiPolygon") } },
["coordinates"] = new()
{
Type = "array",
Items = new OpenApiSchema
{
Type = "array",
Items = new OpenApiSchema
{
Type = "array",
MinItems = 4,
Items = new OpenApiSchema
{
Type = "array",
MinItems = 2,
Items = new OpenApiSchema { Type = "number" }
}
}
}
}
}
};
}
private Dictionary<OperationType, OpenApiOperation> GetFeatureOperations(CollectionOptions collection)
{
var result = new Dictionary<OperationType, OpenApiOperation>
{
[OperationType.Get] = new()
{
Tags = new List<OpenApiTag>
{
new() { Name = collection.Title }
},
Summary = "Fetch feature",
Description = $"Fetch the feature with id featureId in the feature collection with id {collection.Id}.",
Parameters = new List<OpenApiParameter>
{
new()
{
Name = "featureId",
Description = "Identifier of a feature",
Required = true,
In = ParameterLocation.Path,
Schema = new OpenApiSchema { Type = "string" }
},
new()
{
Name = "crs",
Description = "The coordinates of all geometry-valued properties in the response document will be presented in the requested CRS",
In = ParameterLocation.Query,
Schema = new OpenApiSchema
{
Type = "string",
Format = "uri"
}
}
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/geo+json"] = new()
{
Schema = GetFeatureSchema(collection)
}
}
},
["400"] = new()
{
Description = "Bad Request",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["404"] = new()
{
Description = "Not Found",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
}
}
}
};
if (collection.AllowReplace)
{
result.Add(OperationType.Put, new OpenApiOperation
{
Tags = new List<OpenApiTag>
{
new() { Name = collection.Title }
},
Summary = "Replace feature",
Description = "Replace an existing resource",
Parameters = new List<OpenApiParameter>
{
new()
{
Name = "featureId",
Description = "Identifier of a feature to replace",
Required = true,
In = ParameterLocation.Path,
Schema = new OpenApiSchema { Type = "string" }
},
new()
{
Name = "crs",
Description = "The coordinates of all geometry-valued properties in the request document will be converted from the requested CRS",
In = ParameterLocation.Query,
Schema = new OpenApiSchema
{
Type = "string",
Format = "uri"
}
}
},
RequestBody = new OpenApiRequestBody
{
Content = new Dictionary<string, OpenApiMediaType>
{
["application/geo+json"] = new()
{
Schema = GetFeatureSchema(collection)
}
}
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success"
},
["400"] = new()
{
Description = "Bad Request",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["401"] = new()
{
Description = "Unauthorized",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["404"] = new()
{
Description = "Not Found",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
}
}
});
}
if (collection.AllowDelete)
{
result.Add(OperationType.Delete, new OpenApiOperation
{
Tags = new List<OpenApiTag>
{
new() { Name = collection.Title }
},
Summary = "Delete feature",
Description = "Remove a resource from a collection",
Parameters = new List<OpenApiParameter>
{
new()
{
Name = "featureId",
Description = "Identifier of a feature to delete",
Required = true,
In = ParameterLocation.Path,
Schema = new OpenApiSchema { Type = "string" }
}
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success"
},
["400"] = new()
{
Description = "Bad Request",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["401"] = new()
{
Description = "Unauthorized",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["404"] = new()
{
Description = "Not Found",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
}
}
});
}
if (collection.AllowUpdate)
{
result.Add(OperationType.Patch, new OpenApiOperation
{
Tags = new List<OpenApiTag>
{
new() { Name = collection.Title }
},
Summary = "Update feature",
Description = "Modify an existing resource",
Parameters = new List<OpenApiParameter>
{
new()
{
Name = "featureId",
Description = "Identifier of a feature to update",
Required = true,
In = ParameterLocation.Path,
Schema = new OpenApiSchema { Type = "string" }
},
new()
{
Name = "crs",
Description = "The coordinates of all geometry-valued properties in the request document will be converted from the requested CRS",
In = ParameterLocation.Query,
Schema = new OpenApiSchema
{
Type = "string",
Format = "uri"
}
}
},
RequestBody = new OpenApiRequestBody
{
Content = new Dictionary<string, OpenApiMediaType>
{
["application/geo+json"] = new()
{
Schema = GetFeatureSchema(collection)
}
}
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success"
},
["400"] = new()
{
Description = "Bad Request",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["401"] = new()
{
Description = "Unauthorized",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["404"] = new()
{
Description = "Not Found",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
}
}
});
}
return result;
}
private Dictionary<OperationType, OpenApiOperation> GetFeatureCollectionOperations(CollectionOptions collection)
{
var result = new Dictionary<OperationType, OpenApiOperation>
{
[OperationType.Get] = new()
{
Tags = new List<OpenApiTag>
{
new() { Name = collection.Title }
},
Summary = "Fetch features",
Description = $"Fetch features of the feature collection with id {collection.Id}.\n" +
"Every feature in a dataset belongs to a collection. A dataset may consist of multiple feature collections. A feature collection is often a collection of features of a similar type, based on a common schema.",
Parameters = new List<OpenApiParameter>
{
new()
{
Name = "limit",
Description = "Limits the number of items that are presented in the response document",
In = ParameterLocation.Query,
Style = ParameterStyle.Form,
Explode = false,
Schema = new OpenApiSchema
{
Type = "integer",
Format = "int32",
Default = new OpenApiInteger(10),
Minimum = 1,
Maximum = 10000
}
},
new()
{
Name = "offset",
Description = "Offset for requesting objects. The resulting response will contain a link for the next features page",
In = ParameterLocation.Query,
Schema = new OpenApiSchema
{
Type = "integer",
Format = "int32",
Default = new OpenApiInteger(0)
}
},
new()
{
Name = "bbox",
Description = @"Only features that have a geometry that intersects the bounding box are selected.\n" +
"The bounding box is provided as four or six numbers, depending on whether the\n" +
"coordinate reference system includes a vertical axis (height or depth):\n\n" +
"* Lower left corner, coordinate axis 1\n" +
"* Lower left corner, coordinate axis 2\n" +
"* Upper right corner, coordinate axis 1\n" +
"* Upper right corner, coordinate axis 2\n\n" +
"The coordinate reference system of the values is WGS 84 longitude/latitude\n" +
"(http://www.opengis.net/def/crs/OGC/1.3/CRS84) unless a different coordinate\n" +
"reference system is specified in the parameter `bbox-crs`.\n\n" +
"For WGS 84 longitude/latitude the values are in most cases the sequence of\n" +
"minimum longitude, minimum latitude, maximum longitude and maximum latitude.\n" +
"However, in cases where the box spans the antimeridian the first value\n" +
"(west-most box edge) is larger than the third value (east-most box edge).\n\n" +
"If the vertical axis is included, the third and the sixth number are\n" +
"the bottom and the top of the 3-dimensional bounding box.\n\n" +
"If a feature has multiple spatial geometry properties, it is the decision of the\n" +
"server whether only a single spatial geometry property is used to determine\n" +
"the extent or all relevant geometries.",
In = ParameterLocation.Query,
Style = ParameterStyle.Form,
Explode = false,
Schema = new OpenApiSchema
{
Type = "array",
MinItems = 4,
MaxItems = 6,
Items = new OpenApiSchema
{
Type = "number"
}
}
},
new()
{
Name = "bbox-crs",
Description = "Parameter may be used to assert the CRS used for the coordinate values of the bbox parameter. " +
"If the bbox-crs parameter is not specified then the coordinate values of the bbox parameter is the default CRS that is http://www.opengis.net/def/crs/OGC/1.3/CRS84",
In = ParameterLocation.Query,
Schema = new OpenApiSchema
{
Type = "string",
Format = "uri"
}
},
new()
{
Name = "datetime",
Description = "Either a date-time or an interval, open or closed. Date and time expressions\n" +
"adhere to RFC 3339. Open intervals are expressed using double-dots.\n\n" +
"Examples:\n\n" +
"* A date-time: \"2018-02-12T23:20:50Z\"\n" +
"* A closed interval: \"2018-02-12T00:00:00Z/2018-03-18T12:31:12Z\"\n" +
"* Open intervals: \"2018-02-12T00:00:00Z/..\" or \"../2018-03-18T12:31:12Z\"\n\n" +
"Only features that have a temporal property that intersects the value of\n" +
"`datetime` are selected.\n\n" +
"If a feature has multiple temporal properties, it is the decision of the\n" +
"server whether only a single temporal property is used to determine\n" +
"the extent or all relevant temporal properties.",
In = ParameterLocation.Query,
Style = ParameterStyle.Form,
Explode = false,
Schema = new OpenApiSchema
{
Type = "string"
}
},
new()
{
Name = "crs",
Description = "The coordinates of all geometry-valued properties in the response document will be presented in the requested CRS",
In = ParameterLocation.Query,
Schema = new OpenApiSchema
{
Type = "string",
Format = "uri"
}
}
},
Responses = new OpenApiResponses
{
["200"] = new()
{
Description = "Success",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/geo+json"] = new()
{
Schema = GetFeatureCollectionSchema(collection)
}
}
},
["400"] = new()
{
Description = "Bad Request",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["404"] = new()
{
Description = "Not Found",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
}
}
}
};
if (collection.AllowCreate)
{
result.Add(OperationType.Post, new OpenApiOperation
{
Tags = new List<OpenApiTag>
{
new() { Name = collection.Title }
},
Summary = "Create feature",
Description = "Add a new resource to a collection",
Parameters = new List<OpenApiParameter>
{
new()
{
Name = "crs",
Description = "The coordinates of all geometry-valued properties in the request document will be converted from the requested CRS",
In = ParameterLocation.Query,
Schema = new OpenApiSchema
{
Type = "string",
Format = "uri"
}
}
},
RequestBody = new OpenApiRequestBody
{
Content = new Dictionary<string, OpenApiMediaType>
{
["application/geo+json"] = new()
{
Schema = GetFeatureSchema(collection)
}
}
},
Responses = new OpenApiResponses
{
["201"] = new()
{
Description = "Success",
Headers = new Dictionary<string, OpenApiHeader>
{
["Location"] = new()
}
},
["400"] = new()
{
Description = "Bad Request",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["401"] = new()
{
Description = "Unauthorized",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
},
["404"] = new()
{
Description = "Not Found",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new()
{
Schema = new OpenApiSchema
{
Reference = new OpenApiReference { Id = "ProblemDetails", Type = ReferenceType.Schema }
}
}
}
}
}
});
}
return result;
}
}
}
| 50.163447 | 243 | 0.305332 |
1660a42873bc731ebbb955d0cd0ba09c69f4f510 | 806 | cs | C# | src/TypeSafe.Http.Net.Api/Building/IServiceCallContext.cs | HelloKitty/TypeSafe.HTTP.NET | a3f8bc711369033bf2029e26b5c7d868990ed73c | [
"MIT"
] | 7 | 2017-07-10T08:14:31.000Z | 2020-04-28T17:43:56.000Z | src/TypeSafe.Http.Net.Api/Building/IServiceCallContext.cs | HelloKitty/TypeSafe.HTTP.NET | a3f8bc711369033bf2029e26b5c7d868990ed73c | [
"MIT"
] | 3 | 2018-02-25T10:53:58.000Z | 2018-08-25T14:14:57.000Z | src/TypeSafe.Http.Net.Api/Building/IServiceCallContext.cs | HelloKitty/TypeSafe.HTTP.NET | a3f8bc711369033bf2029e26b5c7d868990ed73c | [
"MIT"
] | 1 | 2020-03-14T00:31:24.000Z | 2020-03-14T00:31:24.000Z | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace TypeSafe.Http.Net
{
/// <summary>
/// Represents the context of a service call.
/// (Ex. user calls serviceProxy.Authenticate(username, password) on its custom made IAuthServer interface
/// so we package up contextual information for the service call so it is easily extended and passed around as the current
/// service request/call).
/// </summary>
public interface IServiceCallContext
{
Type ServiceType { get; }
//The reason we have this instead of a raw string is that
//if we don't provide the method info then we have to likely resolve the MethodInfo
//down the line multiple times AND resolve it while considering potential overloads
MethodInfo ServiceMethod { get; }
}
}
| 33.583333 | 124 | 0.754342 |
fbd679fe9b4520f727a64fa7219b65eb0086b3ed | 92 | cs | C# | Sample/SaaSEqt/eShop/Business/Business/SeedWork/IAggregateRoot.cs | Liang-Zhinian/CqrsFrameworkDotNet | a5a332a5138f0338a4741571331cfe0edb9a0031 | [
"MIT"
] | null | null | null | Sample/SaaSEqt/eShop/Business/Business/SeedWork/IAggregateRoot.cs | Liang-Zhinian/CqrsFrameworkDotNet | a5a332a5138f0338a4741571331cfe0edb9a0031 | [
"MIT"
] | null | null | null | Sample/SaaSEqt/eShop/Business/Business/SeedWork/IAggregateRoot.cs | Liang-Zhinian/CqrsFrameworkDotNet | a5a332a5138f0338a4741571331cfe0edb9a0031 | [
"MIT"
] | null | null | null | namespace SaaSEqt.eShop.Business.Seedwork
{
public interface IAggregateRoot { }
}
| 13.142857 | 42 | 0.717391 |
14da6944f0a1197bfe183197c28fb9fd2cea99f9 | 11,850 | cs | C# | ClosedXML_Tests/Excel/Rows/RowTests.cs | diouxis/ClosedXML | 8c60dccf369e4bd471cf0d4b6b6384353d08298c | [
"MIT"
] | 1 | 2021-07-23T03:32:08.000Z | 2021-07-23T03:32:08.000Z | ClosedXML_Tests/Excel/Rows/RowTests.cs | diouxis/ClosedXML | 8c60dccf369e4bd471cf0d4b6b6384353d08298c | [
"MIT"
] | null | null | null | ClosedXML_Tests/Excel/Rows/RowTests.cs | diouxis/ClosedXML | 8c60dccf369e4bd471cf0d4b6b6384353d08298c | [
"MIT"
] | null | null | null | using System;
using System.Linq;
using ClosedXML.Excel;
using NUnit.Framework;
namespace ClosedXML_Tests.Excel
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestFixture]
public class RowTests
{
[Test]
public void CopyRow()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Test").Style.Font.SetBold();
ws.FirstRow().CopyTo(ws.Row(2));
Assert.IsTrue(ws.Cell("A2").Style.Font.Bold);
}
[Test]
public void InsertingRowsAbove1()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Rows("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Row(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLRow row1 = ws.Row(1);
IXLRow row2 = ws.Row(2);
IXLRow row3 = ws.Row(3);
IXLRow rowIns = ws.Row(1).InsertRowsAbove(1).First();
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Row(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Row(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Row(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Row(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Row(3).Cell(2).GetString());
Assert.AreEqual(ws.Style.Fill.BackgroundColor, rowIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, rowIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, rowIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, row2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, row2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, row2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", row2.Cell(2).GetString());
}
[Test]
public void InsertingRowsAbove2()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Rows("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Row(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLRow row1 = ws.Row(1);
IXLRow row2 = ws.Row(2);
IXLRow row3 = ws.Row(3);
IXLRow rowIns = ws.Row(2).InsertRowsAbove(1).First();
Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Row(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Row(3).Cell(2).GetString());
Assert.AreEqual(XLColor.Red, rowIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, rowIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, rowIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, row2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, row2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, row2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", row2.Cell(2).GetString());
}
[Test]
public void InsertingRowsAbove3()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Rows("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Row(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLRow row1 = ws.Row(1);
IXLRow row2 = ws.Row(2);
IXLRow row3 = ws.Row(3);
IXLRow rowIns = ws.Row(3).InsertRowsAbove(1).First();
Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Row(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Row(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Row(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Row(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Row(2).Cell(2).GetString());
Assert.AreEqual(XLColor.Yellow, rowIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, rowIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, rowIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, row2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, row2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, row2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, row3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", row2.Cell(2).GetString());
}
[Test]
public void InsertingRowsAbove4()
{
using (var wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("Sheet1");
ws.Row(2).Height = 15;
ws.Row(3).Height = 20;
ws.Row(4).Height = 25;
ws.Row(5).Height = 35;
ws.Row(2).FirstCell().SetValue("Row height: 15");
ws.Row(3).FirstCell().SetValue("Row height: 20");
ws.Row(4).FirstCell().SetValue("Row height: 25");
ws.Row(5).FirstCell().SetValue("Row height: 35");
ws.Range("3:3").InsertRowsAbove(1);
Assert.AreEqual(15, ws.Row(2).Height);
Assert.AreEqual(20, ws.Row(4).Height);
Assert.AreEqual(25, ws.Row(5).Height);
Assert.AreEqual(35, ws.Row(6).Height);
Assert.AreEqual(20, ws.Row(3).Height);
ws.Row(3).ClearHeight();
Assert.AreEqual(ws.RowHeight, ws.Row(3).Height);
}
}
[Test]
public void NoRowsUsed()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
Int32 count = 0;
foreach (IXLRow row in ws.RowsUsed())
count++;
foreach (IXLRangeRow row in ws.Range("A1:C3").RowsUsed())
count++;
Assert.AreEqual(0, count);
}
[Test]
public void RowUsed()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell(1, 2).SetValue("Test");
ws.Cell(1, 3).SetValue("Test");
IXLRangeRow fromRow = ws.Row(1).RowUsed();
Assert.AreEqual("B1:C1", fromRow.RangeAddress.ToStringRelative());
IXLRangeRow fromRange = ws.Range("A1:E1").FirstRow().RowUsed();
Assert.AreEqual("B1:C1", fromRange.RangeAddress.ToStringRelative());
}
[Test]
public void UngroupFromAll()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Rows(1, 2).Group();
ws.Rows(1, 2).Ungroup(true);
}
[Test]
public void NegativeRowNumberIsInvalid()
{
var ws = new XLWorkbook().AddWorksheet("Sheet1") as XLWorksheet;
var row = new XLRow(ws, -1);
Assert.IsFalse(row.RangeAddress.IsValid);
}
}
}
| 44.216418 | 106 | 0.5973 |
14f0c1d0416406901176fa8956271360c1726da1 | 3,898 | cs | C# | unity_project/Assets/Scripts/GameOverEvaluation.cs | SoPra13/SoPra_Client | e292f9d580ed6926fcf73a26bffc005780d50081 | [
"Apache-2.0"
] | null | null | null | unity_project/Assets/Scripts/GameOverEvaluation.cs | SoPra13/SoPra_Client | e292f9d580ed6926fcf73a26bffc005780d50081 | [
"Apache-2.0"
] | 4 | 2020-03-16T11:49:45.000Z | 2020-03-26T09:03:12.000Z | unity_project/Assets/Scripts/GameOverEvaluation.cs | SoPra13/SoPra_Client | e292f9d580ed6926fcf73a26bffc005780d50081 | [
"Apache-2.0"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using TMPro;
using System;
public class GameOverEvaluation : MonoBehaviour
{
public GameObject mainPlayerBar;
public GameObject otherPlayerBar;
public GameObject mainPlayerFrame;
public GameObject otherPlayerFrame;
private Avatars avatars;
private MockStats mockStats;
private float x;
private float y;
private bool waitForUpdate = false;
[DllImport("__Internal")]
private static extern void FetchScores();
void Start()
{
avatars = GameObject.Find("Canvas").GetComponent<Avatars>();
mockStats = GameObject.Find("MockStats").GetComponent<MockStats>();
x = 0;
y = 200f;
for (int i = 1; i <= mockStats.GetTotalNumberOfPlayers(); i++)
{
if(i == mockStats.GetPlayerPosition())
{
//Debug.Log("main: "+i);
GameObject scoreBar = Instantiate(mainPlayerBar, new Vector3(x, y, -5), Quaternion.identity) as GameObject;
scoreBar.name = "Player" + i + "Bar";
GameObject.Find("NameText").GetComponent<TextMeshProUGUI>().text = mockStats.GetName(i - 1);
GameObject.Find("NameText").name = "NameTagPlayer" + i;
GameObject.Find("ScoreText").name = "ScoreTextPlayer" + i;
GameObject.Find("ScoreNumber").GetComponent<TextMeshProUGUI>().text = mockStats.getScoreListEntry(i - 1).ToString();
GameObject.Find("ScoreNumber").name = "ScoreNumberPlayer" + i;
scoreBar.transform.SetParent(GameObject.Find("Canvas").transform, false);
GameObject.Find("NameTagPlayer" + i).GetComponent<Animator>().SetBool("appear", true);
GameObject.Find("ScoreTextPlayer" + i).GetComponent<Animator>().SetBool("appear", true);
GameObject.Find("ScoreNumberPlayer" + i).GetComponent<Animator>().SetBool("appear", true);
}
else
{
//Debug.Log("off: " + i);
GameObject scoreBar = Instantiate(otherPlayerBar, new Vector3(x,y,-5), Quaternion.identity) as GameObject;
scoreBar.name = "Player" + i + "Bar";
GameObject.Find("NameText").GetComponent<TextMeshProUGUI>().text = mockStats.GetName(i - 1);
GameObject.Find("NameText").name = "NameTagPlayer" + i;
GameObject.Find("ScoreText").name = "ScoreTextPlayer" + i;
GameObject.Find("ScoreNumber").GetComponent<TextMeshProUGUI>().text = mockStats.getScoreListEntry(i-1).ToString();
GameObject.Find("ScoreNumber").name = "ScoreNumberPlayer" + i;
scoreBar.transform.SetParent(GameObject.Find("Canvas").transform, false);
GameObject.Find("NameTagPlayer" + i).GetComponent<Animator>().SetBool("appear",true);
GameObject.Find("ScoreTextPlayer" + i).GetComponent<Animator>().SetBool("appear", true);
GameObject.Find("ScoreNumberPlayer" + i).GetComponent<Animator>().SetBool("appear", true);
}
y -= 80f;
}
}
void Update()
{
if (!waitForUpdate)
{
StartCoroutine(WaitForUpdate());
waitForUpdate = true;
}
}
public IEnumerator WaitForUpdate()
{
try { FetchScores(); }
catch (EntryPointNotFoundException e)
{
Debug.Log("Unity wants to get a score update but Failed " + e);
}
yield return new WaitForSeconds(0.25f);
for (int i = 1; i <= mockStats.GetTotalNumberOfPlayers(); i++)
{
GameObject.Find("ScoreNumberPlayer" + i).GetComponent<TextMeshProUGUI>().text = mockStats.getScoreListEntry(i-1).ToString();
}
waitForUpdate = false;
}
}
| 39.77551 | 136 | 0.606208 |
d091ee3523c26cfad49380ce6f5022bc22a122f1 | 13,272 | cshtml | C# | src/GeneratorBase.MVC/Views/T_LearningCenter/Details.cshtml | etelic/sampleapp | 9791543941d1555e1926ecf8bf3bff428b0d528e | [
"MIT"
] | null | null | null | src/GeneratorBase.MVC/Views/T_LearningCenter/Details.cshtml | etelic/sampleapp | 9791543941d1555e1926ecf8bf3bff428b0d528e | [
"MIT"
] | null | null | null | src/GeneratorBase.MVC/Views/T_LearningCenter/Details.cshtml | etelic/sampleapp | 9791543941d1555e1926ecf8bf3bff428b0d528e | [
"MIT"
] | null | null | null | @model GeneratorBase.MVC.Models.T_LearningCenter
@using PagedList;
@{
ViewBag.Title = "View Learning Center";
var EntityDisplayNameReflector = ModelReflector.Entities.FirstOrDefault(p => p.Name == "T_LearningCenter");
var EntityDisplayName = EntityDisplayNameReflector != null ? EntityDisplayNameReflector.DisplayName : "Learning Center";
}
<script>
$(document).ready(function () {
if ($.cookie('@User.JavaScriptEncodedName@Model.Id' + 'TabCookie') != null) {
$('a[href="#' + $.cookie('@User.JavaScriptEncodedName@Model.Id' + 'TabCookie') + '"]').click();
}
});
</script>
@{
if (!string.IsNullOrEmpty(ViewBag.T_LearningCenterIsHiddenRule))
{
@Html.Raw(ViewBag.T_LearningCenterIsHiddenRule);
}
}
@{
if (!string.IsNullOrEmpty(ViewBag.T_LearningCenterIsGroupsHiddenRule))
{
@Html.Raw(ViewBag.T_LearningCenterIsGroupsHiddenRule);
}
}
@{
if (!string.IsNullOrEmpty(ViewBag.T_LearningCenterIsSetValueUIRule))
{
@Html.Raw(ViewBag.T_LearningCenterIsSetValueUIRule);
}
}
<div class="row">
<div class="col-lg-12">
<h1 class="page-title">
<i class="glyphicon glyphicon-hand-down text-primary"></i> @EntityDisplayName <i class="glyphicon glyphicon-chevron-right small"></i> <span>View</span>
</h1>
<h2 class="text-primary"><span id="HostingEntityDisplayValue">@Html.DisplayFor(model => model.DisplayValue)</span>
<div class="btn-group pull-right fixactionbut">
<button data-toggle="dropdown" class="btn btn-xs dropdown-toggle btn-default pull-right">
Action
<span class="caret"> </span>
</button>
<ul class="dropdown-menu pull-left">
<li>
@if (User.Identity.IsAuthenticated && User != null && User.CanEdit("T_LearningCenter"))
{
<a href="@Url.Action("Edit","T_LearningCenter", new { id = Model.Id, UrlReferrer = Request.Url, AssociatedType=ViewData["AssociatedType"], HostingEntityName = @Convert.ToString(ViewData["HostingEntity"]), HostingEntityID = @Convert.ToString(ViewData["HostingEntityID"]) },null)"><i class="glyphicon glyphicon-edit"></i> Edit</a>
}
</li>
<li>
@if (User.Identity.IsAuthenticated && User != null && User.CanDelete("T_LearningCenter"))
{
<a href="@Url.Action("Delete", "T_LearningCenter", new { id = Model.Id, UrlReferrer = Request.Url, AssociatedType=ViewData["AssociatedType"], HostingEntityName = @Convert.ToString(ViewData["HostingEntity"]), HostingEntityID = @Convert.ToString(ViewData["HostingEntityID"]) }, null)"><i class="glyphicon glyphicon-remove-sign"></i> Delete</a>
}
</li>
<li class="divider" style="clear:both"></li>
<li class="dropdown-submenu pull-left">
<a tabindex="-1" href="#" style="margin-bottom:10px;"><i class="fam-anchor small"></i> Add</a>
<ul class="dropdown-menu pull-left">
@if (User.Identity.IsAuthenticated && User != null && User.CanAdd("T_TimeSlots"))
{
<li>
<a onclick=@Html.Raw("NavigateToUrl('" + Url.Action("Create", "T_TimeSlots",
new { UrlReferrer = Request.Url,
AssociatedType ="T_LearningCenterTimeSlotsAssociation",
HostingEntityName = "T_LearningCenter",
HostingEntityID = @Convert.ToString(Model.Id) }, null) + "');")>
<i class="glyphicon glyphicon-plus"></i> Time Slots
</a>
</li>
}
@if (User.Identity.IsAuthenticated && User != null && User.CanAdd("T_Session"))
{
<li>
<a onclick=@Html.Raw("NavigateToUrl('" + Url.Action("Create", "T_Session",
new { UrlReferrer = Request.Url,
AssociatedType ="T_SessionLearningCenterAssociation",
HostingEntityName = "T_LearningCenter",
HostingEntityID = @Convert.ToString(Model.Id) }, null) + "');")>
<i class="glyphicon glyphicon-plus"></i> Session
</a>
</li>
}
@if (User.Identity.IsAuthenticated && User != null && User.CanAdd("T_SessionEvents"))
{
<li>
<a onclick=@Html.Raw("NavigateToUrl('" + Url.Action("Create", "T_SessionEvents",
new { UrlReferrer = Request.Url,
AssociatedType ="T_SessionEventsLearningCenter",
HostingEntityName = "T_LearningCenter",
HostingEntityID = @Convert.ToString(Model.Id) }, null) + "');")>
<i class="glyphicon glyphicon-plus"></i> Session Events
</a>
</li>
}
</ul>
</li>
</ul>
</div>
</h2>
</div>
<!-- /.col-lg-12 -->
</div>
<div class="tabbable responsive">
<ul class="nav nav-tabs">
<li class="active"><a href="#Details" onclick="ClearTabCookie('@User.JavaScriptEncodedName@Model.Id');" data-toggle="tab">Details</a></li>
<li>
<a href="#ScheduleSession" data-toggle="tab">
Session
</a>
</li>
<li @(!User.CanView("T_TimeSlots") ? "style=display:none;" : "")>
<a onclick="LoadTab('ScheduleSessionT_TimeSlots','@User.JavaScriptEncodedName@Model.Id','@Html.Raw(Url.Action("Index", "T_TimeSlots", new {viewtype="SlotIndexPartial", HostingEntity = "T_LearningCenter", HostingEntityID = Model.Id, RenderPartial = true, TabToken = DateTime.Now.Ticks, }))')" href="#ScheduleSessionT_TimeSlots" data-toggle="tab">
Time Slots View
</a>
</li>
<li @(!User.CanView("T_TimeSlots")?"style=display:none;":"")><a onclick="LoadTab('T_LearningCenterTimeSlotsAssociation','@User.JavaScriptEncodedName@Model.Id','@Html.Raw(Url.Action("Index", "T_TimeSlots", new {RenderPartial=true, HostingEntity ="T_LearningCenter", HostingEntityID = @Model.Id, AssociatedType = "T_LearningCenterTimeSlotsAssociation",TabToken = DateTime.Now.Ticks,}))')" href="#T_LearningCenterTimeSlotsAssociation" data-toggle="tab">
Time Slots
<span class="badge bg-blue"><div id="dvcnt_T_LearningCenterTimeSlotsAssociation">@ViewBag.T_LearningCenterTimeSlotsAssociationCount</div></span>
</a></li>
<li @(!User.CanView("T_SessionEvents")?"style=display:none;":"")><a onclick="LoadTab('T_SessionEventsLearningCenter','@User.JavaScriptEncodedName@Model.Id','@Html.Raw(Url.Action("Index", "T_SessionEvents", new {RenderPartial=true, HostingEntity ="T_LearningCenter", HostingEntityID = @Model.Id, AssociatedType = "T_SessionEventsLearningCenter",TabToken = DateTime.Now.Ticks,}))')" href="#T_SessionEventsLearningCenter" data-toggle="tab">
Session Events
<span class="badge bg-blue"><div id="dvcnt_T_SessionEventsLearningCenter">@ViewBag.T_SessionEventsLearningCenterCount</div></span>
</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="Details">
<div class="panel panel-default AppForm">
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-md-12 col-xs-12">
<div class="row">
@if(User.CanView("T_LearningCenter","T_Name"))
{
<div class='col-sm-6 col-md-6 col-xs-12' id="dvT_Name">
<div class='form-group' title="@Model.T_Name">
<label class="col-sm-5 col-md-5 col-xs-12">@Html.DisplayNameFor(model => model.T_Name) </label>
<div class="input-group col-sm-7 col-md-7 col-xs-12">
<p class="viewlabel">@Model.T_Name</p>
</div>
</div>
</div>
}
@if(User.CanView("T_LearningCenter","T_Description"))
{
<div class='col-sm-6 col-md-6 col-xs-12' id="dvT_Description">
<div class='form-group' title="@Model.T_Description">
<label class="col-sm-5 col-md-5 col-xs-12">@Html.DisplayNameFor(model => model.T_Description)</label>
<div class="input-group col-sm-7 col-md-7 col-xs-12">
<p class="viewlabelmultiline">@Model.T_Description</p>
</div>
</div>
</div>
}
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
@Html.ActionLink("Back", "Cancel", new { UrlReferrer = Request.UrlReferrer }, new { @class = "btn btn-default btn-sm pull-left formbuttonfix" })
@if (User.Identity.IsAuthenticated && User != null && User.CanEdit("T_LearningCenter"))
{
@Html.ActionLink("Edit", "Edit", new { id = Model.Id, AssociatedType = ViewData["AssociatedType"], HostingEntityName = @Convert.ToString(ViewData["HostingEntity"]), HostingEntityID = @Convert.ToString(ViewData["HostingEntityID"]) }, new { @class = "btn btn-primary btn-sm pull-left formbuttonfix" })
}
</div>
</div>
<div class="dropdown pull-left formbuttonfix" style="margin-top:-30px; margin-left:102px;">
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
Add Association
<span class="caret"></span>
</button>
<ul class="dropdown-menu " role="menu" aria-labelledby="dropdownMenu1">
@if (User.Identity.IsAuthenticated && User != null && User.CanAdd("T_TimeSlots"))
{
<li>
<a onclick=@Html.Raw("NavigateToUrl('" + Url.Action("Create", "T_TimeSlots",
new { UrlReferrer = Request.Url,
AssociatedType ="T_LearningCenterTimeSlotsAssociation",
HostingEntityName = "T_LearningCenter",
HostingEntityID = @Convert.ToString(Model.Id)
}, null) + "');") style="margin-top:5px;">
Add Time Slots</a>
</li>
}
</ul>
</div>
<div class="dropdown pull-left formbuttonfix" style="margin-top:-30px; margin-left:102px;">
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
Add Association
<span class="caret"></span>
</button>
<ul class="dropdown-menu " role="menu" aria-labelledby="dropdownMenu1">
@if (User.Identity.IsAuthenticated && User != null && User.CanAdd("T_Session"))
{
<li>
<a onclick=@Html.Raw("NavigateToUrl('" + Url.Action("Create", "T_Session",
new { UrlReferrer = Request.Url,
AssociatedType ="T_SessionLearningCenterAssociation",
HostingEntityName = "T_LearningCenter",
HostingEntityID = @Convert.ToString(Model.Id)
}, null) + "');") style="margin-top:5px;">
Add Session</a>
</li>
}
</ul>
</div>
<div class="dropdown pull-left formbuttonfix" style="margin-top:-30px; margin-left:102px;">
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
Add Association
<span class="caret"></span>
</button>
<ul class="dropdown-menu " role="menu" aria-labelledby="dropdownMenu1">
@if (User.Identity.IsAuthenticated && User != null && User.CanAdd("T_SessionEvents"))
{
<li>
<a onclick=@Html.Raw("NavigateToUrl('" + Url.Action("Create", "T_SessionEvents",
new { UrlReferrer = Request.Url,
AssociatedType ="T_SessionEventsLearningCenter",
HostingEntityName = "T_LearningCenter",
HostingEntityID = @Convert.ToString(Model.Id)
}, null) + "');") style="margin-top:5px;">
Add Session Events</a>
</li>
}
</ul>
</div>
</div>
<div class="tab-pane fade in" id="T_LearningCenterTimeSlotsAssociation">
@if (User.Identity.IsAuthenticated && User != null && User.CanView("T_TimeSlots"))
{
// Html.RenderAction("Index", "T_TimeSlots", new {RenderPartial=true, HostingEntity = "T_LearningCenter", HostingEntityID = @Model.Id, AssociatedType = "T_LearningCenterTimeSlotsAssociation" });
}
</div>
<div class="tab-pane fade in" id="T_SessionLearningCenterAssociation">
@if (User.Identity.IsAuthenticated && User != null && User.CanView("T_Session"))
{
// Html.RenderAction("Index", "T_Session", new {RenderPartial=true, HostingEntity = "T_LearningCenter", HostingEntityID = @Model.Id, AssociatedType = "T_SessionLearningCenterAssociation" });
}
</div>
<div class="tab-pane fade in" id="T_SessionEventsLearningCenter">
@if (User.Identity.IsAuthenticated && User != null && User.CanView("T_SessionEvents"))
{
// Html.RenderAction("Index", "T_SessionEvents", new {RenderPartial=true, HostingEntity = "T_LearningCenter", HostingEntityID = @Model.Id, AssociatedType = "T_SessionEventsLearningCenter" });
}
</div>
<div class="tab-pane fade in" id="ScheduleSessionT_TimeSlots">
</div>
<div class="tab-pane fade in" id="ScheduleSession">
@Html.Partial("~/Views/T_Schedule/CalendarView.cshtml", Model.t_sessioneventslearningcenter.Select(p => p.Id).ToList(), new ViewDataDictionary { { "HostingEntity", "T_LearningCenter" }, { "HostingEntityID", Model.Id } })
</div>
<script>
$(document).ready(function () {
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
$('#calendar').fullCalendar('render');
});
$('#ScheduleSession a:first').tab('show');
});
</script>
</div> <!-- /tab-content --><br />
<br/>
</div>
| 46.083333 | 453 | 0.626808 |
c8b12bcb4d463f3819341b06bbdd49484a1370f7 | 3,088 | cs | C# | SparkleXrmSource/Client/InlineSubGrids/Views/SimpleEditableGridView.cs | michaelmittermair/SparkleXrm | fd1657456d1ff6da64b71e91fbec5abbfd0c89ed | [
"MIT"
] | 228 | 2015-01-12T17:11:02.000Z | 2022-03-06T08:59:54.000Z | SparkleXrmSource/Client/InlineSubGrids/Views/SimpleEditableGridView.cs | michaelmittermair/SparkleXrm | fd1657456d1ff6da64b71e91fbec5abbfd0c89ed | [
"MIT"
] | 367 | 2015-02-04T15:01:07.000Z | 2022-03-22T20:44:56.000Z | SparkleXrmSource/Client/InlineSubGrids/Views/SimpleEditableGridView.cs | michaelmittermair/SparkleXrm | fd1657456d1ff6da64b71e91fbec5abbfd0c89ed | [
"MIT"
] | 185 | 2015-01-02T00:49:05.000Z | 2022-03-18T05:10:20.000Z | // ActivitySubGridView.cs
//
using Client.InlineSubGrids.ViewModels;
using Client.MultiEntitySearch.ViewModels;
using jQueryApi;
using Slick;
using SparkleXrm;
using SparkleXrm.CustomBinding;
using SparkleXrm.GridEditor;
using System;
using System.Collections.Generic;
using System.Html;
using Xrm;
using Xrm.Sdk;
namespace Client.Views.InlineSubGrids
{
public class SimpleEditableGridView
{
public static void Init()
{
PageEx.MajorVersion = 2013;
jQuery.OnDocumentReady(delegate()
{
ValidationApi.RegisterExtenders();
// Init settings
OrganizationServiceProxy.GetUserSettings();
SimpleEditableGridViewModel vm = new SimpleEditableGridViewModel();
// Create Grid
GridDataViewBinder dataViewBinder = new GridDataViewBinder();
dataViewBinder.AddCheckBoxSelectColumn = true;
dataViewBinder.SelectActiveRow = true;
dataViewBinder.MultiSelect = false;
List<Column> columns = new List<Column>();
EditorFactory textEditor = (EditorFactory)Script.Literal("Slick.Editors.Text");
XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Title", 150, "title"));
XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Author", 150, "author"));
XrmDateEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Published", 150, "publishdate"), true);
XrmMoneyEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Price", 150, "price"), 0, 100);
XrmNumberEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Copies", 150, "numberofcopies"), 0, 1000, 0);
XrmLookupEditorOptions languageLookupOptions =
(XrmLookupEditorOptions)XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Language", 150, "language"), vm.GetLanguages, "id", "name", null).Options;
languageLookupOptions.showImage = false;
OptionSetBindingOptions formatBindingOptions = new OptionSetBindingOptions();
formatBindingOptions.allowEmpty = true;
formatBindingOptions.GetOptionSetsDelegate = vm.GetFormats;
XrmOptionSetEditor.BindColumnWithOptions(GridDataViewBinder.AddColumn(columns, "Format", 150, "format"), formatBindingOptions);
XrmDurationEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Audio Length", 150, "audiolength"));
XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Start Time", 150, "starttime"));
Grid grid = dataViewBinder.DataBindXrmGrid(vm.Books, columns, "booksGridContainer", null, true, true);
ViewBase.RegisterViewModel(vm);
Window.SetTimeout(delegate()
{
vm.LoadBooks();
grid.ResizeCanvas();
}, 0);
});
}
}
}
| 41.72973 | 184 | 0.643135 |
74952fd688f916c827e2baf1867334873ae4d557 | 1,183 | cs | C# | AdventuresOfTelerik/AdventuresOfTelerik.Tests/Models/Heroes/MageTests/SpecialAttack_Should.cs | AngelNovoselski/Adventures-of-Telerik | cd04db25c92138f7a31abc6823ef0e64a76e2d20 | [
"MIT"
] | 1 | 2017-12-13T19:33:26.000Z | 2017-12-13T19:33:26.000Z | AdventuresOfTelerik/AdventuresOfTelerik.Tests/Models/Heroes/MageTests/SpecialAttack_Should.cs | A4unecabrat/Adventures-of-Telerik | cd04db25c92138f7a31abc6823ef0e64a76e2d20 | [
"MIT"
] | null | null | null | AdventuresOfTelerik/AdventuresOfTelerik.Tests/Models/Heroes/MageTests/SpecialAttack_Should.cs | A4unecabrat/Adventures-of-Telerik | cd04db25c92138f7a31abc6823ef0e64a76e2d20 | [
"MIT"
] | 1 | 2018-07-05T11:53:32.000Z | 2018-07-05T11:53:32.000Z | using AdventuresOfTelerik.Contracts.WeaponInterfaces;
using AdventuresOfTelerik.Models.Hero;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace AdventuresOfTelerik.Tests.Models.Heroes.MageTests
{
[TestClass]
public class SpecialAttack_Should
{
[TestMethod]
public void ReturnZero_WhenSpecialEnergyIsLessThan35()
{
//Arrange
var mockStaff = new Mock<IStaff>();
var mockKnife = new Mock<IKnife>();
var mage = new Mage(mockStaff.Object, mockKnife.Object);
mage.SpecialEnergy = 34;
// Act & Assert
Assert.AreEqual(0, mage.SpecialAttack());
}
[TestMethod]
public void ReturnCorrectValue_WhenSpecialEnergyIsMoreThan35()
{
//Arrange
var stubStaff = new Mock<IStaff>();
var stubKnife = new Mock<IKnife>();
var mage = new Mage(stubStaff.Object, stubKnife.Object);
mage.SpecialEnergy = 36;
var mageIntelligenceValue = 20;
// Act & Assert
Assert.AreEqual(mageIntelligenceValue, mage.SpecialAttack());
}
}
}
| 30.333333 | 73 | 0.614539 |
2168c0116c69a195b5365028b806562f9af2d53b | 578 | cs | C# | project/Hell For One/Assets/Asset Cleaner/Utils/Ext.cs | Matteo-Moriani/HellForOne | e3b7a0b2929df95cb9559dd0fd0a0d3648a1d40b | [
"MIT"
] | 3 | 2021-11-29T12:09:33.000Z | 2022-03-29T06:59:42.000Z | Zoo VR Explorer/Assets/Resources/Asset Cleaner/Utils/Ext.cs | echo3Dco/Unity-Oculus-echo3D-demo-VR-Zoo-Explorer | 26e13723df8c8278b446cb39fb9b7be5c097b635 | [
"CC-BY-4.0"
] | null | null | null | Zoo VR Explorer/Assets/Resources/Asset Cleaner/Utils/Ext.cs | echo3Dco/Unity-Oculus-echo3D-demo-VR-Zoo-Explorer | 26e13723df8c8278b446cb39fb9b7be5c097b635 | [
"CC-BY-4.0"
] | 2 | 2021-09-09T16:29:48.000Z | 2021-09-09T20:13:57.000Z | using System.Runtime.CompilerServices;
using Leopotam.Ecs;
namespace Asset_Cleaner {
static class Ext {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Eq(this string s1, string s2) => (s1 == s2);
// public static bool Eq(this string s1, string s2) => StringComparer.Ordinal.Equals(s1, s2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T GetSingle<T>(this EcsFilter<T> f) where T : class {
Asr.AreEqual(f.GetEntitiesCount(), 1);
return f.Get1[0];
}
}
} | 34 | 101 | 0.652249 |
41c3e2b46d693966c7f39cf82ba76e3eeff534a8 | 3,268 | cs | C# | src/Cake.Core.Tests/Unit/Scripting/CodeGen/MethodAliasGeneratorTests.cs | janhartmann/cake | 0fbf9d92ba7c53449850e3e8dd50d537e37dc3a7 | [
"MIT"
] | 1 | 2021-01-15T17:01:55.000Z | 2021-01-15T17:01:55.000Z | src/Cake.Core.Tests/Unit/Scripting/CodeGen/MethodAliasGeneratorTests.cs | cpx86/cake | 167f1c1c542072d386dff23a7bec317b4fff2964 | [
"MIT"
] | null | null | null | src/Cake.Core.Tests/Unit/Scripting/CodeGen/MethodAliasGeneratorTests.cs | cpx86/cake | 167f1c1c542072d386dff23a7bec317b4fff2964 | [
"MIT"
] | null | null | null | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Cake.Core.Scripting.CodeGen;
using Cake.Core.Tests.Fixtures;
using Xunit;
namespace Cake.Core.Tests.Unit.Scripting.CodeGen
{
public sealed class MethodAliasGeneratorTests
{
public sealed class TheGeneratorMethod : IClassFixture<MethodAliasGeneratorFixture>
{
private readonly MethodAliasGeneratorFixture _fixture;
public TheGeneratorMethod(MethodAliasGeneratorFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void Should_Throw_If_Method_Is_Null()
{
// Given, When
var result = Record.Exception(() => MethodAliasGenerator.Generate(null));
// Then
Assert.IsArgumentNullException(result, "method");
}
[Theory]
[InlineData("NonGeneric_ExtensionMethodWithNoParameters")]
[InlineData("NonGeneric_ExtensionMethodWithParameter")]
[InlineData("NonGeneric_ExtensionMethodWithGenericParameter")]
[InlineData("NonGeneric_ExtensionMethodWithGenericExpressionParameter")]
[InlineData("NonGeneric_ExtensionMethodWithGenericExpressionArrayParameter")]
[InlineData("NonGeneric_ExtensionMethodWithGenericExpressionParamsArrayParameter")]
[InlineData("NonGeneric_ExtensionMethodWithReturnValue")]
[InlineData("NonGeneric_ExtensionMethodWithParameterArray")]
public void Should_Return_Correct_Generated_Code_For_Non_Generic_Methods(string name)
{
// Given
var expected = _fixture.GetExpectedCode(name);
// When
var result = _fixture.Generate(name);
// Then
Assert.Equal(expected, result);
}
[Theory]
[InlineData("Generic_ExtensionMethod")]
[InlineData("Generic_ExtensionMethodWithParameter")]
[InlineData("Generic_ExtensionMethodWithGenericReturnValue")]
public void Should_Return_Correct_Generated_Code_For_Generic_Methods(string name)
{
// Given
var expected = _fixture.GetExpectedCode(name);
// When
var result = _fixture.Generate(name);
// Then
Assert.Equal(expected, result);
}
[Theory]
[InlineData("Obsolete_ImplicitWarning_NoMessage")]
[InlineData("Obsolete_ImplicitWarning_WithMessage")]
[InlineData("Obsolete_ExplicitWarning_WithMessage")]
[InlineData("Obsolete_ExplicitError_WithMessage")]
public void Should_Return_Correct_Generated_Code_For_Obsolete_Methods(string name)
{
// Given
var expected = _fixture.GetExpectedCode(name);
// When
var result = _fixture.Generate(name);
// Then
Assert.Equal(expected, result);
}
}
}
} | 37.563218 | 97 | 0.615973 |
41ece5bc7838a29679b45d7dbf34cce4984e8fa1 | 236 | cs | C# | DawPastrator.Server/Models/DataStorageModel.cs | DawPastrator/server | 2b659bbfd152a5cf57ae67d87be5cd3760de10d8 | [
"Apache-2.0"
] | 1 | 2021-03-03T07:21:11.000Z | 2021-03-03T07:21:11.000Z | DawPastrator.Server/Models/DataStorageModel.cs | DawPastrator/server | 2b659bbfd152a5cf57ae67d87be5cd3760de10d8 | [
"Apache-2.0"
] | null | null | null | DawPastrator.Server/Models/DataStorageModel.cs | DawPastrator/server | 2b659bbfd152a5cf57ae67d87be5cd3760de10d8 | [
"Apache-2.0"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DawPastrator.Server.Models
{
public record DataStorageModel
{
public string Bs4Data { get; set; } = "";
}
} | 19.666667 | 49 | 0.70339 |
339a49cf2b3c4cf452b447fd08204d795b1c710d | 847 | cs | C# | Assets/Xbox Live/Scripts/XboxSocialUserEntry.cs | JayZuo/XBL-Unity-Plugin | 34ce449e0831a9a64c0ca85bf00fbbe374996ec0 | [
"MIT"
] | 1 | 2020-08-05T20:57:52.000Z | 2020-08-05T20:57:52.000Z | Assets/Xbox Live/Scripts/XboxSocialUserEntry.cs | JayZuo/XBL-Unity-Plugin | 34ce449e0831a9a64c0ca85bf00fbbe374996ec0 | [
"MIT"
] | null | null | null | Assets/Xbox Live/Scripts/XboxSocialUserEntry.cs | JayZuo/XBL-Unity-Plugin | 34ce449e0831a9a64c0ca85bf00fbbe374996ec0 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using UnityEngine;
using UnityEngine.UI;
#if ENABLE_WINMD_SUPPORT
using Microsoft.Xbox.Services.Social.Manager;
#endif
public class XboxSocialUserEntry : MonoBehaviour
{
public Button entryButton;
public Image gamerpicImage;
public Image gamerpicMask;
public Text gamertagText;
public Text presenceText;
#if ENABLE_WINMD_SUPPORT
private XboxSocialUser data;
public XboxSocialUser Data
{
get
{
return this.data;
}
set
{
this.data = value;
this.gamertagText.text = this.data.Gamertag;
this.presenceText.text = this.data.PresenceRecord.UserState.ToString();
}
}
#endif
}
| 22.891892 | 101 | 0.675325 |
332e78f8b0606af2ee718fb49705395c9e3aff6b | 6,561 | cs | C# | mcs/class/System/System.ComponentModel/LicenseManager.cs | DavidKarlas/mono | 6dc06c15638980182f670a0a6b8f8011cd68cd28 | [
"Apache-2.0"
] | 4 | 2015-02-18T11:56:06.000Z | 2017-03-16T11:11:12.000Z | mcs/class/System/System.ComponentModel/LicenseManager.cs | pcc/mono | c64a76e3aae1bd6347f35c1c3bd1ace56247d4f1 | [
"Apache-2.0"
] | 2 | 2020-02-26T11:52:19.000Z | 2021-01-19T16:23:44.000Z | mcs/class/System/System.ComponentModel/LicenseManager.cs | pcc/mono | c64a76e3aae1bd6347f35c1c3bd1ace56247d4f1 | [
"Apache-2.0"
] | 6 | 2016-07-25T01:20:15.000Z | 2022-01-13T02:59:47.000Z | //
// System.ComponentModel.LicenseManager.cs
//
// Authors:
// Ivan Hamilton (ivan@chimerical.com.au)
// Martin Willemoes Hansen (mwh@sysrq.dk)
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//
// (C) 2004 Ivan Hamilton
// (C) 2003 Martin Willemoes Hansen
// (C) 2003 Andreas Nahr
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.ComponentModel
{
public sealed class LicenseManager
{
static LicenseContext mycontext;
static object contextLockUser;
static object lockObject = new object ();
private LicenseManager ()
{
}
public static LicenseContext CurrentContext {
get {
lock (lockObject) {
//Tests indicate a System.ComponentModel.Design.RuntimeLicenseContext should be returned.
if (mycontext==null)
mycontext = new Design.RuntimeLicenseContext();
return mycontext;
}
}
set {
lock (lockObject) {
if (contextLockUser==null) {
mycontext = value;
} else {
throw new InvalidOperationException("The CurrentContext property of the LicenseManager is currently locked and cannot be changed.");
}
}
}
}
public static LicenseUsageMode UsageMode {
get {
return CurrentContext.UsageMode;
}
}
public static object CreateWithContext (Type type,
LicenseContext creationContext)
{
return CreateWithContext (type, creationContext, new object [0]);
}
public static object CreateWithContext (Type type,
LicenseContext creationContext,
object[] args)
{
object newObject = null;
lock (lockObject) {
object contextUser = new object ();
LicenseContext oldContext = CurrentContext;
CurrentContext = creationContext;
LockContext (contextUser);
try {
newObject = Activator.CreateInstance (type, args);
} catch (Reflection.TargetInvocationException exception) {
throw exception.InnerException;
} finally {
UnlockContext (contextUser);
CurrentContext = oldContext;
}
}
return newObject;
}
public static bool IsLicensed (Type type)
{
License license = null;
if (!privateGetLicense (type, null, false, out license)) {
return false;
} else {
if (license != null)
license.Dispose ();
return true;
}
}
public static bool IsValid (Type type)
//This method does not throw a LicenseException when it cannot grant a valid License
{
License license=null;
if (!privateGetLicense (type, null, false, out license)) {
return false;
} else {
if (license != null)
license.Dispose ();
return true;
}
}
public static bool IsValid (Type type, object instance,
out License license)
//This method does not throw a LicenseException when it cannot grant a valid License
{
return privateGetLicense (type, null, false, out license);
}
public static void LockContext (object contextUser)
{
lock (lockObject) {
contextLockUser = contextUser;
}
}
public static void UnlockContext (object contextUser)
{
lock (lockObject) {
//Ignore if we're not locked
if (contextLockUser == null)
return;
//Don't unlock if not locking user
if (contextLockUser != contextUser)
throw new ArgumentException ("The CurrentContext property of the LicenseManager can only be unlocked with the same contextUser.");
//Remove lock
contextLockUser = null;
}
}
public static void Validate (Type type)
// Throws a LicenseException if the type is licensed, but a License could not be granted.
{
License license = null;
if (!privateGetLicense (type, null, true, out license))
throw new LicenseException (type, null);
if (license != null)
license.Dispose ();
}
public static License Validate (Type type, object instance)
// Throws a LicenseException if the type is licensed, but a License could not be granted.
{
License license=null;
if (!privateGetLicense(type, instance, true, out license))
throw new LicenseException(type, instance);
return license;
}
private static bool privateGetLicense (Type type, object instance, bool allowExceptions, out License license)
//Returns if a component is licensed, and the license if provided
{
bool isLicensed = false;
License foundLicense = null;
//Get the LicProc Attrib for our type
LicenseProviderAttribute licenseproviderattribute = (LicenseProviderAttribute) Attribute.GetCustomAttribute(type, typeof (LicenseProviderAttribute), true);
//Check it's got an attrib
if (licenseproviderattribute != null) {
Type licenseprovidertype = licenseproviderattribute.LicenseProvider;
//Check the attrib has a type
if (licenseprovidertype != null) {
//Create the provider
LicenseProvider licenseprovider = (LicenseProvider) Activator.CreateInstance(licenseprovidertype);
//Check we've got the provider
if (licenseprovider != null) {
//Call provider, throw an LicenseException if error.
foundLicense = licenseprovider.GetLicense(CurrentContext, type, instance, allowExceptions);
if (foundLicense != null)
isLicensed = true;
//licenseprovider.Dispose();
} else {
//There is was some problem creating the provider
}
//licenseprovidertype.Dispose();
} else {
//licenseprovidertype is null
}
//licenseproviderattribute.Dispose ();
} else {
//Didn't have a LicenseProviderAttribute, so it's licensed
isLicensed = true;
}
license = foundLicense;
return isLicensed;
}
}
}
| 30.948113 | 158 | 0.702942 |
b5d1569fd297e79d237d714b7fc6eec9e3c0e040 | 961 | cs | C# | src/CSum.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/BasicInfoCreateOrUpdateDtoBase.cs | yinboxie/CSum.Abp | 075780fe7dc61f3c08176b12dad88062015c3399 | [
"MIT"
] | 1 | 2020-10-11T08:48:59.000Z | 2020-10-11T08:48:59.000Z | src/CSum.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/BasicInfoCreateOrUpdateDtoBase.cs | yinboxie/CSum.Abp | 075780fe7dc61f3c08176b12dad88062015c3399 | [
"MIT"
] | null | null | null | src/CSum.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/BasicInfoCreateOrUpdateDtoBase.cs | yinboxie/CSum.Abp | 075780fe7dc61f3c08176b12dad88062015c3399 | [
"MIT"
] | 1 | 2021-02-01T00:37:06.000Z | 2021-02-01T00:37:06.000Z | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Volo.Abp.Application.Dtos
{
/// <summary>
/// 基础资料(添加或更新基类)
/// </summary>
public abstract class BasicInfoCreateOrUpdateDtoBase
{
#region 属性
/// <summary>
/// 编码
/// </summary>
[MaxLength(128)]
public virtual string Code { get; set; }
/// <summary>
/// 名称
/// </summary>
[Required,MaxLength(256)]
public virtual string Name { get; set; }
/// <summary>
/// 排序码
/// </summary>
public virtual int SortCode { get; set; }
/// <summary>
/// 是否有效
/// </summary>
public virtual bool IsActive { get; set; }
/// <summary>
/// 备注
/// </summary>
[MaxLength(512)]
public virtual string Remark { get; set; }
#endregion
}
}
| 21.840909 | 56 | 0.514048 |
550b930a0d5f9fb8671bfd23afe87fcdd207ed52 | 443 | cs | C# | Assets/Scripts/StageCreation/SingleSpaceType.cs | lincolnsch99/PixelBlasterArenaPublic | 471544c7fcc1e956048778a957088b300ca657a8 | [
"MIT"
] | 1 | 2019-11-09T21:55:01.000Z | 2019-11-09T21:55:01.000Z | Assets/Scripts/StageCreation/SingleSpaceType.cs | lincolnsch99/GameOff2019SourceCode | 471544c7fcc1e956048778a957088b300ca657a8 | [
"MIT"
] | null | null | null | Assets/Scripts/StageCreation/SingleSpaceType.cs | lincolnsch99/GameOff2019SourceCode | 471544c7fcc1e956048778a957088b300ca657a8 | [
"MIT"
] | null | null | null | /// File Name: SingleSpaceType.cs
/// File Author(s): Lincoln Schroeder
/// File Purpose: Identifies the type of spaces that can be occupied in a stage. Each
/// type has a cooresponding sprite for displaying the boundary map.
///
/// Date Last Updated: November 12, 2019
public enum SingleSpaceType
{
EMPTY,
VERTICAL_STRAIGHT,
HORIZONTAL_STRAIGHT,
CORNER_1Q,
CORNER_2Q,
CORNER_3Q,
CORNER_4Q,
PLAYER_SPAWN
}
| 23.315789 | 85 | 0.708804 |
3435d8e5b66cc2173a27d66f5bc9867416626a13 | 30,973 | cs | C# | Ppu.cs | jose-garcia-jdas/6502csharp | b1f2a001ba8b6112bf390a2bfa16a25d7e9c550c | [
"Unlicense"
] | null | null | null | Ppu.cs | jose-garcia-jdas/6502csharp | b1f2a001ba8b6112bf390a2bfa16a25d7e9c550c | [
"Unlicense"
] | null | null | null | Ppu.cs | jose-garcia-jdas/6502csharp | b1f2a001ba8b6112bf390a2bfa16a25d7e9c550c | [
"Unlicense"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Components
{
public class Ppu
{
#region fields
private Bus bus;
private Cartridge cartridge;
private byte[,] tblName = new byte[2, 1024];
private byte[] tblPalette = new byte[32];
private byte[,] tblPattern = new byte[2, 4096]; // TO PLAY
private int cycle = 0;
private static int screenHeight = 240;
private static int screenWidth = 256;
private uint[] palScreen;
private uint[] sprScreen = new uint[screenWidth * screenHeight];
private int scanLine = 0;
Random rand = new Random(255);
private LoopyRegister vram_addr;
private LoopyRegister tram_addr;
private PpuCtrl control;
private Mask mask;
private Status status;
byte fine_x = 0x00;
byte address_latch = 0x00;
byte ppu_data_buffer = 0x00;
byte bg_next_tile_id = 0x00;
byte bg_next_tile_attrib = 0x00;
byte bg_next_tile_lsb = 0x00;
byte bg_next_tile_msb = 0x00;
uint bg_shifter_pattern_lo = 0x0000;
uint bg_shifter_pattern_hi = 0x0000;
uint bg_shifter_attrib_lo = 0x0000;
uint bg_shifter_attrib_hi = 0x0000;
byte[] oam = new byte[64 * 4];
byte[] spriteScanline = new byte[8 * 4];
byte oam_addr = 0x00;
byte[] sprite_shifter_pattern_lo = new byte[8];
internal bool nmi = false;
#endregion
#region Constructor
public Ppu(Bus bus)
{
this.bus = bus;
InitScreenPalette();
}
#endregion
#region Properties
public int ScreenHeight { get => screenHeight; }
public int ScreenWidth { get => screenWidth; }
#endregion
#region Methods
internal void Reset()
{
fine_x = 0x00;
address_latch = 0x00;
ppu_data_buffer = 0x00;
scanLine = 0;
cycle = 0;
bg_next_tile_id = 0x00;
bg_next_tile_attrib = 0x00;
bg_next_tile_lsb = 0x00;
bg_next_tile_msb = 0x00;
bg_shifter_pattern_lo = 0x0000;
bg_shifter_pattern_hi = 0x0000;
bg_shifter_attrib_lo = 0x0000;
bg_shifter_attrib_hi = 0x0000;
status = new Status(0x00);
mask = new Mask(0x00);
control = new PpuCtrl(0x00);
vram_addr = new LoopyRegister(0x0000);
tram_addr = new LoopyRegister(0x0000);
}
private void InitScreenPalette()
{
palScreen = new uint[0x40];
palScreen[0x00] = new Pixel(84, 84, 84).Raw;
palScreen[0x01] = new Pixel(0, 30, 116).Raw;
palScreen[0x02] = new Pixel(8, 16, 144).Raw;
palScreen[0x03] = new Pixel(48, 0, 136).Raw;
palScreen[0x04] = new Pixel(68, 0, 100).Raw;
palScreen[0x05] = new Pixel(92, 0, 48).Raw;
palScreen[0x06] = new Pixel(84, 4, 0).Raw;
palScreen[0x07] = new Pixel(60, 24, 0).Raw;
palScreen[0x08] = new Pixel(32, 42, 0).Raw;
palScreen[0x09] = new Pixel(8, 58, 0).Raw;
palScreen[0x0A] = new Pixel(0, 64, 0).Raw;
palScreen[0x0B] = new Pixel(0, 60, 0).Raw;
palScreen[0x0C] = new Pixel(0, 50, 60).Raw;
palScreen[0x0D] = new Pixel(0, 0, 0).Raw;
palScreen[0x0E] = new Pixel(0, 0, 0).Raw;
palScreen[0x0F] = new Pixel(0, 0, 0).Raw;
palScreen[0x10] = new Pixel(152, 150, 152).Raw;
palScreen[0x11] = new Pixel(8, 76, 196).Raw;
palScreen[0x12] = new Pixel(48, 50, 236).Raw;
palScreen[0x13] = new Pixel(92, 30, 228).Raw;
palScreen[0x14] = new Pixel(136, 20, 176).Raw;
palScreen[0x15] = new Pixel(160, 20, 100).Raw;
palScreen[0x16] = new Pixel(152, 34, 32).Raw;
palScreen[0x17] = new Pixel(120, 60, 0).Raw;
palScreen[0x18] = new Pixel(84, 90, 0).Raw;
palScreen[0x19] = new Pixel(40, 114, 0).Raw;
palScreen[0x1A] = new Pixel(8, 124, 0).Raw;
palScreen[0x1B] = new Pixel(0, 118, 40).Raw;
palScreen[0x1C] = new Pixel(0, 102, 120).Raw;
palScreen[0x1D] = new Pixel(0, 0, 0).Raw;
palScreen[0x1E] = new Pixel(0, 0, 0).Raw;
palScreen[0x1F] = new Pixel(0, 0, 0).Raw;
palScreen[0x20] = new Pixel(236, 238, 236).Raw;
palScreen[0x21] = new Pixel(76, 154, 236).Raw;
palScreen[0x22] = new Pixel(120, 124, 236).Raw;
palScreen[0x23] = new Pixel(176, 98, 236).Raw;
palScreen[0x24] = new Pixel(228, 84, 236).Raw;
palScreen[0x25] = new Pixel(236, 88, 180).Raw;
palScreen[0x26] = new Pixel(236, 106, 100).Raw;
palScreen[0x27] = new Pixel(212, 136, 32).Raw;
palScreen[0x28] = new Pixel(160, 170, 0).Raw;
palScreen[0x29] = new Pixel(116, 196, 0).Raw;
palScreen[0x2A] = new Pixel(76, 208, 32).Raw;
palScreen[0x2B] = new Pixel(56, 204, 108).Raw;
palScreen[0x2C] = new Pixel(56, 180, 204).Raw;
palScreen[0x2D] = new Pixel(60, 60, 60).Raw;
palScreen[0x2E] = new Pixel(0, 0, 0).Raw;
palScreen[0x2F] = new Pixel(0, 0, 0).Raw;
palScreen[0x30] = new Pixel(236, 238, 236).Raw;
palScreen[0x31] = new Pixel(168, 204, 236).Raw;
palScreen[0x32] = new Pixel(188, 188, 236).Raw;
palScreen[0x33] = new Pixel(212, 178, 236).Raw;
palScreen[0x34] = new Pixel(236, 174, 236).Raw;
palScreen[0x35] = new Pixel(236, 174, 212).Raw;
palScreen[0x36] = new Pixel(236, 180, 176).Raw;
palScreen[0x37] = new Pixel(228, 196, 144).Raw;
palScreen[0x38] = new Pixel(204, 210, 120).Raw;
palScreen[0x39] = new Pixel(180, 222, 120).Raw;
palScreen[0x3A] = new Pixel(168, 226, 144).Raw;
palScreen[0x3B] = new Pixel(152, 226, 180).Raw;
palScreen[0x3C] = new Pixel(160, 214, 228).Raw;
palScreen[0x3D] = new Pixel(160, 162, 160).Raw;
palScreen[0x3E] = new Pixel(0, 0, 0).Raw;
palScreen[0x3F] = new Pixel(0, 0, 0).Raw;
}
public byte CpuRead(int addr, bool readOnly = false)
{
byte data = 0x00;
if (readOnly)
{
switch (addr)
{
case 0x0000: // Control
data = control.reg;
break;
case 0x0001: // Mask
data = mask.reg;
break;
case 0x0002: // Status
data = status.reg;
break;
case 0x0003: // OAM Address
break;
case 0x0004: // OAM Data
break;
case 0x0005: // Scroll
break;
case 0x0006: // PPU Address
break;
case 0x0007: // PPU Data
break;
}
}
else
{
switch (addr)
{
// Control - Not readable
case 0x0000: break;
// Mask - Not Readable
case 0x0001: break;
// Status
case 0x0002:
data = (byte)((status.reg & 0xE0) | (ppu_data_buffer & 0x1F));
status.vertical_blank = false;
status.reg &= (byte)(~0x0080 & 0xFF);
address_latch = 0;
break;
// OAM Address
case 0x0003: break;
// OAM Data
case 0x0004:
data = oam[oam_addr];
break;
// Scroll - Not Readable
case 0x0005: break;
// PPU Address - Not Readable
case 0x0006: break;
// PPU Data
case 0x0007:
data = ppu_data_buffer;
ppu_data_buffer = PpuRead(vram_addr.reg);
if (vram_addr.reg >= 0x3F00) data = ppu_data_buffer;
vram_addr = new LoopyRegister(vram_addr.reg + (control.increment_mode ? 32 : 1));
break;
}
}
return data;
}
public void CpuWrite(int addr, byte data)
{
switch (addr)
{
case 0x0000: // Control
control = new PpuCtrl(data);
tram_addr.AddNametableX(control.nametable_x);
tram_addr.AddNametableY(control.nametable_y);
break;
case 0x0001: // Mask
mask = new Mask(data);
break;
case 0x0002: // Status
break;
case 0x0003: // OAM Address
oam_addr = data;
break;
case 0x0004: // OAM Data
oam[oam_addr] = data;
break;
case 0x0005: // Scroll
if (address_latch == 0)
{
fine_x = (byte)(data & 0x07);
tram_addr.AddCoarseX((byte)(data >> 3));
address_latch = 1;
}
else
{
tram_addr.AddFineY((byte)(data & 0x07));
tram_addr.AddCoarseY((byte)(data >> 3));
address_latch = 0;
}
break;
case 0x0006: // PPU Address
if (address_latch == 0)
{
tram_addr = new LoopyRegister(((data & 0x3F) << 8) | (tram_addr.reg & 0x00FF));
address_latch = 1;
}
else
{
tram_addr = new LoopyRegister((tram_addr.reg & 0xFF00) | data);
vram_addr = tram_addr;
address_latch = 0;
}
break;
case 0x0007: // PPU Data
PpuWrite(vram_addr.reg, data);
vram_addr = new LoopyRegister(vram_addr.reg + (control.increment_mode ? 32 : 1));
break;
}
}
public byte PpuRead(int addr, bool readOnly = false)
{
byte data = 0x00;
addr &= 0x3FFF;
if (cartridge.PpuRead(addr, ref data))
{
//return data;
}
else if (addr >= 0x0000 && addr <= 0x1FFF)
{
return tblPattern[(addr & 0x1000) >> 12, addr & 0x0FFF];
}
else if (addr >= 0x2000 && addr <= 0x3EFF)
{
addr &= 0x0FFF;
if (cartridge.Mirror == Mirror.VERTICAL)
{
// Vertical
if (addr >= 0x0000 && addr <= 0x03FF)
data = tblName[0, addr & 0x03FF];
if (addr >= 0x0400 && addr <= 0x07FF)
data = tblName[1, addr & 0x03FF];
if (addr >= 0x0800 && addr <= 0x0BFF)
data = tblName[0, addr & 0x03FF];
if (addr >= 0x0C00 && addr <= 0x0FFF)
data = tblName[1, addr & 0x03FF];
}
else if (cartridge.Mirror == Mirror.HORIZONTAL)
{
// Horizontal
if (addr >= 0x0000 && addr <= 0x03FF)
data = tblName[0, addr & 0x03FF];
if (addr >= 0x0400 && addr <= 0x07FF)
data = tblName[0, addr & 0x03FF];
if (addr >= 0x0800 && addr <= 0x0BFF)
data = tblName[1, addr & 0x03FF];
if (addr >= 0x0C00 && addr <= 0x0FFF)
data = tblName[1, addr & 0x03FF];
}
}
else if (addr >= 0x3F00 && addr <= 0x3FFF)
{
addr &= 0x001F;
if (addr == 0x0010) addr = 0x0000;
if (addr == 0x0014) addr = 0x0004;
if (addr == 0x0018) addr = 0x0008;
if (addr == 0x001C) addr = 0x000C;
data = (byte)(tblPalette[addr] & (mask.grayscale ? 0x30 : 0x3F));
}
return data;
}
public void PpuWrite(int addr, byte data)
{
addr &= 0x3FFF;
if (cartridge.PpuWrite(addr, ref data))
{
}
else if (addr >= 0x0000 && addr <= 0x1FFF)
{
tblPattern[(addr & 0x1000) >> 12, addr & 0x0FFF] = data;
}
else if (addr >= 0x2000 && addr <= 0x3EFF)
{
addr &= 0x0FFF;
if (cartridge.Mirror == Mirror.VERTICAL)
{
// Vertical
if (addr >= 0x0000 && addr <= 0x03FF)
tblName[0, addr & 0x03FF] = data;
if (addr >= 0x0400 && addr <= 0x07FF)
tblName[1, addr & 0x03FF] = data;
if (addr >= 0x0800 && addr <= 0x0BFF)
tblName[0, addr & 0x03FF] = data;
if (addr >= 0x0C00 && addr <= 0x0FFF)
tblName[1, addr & 0x03FF] = data;
}
else if (cartridge.Mirror == Mirror.HORIZONTAL)
{
// Horizontal
if (addr >= 0x0000 && addr <= 0x03FF)
tblName[0, addr & 0x03FF] = data;
if (addr >= 0x0400 && addr <= 0x07FF)
tblName[0, addr & 0x03FF] = data;
if (addr >= 0x0800 && addr <= 0x0BFF)
tblName[1, addr & 0x03FF] = data;
if (addr >= 0x0C00 && addr <= 0x0FFF)
tblName[1, addr & 0x03FF] = data;
}
}
else if (addr >= 0x3F00 && addr <= 0x3FFF)
{
addr &= 0x001F;
if (addr == 0x0010) addr = 0x0000;
if (addr == 0x0014) addr = 0x0004;
if (addr == 0x0018) addr = 0x0008;
if (addr == 0x001C) addr = 0x000C;
tblPalette[addr] = data;
}
}
public uint[] GetPatternTable(byte i, byte palette)
{
return null;
}
public uint GetColourFromPaletteRam(byte palette, byte pixel)
{
return palScreen[PpuRead(0x3F00 + (palette << 2) + pixel) & 0x3F];
}
internal void ConnectCartridge(Cartridge cartridge)
{
this.cartridge = cartridge;
}
private void IncrementScrollX()
{
if (mask.render_background || mask.render_sprites)
{
if (vram_addr.coarse_x == 31)
{
vram_addr.coarse_x = 0;
vram_addr.nametable_x = !vram_addr.nametable_x;
}
else
{
// Staying in current nametable, so just increment
vram_addr.AddCoarseX(++vram_addr.coarse_x);
}
}
}
private void IncrementScrollY()
{
if (mask.render_background || mask.render_sprites)
{
if (vram_addr.fine_y < 7)
{
vram_addr.AddFineY(++vram_addr.fine_y);
}
else
{
vram_addr.fine_y = 0;
if (vram_addr.coarse_y == 29)
{
vram_addr.coarse_y = 0;
vram_addr.nametable_y = !vram_addr.nametable_y;
}
else if (vram_addr.coarse_y == 31)
{
vram_addr.coarse_y = 0;
}
else
{
vram_addr.AddCoarseY(++vram_addr.coarse_y);
}
}
}
}
private void TransferAddressX()
{
if (mask.render_background || mask.render_sprites)
{
vram_addr.AddNametableX(tram_addr.nametable_x);
vram_addr.AddCoarseX(tram_addr.coarse_x);
}
}
private void TransferAddressY ()
{
// Ony if rendering is enabled
if (mask.render_background || mask.render_sprites)
{
vram_addr.fine_y = tram_addr.fine_y;
vram_addr.nametable_y = tram_addr.nametable_y;
vram_addr.coarse_y = tram_addr.coarse_y;
vram_addr.reg |= tram_addr.fine_y;
vram_addr.reg |= tram_addr.nametable_y ? 0x1000 : 0x0000;
vram_addr.reg |= tram_addr.fine_y;
}
}
private void LoadBackgroundShifters()
{
bg_shifter_pattern_lo = (bg_shifter_pattern_lo & 0xFF00) | bg_next_tile_lsb;
bg_shifter_pattern_hi = (bg_shifter_pattern_hi & 0xFF00) | bg_next_tile_msb;
bg_shifter_attrib_lo = ((bg_shifter_attrib_lo & 0xFF00) | (uint)((bg_next_tile_attrib & 0b01) != 0 ? 0xFF : 0x00));
bg_shifter_attrib_hi = ((bg_shifter_attrib_hi & 0xFF00) | (uint)((bg_next_tile_attrib & 0b10) != 0 ? 0xFF : 0x00));
}
private void UpdateShifters()
{
if (mask.render_background)
{
// Shifting background tile pattern row
bg_shifter_pattern_lo <<= 1;
bg_shifter_pattern_hi <<= 1;
// Shifting palette attributes by 1
bg_shifter_attrib_lo <<= 1;
bg_shifter_attrib_hi <<= 1;
}
}
public void Clock()
{
if (scanLine >= -1 && scanLine < 240)
{
if (scanLine == 0 && cycle == 0)
{
// "Odd Frame" cycle skip
cycle = 1;
}
if (scanLine == -1 && cycle == 1)
{
status.vertical_blank = false;
status.reg &= (byte)(~0x0080 & 0xFF);
}
if ((cycle >= 2 && cycle < 258) || (cycle >= 321 && cycle < 338))
{
UpdateShifters();
switch ((cycle - 1) % 8)
{
case 0:
LoadBackgroundShifters();
bg_next_tile_id = PpuRead(0x2000 | (vram_addr.reg & 0x0FFF));
break;
case 2:
bg_next_tile_attrib = PpuRead(0x23C0 | (vram_addr.nametable_y ? 1 : 0 << 11)
| (vram_addr.nametable_x ? 1 : 0 << 10)
| ((vram_addr.coarse_y >> 2) << 3)
| (vram_addr.coarse_x >> 2));
if ((vram_addr.coarse_y & 0x02) != 0) bg_next_tile_attrib >>= 4;
if ((vram_addr.coarse_x & 0x02) != 0) bg_next_tile_attrib >>= 2;
bg_next_tile_attrib &= 0x03;
break;
// Compared to the last two, the next two are the easy ones... :P
case 4:
bg_next_tile_lsb = PpuRead((control.pattern_background ? 1 : 0 << 12)
+ (bg_next_tile_id << 4)
+ (vram_addr.fine_y) + 0);
break;
case 6:
bg_next_tile_msb = PpuRead((control.pattern_background ? 1 : 0 << 12)
+ (bg_next_tile_id << 4)
+ (vram_addr.fine_y) + 8);
break;
case 7:
IncrementScrollX();
break;
}
}
// End of a visible scanline, so increment downwards...
if (cycle == 256)
{
IncrementScrollY();
}
//...and reset the x position
if (cycle == 257)
{
LoadBackgroundShifters();
TransferAddressX();
}
// Superfluous reads of tile id at end of scanline
if (cycle == 338 || cycle == 340)
{
bg_next_tile_id = PpuRead(0x2000 | (vram_addr.reg & 0x0FFF));
}
if (scanLine == -1 && cycle >= 280 && cycle < 305)
{
// End of vertical blank period so reset the Y address ready for rendering
TransferAddressY();
}
}
if (scanLine >= 241 && scanLine < 261)
{
if (scanLine == 241 && cycle == 1)
{
// Effectively end of frame, so set vertical blank flag
status.vertical_blank = true;
status.reg |= 0x80;
if (control.enable_nmi)
nmi = true;
}
}
byte bg_pixel = 0x00; // The 2-bit pixel to be rendered
byte bg_palette = 0x00; // The 3-bit index of the palette the pixel indexes
if (mask.render_background)
{
// Handle Pixel Selection by selecting the relevant bit
// depending upon fine x scolling. This has the effect of
// offsetting ALL background rendering by a set number
// of pixels, permitting smooth scrolling
int bit_mux = 0x8000 >> fine_x;
// Select Plane pixels by extracting from the shifter
// at the required location.
byte p0_pixel = (byte)((bg_shifter_pattern_lo & bit_mux) > 0 ? 0x01 : 0x00);
byte p1_pixel = (byte)((bg_shifter_pattern_hi & bit_mux) > 0 ? 1: 0);
// Combine to form pixel index
bg_pixel = (byte)((p1_pixel << 1) | p0_pixel);
// Get palette
byte bg_pal0 = (byte)((bg_shifter_attrib_lo & bit_mux) > 0 ? 1 : 0);
byte bg_pal1 = (byte)((bg_shifter_attrib_hi & bit_mux) > 0 ? 1 : 0);
bg_palette = (byte)((bg_pal1 << 1) | bg_pal0);
}
// Now we have a final pixel colour, and a palette for this cycle
// of the current scanline. Let's at long last, draw that ^&%*er :P
//sprScreen[(cycle - 1) + scanLine] = GetColourFromPaletteRam(bg_palette, bg_pixel);
if (cycle < screenWidth && scanLine >= 0 && scanLine < screenHeight)
{
sprScreen[(scanLine * screenWidth) + (cycle)] = (uint)(GetColourFromPaletteRam(bg_palette, bg_pixel) >> 8);
}
cycle++;
if (cycle >= 341)
{
cycle = 0;
scanLine++;
if (scanLine >= 261)
{
scanLine = -1;
OnFrameCompleted?.Invoke(sprScreen);
}
}
}
#endregion
#region Events
public event FrameCompleted OnFrameCompleted;
#endregion
}
[StructLayout(LayoutKind.Sequential)]
struct Mask
{
internal bool grayscale;
internal bool render_background_left;
internal bool render_sprites_left;
internal bool render_background;
internal bool render_sprites;
internal bool enhance_red;
internal bool enhance_green;
internal bool enhance_blue;
public byte reg;
public Mask(byte mask)
{
int indx = 1;
grayscale = (mask & indx) == indx; indx <<= 1;
render_background_left = (mask & indx) == indx; indx <<= 1;
render_sprites_left = (mask & indx) == indx; indx <<= 1;
render_background = (mask & indx) == indx; indx <<= 1;
render_sprites = (mask & indx) == indx; indx <<= 1;
enhance_red = (mask & indx) == indx; indx <<= 1;
enhance_green = (mask & indx) == indx; indx <<= 1;
enhance_blue = (mask & indx) == indx;
reg = mask;
}
}
struct Status
{
internal byte unused;
internal bool sprite_overflow;
internal bool sprite_zero_hit;
internal bool vertical_blank;
internal byte reg;
public Status(byte status)
{
int indx = 1 << 5;
unused = (byte)(status & 0x1F);
sprite_overflow = (status & indx) == indx; indx <<= 1;
sprite_zero_hit = (status & indx) == indx; indx <<= 1;
vertical_blank = (status & indx) == indx; indx <<= 1;
reg = status;
}
}
struct PpuCtrl
{
internal bool nametable_x;
internal bool nametable_y;
internal bool increment_mode;
internal bool pattern_sprite;
internal bool pattern_background;
internal bool sprite_size;
internal bool slave_mode; // unused
internal bool enable_nmi;
internal byte reg;
public PpuCtrl(byte ppuCtrl)
{
int indx = 1;
nametable_x = (ppuCtrl & indx) == indx; indx <<= 1;
nametable_y = (ppuCtrl & indx) == indx; indx <<= 1;
increment_mode = (ppuCtrl & indx) == indx; indx <<= 1;
pattern_sprite = (ppuCtrl & indx) == indx; indx <<= 1;
pattern_background = (ppuCtrl & indx) == indx; indx <<= 1;
sprite_size = (ppuCtrl & indx) == indx; indx <<= 1;
slave_mode = (ppuCtrl & indx) == indx; indx <<= 1;
enable_nmi = (ppuCtrl & indx) == indx;
reg = ppuCtrl;
}
}
struct LoopyRegister
{
internal byte coarse_x;
internal byte coarse_y;
internal bool nametable_x;
internal bool nametable_y;
internal byte fine_y;
internal bool unused;
internal int reg;
public LoopyRegister(int loopyRegister)
{
coarse_x = (byte)(loopyRegister & 0x1F);
coarse_y = (byte)((loopyRegister >> 5) & 0x1F);
nametable_x = ((loopyRegister >> 10) & 0x01) == 1;
nametable_y = ((loopyRegister >> 11) & 0x01) == 1;
fine_y = (byte)((loopyRegister >> 12) & 0x07);
unused = false;
reg = loopyRegister & 0x0000FFFF;
}
internal LoopyRegister AddCoarseX(byte coarse_x)
{
this.coarse_x = coarse_x;
reg = (reg & ~0x1F) | coarse_x;
return this;
}
internal LoopyRegister AddCoarseY(byte coarse_y)
{
this.coarse_y = coarse_y;
reg = (reg & ~(0x1F << 5)) | ((coarse_y & 0x1F) << 5);
return this;
}
internal LoopyRegister AddFineY(byte fine_y)
{
if(fine_y > 7)
{
unused = true;
this.fine_y = 0;
}
this.fine_y = fine_y;
reg = reg | ((fine_y & 0xFFFF) << 12);
return this;
}
internal LoopyRegister AddNametableX(bool nametable_x)
{
this.nametable_x = nametable_x;
if (nametable_x)
{
reg = reg | (1 << 10);
}
else
{
reg = reg & ~(1 << 10);
}
return this;
}
internal LoopyRegister AddNametableY(bool nametable_y)
{
this.nametable_y = nametable_y;
if (nametable_y)
{
reg = reg | (1 << 10);
}
else
{
reg = reg & ~(1 << 10);
}
return this;
}
}
[StructLayout(LayoutKind.Explicit)]
struct ObjectAttributeEntry
{
[FieldOffset(0)]
internal byte y; // Y position of sprite
[FieldOffset(1)]
internal byte id; // ID of tile from pattern memory
[FieldOffset(2)]
internal byte attribute; // Flags define how sprite should be rendered
[FieldOffset(3)]
internal byte x; // X position of sprite
[FieldOffset(0)]
internal uint oae;
public ObjectAttributeEntry(uint oae) : this()
{
y = (byte)(oae & 0x000000FFu);
id = (byte)((oae >> 8) & 0x000000FFu);
attribute = (byte)((oae >> 16) & 0x000000FFu);
x = (byte)((oae >> 24) & 0x000000FFu);
this.oae = oae;
}
}
public delegate void FrameCompleted(uint[] frame);
}
| 35.973287 | 128 | 0.435024 |
5a7df3719b8e329be26b7f9709883c2ee501ffe1 | 9,213 | cs | C# | src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs | l-hubner/opencvsharp | 6c59b20379d9606d0226041a1603eb1417310ff6 | [
"BSD-3-Clause"
] | 1 | 2018-12-10T21:52:49.000Z | 2018-12-10T21:52:49.000Z | src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs | libeitelynn/opencvsharp | eef21e0c7effaaeb997cfdae63c7584ba5ce1f35 | [
"BSD-3-Clause"
] | null | null | null | src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs | libeitelynn/opencvsharp | eef21e0c7effaaeb997cfdae63c7584ba5ce1f35 | [
"BSD-3-Clause"
] | 1 | 2021-02-02T02:47:58.000Z | 2021-02-02T02:47:58.000Z | using System;
namespace OpenCvSharp
{
/// <summary>
/// Line segment detector class
/// </summary>
public class LineSegmentDetector : Algorithm
{
/// <summary>
/// cv::Ptr<LineSegmentDetector>
/// </summary>
private Ptr ptrObj;
/// <summary>
///
/// </summary>
protected LineSegmentDetector(IntPtr p)
{
ptrObj = new Ptr(p);
ptr = ptrObj.Get();
}
/// <summary>
/// Creates a smart pointer to a LineSegmentDetector object and initializes it.
/// </summary>
/// <param name="refine">The way found lines will be refined, see cv::LineSegmentDetectorModes</param>
/// <param name="scale">The scale of the image that will be used to find the lines. Range (0..1].</param>
/// <param name="sigmaScale">Sigma for Gaussian filter. It is computed as sigma = _sigma_scale/_scale.</param>
/// <param name="quant">Bound to the quantization error on the gradient norm.</param>
/// <param name="angTh">Gradient angle tolerance in degrees.</param>
/// <param name="logEps">Detection threshold: -log10(NFA) \> log_eps.
/// Used only when advancent refinement is chosen.</param>
/// <param name="densityTh">Minimal density of aligned region points in the enclosing rectangle.</param>
/// <param name="nBins">Number of bins in pseudo-ordering of gradient modulus.</param>
/// <returns></returns>
public static LineSegmentDetector Create(
LineSegmentDetectorModes refine = LineSegmentDetectorModes.RefineNone,
double scale = 0.8, double sigmaScale = 0.6, double quant = 2.0, double angTh = 22.5,
double logEps = 0, double densityTh = 0.7, int nBins = 1024)
{
IntPtr ptr = NativeMethods.imgproc_createLineSegmentDetector(
(int)refine, scale, sigmaScale, quant, angTh, logEps, densityTh, nBins);
return new LineSegmentDetector(ptr);
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void DisposeManaged()
{
ptrObj?.Dispose();
ptrObj = null;
base.DisposeManaged();
}
/// <summary>
/// Finds lines in the input image.
/// This is the output of the default parameters of the algorithm on the above shown image.
/// </summary>
/// <param name="image">A grayscale (CV_8UC1) input image. </param>
/// <param name="lines">A vector of Vec4i or Vec4f elements specifying the beginning and ending point of a line.
/// Where Vec4i/Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly oriented depending on the gradient.</param>
/// <param name="width">Vector of widths of the regions, where the lines are found. E.g. Width of line.</param>
/// <param name="prec">Vector of precisions with which the lines are found.</param>
/// <param name="nfa">Vector containing number of false alarms in the line region,
/// with precision of 10%. The bigger the value, logarithmically better the detection.</param>
public virtual void Detect(InputArray image, OutputArray lines,
OutputArray width = null, OutputArray prec = null, OutputArray nfa = null)
{
if (image == null)
throw new ArgumentNullException(nameof(image));
if (lines == null)
throw new ArgumentNullException(nameof(lines));
image.ThrowIfDisposed();
lines.ThrowIfNotReady();
width?.ThrowIfNotReady();
prec?.ThrowIfNotReady();
nfa?.ThrowIfNotReady();
NativeMethods.imgproc_LineSegmentDetector_detect_OutputArray(ptr, image.CvPtr, lines.CvPtr,
Cv2.ToPtr(width), Cv2.ToPtr(prec), Cv2.ToPtr(nfa));
GC.KeepAlive(this);
GC.KeepAlive(image);
GC.KeepAlive(lines);
GC.KeepAlive(width);
GC.KeepAlive(prec);
GC.KeepAlive(nfa);
lines.Fix();
width?.Fix();
prec?.Fix();
nfa?.Fix();
}
/// <summary>
/// Finds lines in the input image.
/// This is the output of the default parameters of the algorithm on the above shown image.
/// </summary>
/// <param name="image">A grayscale (CV_8UC1) input image. </param>
/// <param name="lines">A vector of Vec4i or Vec4f elements specifying the beginning and ending point of a line.
/// Where Vec4i/Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly oriented depending on the gradient.</param>
/// <param name="width">Vector of widths of the regions, where the lines are found. E.g. Width of line.</param>
/// <param name="prec">Vector of precisions with which the lines are found.</param>
/// <param name="nfa">Vector containing number of false alarms in the line region,
/// with precision of 10%. The bigger the value, logarithmically better the detection.</param>
public virtual void Detect(InputArray image, out Vec4f[] lines,
out double[] width, out double[] prec, out double[] nfa)
{
if (image == null)
throw new ArgumentNullException(nameof(image));
image.ThrowIfDisposed();
using (var linesVec = new VectorOfVec4f())
using (var widthVec = new VectorOfDouble())
using (var precVec = new VectorOfDouble())
using (var nfaVec = new VectorOfDouble())
{
NativeMethods.imgproc_LineSegmentDetector_detect_vector(ptr, image.CvPtr,
linesVec.CvPtr, widthVec.CvPtr, precVec.CvPtr, nfaVec.CvPtr);
lines = linesVec.ToArray();
width = widthVec.ToArray();
prec = precVec.ToArray();
nfa = nfaVec.ToArray();
}
GC.KeepAlive(this);
GC.KeepAlive(image);
}
/// <summary>
/// Draws the line segments on a given image.
/// </summary>
/// <param name="image">The image, where the liens will be drawn.
/// Should be bigger or equal to the image, where the lines were found.</param>
/// <param name="lines">A vector of the lines that needed to be drawn.</param>
public virtual void DrawSegments(InputOutputArray image, InputArray lines)
{
if (image == null)
throw new ArgumentNullException(nameof(image));
if (lines == null)
throw new ArgumentNullException(nameof(lines));
image.ThrowIfNotReady();
lines.ThrowIfDisposed();
NativeMethods.imgproc_LineSegmentDetector_drawSegments(ptr, image.CvPtr, lines.CvPtr);
GC.KeepAlive(this);
GC.KeepAlive(image);
image.Fix();
GC.KeepAlive(lines);
}
/// <summary>
/// Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels.
/// </summary>
/// <param name="size">The size of the image, where lines1 and lines2 were found.</param>
/// <param name="lines1">The first group of lines that needs to be drawn. It is visualized in blue color.</param>
/// <param name="lines2">The second group of lines. They visualized in red color.</param>
/// <param name="image">Optional image, where the lines will be drawn.
/// The image should be color(3-channel) in order for lines1 and lines2 to be drawn
/// in the above mentioned colors.</param>
/// <returns></returns>
public virtual int CompareSegments(
Size size, InputArray lines1, InputArray lines2, InputOutputArray image = null)
{
if (lines1 == null)
throw new ArgumentNullException(nameof(lines1));
if (lines2 == null)
throw new ArgumentNullException(nameof(lines2));
lines1.ThrowIfDisposed();
lines2.ThrowIfDisposed();
image?.ThrowIfNotReady();
var ret = NativeMethods.imgproc_LineSegmentDetector_compareSegments(
ptr, size, lines1.CvPtr, lines2.CvPtr, Cv2.ToPtr(image));
GC.KeepAlive(this);
GC.KeepAlive(lines1);
GC.KeepAlive(lines2);
GC.KeepAlive(image);
image?.Fix();
return ret;
}
internal class Ptr : OpenCvSharp.Ptr
{
public Ptr(IntPtr ptr) : base(ptr)
{
}
public override IntPtr Get()
{
var res = NativeMethods.imgproc_Ptr_LineSegmentDetector_get(ptr);
GC.KeepAlive(this);
return res;
}
protected override void DisposeUnmanaged()
{
NativeMethods.imgproc_Ptr_LineSegmentDetector_delete(ptr);
base.DisposeUnmanaged();
}
}
}
}
| 45.161765 | 159 | 0.586345 |
d8b7f15e6be3a84ca2b7dda317ec2a5406ebc462 | 15,937 | cs | C# | AdventOfCode/Solutions/Year2020/Day20/Solution.cs | nerddtvg/aoc | 243622aec276970e5ed4f53ad903d5678cd0a52b | [
"MIT"
] | null | null | null | AdventOfCode/Solutions/Year2020/Day20/Solution.cs | nerddtvg/aoc | 243622aec276970e5ed4f53ad903d5678cd0a52b | [
"MIT"
] | null | null | null | AdventOfCode/Solutions/Year2020/Day20/Solution.cs | nerddtvg/aoc | 243622aec276970e5ed4f53ad903d5678cd0a52b | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace AdventOfCode.Solutions.Year2020
{
class SatTileVariant {
public List<List<string>> tile {get;set;}
public List<string> edges {get;set;}
public SatTileVariant(string[] input) {
// Input is an array of strings (one per line of the tile)
this.tile = input.Select(a => a.Select(b => b.ToString()).ToList()).ToList();
// Set the edges (top, right, bottom, left)
this.edges = new List<string>();
this.edges.Add(input[0]);
this.edges.Add(string.Join("", input.Select(a => a.Substring(a.Length-1, 1))));
this.edges.Add(input[9]);
this.edges.Add(string.Join("", input.Select(a => a.Substring(0, 1))));
}
}
class SatTile {
public int id {get;set;}
public List<List<string>> tile {get;set;}
public int x {get;set;}
public int y {get;set;}
public bool corner {get;set;}
public bool searched {get;set;}
// Let's keep a list of all rotated and flipped tile variants
// This will make matching/string manipulation easier later
public List<SatTileVariant> variants {get;set;}
// A quick list of our edges
public List<string> edges {get;set;}
public override string ToString()
{
return $"{this.id} [{(this.x == Int32.MinValue ? "unk" : this.x)}, {(this.y == Int32.MinValue ? "unk" : this.y)}]: {string.Join(", ", this.variants[0].edges)}";
}
public SatTile(string[] input) {
this.x = Int32.MinValue;
this.y = Int32.MinValue;
this.corner = false;
this.searched = false;
// Get the Tile ID
this.id = Int32.Parse(input[0].Split(" ", StringSplitOptions.TrimEntries)[1].Replace(":", ""));
// The rest of the input...
input = input.Skip(1).ToArray();
this.tile = input.Select(a => a.Select(b => b.ToString()).ToList()).ToList();
// Set our edges for part 1
this.edges = new List<string>();
this.edges.Add(input[0]);
this.edges.Add(string.Join("", input.Select(a => a.Substring(a.Length-1, 1))));
this.edges.Add(input[9]);
this.edges.Add(string.Join("", input.Select(a => a.Substring(0, 1))));
// Get all variants
this.variants = new List<SatTileVariant>();
for(int flip=0; flip<2; flip++) {
for(int rotate=0; rotate<4; rotate++) {
// Load the variant
var v = (string[]) input.Clone();
// We need to work on this
// Flip all of the lines around
if (flip > 0)
for(int i=0; i<v.Length; i++)
v[i] = v[i].Reverse();
// Now we need to (maybe) rotate
for(int i=0; i<rotate; i++)
v = rotateArray(v);
this.variants.Add(new SatTileVariant(v));
}
}
}
public List<string> getTileWithoutBorder() =>
// This returns the tile string without the borders (1 pixel on each side)
this.tile.Skip(1).Take(8).Select(a => string.Join("", a.Skip(1).Take(8))).ToList();
public string[] rotateArray(string[] input) {
// Take the input array and rotate it 90 degrees
string[] outArr = new string[input.Length];
// Rotating 90 degrees is "simply" reading bottom to top, left to right
for(int line=0; line<input[0].Length; line++) {
// line is the index for outArr
outArr[line] = "";
// line is also the 'x' value in input
for(int y=input.Length-1; y>=0; y--)
outArr[line] += input[y].Substring(line, 1);
}
return outArr;
}
public List<List<string>> rotateArray(List<List<string>> input) =>
rotateArray(
input.Select(a => string.Join("", a)).ToArray()
).Select(a => a.Select(a => a.ToString()).ToList()).ToList();
public void FindNeighbors(ref List<SatTile> tiles) {
// Avoiding stack issues
if (this.searched) return;
this.searched = true;
// We need to look for each of our neighbors (up, right, down, left)
// Find up
FindNeighbor(ref tiles, 0);
// Find right
FindNeighbor(ref tiles, 1);
// Find down
FindNeighbor(ref tiles, 2);
// Find left
FindNeighbor(ref tiles, 3);
}
private void FindNeighbor(ref List<SatTile> tiles, int direction) {
int newX = this.x + (direction % 2 == 0 ? 0 : (direction == 1 ? 1 : -1));
int newY = this.y + (direction % 2 == 0 ? (direction == 0 ? -1 : 1) : 0);
// Already done
if (tiles.Count(a => a.x == newX && a.y == newY) > 0) return;
// Find a tile that has a variant matches our desired edge
// Since we have every variant of each tile, we should be able to find one where the side we want is opposite our current side
int newDirection = (direction + 2) % 4;
var newTile = tiles.Where(a => a.searched == false && a.variants.Select(b => b.edges[newDirection]).Contains(this.edges[direction])).FirstOrDefault();
if (newTile != null) {
// Found it!
// Get the specific variant
var variant = newTile.variants.First(a => a.edges[newDirection] == this.edges[direction]);
// Replace this tile information to account for the new rotation/flip information
newTile.tile = variant.tile;
newTile.edges = variant.edges;
// Clear the variants to prevent double-matching later
newTile.variants.Clear();
// Set the new x,y
newTile.x = newX;
newTile.y = newY;
// Find neighbors!
newTile.FindNeighbors(ref tiles);
}
}
}
class Day20 : ASolution
{
List<SatTile> tiles = new List<SatTile>();
public Day20() : base(20, 2020, "")
{
// Debug Input
/** /
DebugInput = @"
Tile 2311:
..##.#..#.
##..#.....
#...##..#.
####.#...#
##.##.###.
##...#.###
.#.#.#..##
..#....#..
###...#.#.
..###..###
Tile 1951:
#.##...##.
#.####...#
.....#..##
#...######
.##.#....#
.###.#####
###.##.##.
.###....#.
..#.#..#.#
#...##.#..
Tile 1171:
####...##.
#..##.#..#
##.#..#.#.
.###.####.
..###.####
.##....##.
.#...####.
#.##.####.
####..#...
.....##...
Tile 1427:
###.##.#..
.#..#.##..
.#.##.#..#
#.#.#.##.#
....#...##
...##..##.
...#.#####
.#.####.#.
..#..###.#
..##.#..#.
Tile 1489:
##.#.#....
..##...#..
.##..##...
..#...#...
#####...#.
#..#.#.#.#
...#.#.#..
##.#...##.
..##.##.##
###.##.#..
Tile 2473:
#....####.
#..#.##...
#.##..#...
######.#.#
.#...#.#.#
.#########
.###.#..#.
########.#
##...##.#.
..###.#.#.
Tile 2971:
..#.#....#
#...###...
#.#.###...
##.##..#..
.#####..##
.#..####.#
#..#.#..#.
..####.###
..#.#.###.
...#.#.#.#
Tile 2729:
...#.#.#.#
####.#....
..#.#.....
....#..#.#
.##..##.#.
.#.####...
####.#.#..
##.####...
##..#.##..
#.##...##.
Tile 3079:
#.#.#####.
.#..######
..#.......
######....
####.#..#.
.#...#.##.
#.#####.##
..#.###...
..#.......
..#.###...";
/**/
// Load the tiles
foreach(var tile in Input.SplitByBlankLine(true))
tiles.Add(new SatTile(tile));
// Go through and find the corners
tiles.ForEach(tile => {
// If a tile only matches on two sides, it's a corner
// Get all edges that are not this one
// Get the reverse of each to match against flips
var allEdges = tiles.Where(a => a.id != tile.id).SelectMany(a => a.edges.Union(a.edges.Select(a => a.Reverse()))).Distinct().ToList();
var matches = tile.edges.Intersect(allEdges);
var count = matches.Count();
//Console.WriteLine($"{tile.id}: {count}");
// Check if we only have two matching
if (count == 2)
tile.corner = true;
});
}
protected override string SolvePartOne()
{
return tiles.Where(a => a.corner == true).Aggregate((long) 1, (x, y) => x * (long) y.id).ToString();
}
protected override string SolvePartTwo()
{
// We need to count the '#' that are not a part of the sea monsters
// Sea monsters are 15 '#' characters
/*
#
# ## ## ###
# # # # # #
*/
// We need to remove the edges from each tile before stitching them together
// First we get the tiles in order
// Start in a corner
var corner = tiles.First(a => a.corner == true);
corner.x = 0;
corner.y = 0;
corner.FindNeighbors(ref tiles);
// Let's go through and put all of these together into one large image
int minX = tiles.Where(a => a.searched).Min(a => a.x);
int maxX = tiles.Where(a => a.searched).Max(a => a.x);
int minY = tiles.Where(a => a.searched).Min(a => a.y);
int maxY = tiles.Where(a => a.searched).Max(a => a.y);
Dictionary<int, string> image = new Dictionary<int, string>();
for(int y=minY; y<=maxY; y++)
for(int x=minX; x<=maxX; x++) {
var tile = tiles.FirstOrDefault(a => a.x == x && a.y == y);
List<string> tileString;
if (tile != null) {
tileString = tile.getTileWithoutBorder();
} else {
throw new Exception($"Ended up with a missing tile: X: {x}, Y: {y}");
}
// Go through the image and add this on to each line
int b = (y - minY); // What "line" are we one, jumps of 10
for(int i=0; i<tileString.Count; i++) {
int key = (b * 10) + i;
if(image.ContainsKey(key)) {
image[key] += tileString[i];
} else {
image[key] = tileString[i];
}
}
}
// Get the image in array form (so we can work with it again)
// 2D array: [y][x]
var imageArr = image.OrderBy(a => a.Key).Select(a => a.Value.Select(a => a.ToString()).ToList()).ToList();
// Now we have an array of strings that form our image
// We need to go through and find all of the sea monsters
// Then replace those with 'O' so we don't double-count
// Be sure to rotate the image to find all of them
// We define an array of 'monster' dx,dy of what is expected
/*
1111111111
01234567890123456789
+--------------------+
0| # |0
1|# ## ## ###|1
2| # # # # # # |2
+--------------------+
1111111111
01234567890123456789
+--------------------+
0| # |0
+--------------------+
| 1111111111|
|01234567890123456789|
+--------------------+
1|# ## ## ###|1
+--------------------+
| 1111111111|
|01234567890123456789|
+--------------------+
2| # # # # # # |2
+--------------------+
*/
List<(int dy, int dx)> monster = new List<(int dy, int dx)>() {
(0, 18),
(1, 0),
(1, 5),
(1, 6),
(1, 11),
(1, 12),
(1, 17),
(1, 18),
(1, 19),
(2, 1),
(2, 4),
(2, 7),
(2, 10),
(2, 13),
(2, 16)
};
// Helpers for loops later
int monsterWidth = 20;
int monsterHeight = 3;
// Print the starting image
Console.WriteLine("\n" + string.Join("\n", imageArr));
Console.WriteLine();
int monsters = 0;
for(int flip=0; flip<2; flip++) {
for(int rotate=0; rotate<4; rotate++) {
// We need to go through and find all instances where the '#' lines up to a monster
for(int y=0; y<imageArr.Count-monsterHeight+1; y++) {
for(int x=0; x<imageArr[0].Count-monsterWidth+1; x++) {
// If we have the same number of '#' as the monster array, then we have a monster!
if (monster.Count(a => imageArr[y+a.dy][x+a.dx] == "#") == monster.Count) {
monsters++;
// Change all of them to 'O' to avoid double counting
monster.ForEach(a => imageArr[y+a.dy][x+a.dx] = "O");
}
}
}
// If we found monsters, we're in the right position, break out
if (monsters > 0) break;
// Using the helper to rotate the image
imageArr = this.tiles[0].rotateArray(imageArr);
}
// If we found monsters, we're in the right position, break out
if (monsters > 0) break;
// Need to flip the image
imageArr.ForEach(a => a.Reverse());
}
// Print the final image
Console.WriteLine("\n" + string.Join("\n", imageArr.Select(a => string.Join("", a))));
Console.WriteLine($"Monsters: {monsters}");
return imageArr.Sum(a => a.Count(b => b == "#")).ToString();
}
}
}
| 34.053419 | 172 | 0.39355 |
9176f37ae69d933aea889c773910003c3048a688 | 11,944 | cs | C# | Discount/Discount/Models/ShopModel.cs | CavaleriDK/Discount | 709c716b53d94186b5df818aa5eb68aa84164949 | [
"Unlicense"
] | null | null | null | Discount/Discount/Models/ShopModel.cs | CavaleriDK/Discount | 709c716b53d94186b5df818aa5eb68aa84164949 | [
"Unlicense"
] | null | null | null | Discount/Discount/Models/ShopModel.cs | CavaleriDK/Discount | 709c716b53d94186b5df818aa5eb68aa84164949 | [
"Unlicense"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace Discount.Models
{
/// <summary>
/// Model representing a row in the Shop table
/// </summary>
public class ShopModel
{
/// <summary>
/// The Primary key ID of this model
/// </summary>
public int ID { get => id; }
/// <summary>
/// The shop Name from Shopgun API
/// </summary>
public string Name { get => name.Replace(@"\u0027", "'"); }
/// <summary>
/// The Shopgun Dealer ID from the Shopgun API
/// </summary>
public string ShopgunDealerID { get => shopgunDealerId; }
private int id;
private string name;
private string shopgunDealerId;
private bool isUnchanged;
private bool readOnly;
/// <summary>
/// Private constructor for this model
/// </summary>
/// <param name="isNew">Whether or not this is a new model</param>
private ShopModel(bool isNew)
{
// Make sure this reflects wether or not this is a new model or fetched from database
this.isUnchanged = !isNew;
this.readOnly = false;
}
/// <summary>
/// Public constructor used for instantiating this model as part of foreign key reference on OfferModel
/// </summary>
/// <param name="id">The Primary ID of this model</param>
/// <param name="name">The Name of this shop</param>
public ShopModel(int id, string name)
{
this.id = id;
this.name = name;
this.readOnly = true;
}
/// <summary>
/// Method used to save a models changes to the database. Only usable for new models as this model cannot change values
/// </summary>
/// <returns>True if the model was succesfully saved, false otherwise</returns>
public bool Save()
{
if (!this.isUnchanged && !this.readOnly)
{
StringBuilder stringBuilder = new StringBuilder();
// Prepare statement to create a new Offer row
stringBuilder.Append("INSERT INTO [Shop](Name, Shopgun_dealer_ID) OUTPUT INSERTED.ID VALUES (");
stringBuilder.Append("'" + this.name + "', ");
stringBuilder.Append("'" + this.shopgunDealerId + "')");
// Setup appropriate SQL statement to save
string commandText = stringBuilder.ToString();
// Lock this protected area with the SQL connection itself
Monitor.Enter(ConnectionController.Instance.SqlCon);
try
{
// Open the SQL connection
ConnectionController.Instance.OpenSqlConnection();
// Create the SQL Command object and setup the command statement
SqlCommand cmd = ConnectionController.Instance.SqlCon.CreateCommand();
cmd.CommandText = commandText;
// Set the ID property if this is an insert statement
if (this.id == default(int))
{
this.id = (int)cmd.ExecuteScalar();
}
else
{
// Execute the statement blankly
cmd.ExecuteNonQuery();
}
// Set state as saved
this.isUnchanged = true;
}
catch (Exception e)
{
// Show error if something went horribly wrong
MessageBox.Show("Error: " + e.Message, "Connection error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
finally
{
// Close the connection always
ConnectionController.Instance.CloseSqlConnection();
// Release the lock
Monitor.Exit(ConnectionController.Instance.SqlCon);
}
}
return this.isUnchanged;
}
/// <summary>
/// Creates and saves a new model of this type in the database
/// </summary>
/// <param name="name">Name of this shop</param>
/// <param name="shopgun_dealer_id">Shopgun Dealer ID of this shop</param>
/// <returns>The new model saved in database, null if error while saving</returns>
public static ShopModel New(string name, string shopgun_dealer_id)
{
// Create blank model and set all fields
ShopModel model = new ShopModel(true);
model.name = name;
model.shopgunDealerId = shopgun_dealer_id;
// Save the model
if (model.Save())
{
return model;
}
// Return null if the model was failed to be saved
return null;
}
/// <summary>
/// Method used to return a ShopModel from the table by its ID
/// </summary>
/// <param name="id">The primary ID of the model to find</param>
/// <returns>A ShopModel representing this row. Null if failed</returns>
public static ShopModel FindByID(int id)
{
return Find("id = " + id);
}
/// <summary>
/// Method used to return a ShopModel from the table by its Shopgun Dealer ID
/// </summary>
/// <param name="shopgun_dealer_id">The Shopgun Dealer ID of the model to find</param>
/// <returns>A ShopModel representing this row. Null if failed</returns>
public static ShopModel FindByShopgunDealerID(string shopgun_dealer_id)
{
return Find("Shopgun_dealer_ID = '" + shopgun_dealer_id + "'");
}
/// <summary>
/// Get a list of all shops
/// </summary>
/// <returns>A list of ShopModels with all shops in the Database</returns>
public static List<ShopModel> FindAll()
{
// Fake where clause to make sure all results are returned
string whereClause = "id > 0";
return FindList(whereClause);
}
/// <summary>
/// Method to search after all shops by part of a name string
/// </summary>
/// <param name="query">The case insensitive search query</param>
/// <returns>List of ShopModels that all contain the query as part of their name</returns>
public static List<ShopModel> SearchByName(string query)
{
// Make sure the search is case insensitive by changing all characters to lower case
string whereClause = "LOWER(Name) LIKE LOWER('%" + query + "%')";
return FindList(whereClause);
}
/// <summary>
/// Used internally to find row in the table and return as model object
/// </summary>
/// <param name="where_clause">There WHERE clause to use as part of the SQL statement</param>
/// <returns>A ShopModel representing this row. Null if failed</returns>
private static ShopModel Find(string where_clause)
{
// Create new model and set it up as existing row
ShopModel model = default(ShopModel);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("SELECT * FROM [Shop] WHERE ");
stringBuilder.Append(where_clause);
// Build full SQL statement
string commandText = stringBuilder.ToString();
// Enter the protected area to prevent race conditions
Monitor.Enter(ConnectionController.Instance.SqlCon);
try
{
// Open the SQL connection
ConnectionController.Instance.OpenSqlConnection();
// Create the SQL Command object and setup the command statement
SqlCommand cmd = ConnectionController.Instance.SqlCon.CreateCommand();
cmd.CommandText = commandText;
// Execute the statement
SqlDataReader reader = cmd.ExecuteReader();
// Parse data as Model
while (reader.Read())
{
model = new ShopModel(false);
model.id = reader.GetInt32(0);
model.name = reader.GetString(1);
model.shopgunDealerId = reader.GetString(2);
}
// Close the reader after being used
reader.Close();
}
catch (Exception e)
{
// Show error if something went horribly wrong
MessageBox.Show("Error: " + e.Message, "Connection error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
finally
{
// Gracefully close the connection
ConnectionController.Instance.CloseSqlConnection();
// Exit the protected area
Monitor.Exit(ConnectionController.Instance.SqlCon);
}
// Return the model if anything was succesfully found or null
return model;
}
/// <summary>
/// Used internally to find rows in the table and return as a list of model object
/// </summary>
/// <param name="where_clause">The WHERE clause to use as part of the SQL statement</param>
/// <returns>A list of ShopModels representing these rows. Empty list if failed</returns>
private static List<ShopModel> FindList(string where_clause)
{
List<ShopModel> models = new List<ShopModel>();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("SELECT * FROM [Shop] WHERE ");
stringBuilder.Append(where_clause);
// Build SQL statement
string commandText = stringBuilder.ToString();
// Enter the protected area to prevent race conditions
Monitor.Enter(ConnectionController.Instance.SqlCon);
try
{
// Open the SQL connection
ConnectionController.Instance.OpenSqlConnection();
// Create the SQL Command object and setup the command statement
SqlCommand cmd = ConnectionController.Instance.SqlCon.CreateCommand();
cmd.CommandText = commandText;
// Execute the statement
SqlDataReader reader = cmd.ExecuteReader();
// Parse data as Model and append to the list of models
while (reader.Read())
{
// Create blank OfferModel and set it up as a an existing row
ShopModel model = new ShopModel(false);
model.id = reader.GetInt32(0);
model.name = reader.GetString(1);
model.shopgunDealerId = reader.GetString(2);
models.Add(model);
}
// Close the reader after being used
reader.Close();
}
catch (Exception e)
{
// Show error if something went horribly wrong
MessageBox.Show("Error: " + e.Message, "Connection error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
finally
{
// Gracefully close the connection
ConnectionController.Instance.CloseSqlConnection();
// Exit the protected area
Monitor.Exit(ConnectionController.Instance.SqlCon);
}
return models;
}
}
}
| 37.325 | 127 | 0.548058 |
cbee75d493a10109d03c640437d845e6b1443043 | 5,453 | cs | C# | Gibbo.Editor.WPF/Windows/CompilerWindow.xaml.cs | bradparks/Gibbo2DEditor__2d_game_editor_haxe_openfl_fork | ebe0a5cfd1b13e5a8907865e53df0a2518a772ad | [
"MIT"
] | 14 | 2015-03-26T10:03:42.000Z | 2017-01-05T13:23:34.000Z | Gibbo.Editor.WPF/Windows/CompilerWindow.xaml.cs | Whitebeard86/Gibbo2D | ac493e42826980451cbcce8edb8da8b326e63bfd | [
"MIT"
] | 1 | 2017-09-19T20:35:07.000Z | 2018-02-01T17:45:43.000Z | Gibbo.Editor.WPF/Windows/CompilerWindow.xaml.cs | Whitebeard86/Gibbo2D | ac493e42826980451cbcce8edb8da8b326e63bfd | [
"MIT"
] | 6 | 2015-03-03T07:47:51.000Z | 2016-08-30T05:30:38.000Z | #region Copyrights
/*
Gibbo2D License - Version 1.0
Copyright (c) 2013 - Gibbo2D Team
Founders Joao Alves <joao.cpp.sca@gmail.com> & Luis Fernandes <luisapidcloud@hotmail.com>
Permission is granted to use this software and associated documentation files (the "Software") free of charge,
to any person or company. The code can be used, modified and merged without restrictions, but you cannot sell
the software itself and parts where this license applies. Still, permission is granted for anyone to sell
applications made using this software (for example, a game). This software cannot be claimed as your own,
except for copyright holders. This license notes should also be available on any of the changed or added files.
The software is provided "as is", without warranty of any kind, express or implied, including but not limited to
the warranties of merchantability, fitness for a particular purpose and non-infrigement. In no event shall the
authors or copyright holders be liable for any claim, damages or other liability.
The license applies to all versions of the software, both newer and older than the one listed, unless a newer copy
of the license is available, in which case the most recent copy of the license supercedes all others.
*/
#endregion
using Gibbo.Editor.Model;
using Gibbo.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Gibbo.Editor.WPF
{
/// <summary>
/// Interaction logic for CompilerForm.xaml
/// </summary>
public partial class CompilerWindow : Window
{
public bool Result { get; set; }
public CompilerWindow()
{
InitializeComponent();
ErrorDataGrid.Visibility = Visibility.Collapsed;
ErrorDataGrid.MouseDoubleClick += ErrorDataGrid_MouseDoubleClick;
}
void Row_DoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender != null)
{
DataGridRow row = sender as DataGridRow;
if (row != null)
{
ErrorLog item = row.Item as ErrorLog;
LimeScriptEditor.Instance.OpenScriptAndSeek(SceneManager.GameProject.ProjectPath + @"\" + item.FileName, item.LineNumber, item.ColumnNumber);
this.Close();
}
}
}
void ErrorDataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
//if (sender != null)
//{
// DataGrid grid = sender as DataGrid;
// if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
// {
// //DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
// ErrorLog item = grid.SelectedItem as ErrorLog;
// LimeScriptEditor.Instance.OpenScriptAndSeek(SceneManager.GameProject.ProjectPath + @"\" + item.FileName, item.LineNumber, item.ColumnNumber);
// }
//}
}
public void SafeClose()
{
// Make sure we're running on the UI thread
//if (this.InvokeRequired)
//{
// BeginInvoke(new Action(SafeClose));
// return;
//}
if (this.Dispatcher.CheckAccess())
{
this.Dispatcher.BeginInvoke(new Action(SafeClose));
return;
}
//// Close the form now that we're running on the UI thread
//this.DialogResult = System.Windows.Forms.DialogResult.Yes;
DialogResult = true;
Close();
}
private void Window_ContentRendered(object sender, EventArgs e)
{
if (ScriptsBuilder.ReloadScripts())
{
// Sucess:
this.progresslbl.Content = "Loading...";
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 5;
timer.Tick += timer_Tick;
timer.Enabled = true;
Result = true;
}
else
{
progressBar.Value = 80;
this.progresslbl.Content = "Failure!";
Result = false;
EditorCommands.ShowOutputMessage("Error while compiling the scripts");
ErrorDataGrid.Visibility = Visibility.Visible;
ErrorDataGrid.ItemsSource = ScriptsBuilder.Logger.Errors;
}
}
void timer_Tick(object sender, EventArgs e)
{
progressBar.Value += GibboHelper.RandomNumber(4, 5) ;
if (progressBar.Value >= 100)
{
this.progresslbl.Content = "Success!";
(sender as System.Windows.Forms.Timer).Enabled = false;
this.Close();
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.progresslbl.Content = "Gathering data and setting parameters to compile...";
}
}
}
| 35.409091 | 163 | 0.604438 |
a39fad4ea76e91ea222a328599401878587131d6 | 885 | cs | C# | unity/demo/Assets/Scripts/Core/Plugins/UnityLogTrace.cs | hexrain/utymap | 39cb7684bf014ecc770ed1c46d953f13e103f3f5 | [
"Apache-2.0"
] | 946 | 2016-03-13T23:00:37.000Z | 2022-03-29T08:35:30.000Z | unity/demo/Assets/Scripts/Core/Plugins/UnityLogTrace.cs | hexrain/utymap | 39cb7684bf014ecc770ed1c46d953f13e103f3f5 | [
"Apache-2.0"
] | 136 | 2016-03-30T11:54:45.000Z | 2020-10-31T13:05:27.000Z | unity/demo/Assets/Scripts/Core/Plugins/UnityLogTrace.cs | hexrain/utymap | 39cb7684bf014ecc770ed1c46d953f13e103f3f5 | [
"Apache-2.0"
] | 168 | 2016-05-02T15:04:53.000Z | 2022-03-28T17:23:26.000Z | using System;
using UtyMap.Unity.Infrastructure.Diagnostic;
namespace Assets.Scripts.Core.Plugins
{
internal sealed class UnityLogTrace : DefaultTrace
{
protected override void OnWriteRecord(TraceLevel type, string category, string message, Exception exception)
{
switch (type)
{
case TraceLevel.Error:
UnityEngine.Debug.LogError(String.Format("[{0}] {1}:{2}. Exception: {3}", type, category, message, exception));
break;
case TraceLevel.Warn:
UnityEngine.Debug.LogWarning(String.Format("[{0}] {1}:{2}", type, category, message));
break;
default:
UnityEngine.Debug.Log(String.Format("[{0}] {1}: {2}", type, category, message));
break;
}
}
}
}
| 35.4 | 131 | 0.542373 |
58127b07d9aa530b070fd16c18a13205381cb570 | 2,569 | cs | C# | CefGlue.Client/Options.cs | yasoonOfficial/cefglue | 2df113f70ddc8159b4f5eec14c532629eb94259f | [
"BSD-3-Clause"
] | 1 | 2015-11-28T09:02:05.000Z | 2015-11-28T09:02:05.000Z | CefGlue.Client/Options.cs | yasoonOfficial/cefglue | 2df113f70ddc8159b4f5eec14c532629eb94259f | [
"BSD-3-Clause"
] | null | null | null | CefGlue.Client/Options.cs | yasoonOfficial/cefglue | 2df113f70ddc8159b4f5eec14c532629eb94259f | [
"BSD-3-Clause"
] | 4 | 2015-11-02T00:16:51.000Z | 2021-10-01T15:57:14.000Z | namespace CefGlue.Client
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
internal sealed class Options
{
public static Options Parse(string[] args)
{
return new Options(args);
}
public bool MultiThreadedMessageLoop { get; private set; }
public bool CefMessageLoop { get; private set; }
public bool Help { get; private set; }
private Options(string[] args)
{
// apply defaults
this.MultiThreadedMessageLoop = true;
this.CefMessageLoop = true;
this.Help = false;
ParseArgs(args);
}
private void ParseArgs(string[] args)
{
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.StartsWith("--")) arg = arg.Substring(2);
else if (arg.StartsWith("-") || arg.StartsWith("/")) arg = arg.Substring(1);
else throw new ArgumentException("args");
switch (arg)
{
case "multi-threaded-message-loop":
case "mt":
this.MultiThreadedMessageLoop = true;
break;
case "single-threaded-message-loop":
case "st":
this.MultiThreadedMessageLoop = false;
break;
case "cef-message-loop":
this.CefMessageLoop = true;
break;
case "idle-loop":
this.CefMessageLoop = false;
break;
case "help":
case "?":
this.Help = true;
break;
default:
this.Help = true;
break;
}
}
}
public string GetHelpText()
{
return "CefGlue Client options:\n" +
"-mt, --multi-threaded-message-loop: use multi-threaded message loop.\n" +
"-st, --single-threaded-message-loop: use single-threaded message loop.\n" +
"--cef-message-loop: use cef message loop (in single-threaded message loop mode).\n" +
"--idle-loop: process cef messages on idle (in single-threaded message loop mode).\n" +
"--help: this help.";
}
}
}
| 31.716049 | 106 | 0.452705 |
58718c910332a9085dc1fb756940b64017329a35 | 2,078 | cs | C# | dog-agent-game/UnitySDK/Assets/FiRescue/Scripts/CameraFollow.cs | antopraju/FiRescue | a67c8fa3ee3422f6c6979ed242d6d68309b4230f | [
"MIT"
] | null | null | null | dog-agent-game/UnitySDK/Assets/FiRescue/Scripts/CameraFollow.cs | antopraju/FiRescue | a67c8fa3ee3422f6c6979ed242d6d68309b4230f | [
"MIT"
] | null | null | null | dog-agent-game/UnitySDK/Assets/FiRescue/Scripts/CameraFollow.cs | antopraju/FiRescue | a67c8fa3ee3422f6c6979ed242d6d68309b4230f | [
"MIT"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public GameObject dog;
// Start is called before the first frame update
void Start()
{
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionY;
Vector3 dogloc = new Vector3(dog.transform.position.x, 3, dog.transform.position.z);
Vector3 viewPos = GetComponent<Camera>().WorldToViewportPoint(dog.transform.position);
transform.LookAt(dogloc);
Vector3 dogpos = new Vector3(dog.transform.position.x + 8, 3f, dog.transform.position.z);
transform.position = Vector3.Lerp(transform.position, dogpos, 0.5f * Time.deltaTime);
/*
if (!(viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1 && viewPos.z > 0))
{
transform.LookAt(dogloc);
//Vector3 dogpos = new Vector3(dog.transform.position.x + 3, 3f, dog.transform.position.z);
//transform.position = Vector3.Lerp(transform.position, dogpos, 0.5f * Time.deltaTime);
}
*/
}
// Update is called once per frame
void Update()
{
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionY;
Vector3 dogloc = new Vector3(dog.transform.position.x, 3, dog.transform.position.z);
Vector3 viewPos = GetComponent<Camera>().WorldToViewportPoint(dog.transform.position);
transform.LookAt(dogloc);
Vector3 dogpos = new Vector3(dog.transform.position.x + 8, 3f, dog.transform.position.z);
transform.position = Vector3.Lerp(transform.position, dogpos, 0.5f * Time.deltaTime);
/*
if (!(viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1 && viewPos.z > 0))
{
transform.LookAt(dogloc);
//Vector3 dogpos = new Vector3(dog.transform.position.x + 3, 3f, dog.transform.position.z);
//transform.position = Vector3.Lerp(transform.position, dogpos, 0.5f * Time.deltaTime);
}
*/
}
}
| 45.173913 | 103 | 0.641482 |
45202a0871de15aa918008a1458b2e45be74c58e | 605 | cs | C# | src/Http/Http.Features/src/IHttpResponseStartFeature.cs | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 16 | 2019-07-16T15:08:32.000Z | 2022-02-07T09:37:02.000Z | src/Http/Http.Features/src/IHttpResponseStartFeature.cs | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 29 | 2020-09-06T06:57:21.000Z | 2022-03-03T22:45:35.000Z | src/Http/Http.Features/src/IHttpResponseStartFeature.cs | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 2 | 2020-07-10T01:10:09.000Z | 2022-01-30T12:52:11.000Z | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Http.Features
{
/// <summary>
/// Feature to start response writing.
/// </summary>
public interface IHttpResponseStartFeature
{
/// <summary>
/// Starts the response by calling OnStarting() and making headers unmodifiable.
/// </summary>
Task StartAsync(CancellationToken token = default);
}
}
| 30.25 | 111 | 0.689256 |
621283af2a3d58896425315ffdea6ba91074aa8c | 2,338 | cs | C# | tests/src/Loader/classloader/generics/Variance/IL/InterfaceInheritanceTest2.cs | elinor-fung/coreclr | c1801e85024add717f518feb6a9caed60d54500f | [
"MIT"
] | 159 | 2020-06-17T01:01:55.000Z | 2022-03-28T10:33:37.000Z | tests/src/Loader/classloader/generics/Variance/IL/InterfaceInheritanceTest2.cs | elinor-fung/coreclr | c1801e85024add717f518feb6a9caed60d54500f | [
"MIT"
] | 19 | 2020-06-27T01:16:35.000Z | 2022-02-06T20:33:24.000Z | tests/src/Loader/classloader/generics/Variance/IL/InterfaceInheritanceTest2.cs | elinor-fung/coreclr | c1801e85024add717f518feb6a9caed60d54500f | [
"MIT"
] | 19 | 2020-05-21T08:18:20.000Z | 2021-06-29T01:13:13.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*
Test that variance is not inherited across interfaces.
So if the parent interface is co/contra variant but the child interface is not variant
we can use the generic type parameter of the child in any position
(both as return parameter and argument type to a method)
*/
using System;
public class C1<T> : I1<T>
{
public T produce()
{
return default(T);
}
public void consume(T t)
{
}
}
public class C2<T> : I2<T>
{
public T produce()
{
return default(T);
}
public void consume(T t)
{
}
}
public class Test
{
static bool pass;
delegate void Case();
public static void Test1a()
{
C1<int> obj = new C1<int>();
int i = obj.produce();
obj.consume(5);
}
public static void Test1b()
{
C1<object> obj = new C1<object>();
Object o = obj.produce();
obj.consume(new Object());
}
public static void Test2a()
{
C2<int> obj = new C2<int>();
int i = obj.produce();
obj.consume(5);
}
public static void Test2b()
{
C2<object> obj = new C2<object>();
Object o = obj.produce();
obj.consume(new Object());
}
static void Check(Case mytest, string testName)
{
Console.WriteLine(testName);
try
{
mytest();
}
catch (Exception e)
{
Console.WriteLine("FAIL: Caught unexpected exception: " + e);
pass = false;
}
}
public static int Main()
{
pass = true;
Console.WriteLine("\nInherited interface : covariant");
Check(new Case(Test1a), "Test 1a: Implementing interface: non variant"); // primitive generic param
Check(new Case(Test1b), "Test 1b: Implementing interface: non variant"); // reference type generic param
Console.WriteLine("\nInherited interface : contravariant");
Check(new Case(Test2a), "Test 2a: Implementing interface: non variant"); // primitive generic param
Check(new Case(Test2b), "Test 2b: Implementing interface: non variant"); // reference type generic param
if (pass)
{
Console.WriteLine("\nPASS");
return 100;
}
else
{
Console.WriteLine("\nFAIL");
return 101;
}
}
}
| 17.318519 | 110 | 0.635158 |
624af3b0e959ed835a954f12b13bb8a6c64d8a59 | 516 | cs | C# | src/WAYWF.Agent.Core/Native/SymbolStoreApi/ISymUnmanagedDispose.cs | brian-reichle/WAYWF | fe8c454d348a2943e38cfb77aa9c91ee941c5afb | [
"Apache-2.0"
] | 2 | 2018-03-15T12:19:42.000Z | 2018-05-20T10:42:06.000Z | src/WAYWF.Agent.Core/Native/SymbolStoreApi/ISymUnmanagedDispose.cs | brian-reichle/WAYWF | fe8c454d348a2943e38cfb77aa9c91ee941c5afb | [
"Apache-2.0"
] | null | null | null | src/WAYWF.Agent.Core/Native/SymbolStoreApi/ISymUnmanagedDispose.cs | brian-reichle/WAYWF | fe8c454d348a2943e38cfb77aa9c91ee941c5afb | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Brian Reichle. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace WAYWF.Agent.Core.SymbolStoreApi
{
[ComImport]
[SuppressUnmanagedCodeSecurity]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("969708D2-05E5-4861-A3B0-96E473CDF63F")]
interface ISymUnmanagedDispose
{
// HRESULT Destroy();
void Destroy();
}
}
| 28.666667 | 164 | 0.781008 |
ce67252146ac734aef5371668923ced5a2b8f4fa | 614 | cs | C# | src/Uni.Api.Web/Validators/UniversityRequestModelValidator.cs | UniverPro/core | 9e901f434444bdfbc959861eb43466ee4ed63afa | [
"MIT"
] | null | null | null | src/Uni.Api.Web/Validators/UniversityRequestModelValidator.cs | UniverPro/core | 9e901f434444bdfbc959861eb43466ee4ed63afa | [
"MIT"
] | null | null | null | src/Uni.Api.Web/Validators/UniversityRequestModelValidator.cs | UniverPro/core | 9e901f434444bdfbc959861eb43466ee4ed63afa | [
"MIT"
] | null | null | null | using FluentValidation;
using JetBrains.Annotations;
using Uni.Api.Core;
using Uni.Api.Shared.Requests;
namespace Uni.Api.Web.Validators
{
[UsedImplicitly]
public class UniversityRequestModelValidator : AbstractValidator<UniversityRequestModel>
{
public UniversityRequestModelValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(Consts.MaxNameLength);
RuleFor(x => x.ShortName)
.MaximumLength(Consts.MaxShortNameLength)
.When(x => !string.IsNullOrEmpty(x.ShortName));
}
}
}
| 26.695652 | 92 | 0.631922 |
ce87298039d3d53dfdb930cc2dced01fdf58cc8e | 1,551 | cs | C# | src/SKIT.FlurlHttpClient.Wechat.Api/Events/CardInvoice/UpdateInvoiceStatusEvent.cs | magotop/DotNetCore.SKIT.FlurlHttpClient.Wechat | 82397f88c67ceac107d6988f9999b90916a93952 | [
"MIT"
] | 1 | 2021-09-15T04:11:39.000Z | 2021-09-15T04:11:39.000Z | src/SKIT.FlurlHttpClient.Wechat.Api/Events/CardInvoice/UpdateInvoiceStatusEvent.cs | magotop/DotNetCore.SKIT.FlurlHttpClient.Wechat | 82397f88c67ceac107d6988f9999b90916a93952 | [
"MIT"
] | null | null | null | src/SKIT.FlurlHttpClient.Wechat.Api/Events/CardInvoice/UpdateInvoiceStatusEvent.cs | magotop/DotNetCore.SKIT.FlurlHttpClient.Wechat | 82397f88c67ceac107d6988f9999b90916a93952 | [
"MIT"
] | 2 | 2021-12-02T09:08:13.000Z | 2022-01-04T02:45:14.000Z | using System;
using System.Collections.Generic;
namespace SKIT.FlurlHttpClient.Wechat.Api.Events
{
/// <summary>
/// <para>表示 EVENT.update_invoice_status 事件的数据。</para>
/// <para>REF: https://developers.weixin.qq.com/doc/offiaccount/WeChat_Invoice/E_Invoice/Invoicing_Platform_API_List.html#7 </para>
/// <para>REF: https://developers.weixin.qq.com/doc/offiaccount/WeChat_Invoice/Nontax_Bill/API_list.html#3.6 </para>
/// </summary>
public class UpdateInvoiceStatusEvent : WechatApiEvent, WechatApiEvent.Serialization.IJsonSerializable, WechatApiEvent.Serialization.IXmlSerializable
{
/// <summary>
/// 获取或设置发票或非税票据卡券模板编号。
/// </summary>
[Newtonsoft.Json.JsonProperty("CardId")]
[System.Text.Json.Serialization.JsonPropertyName("CardId")]
[System.Xml.Serialization.XmlElement("CardId")]
public string CardId { get; set; } = default!;
/// <summary>
/// 获取或设置发票或非税票据卡券 Code。
/// </summary>
[Newtonsoft.Json.JsonProperty("Code")]
[System.Text.Json.Serialization.JsonPropertyName("Code")]
[System.Xml.Serialization.XmlElement("Code")]
public string CardCode { get; set; } = default!;
/// <summary>
/// 获取或设置发票或非税票据报销状态。
/// </summary>
[Newtonsoft.Json.JsonProperty("Status")]
[System.Text.Json.Serialization.JsonPropertyName("Status")]
[System.Xml.Serialization.XmlElement("Status", IsNullable = true)]
public string? ReimburseStatus { get; set; }
}
}
| 40.815789 | 153 | 0.661509 |
3005d9ffcca97d5a6dc798cf889d437001a8c80e | 1,364 | cs | C# | Product/Desktop/XmlRunner/ULib/Controls/ActionTreeView.cs | mind0n/hive | b8b887ff4a822ea5cd1afa3b4298febafa5e2fff | [
"MIT"
] | 5 | 2017-03-03T02:13:16.000Z | 2021-08-18T09:59:56.000Z | Product/Desktop/XmlRunner/ULib/Controls/ActionTreeView.cs | mind0n/hive | b8b887ff4a822ea5cd1afa3b4298febafa5e2fff | [
"MIT"
] | null | null | null | Product/Desktop/XmlRunner/ULib/Controls/ActionTreeView.cs | mind0n/hive | b8b887ff4a822ea5cd1afa3b4298febafa5e2fff | [
"MIT"
] | 4 | 2016-11-15T05:20:12.000Z | 2021-11-13T16:32:11.000Z | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ULib.Controls
{
public class ActionTreeView : System.Windows.Forms.TreeView
{
//protected ActionTreeViewNode prevSelectedNode;
public ActionTreeView()
{
}
protected override void OnNodeMouseDoubleClick(System.Windows.Forms.TreeNodeMouseClickEventArgs e)
{
ActionTreeViewNode node = e.Node as ActionTreeViewNode;
if (e.Button == System.Windows.Forms.MouseButtons.Left && node != null)
{
if (node.DoubleClickCallback != null)
{
node.DoubleClickCallback(node);
//prevSelectedNode = node;
}
}
base.OnNodeMouseDoubleClick(e);
}
protected override void OnNodeMouseClick(System.Windows.Forms.TreeNodeMouseClickEventArgs e)
{
ActionTreeViewNode node = e.Node as ActionTreeViewNode;
if (e.Button == System.Windows.Forms.MouseButtons.Left && node != null)
{
if (node.ActivateCallback != null)
{
node.ActivateCallback(node);
//prevSelectedNode = node;
}
}
base.OnNodeMouseClick(e);
}
}
}
| 31.72093 | 106 | 0.562317 |
3601ac5a1653d4db254239f15554dcdaa7988e95 | 137 | cs | C# | src/Bitbucket.Net/Models/Core/Projects/DiffTypes.cs | lrv1668/Bitbucket.Net | b77f509081fd3bde62f4daf52a592b2019e90fd1 | [
"MIT"
] | 29 | 2018-07-14T20:15:42.000Z | 2021-12-30T22:35:34.000Z | src/Bitbucket.Net/Models/Core/Projects/DiffTypes.cs | lrv1668/Bitbucket.Net | b77f509081fd3bde62f4daf52a592b2019e90fd1 | [
"MIT"
] | 27 | 2018-06-26T00:36:54.000Z | 2022-02-02T00:01:01.000Z | src/Bitbucket.Net/Models/Core/Projects/DiffTypes.cs | lrv1668/Bitbucket.Net | b77f509081fd3bde62f4daf52a592b2019e90fd1 | [
"MIT"
] | 22 | 2018-06-26T00:31:42.000Z | 2021-12-22T17:00:16.000Z | namespace Bitbucket.Net.Models.Core.Projects
{
public enum DiffTypes
{
Effective,
Range,
Commit
}
}
| 13.7 | 45 | 0.569343 |
3641fb32cf1d4f276e75fdb544bdf2ad7b1c0d89 | 433 | cs | C# | FinalWork/Assets/MobileConsole/Scripts/Utils.cs | wouwehb/FinalWork | ac06d7ee5d5f2a1cb782a465c946883159c0e2d2 | [
"MIT"
] | null | null | null | FinalWork/Assets/MobileConsole/Scripts/Utils.cs | wouwehb/FinalWork | ac06d7ee5d5f2a1cb782a465c946883159c0e2d2 | [
"MIT"
] | null | null | null | FinalWork/Assets/MobileConsole/Scripts/Utils.cs | wouwehb/FinalWork | ac06d7ee5d5f2a1cb782a465c946883159c0e2d2 | [
"MIT"
] | null | null | null | using UnityEngine;
namespace MobileConsole
{
internal static class Utils
{
public static int CalculateHashCode(LogType type, string logString, string stackTrace)
{
var hashCode = type.GetHashCode();
hashCode = (hashCode * 397) ^ (logString?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (stackTrace?.GetHashCode() ?? 0);
return hashCode;
}
}
} | 28.866667 | 94 | 0.593533 |
76badcd439d9e8adea542e391cf4c5330c4a85f9 | 505 | cs | C# | src/Oculus.Platform/LivestreamingStartStatus.cs | libcs/unity.oculus | 84884ccc57e5a53423d86de194490b5d4dd8a961 | [
"MIT"
] | null | null | null | src/Oculus.Platform/LivestreamingStartStatus.cs | libcs/unity.oculus | 84884ccc57e5a53423d86de194490b5d4dd8a961 | [
"MIT"
] | null | null | null | src/Oculus.Platform/LivestreamingStartStatus.cs | libcs/unity.oculus | 84884ccc57e5a53423d86de194490b5d4dd8a961 | [
"MIT"
] | null | null | null | namespace Oculus.Platform
{
using Description = System.ComponentModel.DescriptionAttribute;
public enum LivestreamingStartStatus : int
{
[Description("SUCCESS")] Success = 1,
[Description("UNKNOWN")] Unknown = 0,
[Description("NO_PACKAGE_SET")] NoPackageSet = -1,
[Description("NO_FB_CONNECT")] NoFbConnect = -2,
[Description("NO_SESSION_ID")] NoSessionId = -3,
[Description("MISSING_PARAMETERS")] MissingParameters = -4,
}
}
| 33.666667 | 68 | 0.643564 |
8ccd9ce8783d523d354e6ce4980aaa30a71ce076 | 503 | cs | C# | src/nPact.Provider/HttpClientWrapper.cs | rodrigoramos/nPact | 15199381332fabf148a016dcf51768e92a2bd082 | [
"MIT"
] | 9 | 2020-09-26T01:36:33.000Z | 2021-08-20T22:12:42.000Z | src/nPact.Provider/HttpClientWrapper.cs | rodrigoramos/bekk-pact-dotnet | 15199381332fabf148a016dcf51768e92a2bd082 | [
"MIT"
] | 2 | 2020-09-18T13:20:37.000Z | 2021-02-05T22:34:23.000Z | src/nPact.Provider/HttpClientWrapper.cs | rodrigoramos/bekk-pact-dotnet | 15199381332fabf148a016dcf51768e92a2bd082 | [
"MIT"
] | null | null | null | using System.Net.Http;
using System.Threading.Tasks;
namespace nPact.Provider
{
public class HttpClientWrapper
{
private readonly HttpClient _httpClient;
protected HttpClientWrapper()
{
}
public HttpClientWrapper(HttpClient httpClient)
: this()
=> _httpClient = httpClient;
public virtual async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
=> await _httpClient.SendAsync(request);
}
} | 23.952381 | 92 | 0.656064 |
ea1f0e0790563d3f0aa4193ba8174bea9dfda31a | 446 | cs | C# | samples/WPFSample/Command.cs | dorisoy/LiveCharts | 343996fb90aaf8b7310b9bdafae3db830896609f | [
"MIT"
] | 1,311 | 2021-02-27T18:04:29.000Z | 2022-03-31T18:18:07.000Z | samples/WPFSample/Command.cs | dorisoy/LiveCharts | 343996fb90aaf8b7310b9bdafae3db830896609f | [
"MIT"
] | 233 | 2021-03-06T04:47:29.000Z | 2022-03-31T15:02:02.000Z | samples/WPFSample/Command.cs | dorisoy/LiveCharts | 343996fb90aaf8b7310b9bdafae3db830896609f | [
"MIT"
] | 215 | 2021-03-02T07:33:20.000Z | 2022-03-30T12:33:40.000Z | using System;
using System.Windows.Input;
namespace WPFSample;
public class Command : ICommand
{
private readonly Action<object> command;
public event EventHandler CanExecuteChanged;
public Command(Action<object> command)
{
this.command = command;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
command(parameter);
}
}
| 17.153846 | 48 | 0.661435 |
4c1a99104154cc5b79221da55b7818cb5d78e1d2 | 813 | cs | C# | src/DotNetRevolution.Core/Domain/DomainEventHandler.cs | DotNetRevolution/DotNetRevolution-Framework | f9d21aedc21ccb7bc54d52727a82f94a47535957 | [
"MIT"
] | 1 | 2016-09-13T19:14:38.000Z | 2016-09-13T19:14:38.000Z | src/DotNetRevolution.Core/Domain/DomainEventHandler.cs | DotNetRevolution/DotNetRevolution-Framework | f9d21aedc21ccb7bc54d52727a82f94a47535957 | [
"MIT"
] | 1 | 2018-03-20T03:16:45.000Z | 2018-03-20T03:16:45.000Z | src/DotNetRevolution.Core/Domain/DomainEventHandler.cs | DotNetRevolution/DotNetRevolution-Framework | f9d21aedc21ccb7bc54d52727a82f94a47535957 | [
"MIT"
] | null | null | null | namespace DotNetRevolution.Core.Domain
{
public abstract class DomainEventHandler<TDomainEvent> : IDomainEventHandler<TDomainEvent>
where TDomainEvent : IDomainEvent
{
public virtual bool Reusable
{
get
{
return true;
}
}
public abstract void Handle(IDomainEventHandlerContext<TDomainEvent> context);
public void Handle(IDomainEventHandlerContext context)
{
var genericContext = context as IDomainEventHandlerContext<TDomainEvent>;
if (genericContext == null)
{
Handle(new DomainEventHandlerContext<TDomainEvent>(context));
}
else
{
Handle(genericContext);
}
}
}
}
| 26.225806 | 94 | 0.567036 |
eadfee8b3ab5037dd9fc81f329234678f5ff2323 | 2,413 | cs | C# | Public/Src/Cache/ContentStore/Hashing/HashInfo.cs | miniksa/BuildXL | 4dc257a82a6126fe7516f15fa6f505c14c122ffb | [
"MIT"
] | 448 | 2018-11-07T21:00:58.000Z | 2019-05-06T17:29:34.000Z | Public/Src/Cache/ContentStore/Hashing/HashInfo.cs | miniksa/BuildXL | 4dc257a82a6126fe7516f15fa6f505c14c122ffb | [
"MIT"
] | 496 | 2019-05-06T21:38:22.000Z | 2022-03-14T18:17:14.000Z | Public/Src/Cache/ContentStore/Hashing/HashInfo.cs | miniksa/BuildXL | 4dc257a82a6126fe7516f15fa6f505c14c122ffb | [
"MIT"
] | 88 | 2019-05-08T08:28:45.000Z | 2022-03-24T23:43:21.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using BuildXL.Cache.ContentStore.UtilitiesCore.Internal;
namespace BuildXL.Cache.ContentStore.Hashing
{
/// <summary>
/// Simple description of a hash.
/// </summary>
public abstract class HashInfo
{
private readonly object _obj = new object();
private ContentHash _emptyHash = default;
/// <summary>
/// Initializes a new instance of the <see cref="HashInfo" /> class.
/// </summary>
protected HashInfo(HashType hashType, int length)
{
HashType = hashType;
ByteLength = length;
Zero = new ContentHash(HashType);
}
/// <summary>
/// Create a content hasher of this type.
/// This operation maybe quite expensive. Try to avoid it and use an existing hasher from the pool.
/// </summary>
public abstract IContentHasher CreateContentHasher();
/// <summary>
/// The content hash for empty content.
/// </summary>
public ContentHash EmptyHash
{
get
{
if (_emptyHash == default)
{
lock (_obj)
{
if (_emptyHash == default)
{
_emptyHash = HashInfoLookup.GetContentHasher(HashType).GetContentHash(CollectionUtilities.EmptyArray<byte>());
}
}
}
return _emptyHash;
}
}
/// <summary>
/// The content hash with all zeros.
/// </summary>
public ContentHash Zero { get; }
/// <summary>
/// Gets hash algorithm.
/// </summary>
public HashType HashType { get; }
/// <summary>
/// Gets name of the hash type.
/// </summary>
public string Name => HashType.ToString();
/// <summary>
/// Gets hash length in bytes.
/// </summary>
public int ByteLength { get; }
/// <summary>
/// Gets number of characters in the string representation.
/// </summary>
public int StringLength => ByteLength * 2;
}
}
| 30.1625 | 139 | 0.48736 |
3a4fbe2c7f329d167a546370c176b6a14babd874 | 10,449 | cs | C# | test/FunctionalTests/Tests/DataOData/Tests/OData.Reader.Tests/JsonLight/CollectionValueReaderJsonLightTests.cs | LewisCheng-MSFT/odata.net | bee5b58d9b890e19e7376e5359b51ba94b238837 | [
"CC-BY-3.0"
] | null | null | null | test/FunctionalTests/Tests/DataOData/Tests/OData.Reader.Tests/JsonLight/CollectionValueReaderJsonLightTests.cs | LewisCheng-MSFT/odata.net | bee5b58d9b890e19e7376e5359b51ba94b238837 | [
"CC-BY-3.0"
] | null | null | null | test/FunctionalTests/Tests/DataOData/Tests/OData.Reader.Tests/JsonLight/CollectionValueReaderJsonLightTests.cs | LewisCheng-MSFT/odata.net | bee5b58d9b890e19e7376e5359b51ba94b238837 | [
"CC-BY-3.0"
] | null | null | null | //---------------------------------------------------------------------
// <copyright file="CollectionValueReaderJsonLightTests.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.Taupo.OData.Reader.Tests.JsonLight
{
#region Namespaces
using System.Collections.Generic;
using Microsoft.OData.Edm;
using Microsoft.Test.OData.Utils.ODataLibTest;
using Microsoft.Test.Taupo.Astoria.Contracts.OData;
using Microsoft.Test.Taupo.Common;
using Microsoft.Test.Taupo.Contracts.EntityModel;
using Microsoft.Test.Taupo.Contracts.EntityModel.Edm;
using Microsoft.Test.Taupo.Contracts.Types;
using Microsoft.Test.Taupo.Execution;
using Microsoft.Test.Taupo.OData.Common;
using Microsoft.Test.Taupo.OData.Common.Annotations;
using Microsoft.Test.Taupo.OData.Contracts.Json;
using Microsoft.Test.Taupo.OData.JsonLight;
using Microsoft.Test.Taupo.OData.Reader.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endregion Namespaces
/// <summary>
/// Tests reading of collection values in JSON.
/// </summary>
[TestClass, TestCase]
public class CollectionValueReaderJsonLightTests : ODataReaderTestCase
{
[InjectDependency]
public PayloadReaderTestDescriptor.Settings Settings { get; set; }
[TestMethod, TestCategory("Reader.Json"), Variation(Description = "Verifies correct reading of collection values")]
// TODO: Change the payload of null top-level properties #645
public void CollectionValueTest()
{
EdmModel model = new EdmModel();
var complexType = new EdmComplexType("TestModel", "ComplexType").Property("Name", EdmPrimitiveTypeKind.String, true);
model.AddElement(complexType);
var owningType = new EdmEntityType("TestModel", "OwningType");
owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false)));
owningType.AddStructuralProperty("PrimitiveCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
model.AddElement(owningType);
model.Fixup();
var primitiveMultiValue = PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)").Item(42).Item(43);
IEnumerable<PayloadReaderTestDescriptor> testDescriptors = new[]
{
new PayloadReaderTestDescriptor(this.Settings)
{
DebugDescription = "null collection in request - should fail.",
PayloadEdmModel = model,
PayloadElement = PayloadBuilder.Property("PrimitiveCollection",
PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)"))
.JsonRepresentation("{\"value\":null }")
.ExpectedProperty(owningType, "PrimitiveCollection"),
SkipTestConfiguration = tc => !tc.IsRequest,
ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "value", "Collection(Edm.Int32)")
},
new PayloadReaderTestDescriptor(this.Settings)
{
DebugDescription = "null collection in response - should fail.",
PayloadEdmModel = model,
PayloadElement = PayloadBuilder.Property("PrimitiveCollection",
PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)"))
.JsonRepresentation(
"{" +
"\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Collection(Edm.Int32)\"," +
"\"value\":null" +
"}")
.ExpectedProperty(owningType, "PrimitiveCollection"),
SkipTestConfiguration = tc => tc.IsRequest,
ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "value", "Collection(Edm.Int32)")
},
new PayloadReaderTestDescriptor(this.Settings)
{
DebugDescription = "Primitive value for collection - should fail.",
PayloadEdmModel = model,
PayloadElement = PayloadBuilder.Property("PrimitiveCollection",
PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)")
.JsonRepresentation("42"))
.ExpectedProperty(owningType, "PrimitiveCollection"),
ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "StartArray", "PrimitiveValue")
},
new PayloadReaderTestDescriptor(this.Settings)
{
DebugDescription = "Object value for collection - should fail.",
PayloadEdmModel = model,
PayloadElement = PayloadBuilder.Property("PrimitiveCollection",
PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)")
.JsonRepresentation("{}"))
.ExpectedProperty(owningType, "PrimitiveCollection"),
ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetectedWithPropertyName", "StartArray", "StartObject", "value")
},
new PayloadReaderTestDescriptor(this.Settings)
{
DebugDescription = "Simple primitive collection.",
PayloadEdmModel = model,
PayloadElement = PayloadBuilder.Property("PrimitiveCollection",
primitiveMultiValue
.JsonRepresentation("[42,43]")
.AddAnnotation(new SerializationTypeNameTestAnnotation() { TypeName = null }))
.ExpectedProperty(owningType, "PrimitiveCollection"),
ExpectedResultPayloadElement = tc => tc.IsRequest
? PayloadBuilder.Property(string.Empty, primitiveMultiValue)
: PayloadBuilder.Property("PrimitiveCollection", primitiveMultiValue)
},
};
this.CombinatorialEngineProvider.RunCombinations(
testDescriptors,
this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
(testDescriptor, testConfiguration) =>
{
// These descriptors are already tailored specifically for Json Light and
// do not require normalization.
testDescriptor.TestDescriptorNormalizers.Clear();
testDescriptor.RunTest(testConfiguration);
});
}
[Ignore]
[TestMethod, TestCategory("Reader.Json"), Variation(Description = "Verifies correct reading of collection values of complex type")]
public void CollectionOfComplexInstanceTest()
{
EdmModel model = new EdmModel();
var complexType = new EdmComplexType("TestModel", "ComplexType").Property("Name", EdmPrimitiveTypeKind.String, true);
model.AddElement(complexType);
var owningType = new EdmEntityType("TestModel", "OwningType");
owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false)));
owningType.AddStructuralProperty("PrimitiveCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
owningType.AddStructuralProperty("ComplexCollection", EdmCoreModel.GetCollection(complexType.ToTypeReference()));
model.AddElement(owningType);
model.Fixup();
var primitiveMultiValue = PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)").Item(42).Item(43);
var complexMultiValue = PayloadBuilder.EntitySet(new EntityInstance[]
{
PayloadBuilder.Entity("TestModel.ComplexType")
.PrimitiveProperty("Name", "Value")
.AddAnnotation(new SerializationTypeNameTestAnnotation() { TypeName = null })
.IsComplex(true)
})
.JsonRepresentation("[{\"Name\":\"Value\"}]")
.AddAnnotation(new SerializationTypeNameTestAnnotation() { TypeName = null });
IEnumerable<PayloadReaderTestDescriptor> testDescriptors = new[]
{
new PayloadReaderTestDescriptor(this.Settings)
{
DebugDescription = "Simple complex collection.",
PayloadEdmModel = model,
PayloadElement = PayloadBuilder.Property("ComplexCollection", complexMultiValue)
.ExpectedProperty(owningType, "ComplexCollection"),
ExpectedResultPayloadElement = tc => tc.IsRequest
? PayloadBuilder.Property(string.Empty, complexMultiValue)
: PayloadBuilder.Property("ComplexCollection", complexMultiValue)
},
};
this.CombinatorialEngineProvider.RunCombinations(
testDescriptors,
this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
(testDescriptor, testConfiguration) =>
{
// These descriptors are already tailored specifically for Json Light and
// do not require normalization.
testDescriptor.TestDescriptorNormalizers.Clear();
testDescriptor.RunTest(testConfiguration);
});
}
}
} | 59.033898 | 203 | 0.592784 |
ba0cba64bd02d09d03c706de9de07a9a5c3138f2 | 132 | cs | C# | android/naked-stubs/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.cs | gordonjohnpatrick/XobotOS | 888ed3b8cc8d8e0a54b1858bfa5a3572545f4d2f | [
"Apache-2.0"
] | 263 | 2015-01-04T16:39:18.000Z | 2022-01-05T17:52:38.000Z | android/naked-stubs/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.cs | DooMLoRD/XobotOS | f20db6295e878a2f298c5e3896528e240785805b | [
"Apache-2.0"
] | 3 | 2015-09-06T09:06:39.000Z | 2019-10-15T00:52:49.000Z | android/naked-stubs/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.cs | DooMLoRD/XobotOS | f20db6295e878a2f298c5e3896528e240785805b | [
"Apache-2.0"
] | 105 | 2015-01-11T11:45:12.000Z | 2022-02-22T07:26:36.000Z | using Sharpen;
namespace org.apache.harmony.xnet.provider.jsse
{
[Sharpen.NakedStub]
internal class ServerSessionContext
{
}
}
| 13.2 | 47 | 0.772727 |
08abc61035b1b5dffb737b14d3f8c469825bd9e5 | 326 | cs | C# | framework/src/Silky.Http.Auditing/AuditingApplicationBuilderExtensions.cs | microserviceframe/Silky | 99375ca9ba42db384810776c6e811dab4f0e9532 | [
"MIT"
] | 116 | 2021-07-22T11:56:32.000Z | 2022-03-31T03:48:32.000Z | framework/src/Silky.Http.Auditing/AuditingApplicationBuilderExtensions.cs | microserviceframe/Silky | 99375ca9ba42db384810776c6e811dab4f0e9532 | [
"MIT"
] | 5 | 2021-09-06T17:18:00.000Z | 2022-02-18T00:53:58.000Z | framework/src/Silky.Http.Auditing/AuditingApplicationBuilderExtensions.cs | microserviceframe/Silky | 99375ca9ba42db384810776c6e811dab4f0e9532 | [
"MIT"
] | 36 | 2021-07-24T15:30:16.000Z | 2022-03-30T03:11:43.000Z | using Silky.Http.Auditing.Middlewares;
namespace Microsoft.AspNetCore.Builder;
public static class AuditingApplicationBuilderExtensions
{
public static IApplicationBuilder UseAuditing(this IApplicationBuilder application)
{
application.UseMiddleware<AuditingMiddleware>();
return application;
}
} | 27.166667 | 87 | 0.785276 |
08b7a73ade5f74fc167c9a313d1bf7e134297fc8 | 4,549 | cs | C# | src/event-sourcing-demo/event-sourcing-demo.web.api/Startup.cs | aayush-pokharel/event-source-demo | 78569788e631c6ca30065037b6a2afde8e05a307 | [
"MIT"
] | null | null | null | src/event-sourcing-demo/event-sourcing-demo.web.api/Startup.cs | aayush-pokharel/event-source-demo | 78569788e631c6ca30065037b6a2afde8e05a307 | [
"MIT"
] | null | null | null | src/event-sourcing-demo/event-sourcing-demo.web.api/Startup.cs | aayush-pokharel/event-source-demo | 78569788e631c6ca30065037b6a2afde8e05a307 | [
"MIT"
] | null | null | null | using event_sourcing_demo.cart.core.Interfaces;
using event_sourcing_demo.cart.core.Utility;
using event_sourcing_demo.cart.domain.Commands;
using event_sourcing_demo.cart.domain.Events;
using event_sourcing_demo.cart.domain.Exceptions;
using event_sourcing_demo.cart.domain.Interfaces;
using event_sourcing_demo.cart.domain.Services;
using event_sourcing_demo.web.api.EventHandlers;
using event_sourcing_demo.web.api.Registries;
using Hellang.Middleware.ProblemDetails;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace event_sourcing_demo.web.api
{
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.AddControllers();
services.AddSingleton<ICurrencyConverter, FakeCurrencyConverter>();
services.AddSingleton<IEventSerializer>(new JsonEventSerializer(new[]
{
typeof(CartCreated).Assembly
})).AddInfrastructure(this.Configuration);
services.AddScoped<ServiceFactory>(ctx => ctx.GetRequiredService);
services.AddScoped<IMediator, Mediator>();
services.Scan(scan =>
{
scan.FromAssembliesOf(typeof(CreateCart))
.RegisterHandlers(typeof(IRequestHandler<>))
.RegisterHandlers(typeof(IRequestHandler<,>))
.RegisterHandlers(typeof(INotificationHandler<>));
scan.FromAssembliesOf(typeof(CreateProduct))
.RegisterHandlers(typeof(IRequestHandler<>))
.RegisterHandlers(typeof(IRequestHandler<,>))
.RegisterHandlers(typeof(INotificationHandler<>));
scan.FromAssembliesOf(typeof(CreateCartLineItem))
.RegisterHandlers(typeof(IRequestHandler<>))
.RegisterHandlers(typeof(IRequestHandler<,>))
.RegisterHandlers(typeof(INotificationHandler<>));
scan.FromAssembliesOf(typeof(AddCartLineItemQuantity))
.RegisterHandlers(typeof(IRequestHandler<>))
.RegisterHandlers(typeof(IRequestHandler<,>))
.RegisterHandlers(typeof(INotificationHandler<>));
scan.FromAssembliesOf(typeof(RemoveCartLineItemQuantity))
.RegisterHandlers(typeof(IRequestHandler<>))
.RegisterHandlers(typeof(IRequestHandler<,>))
.RegisterHandlers(typeof(INotificationHandler<>));
});
services.Decorate(typeof(INotificationHandler<>), typeof(RetryDecorator<>));
services.AddProblemDetails(opts =>
{
opts.IncludeExceptionDetails = (ctx, ex) =>
{
var env = ctx.RequestServices.GetRequiredService<IHostEnvironment>();
return env.IsDevelopment() || env.IsStaging();
};
opts.MapToStatusCode<ArgumentOutOfRangeException>((int)HttpStatusCode.BadRequest);
opts.MapToStatusCode<ValidationException>((int)HttpStatusCode.BadRequest);
opts.MapToStatusCode<CartLineItemTransactionException>((int)HttpStatusCode.BadRequest);
});
#if OnPremise
services.RegisterWorker(this.Configuration);
#endif
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 37.908333 | 106 | 0.646955 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.