content stringlengths 23 1.05M |
|---|
using Bridge.Test.NUnit;
using System;
namespace Bridge.ClientTest.CSharp6
{
[Category(Constants.MODULE_BASIC_CSHARP)]
[TestFixture(TestNameFormat = "Interpolated Strings - {0}")]
public class TestInterpolatedStrings
{
private class Person
{
public string Name { get; set; } = "Jane";
public int Age { get; set; } = 10;
}
public static int P { get; set; }
public static int F1()
{
return 0;
}
public static int F2()
{
return 0;
}
public static int F3()
{
return 0;
}
[Test]
public static void TestBasic()
{
var p = new Person();
Assert.AreEqual("Jane is 10 year{s} old", $"{p.Name} is {p.Age} year{{s}} old");
Assert.AreEqual(" Jane is 010 year{s} old", $"{p.Name,20} is {p.Age:D3} year{{s}} old");
Assert.AreEqual("Jane is 10 years old", $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old");
p.Age = 1;
Assert.AreEqual("Jane is 1 year old", $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old");
int i = 0, j = 1, k = 2;
Assert.AreEqual("i = 0, j = 1", $"i = {i}, j = {j}");
Assert.AreEqual("{0, 1}", $"{{{i}, {j}}}");
Assert.AreEqual("i = 00, j = 1, k = 2", $"i = {i:00}, j = {j:##}, k = {k,12:#0}");
Assert.AreEqual("0, 0, 0", $"{F1()}, {P = F2()}, {F3()}");
IFormattable f1 = $"i = {i}, j = {j}";
FormattableString f2 = $"i = {i}, j = {j}";
Assert.AreEqual(2, f2.ArgumentCount);
Assert.AreEqual("i = {0}, j = {1}", f2.Format);
Assert.AreEqual(0, f2.GetArgument(0));
Assert.AreEqual(1, f2.GetArgument(1));
Assert.AreEqual(2, f2.GetArguments().Length);
Assert.AreEqual("i = 0, j = 1", f2.ToString());
}
}
} |
using System;
namespace Pioneer.Common.Commands.Converters;
public static class BasicConverter
{
public static readonly Type UShortType = typeof(ushort);
public static readonly Type IntType = typeof(int);
public static readonly Type LongType = typeof(long);
public static readonly Type ShortType = typeof(short);
public static readonly Type ByteType = typeof(byte);
public static readonly Type CharType = typeof(char);
public static readonly Type FloatType = typeof(float);
public static readonly Type DoubleType = typeof(double);
public static readonly Type BoolType = typeof(bool);
public static readonly Type StringType = typeof(string);
private static readonly Type DecimalType = typeof(decimal);
private static readonly Type UIntType = typeof(uint);
private static readonly Type ULongType = typeof(ulong);
internal static object Convert(string givenObject, Type wantedType)
{
if (wantedType == UIntType)
{
return uint.Parse(givenObject);
}
if (wantedType == ULongType)
{
return ulong.Parse(givenObject);
}
if (wantedType == UShortType)
{
return ushort.Parse(givenObject);
}
if (wantedType == IntType)
{
return int.Parse(givenObject);
}
if (wantedType == LongType)
{
return long.Parse(givenObject);
}
if (wantedType == ShortType)
{
return short.Parse(givenObject);
}
if (wantedType == ByteType)
{
return byte.Parse(givenObject);
}
if (wantedType == CharType)
{
return char.Parse(givenObject);
}
if (wantedType == FloatType)
{
return float.Parse(givenObject);
}
if (wantedType == DoubleType)
{
return double.Parse(givenObject);
}
if (wantedType == DecimalType)
{
return decimal.Parse(givenObject);
}
if (wantedType == BoolType)
{
return bool.Parse(givenObject);
}
return givenObject;
}
} |
using System;
using System.Linq;
using CarsFactory.Data.Contracts;
using CarsFactory.Models.Enums;
using CarsFactory.Reports.Documents.Contracts;
using CarsFactory.Reports.Reports.Contracts;
namespace CarsFactory.Reports.Reports
{
public class TopSellingManufacturersReport : IReport
{
/// <summary>
/// Generates a new TopSellingManufacturersReport.
/// </summary>
public void Generate(IDocumentAdapter document, ICarsFactoryDbContext dbContext)
{
var topManufacturers =
(from car in
dbContext.Cars.Where(car => car.OrderId != null && car.Order.OrderStatus == OrderStatus.Closed)
group car by car.Model.Manufacturer.Name
into g
orderby g.Count() descending
select new
{
Model = g.Key,
OrderCount = g.Count()
})
.ToList();
document.AddMetadata()
.AddHeader($"Top selling manufacturers of all time. Generated on {DateTime.Now}")
.AddTabularData(topManufacturers)
.Save();
}
}
}
|
using Godot;
using System;
public class RemainParticles : Particles2D
{
public void ParticleTimeout()
{
SpeedScale = 0;
SetProcess(false);
SetPhysicsProcess(false);
SetProcessInput(false);
SetProcessInternal(false);
SetProcessUnhandledInput(false);
SetProcessUnhandledKeyInput(false);
}
}
|
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 System.Net;
using System.Net.Sockets;
using System.IO;
namespace p4_jwm8483_client
{
public partial class Form1 : Form
{
private TcpClient client;
private StreamReader reader;
private StreamWriter writer;
private String textReceived;
private String textToSend;
private String UN;
private String IP;
private String Port;
public Form1()
{
InitializeComponent();
}
private void StartClient_Click(object sender, EventArgs e)
{
client = new TcpClient();
IP = IPBox.Text;
Port = portBox.Text;
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 51111);
if (username.Text != "")
{
UN = username.Text;
try
{
client.Connect(IpEnd);
if (client.Connected)
{
textBox1.AppendText("Connected! \n");
this.writer = new StreamWriter(client.GetStream());
this.reader = new StreamReader(client.GetStream());
writer.AutoFlush = true;
TestUsername();
recieveMessages.RunWorkerAsync();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void TestUsername()
{
writer.WriteLine(UN);
}
private void Send_Click(object sender, EventArgs e)
{
if (message.Text != "")
{
dataSender(message.Text);
}
message.Text = "";
}
private async void dataSender(String toSend)
{
await writer.WriteLineAsync(UN + ": " + toSend);
}
private void recieveMessages_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
try
{
textReceived = this.reader.ReadLine();
textBox1.Invoke(new MethodInvoker(delegate ()
{
textBox1.AppendText(textReceived + "\n");
}));
textReceived = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
|
using Newtonsoft.Json;
using WampSharp.Binding;
namespace WampSharp.V2.Fluent
{
public static class NewtonsoftJsonChannelFactoryExtensions
{
private static readonly JTokenJsonBinding mJsonBinding = new JTokenJsonBinding();
/// <summary>
/// Indicates that the user wants to use JSON serialization.
/// </summary>
public static ChannelFactorySyntax.ISerializationSyntax JsonSerialization(this ChannelFactorySyntax.ITransportSyntax transportSyntax)
{
ChannelState state = transportSyntax.State;
state.Binding = mJsonBinding;
return state;
}
/// <summary>
/// Indicates that the user wants to use JSON serialization.
/// </summary>
/// <param name="transportSyntax">The current fluent syntax state.</param>
/// <param name="serializer">The <see cref="JsonSerializer"/> to serialize messages with.</param>
public static ChannelFactorySyntax.ISerializationSyntax JsonSerialization(this ChannelFactorySyntax.ITransportSyntax transportSyntax, JsonSerializer serializer)
{
ChannelState state = transportSyntax.State;
state.Binding = new JTokenJsonBinding(serializer);
return state;
}
}
} |
/*
* Trevor Pence
* ITSE-1430
* 10/9/2017
*/
namespace MovieLib
{
public class Movie
{
public string Title
{
set { _title = value; }
get { return _title ?? ""; }
}
public string Description
{
set { _description = value; }
get { return _description ?? ""; }
}
public decimal Length { get; set; }
public bool IsOwned { get; set; }
private string _title;
private string _description;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fhr.ModernHistory.Dtos;
using Fhr.ModernHistory.Models;
namespace Fhr.ModernHistory.DtoConverters
{
/// <summary>
/// 名人信息转换器
/// 201/7/20
/// </summary>
public class FamousPersonConverter
{
public static FamousPersonInfo ConvertToDto(FamousPerson famousPerson,IEnumerable<Int32> typeIds)
{
if (famousPerson == null)
{
return null;
}
var personInfo = new FamousPersonInfo()
{
BornDate = famousPerson.BornDate,
BornPlace = famousPerson.BornPlace,
BornX = famousPerson.BornX,
BornY = famousPerson.BornY,
DeadDate = famousPerson.DeadDate,
FamousPersonId = famousPerson.FamousPersonId,
Province = famousPerson.Province,
Gender = famousPerson.Gender,
Nation = famousPerson.Nation,
PersonName = famousPerson.PersonName,
PersonTypeIds=typeIds
};
return personInfo;
}
public static FamousPerson ConvertToDo(FamousPersonInfo famousPersonInfo)
{
if (famousPersonInfo == null)
{
return null;
}
var person= new FamousPerson()
{
BornDate = famousPersonInfo.BornDate,
BornPlace = famousPersonInfo.BornPlace,
BornX = famousPersonInfo.BornX,
BornY = famousPersonInfo.BornY,
DeadDate = famousPersonInfo.DeadDate,
FamousPersonId = famousPersonInfo.FamousPersonId,
Province = famousPersonInfo.Province,
Gender = famousPersonInfo.Gender,
Nation = famousPersonInfo.Nation,
PersonName = famousPersonInfo.PersonName,
};
return person;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Heater : MonoBehaviour
{
[SerializeField]
private Converter converter;
private void OnTriggerEnter(Collider other)
{
if ((other.GetComponent("Heating") as Heating) != null)
{
other.gameObject.GetComponent<Heating>().Converter = converter;
}
}
private void OnTriggerStay(Collider other)
{
if ((other.GetComponent("Heating") as Heating) != null)
{
Debug.Log("Heating");
other.gameObject.GetComponent<Heating>().timeHeated += Time.deltaTime;
}
}
}
|
using domador.orm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace domador.managers
{
public class ManagerBase
{
protected Session Session;
public ManagerBase()
{
this.Session = new StatefullSession();
}
public ManagerBase(Session session)
{
this.Session = session;
}
}
}
|
// 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.Common.Build.GitLabCI;
using Cake.Common.Tests.Fixtures.Build;
using Xunit;
namespace Cake.Common.Tests.Unit.Build.GitLabCI
{
public sealed class GitLabCIProviderTests
{
public sealed class TheConstructor
{
[Fact]
public void Should_Throw_If_Environment_Is_Null()
{
// Given, When
var result = Record.Exception(() => new GitLabCIProvider(null));
// Then
AssertEx.IsArgumentNullException(result, "environment");
}
}
public sealed class TheIsRunningOnGitLabCIProperty
{
[Fact]
public void Should_Return_True_If_Running_On_GitLabCI()
{
// Given
var fixture = new GitLabCIFixture();
fixture.IsRunningOnGitLabCI();
var gitLabCI = fixture.CreateGitLabCIService();
// When
var result = gitLabCI.IsRunningOnGitLabCI;
// Then
Assert.True(result);
}
[Fact]
public void Should_Return_False_If_Not_Running_On_GitLabCI()
{
// Given
var fixture = new GitLabCIFixture();
var gitLabCI = fixture.CreateGitLabCIService();
// When
var result = gitLabCI.IsRunningOnGitLabCI;
// Then
Assert.False(result);
}
}
public sealed class TheEnvironmentProperty
{
[Fact]
public void Should_Return_Non_Null_Reference()
{
// Given
var fixture = new GitLabCIFixture();
var gitLabCI = fixture.CreateGitLabCIService();
// When
var result = gitLabCI.Environment;
// Then
Assert.NotNull(result);
}
}
}
}
|
// ------------------------------------------------------------
// 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.Azure.IIoT.Services.OpcUa.Gateway.Runtime {
using Microsoft.Azure.IIoT.OpcUa.Protocol;
using Microsoft.Azure.IIoT.OpcUa.Protocol.Runtime;
using Microsoft.Azure.IIoT.OpcUa.Protocol.Transport;
using Microsoft.Azure.IIoT.OpcUa.Api.Runtime;
using Microsoft.Azure.IIoT.OpcUa.Api.Registry;
using Microsoft.Azure.IIoT.Services.Cors;
using Microsoft.Azure.IIoT.Services.Cors.Runtime;
using Microsoft.Azure.IIoT.Hub.Client;
using Microsoft.Azure.IIoT.Hub.Client.Runtime;
using Microsoft.Azure.IIoT.Messaging.EventHub.Runtime;
using Microsoft.Azure.IIoT.Messaging.EventHub;
using Microsoft.Azure.IIoT.Auth.Server;
using Microsoft.Azure.IIoT.Auth.Runtime;
using Microsoft.Azure.IIoT.Auth.Clients;
using Microsoft.Azure.IIoT.Utils;
using Microsoft.Azure.IIoT.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.ApplicationInsights.Extensibility;
using System;
using System.IdentityModel.Selectors;
using System.Security.Cryptography.X509Certificates;
/// <summary>
/// Common web service configuration aggregation
/// </summary>
public class Config : ConfigBase, IAuthConfig, IIoTHubConfig,
ICorsConfig, IClientConfig, IEventHubConfig, ITcpListenerConfig,
IWebListenerConfig, ISessionServicesConfig, IRegistryConfig, IApplicationInsightsConfig {
/// <inheritdoc/>
public string IoTHubConnString => _hub.IoTHubConnString;
/// <inheritdoc/>
public string IoTHubResourceId => _hub.IoTHubResourceId;
/// <inheritdoc/>
public string CorsWhitelist => _cors.CorsWhitelist;
/// <inheritdoc/>
public bool CorsEnabled => _cors.CorsEnabled;
/// <inheritdoc/>
public string AppId => _auth.AppId;
/// <inheritdoc/>
public string AppSecret => _auth.AppSecret;
/// <inheritdoc/>
public string TenantId => _auth.TenantId;
/// <inheritdoc/>
public string InstanceUrl => _auth.InstanceUrl;
/// <inheritdoc/>
public string Audience => _auth.Audience;
/// <inheritdoc/>
public int HttpsRedirectPort => _auth.HttpsRedirectPort;
/// <inheritdoc/>
public bool AuthRequired => _auth.AuthRequired;
/// <inheritdoc/>
public string TrustedIssuer => _auth.TrustedIssuer;
/// <inheritdoc/>
public TimeSpan AllowedClockSkew => _auth.AllowedClockSkew;
/// <inheritdoc/>
public string EventHubConnString => _eh.EventHubConnString;
/// <inheritdoc/>
public string EventHubPath => _eh.EventHubPath;
/// <inheritdoc/>
public bool UseWebsockets => _eh.UseWebsockets;
/// <inheritdoc/>
public string ConsumerGroup => _eh.ConsumerGroup;
/// <inheritdoc/>
public string[] ListenUrls => null;
/// <inheritdoc/>
public X509Certificate2 TcpListenerCertificate => null;
/// <inheritdoc/>
public X509Certificate2Collection TcpListenerCertificateChain => null;
/// <inheritdoc/>
public X509CertificateValidator CertificateValidator => null;
/// <inheritdoc/>
public string PublicDnsAddress => null;
/// <inheritdoc/>
public int Port => 51111; // Utils.UaTcpDefaultPort;
/// <inheritdoc/>
public TimeSpan MaxRequestAge => _sessions.MaxRequestAge;
/// <inheritdoc/>
public int NonceLength => _sessions.NonceLength;
/// <inheritdoc/>
public int MaxSessionCount => _sessions.MaxSessionCount;
/// <inheritdoc/>
public TimeSpan MaxSessionTimeout => _sessions.MaxSessionTimeout;
/// <inheritdoc/>
public TimeSpan MinSessionTimeout => _sessions.MinSessionTimeout;
/// <inheritdoc/>
public string OpcUaRegistryServiceUrl => _api.OpcUaRegistryServiceUrl;
/// <inheritdoc/>
public string OpcUaRegistryServiceResourceId => _api.OpcUaRegistryServiceResourceId;
/// <inheritdoc/>
public TelemetryConfiguration TelemetryConfiguration => _ai.TelemetryConfiguration;
/// <summary>
/// Configuration constructor
/// </summary>
/// <param name="configuration"></param>
public Config(IConfigurationRoot configuration) :
base(configuration) {
_auth = new AuthConfig(configuration);
_hub = new IoTHubConfig(configuration);
_cors = new CorsConfig(configuration);
_eh = new EventHubConfig(configuration);
_sessions = new SessionServicesConfig(configuration);
_api = new ApiConfig(configuration);
_ai = new ApplicationInsightsConfig(configuration);
}
private readonly AuthConfig _auth;
private readonly CorsConfig _cors;
private readonly EventHubConfig _eh;
private readonly IoTHubConfig _hub;
private readonly SessionServicesConfig _sessions;
private readonly ApiConfig _api;
private readonly ApplicationInsightsConfig _ai;
}
}
|
using Xamarin.Forms;
namespace Presently.MobileApp.Views
{
public partial class AttendanceLogPage : MobileContentPageBase
{
public AttendanceLogPage()
{
InitializeComponent();
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="IMenuService.cs" company="1-system-group">
// Copyright (c) 1-system-group. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using Diary_Sample.Models;
namespace Diary_Sample.Services
{
public interface IMenuService
{
public MenuViewModel Index(string notification);
public MenuViewModel Paging(int page);
}
} |
using System;
namespace SemanticVersionEnforcer.Core
{
internal class ComparableType : IComparable
{
public ComparableType(Type type)
{
Type = type;
}
public Type Type { get; set; }
public int CompareTo(object other)
{
return String.Compare(ToString(), other.ToString(), StringComparison.Ordinal);
}
public override string ToString()
{
return Type.ToString();
}
}
} |
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
using Freezer.Pools;
using Freezer.Utils.Threading;
namespace Freezer.Runner
{
internal class RunnerCore
{
/// <summary>
/// Initialize a freezerCapture instance in boundingHostName:boudingPort with the specified xulPath and the parentIdentifer
/// </summary>
/// <param name="boundingHostName"></param>
/// <param name="boundingPort"></param>
/// <param name="xulPath"></param>
/// <param name="parentLockIdentifier"></param>
public static void SetupHost(string boundingHostName, int boundingPort, string xulPath, string parentLockIdentifier)
{
RunnerCoreGlobal.XulPath = xulPath;
var baseAddress = new Uri($"net.tcp://{boundingHostName}:{boundingPort}/freezerworker");
WaitForParentToExitAsync(parentLockIdentifier);
using (var host = new ServiceHost(typeof (RunnerEngineHost), baseAddress))
{
var smb = new ServiceMetadataBehavior
{
MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
};
host.AddServiceEndpoint(typeof(IWorker), ServiceSettings.GetDefaultBinding(), string.Empty);
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine();
Console.WriteLine(@"freezercapture started");
ThreadGuard.Instance.Block();
host.Close();
}
}
public static void SetupHostAsync(string boundingHostName, int boundingPort, string xulPath, string parentLockIdentifier)
{
Thread thread = new Thread(o =>
{
try
{
SetupHost(boundingHostName, boundingPort, xulPath, parentLockIdentifier);
}
catch
{
}
})
{
IsBackground = true,
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
/// <summary>
/// This process allows freezercapture instance to exit when the corresponding parent dispose.
/// </summary>
/// <param name="parentIdentifier"></param>
private static void WaitForParentToExit(string parentIdentifier)
{
try
{
// Current instance will wait for a mutex to be released
// Acquiring this mutex means that the owner pool have disposed
using (new ExclusiveBlock(parentIdentifier))
{
}
// Mutex Acquired and realeased. So let's quit
ThreadGuard.Instance.Quit();
}
catch
{
}
}
/// <summary>
/// Same as WaitForParentToExit with a fork thread.
/// </summary>
/// <param name="parentIdentifier"></param>
private static void WaitForParentToExitAsync(string parentIdentifier)
{
Thread thread = new Thread(o => WaitForParentToExit((string) o))
{
IsBackground = true,
};
thread.Start(parentIdentifier);
}
}
[Serializable]
public class RunnerCoreDomainWrapper
{
public void SetupHost(string boundingHostName, int boundingPort, string xulPath, string parentIdentifier)
{
RunnerCore.SetupHostAsync(boundingHostName, boundingPort, xulPath, parentIdentifier);
}
}
} |
using System.Collections.Generic;
namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL
{
/// <summary>
/// GraphQL.ExecutionError interface for ducktyping
/// </summary>
public interface IExecutionError
{
/// <summary>
/// Gets a code for the error
/// </summary>
string Code { get; }
/// <summary>
/// Gets a list of locations in the document where the error applies
/// </summary>
IEnumerable<object> Locations { get; }
/// <summary>
/// Gets a message for the error
/// </summary>
string Message { get; }
/// <summary>
/// Gets the path in the document where the error applies
/// </summary>
IEnumerable<string> Path { get; }
}
}
|
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using FluentSerializer.Core.DataNodes;
using FluentSerializer.Core.BenchmarkUtils.Profiles;
using FluentSerializer.Core.BenchmarkUtils.TestData;
using FluentSerializer.Xml.Benchmark.Data;
namespace FluentSerializer.Xml.Benchmark.Profiles;
public class XmlWriteProfile : WriteProfile
{
public static IEnumerable<TestCase<IDataNode>> Values() => XmlDataCollection.Default.ObjectTestData;
[ParamsSource(nameof(Values))]
public TestCase<IDataNode> Value { get; set; }
[Benchmark, BenchmarkCategory(nameof(Write))]
public string WriteXml() => Write(Value);
} |
using Microsoft.AspNetCore.Http;
using Microsoft.DotNet.Interactive;
using Microsoft.DotNet.Interactive.Commands;
using Microsoft.DotNet.Interactive.CSharp;
using Microsoft.DotNet.Interactive.Events;
using Microsoft.DotNet.Interactive.Notebook;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace DemoWebAPI
{
public class NotebookHandler
{
private CompositeKernel kernel;
private CSharpKernel csharpKernel;
private NotebookDocument notebook;
private Log log;
public NotebookHandler(string notebookName, byte[] notebookBytes)
{
this.kernel = new CompositeKernel();
this.csharpKernel = new CSharpKernel()
.UseDefaultFormatting()
.UseNugetDirective()
.UseKernelHelpers()
.UseWho()
.UseDotNetVariableSharing()
;
this.kernel.Add(csharpKernel);
// notebook
this.notebook = kernel.ParseNotebook($"{notebookName}.ipynb", notebookBytes);
// logging and handling events
this.log = new Log();
kernel.KernelEvents.Subscribe(ev =>
{
switch (ev)
{
case ReturnValueProduced rvp:
//if (rvp.Command is SubmitCode sc)
//{
// log.Code(sc.Code);
//}
log.Value(rvp.Value.ToString());
break;
case CommandFailed cf:
log.Error(cf.Message);
break;
case CommandSucceeded cs:
//log.Info(cs.Command.ToString());
break;
default:
//log.Info(ev.Command.ToString());
break;
}
});
}
public async Task Handle(HttpContext context)
{
var mre = new ManualResetEvent(false);
foreach (var cell in notebook.Cells)
{
var result = await kernel.SendAsync(new SubmitCode(cell.Contents, cell.Language));
result.KernelEvents.Subscribe((ev) =>
{
if (ev is CommandSucceeded || ev is CommandFailed)
{
log.Write(context.Response.BodyWriter);
mre.Reset();
}
});
mre.Set();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using Ocelot.Infrastructure.RequestData;
using Ocelot.Middleware;
using Ocelot.Responses;
namespace Ocelot.Infrastructure
{
public class Placeholders : IPlaceholders
{
private Dictionary<string, Func<Response<string>>> _placeholders;
private Dictionary<string, Func<HttpRequestMessage, string>> _requestPlaceholders;
private readonly IBaseUrlFinder _finder;
private readonly IRequestScopedDataRepository _repo;
public Placeholders(IBaseUrlFinder finder, IRequestScopedDataRepository repo)
{
_repo = repo;
_finder = finder;
_placeholders = new Dictionary<string, Func<Response<string>>>();
_placeholders.Add("{BaseUrl}", () => new OkResponse<string>(_finder.Find()));
_placeholders.Add("{TraceId}", () => {
var traceId = _repo.Get<string>("TraceId");
if(traceId.IsError)
{
return new ErrorResponse<string>(traceId.Errors);
}
return new OkResponse<string>(traceId.Data);
});
_requestPlaceholders = new Dictionary<string, Func<HttpRequestMessage, string>>();
_requestPlaceholders.Add("{DownstreamBaseUrl}", x => {
var downstreamUrl = $"{x.RequestUri.Scheme}://{x.RequestUri.Host}";
if(x.RequestUri.Port != 80 && x.RequestUri.Port != 443)
{
downstreamUrl = $"{downstreamUrl}:{x.RequestUri.Port}";
}
return $"{downstreamUrl}/";
});
}
public Response<string> Get(string key)
{
if(_placeholders.ContainsKey(key))
{
var response = _placeholders[key].Invoke();
if(!response.IsError)
{
return new OkResponse<string>(response.Data);
}
}
return new ErrorResponse<string>(new CouldNotFindPlaceholderError(key));
}
public Response<string> Get(string key, HttpRequestMessage request)
{
if(_requestPlaceholders.ContainsKey(key))
{
return new OkResponse<string>(_requestPlaceholders[key].Invoke(request));
}
return new ErrorResponse<string>(new CouldNotFindPlaceholderError(key));
}
}
} |
// <copyright filename="AdapterBase.cs" project="Framework">
// This file is licensed to you under the MIT License.
// Full license in the project root.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Xml.Linq;
using B1PP.Exceptions;
namespace B1PP.Database.Adapters
{
/// <summary>
/// Common code to extract values from XML and fill in the Metadata objects.
/// </summary>
internal class AdapterBase
{
protected void PopulateCollection<T>(IEnumerable<XElement> elements, object instance)
{
foreach (var element in elements)
{
var attributes = element.Attributes();
PopulateProperties<T>(attributes, instance);
typeof(T).GetMethod("Add").Invoke(instance, new object[] { });
}
}
/// <summary>
/// Populates the properties.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="attributes">The attributes.</param>
/// <param name="instance">The instance.</param>
protected void PopulateProperties<T>(IEnumerable<XAttribute> attributes, object instance)
{
foreach (var attribute in attributes)
{
PopulateProperty<T>(instance, attribute);
}
}
/// <summary>
/// Extracts the value from the <paramref name="attribute" /> and
/// <para />
/// performs necessary conversions, e.g.: to B1 enumerations, when required.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="propertyType">The type of the property.</param>
/// <returns>
/// The value for the property.
/// </returns>
private object GetPropertyValue(XAttribute attribute, Type propertyType)
{
string attributeValue = attribute.Value;
object value;
if (propertyType.IsEnum)
{
var converter = new B1EnumConverter();
value = converter.Convert(propertyType, attributeValue);
}
else
{
value = Convert.ChangeType(attributeValue, propertyType, CultureInfo.InvariantCulture);
}
return value;
}
private void PopulateProperty<T>(object instance, XAttribute attribute)
{
string propertyName = attribute.Name.LocalName ?? string.Empty;
try
{
var property = typeof(T).GetProperty(propertyName);
var value = GetPropertyValue(attribute, property.PropertyType);
property.SetValue(instance, value);
}
catch (Exception e) when (
e is ArgumentNullException ||
e is AmbiguousMatchException ||
e is TargetException ||
e is MethodAccessException ||
e is TargetInvocationException)
{
throw new SetPropertyException($"Couldn't set property '{propertyName}'.", e);
}
}
}
} |
using PolicyServer1.Configuration.Options;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
namespace PolicyServer1.Configuration {
public class PolicyServerOptions {
public CachingOptions Caching { get; set; } = new CachingOptions();
public EndpointsOptions Endpoints { get; set; } = new EndpointsOptions();
public DiscoveryOptions Discovery { get; set; } = new DiscoveryOptions();
public String ClientIdentifier { get; set; } = "client_id";
public String IssuerUri { get; set; }
public String PublicOrigin { get; set; }
}
}
|
using Rallydator.Core.Test;
namespace Rallydator
{
class Program
{
static void Main()
{
new ValidationTest().Real_world_example_2018_November();
}
}
}
|
using Discord.API.Converters;
using Newtonsoft.Json;
namespace Discord.API.Client
{
public class MessageReference
{
[JsonProperty("id"), JsonConverter(typeof(LongStringConverter))]
public ulong Id { get; set; }
[JsonProperty("message_id"), JsonConverter(typeof(LongStringConverter))] //Only used in MESSAGE_ACK
public ulong MessageId { get { return Id; } set { Id = value; } }
[JsonProperty("channel_id"), JsonConverter(typeof(LongStringConverter))]
public ulong ChannelId { get; set; }
}
}
|
using System.Collections.Generic;
namespace AlizeeEngine {
public static class AssetManager {
private static Dictionary<string, Sprite> assetsSprite;
private static Dictionary<string, Font> assetsFont;
static AssetManager() {
assetsSprite = new Dictionary<string, Sprite>();
assetsFont = new Dictionary<string, Font>();
}
public static Sprite GetAssetSprite(string texture) {
if (!assetsSprite.ContainsKey(texture)) {
Sprite sprt = new Sprite();
sprt.SetTexture(new Texture(texture));
assetsSprite.Add(texture, sprt);
}
return assetsSprite[texture];
}
public static Font GetAssetFont(string font) {
if (!assetsFont.ContainsKey(font)) {
assetsFont.Add(font, new Font(font));
}
return assetsFont[font];
}
}
} |
@{
if (Session["compname"] == null)
{
Response.Redirect("~/db/resultpage");
}
}
<!DOCTYPE html>
@using dbconnectivity_C.Models;
@model int
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>totaliposshow</title>
<style>
.head1 {
font-size: 50px;
font-weight: bolder;
margin-left: 400px;
font-family: 'Agency FB';
margin-bottom: 1px;
color: white;
/* THE CHANGE TO ADD IS BELOW*/
text-shadow: 1px 2px 1px 2px #999;
}
.head2 {
font-size: 12px;
margin-left: 550px;
margin-bottom: 8px;
font-weight: bolder;
color: white
}
.head3 {
font-size: 80px;
margin-left: 400px;
margin-bottom: 20px;
font-weight: bolder;
color: white
}
.align {
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
color: black;
font-size: 100px;
font-weight: 900;
font-family: Asap;
margin-left:50px;
}
</style>
</head>
<body style="background-color:black;">
<header>
<div class="head1">Bull's Stock Exchange</div>
<div class="head2">PAKISTAN</div>
<hr />
<div class="bik"><p class="head3">Total Ipos</p></div>
</header>
<div class="align"><label style="color:dodgerblue" ;>@Model</label></div>
<br />
<p class="lead">
<a class="btn btn-primary btn-sm" href="../../db/bullscompany" role="button">Go to Dashboard</a>
</p>
<br />
<hr />
</body>
</html>
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
namespace KdSoft.Utils
{
/// <summary>
/// <see cref="ObservableCollection{T}"/> subclass that adds range modification methods.
/// </summary>
/// <typeparam name="T"></typeparam>
public class RangeObservableCollection<T>: ObservableCollection<T>
{
ListSegment<T> insertedItems = new ListSegment<T>();
List<T> removedItems = new List<T>();
public void InsertRange(int index, IEnumerable<T> items) {
if (items == null)
return;
CheckReentrancy();
int startIndex = index;
foreach (T current in items) {
base.Items.Insert(index++, current);
}
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
var newItems = insertedItems.Initialize(base.Items, startIndex, index - startIndex);
var eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems, startIndex);
this.OnCollectionChanged(eventArgs);
}
public void AddRange(IEnumerable<T> items) {
InsertRange(Count, items);
}
public void RemoveRange(int index, int count) {
if (count == 0) {
return;
}
CheckReentrancy();
removedItems.Clear();
while (count-- > 0) {
removedItems.Add(base.Items[index]);
base.Items.RemoveAt(index);
}
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
var eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, index);
this.OnCollectionChanged(eventArgs);
}
}
}
|
using NUnit.Framework;
using static Markdig.Tests.TestRoundtrip;
namespace Markdig.Tests.RoundtripSpecs
{
[TestFixture]
public class TestLinkReferenceDefinition
{
[TestCase(@"[a]: /r")]
[TestCase(@" [a]: /r")]
[TestCase(@" [a]: /r")]
[TestCase(@" [a]: /r")]
[TestCase(@"[a]: /r")]
[TestCase(@" [a]: /r")]
[TestCase(@" [a]: /r")]
[TestCase(@" [a]: /r")]
[TestCase(@"[a]: /r ")]
[TestCase(@" [a]: /r ")]
[TestCase(@" [a]: /r ")]
[TestCase(@" [a]: /r ")]
[TestCase(@"[a]: /r ""l""")]
[TestCase(@"[a]: /r ""l""")]
[TestCase(@"[a]: /r ""l""")]
[TestCase(@"[a]: /r ""l"" ")]
[TestCase(@"[a]: /r ""l""")]
[TestCase(@"[a]: /r ""l"" ")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l"" ")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l"" ")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l"" ")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l"" ")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l"" ")]
[TestCase(@" [a]: /r ""l""")]
[TestCase(@" [a]: /r ""l"" ")]
[TestCase("[a]:\t/r")]
[TestCase("[a]:\t/r\t")]
[TestCase("[a]:\t/r\t\"l\"")]
[TestCase("[a]:\t/r\t\"l\"\t")]
[TestCase("[a]: \t/r")]
[TestCase("[a]: \t/r\t")]
[TestCase("[a]: \t/r\t\"l\"")]
[TestCase("[a]: \t/r\t\"l\"\t")]
[TestCase("[a]:\t /r")]
[TestCase("[a]:\t /r\t")]
[TestCase("[a]:\t /r\t\"l\"")]
[TestCase("[a]:\t /r\t\"l\"\t")]
[TestCase("[a]: \t /r")]
[TestCase("[a]: \t /r\t")]
[TestCase("[a]: \t /r\t\"l\"")]
[TestCase("[a]: \t /r\t\"l\"\t")]
[TestCase("[a]:\t/r \t")]
[TestCase("[a]:\t/r \t\"l\"")]
[TestCase("[a]:\t/r \t\"l\"\t")]
[TestCase("[a]: \t/r")]
[TestCase("[a]: \t/r \t")]
[TestCase("[a]: \t/r \t\"l\"")]
[TestCase("[a]: \t/r \t\"l\"\t")]
[TestCase("[a]:\t /r")]
[TestCase("[a]:\t /r \t")]
[TestCase("[a]:\t /r \t\"l\"")]
[TestCase("[a]:\t /r \t\"l\"\t")]
[TestCase("[a]: \t /r")]
[TestCase("[a]: \t /r \t")]
[TestCase("[a]: \t /r \t\"l\"")]
[TestCase("[a]: \t /r \t\"l\"\t")]
[TestCase("[a]:\t/r\t ")]
[TestCase("[a]:\t/r\t \"l\"")]
[TestCase("[a]:\t/r\t \"l\"\t")]
[TestCase("[a]: \t/r")]
[TestCase("[a]: \t/r\t ")]
[TestCase("[a]: \t/r\t \"l\"")]
[TestCase("[a]: \t/r\t \"l\"\t")]
[TestCase("[a]:\t /r")]
[TestCase("[a]:\t /r\t ")]
[TestCase("[a]:\t /r\t \"l\"")]
[TestCase("[a]:\t /r\t \"l\"\t")]
[TestCase("[a]: \t /r")]
[TestCase("[a]: \t /r\t ")]
[TestCase("[a]: \t /r\t \"l\"")]
[TestCase("[a]: \t /r\t \"l\"\t")]
[TestCase("[a]:\t/r \t ")]
[TestCase("[a]:\t/r \t \"l\"")]
[TestCase("[a]:\t/r \t \"l\"\t")]
[TestCase("[a]: \t/r")]
[TestCase("[a]: \t/r \t ")]
[TestCase("[a]: \t/r \t \"l\"")]
[TestCase("[a]: \t/r \t \"l\"\t")]
[TestCase("[a]:\t /r")]
[TestCase("[a]:\t /r \t ")]
[TestCase("[a]:\t /r \t \"l\"")]
[TestCase("[a]:\t /r \t \"l\"\t")]
[TestCase("[a]: \t /r")]
[TestCase("[a]: \t /r \t ")]
[TestCase("[a]: \t /r \t \"l\"")]
[TestCase("[a]: \t /r \t \"l\"\t")]
public void Test(string value)
{
RoundTrip(value);
}
[TestCase("[a]: /r\n[b]: /r\n")]
[TestCase("[a]: /r\n[b]: /r\n[c] /r\n")]
public void TestMultiple(string value)
{
RoundTrip(value);
}
[TestCase("[a]:\f/r\f\"l\"")]
[TestCase("[a]:\v/r\v\"l\"")]
public void TestUncommonWhitespace(string value)
{
RoundTrip(value);
}
[TestCase("[a]:\n/r\n\"t\"")]
[TestCase("[a]:\n/r\r\"t\"")]
[TestCase("[a]:\n/r\r\n\"t\"")]
[TestCase("[a]:\r/r\n\"t\"")]
[TestCase("[a]:\r/r\r\"t\"")]
[TestCase("[a]:\r/r\r\n\"t\"")]
[TestCase("[a]:\r\n/r\n\"t\"")]
[TestCase("[a]:\r\n/r\r\"t\"")]
[TestCase("[a]:\r\n/r\r\n\"t\"")]
[TestCase("[a]:\n/r\n\"t\nt\"")]
[TestCase("[a]:\n/r\n\"t\rt\"")]
[TestCase("[a]:\n/r\n\"t\r\nt\"")]
[TestCase("[a]:\r\n /r\t \n \t \"t\r\nt\" ")]
[TestCase("[a]:\n/r\n\n[a],")]
[TestCase("[a]: /r\n[b]: /r\n\n[a],")]
public void TestNewlines(string value)
{
RoundTrip(value);
}
[TestCase("[ a]: /r")]
[TestCase("[a ]: /r")]
[TestCase("[ a ]: /r")]
[TestCase("[ a]: /r")]
[TestCase("[ a ]: /r")]
[TestCase("[a ]: /r")]
[TestCase("[ a ]: /r")]
[TestCase("[ a ]: /r")]
[TestCase("[a a]: /r")]
[TestCase("[a\va]: /r")]
[TestCase("[a\fa]: /r")]
[TestCase("[a\ta]: /r")]
[TestCase("[\va]: /r")]
[TestCase("[\fa]: /r")]
[TestCase("[\ta]: /r")]
[TestCase(@"[\]]: /r")]
public void TestLabel(string value)
{
RoundTrip(value);
}
[TestCase("[a]: /r ()")]
[TestCase("[a]: /r (t)")]
[TestCase("[a]: /r ( t)")]
[TestCase("[a]: /r (t )")]
[TestCase("[a]: /r ( t )")]
[TestCase("[a]: /r ''")]
[TestCase("[a]: /r 't'")]
[TestCase("[a]: /r ' t'")]
[TestCase("[a]: /r 't '")]
[TestCase("[a]: /r ' t '")]
public void Test_Title(string value)
{
RoundTrip(value);
}
[TestCase("[a]: /r\n===\n[a]")]
public void TestSetextHeader(string value)
{
RoundTrip(value);
}
}
}
|
//
// This file was generated by "KanColleProxy.Endpoints.tt"
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Fiddler;
// ReSharper disable InconsistentNaming
namespace Grabacr07.KanColleWrapper
{
partial class KanColleProxy
{
/// <summary>
/// エンド ポイント "/kcsapi/api_start2" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_start2
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_start2"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_port/port" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_port
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_port/port"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/basic" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_basic
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/basic"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/ship" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_ship
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/ship"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/ship2" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_ship2
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/ship2"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/ship3" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_ship3
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/ship3"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/slot_item" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_slot_item
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/slot_item"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/useitem" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_useitem
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/useitem"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/deck" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_deck
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/deck"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/deck_port" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_deck_port
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/deck_port"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/ndock" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_ndock
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/ndock"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/kdock" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_kdock
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/kdock"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/material" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_material
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/material"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/questlist" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_questlist
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/questlist"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_get_member/ship_deck" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_get_member_ship_deck
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_get_member/ship_deck"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_battle_midnight/battle" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_battle_midnight_battle
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_battle_midnight/battle"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_hensei/change" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_hensei_change
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_hensei/change"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_hokyu/charge" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_hokyu_charge
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_hokyu/charge"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kaisou/powerup" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kaisou_powerup
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kaisou/powerup"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/getship" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_getship
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/getship"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/createitem" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_createitem
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/createitem"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/createship" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_createship
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/createship"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/createship_speedchange" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_createship_speedchange
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/createship_speedchange"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/destroyship" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_destroyship
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/destroyship"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/destroyitem2" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_destroyitem2
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/destroyitem2"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/remodel_slotlist" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_remodel_slotlist
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/remodel_slotlist"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/remodel_slotlist_detail" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_remodel_slotlist_detail
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/remodel_slotlist_detail"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_kousyou/remodel_slot" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_kousyou_remodel_slot
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_kousyou/remodel_slot"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_nyukyo/start" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_nyukyo_start
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_nyukyo/start"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_nyukyo/speedchange" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_nyukyo_speedchange
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_nyukyo/speedchange"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_map/start" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_map_start
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_map/start"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_member/updatedeckname" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_member_updatedeckname
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_member/updatedeckname"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_member/updatecomment" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_member_updatecomment
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_member/updatecomment"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_mission/result" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_mission_result
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_mission/result"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_sortie/battle" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_sortie_battle
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_sortie/battle"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_sortie/battleresult" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_sortie_battleresult
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_sortie/battleresult"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_hensei/combined" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_hensei_combined
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_hensei/combined"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_combined_battle/battle" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_combined_battle_battle
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_combined_battle/battle"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_combined_battle/airbattle" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_combined_battle_airbattle
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_combined_battle/airbattle"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_combined_battle/battleresult" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_combined_battle_battleresult
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_combined_battle/battleresult"); }
}
/// <summary>
/// エンド ポイント "/kcsapi/api_req_combined_battle/goback_port" からのセッションを配信します。
/// </summary>
public IObservable<Session> api_req_combined_battle_goback_port
{
get { return this.ApiSessionSource.Where(x => x.PathAndQuery == "/kcsapi/api_req_combined_battle/goback_port"); }
}
}
}
|
namespace KS3.Model
{
public class HeadObjectResult
{
public ObjectMetadata ObjectMetadata { get; set; } = new ObjectMetadata();
public bool IfModified { get; set; }
public bool IfPreconditionSuccess { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UXI.CQRS.Commands;
using UXR.Studies.Models;
namespace UXR.Studies.Models.Commands
{
public class SessionCommandsHandler
: ICommandHandler<CreateSessionCommand>
, ICommandHandler<EditSessionCommand>
, ICommandHandler<DeleteSessionCommand>
{
private readonly IStudiesDbContext _context;
public SessionCommandsHandler(IStudiesDbContext context)
{
_context = context;
}
public void Handle(CreateSessionCommand command)
{
Session session = new Session()
{
Name = command.Name,
StartTime = command.StartTime,
Length = command.Length,
Project = command.Project,
Definition = command.Definition
};
_context.Sessions.Add(session);
_context.SaveChanges();
command.NewId = session.Id;
}
public void Handle(EditSessionCommand command)
{
if (command.Session.Name != command.Name)
command.Session.Name = command.Name;
if (command.Session.StartTime != command.StartTime)
command.Session.StartTime = command.StartTime;
if (command.Session.Length != command.Length)
command.Session.Length = command.Length;
if (command.Session.ProjectId != command.Project.Id)
command.Session.Project = command.Project;
if (command.Session.Definition != command.Definition)
command.Session.Definition = command.Definition;
}
public void Handle(DeleteSessionCommand command)
{
_context.Sessions.Remove(command.Session);
}
}
}
|
namespace vtortola.WebSockets
{
public sealed class WebSocketExtensionFlags
{
bool _rsv1, _rsv2, _rsv3;
readonly bool _none;
public bool Rsv1 { get { return _rsv1; } set { _rsv1 = value && !_none; } }
public bool Rsv2 { get { return _rsv2; } set { _rsv2 = value && !_none; } }
public bool Rsv3 { get { return _rsv3; } set { _rsv3 = value && !_none; } }
public static readonly WebSocketExtensionFlags None = new WebSocketExtensionFlags(true);
public WebSocketExtensionFlags()
{
_none = false;
}
private WebSocketExtensionFlags(bool none)
{
_none = true;
}
}
}
|
namespace Startkicker.Services.Data.Contracts
{
using Startkicker.Data.Models;
public interface IUsersService
{
User GetById(string id);
User GetByUserName(string userName);
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Application.Applicants.Dtos
{
public class ApplicantCreationVariantsDto
{
[JsonProperty("firstName")]
public IEnumerable<string> FirstName { get; set; }
[JsonProperty("lastName")]
public IEnumerable<string> LastName { get; set; }
[JsonProperty("experience")]
public IEnumerable<string> Experience { get; set; }
[JsonProperty("phone")]
public IEnumerable<string> Phone { get; set; }
[JsonProperty("email")]
public IEnumerable<string> Email { get; set; }
[JsonProperty("skills")]
public IEnumerable<string> Skills { get; set; }
[JsonProperty("company")]
public IEnumerable<string> Company { get; set; }
[JsonProperty("birthDate")]
public IEnumerable<string> BirthDate { get; set; }
[JsonProperty("cv")]
public string Cv { get; set; }
}
}
|
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using MultiFunctionApplicationHelpers;
using NewRelic.Agent.IntegrationTestHelpers;
using Xunit;
using Xunit.Abstractions;
namespace NewRelic.Agent.IntegrationTests.InfiniteTracing
{
public abstract class InfiniteTracingTestsBase<TFixture> : NewRelicIntegrationTest<TFixture>
where TFixture : ConsoleDynamicMethodFixture
{
private readonly TFixture _fixture;
public InfiniteTracingTestsBase(TFixture fixture, ITestOutputHelper output):base(fixture)
{
_fixture = fixture;
_fixture.SetTimeout(System.TimeSpan.FromMinutes(2));
_fixture.TestLogger = output;
_fixture.AddCommand($"InfiniteTracingTester StartAgent");
_fixture.AddCommand($"InfiniteTracingTester Make8TSpan");
_fixture.AddCommand($"InfiniteTracingTester Wait");
_fixture.Actions
(
setupConfiguration: () =>
{
var configModifier = new NewRelicConfigModifier(fixture.DestinationNewRelicConfigFilePath);
configModifier.ForceTransactionTraces()
.EnableDistributedTrace()
.EnableInfinteTracing(_fixture.TestConfiguration.TraceObserverUrl)
.SetLogLevel("finest");
}
);
_fixture.Initialize();
}
[Fact]
public void Test()
{
//1 span count for the Make8TSpan method, another span count for the root span.
var expectedSeenCount = 2;
var expectedSentCount = 2;
var expectedReceivedCount = 2;
var actualMetrics = new List<Assertions.ExpectedMetric>
{
new Assertions.ExpectedMetric { metricName = @"Supportability/InfiniteTracing/Span/Seen", callCount = expectedSeenCount },
new Assertions.ExpectedMetric { metricName = @"Supportability/InfiniteTracing/Span/Sent", callCount = expectedSentCount },
new Assertions.ExpectedMetric { metricName = @"Supportability/InfiniteTracing/Span/Received", callCount = expectedReceivedCount }
};
var metrics = _fixture.AgentLog.GetMetrics();
Assertions.MetricsExist(actualMetrics, metrics);
}
}
[NetFrameworkTest]
public class InfiniteTracingFWLatestTests : InfiniteTracingTestsBase<ConsoleDynamicMethodFixtureFWLatest>
{
public InfiniteTracingFWLatestTests(ConsoleDynamicMethodFixtureFWLatest fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
}
[NetFrameworkTest]
public class InfiniteTracingFW471Tests : InfiniteTracingTestsBase<ConsoleDynamicMethodFixtureFW471>
{
public InfiniteTracingFW471Tests(ConsoleDynamicMethodFixtureFW471 fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
}
[NetFrameworkTest]
public class InfiniteTracingFW462Tests : InfiniteTracingTestsBase<ConsoleDynamicMethodFixtureFW462>
{
public InfiniteTracingFW462Tests(ConsoleDynamicMethodFixtureFW462 fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
}
[NetCoreTest]
public class InfiniteTracingNetCoreLatestTests : InfiniteTracingTestsBase<ConsoleDynamicMethodFixtureCoreLatest>
{
public InfiniteTracingNetCoreLatestTests(ConsoleDynamicMethodFixtureCoreLatest fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
}
[NetCoreTest]
public class InfiniteTracingNetCore50Tests : InfiniteTracingTestsBase<ConsoleDynamicMethodFixtureCore50>
{
public InfiniteTracingNetCore50Tests(ConsoleDynamicMethodFixtureCore50 fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
}
[NetCoreTest]
public class InfiniteTracingNetCore31Tests : InfiniteTracingTestsBase<ConsoleDynamicMethodFixtureCore31>
{
public InfiniteTracingNetCore31Tests(ConsoleDynamicMethodFixtureCore31 fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
}
[NetCoreTest]
public class InfiniteTracingNetCore21Tests : InfiniteTracingTestsBase<ConsoleDynamicMethodFixtureCore21>
{
public InfiniteTracingNetCore21Tests(ConsoleDynamicMethodFixtureCore21 fixture, ITestOutputHelper output)
: base(fixture, output)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Jace.Operations;
using Jace.Util;
namespace Jace.Execution
{
public class DynamicCompiler : IExecutor
{
private string FuncAssemblyQualifiedName;
private readonly bool caseSensitive;
public DynamicCompiler(): this(false) { }
public DynamicCompiler(bool caseSensitive)
{
this.caseSensitive = caseSensitive;
// The lower func reside in mscorelib, the higher ones in another assembly.
// This is an easy cross platform way to to have this AssemblyQualifiedName.
FuncAssemblyQualifiedName =
typeof(Func<double, double, double, double, double, double, double, double, double, double>).GetTypeInfo().Assembly.FullName;
}
public double Execute(Operation operation, IFunctionRegistry functionRegistry, IConstantRegistry constantRegistry)
{
return Execute(operation, functionRegistry, constantRegistry, new Dictionary<string, double>());
}
public double Execute(Operation operation, IFunctionRegistry functionRegistry, IConstantRegistry constantRegistry,
IDictionary<string, double> variables)
{
return BuildFormula(operation, functionRegistry, constantRegistry)(variables);
}
public Func<IDictionary<string, double>, double> BuildFormula(Operation operation,
IFunctionRegistry functionRegistry, IConstantRegistry constantRegistry)
{
Func<FormulaContext, double> func = BuildFormulaInternal(operation, functionRegistry);
return caseSensitive
? (Func<IDictionary<string, double>, double>)(variables =>
{
return func(new FormulaContext(variables, functionRegistry, constantRegistry));
})
: (Func<IDictionary<string, double>, double>)(variables =>
{
variables = EngineUtil.ConvertVariableNamesToLowerCase(variables);
FormulaContext context = new FormulaContext(variables, functionRegistry, constantRegistry);
return func(context);
});
}
private Func<FormulaContext, double> BuildFormulaInternal(Operation operation,
IFunctionRegistry functionRegistry)
{
ParameterExpression contextParameter = Expression.Parameter(typeof(FormulaContext), "context");
LabelTarget returnLabel = Expression.Label(typeof(double));
Expression<Func<FormulaContext, double>> lambda = Expression.Lambda<Func<FormulaContext, double>>(
GenerateMethodBody(operation, contextParameter, functionRegistry),
contextParameter
);
return lambda.Compile();
}
private Expression GenerateMethodBody(Operation operation, ParameterExpression contextParameter,
IFunctionRegistry functionRegistry)
{
if (operation == null)
throw new ArgumentNullException("operation");
if (operation.GetType() == typeof(IntegerConstant))
{
IntegerConstant constant = (IntegerConstant)operation;
double value = constant.Value;
return Expression.Constant(value, typeof(double));
}
else if (operation.GetType() == typeof(FloatingPointConstant))
{
FloatingPointConstant constant = (FloatingPointConstant)operation;
return Expression.Constant(constant.Value, typeof(double));
}
else if (operation.GetType() == typeof(Variable))
{
Variable variable = (Variable)operation;
Func<string, FormulaContext, double> getVariableValueOrThrow = PrecompiledMethods.GetVariableValueOrThrow;
return Expression.Call(null,
getVariableValueOrThrow.GetMethodInfo(),
Expression.Constant(variable.Name),
contextParameter);
}
else if (operation.GetType() == typeof(Multiplication))
{
Multiplication multiplication = (Multiplication)operation;
Expression argument1 = GenerateMethodBody(multiplication.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(multiplication.Argument2, contextParameter, functionRegistry);
return Expression.Multiply(argument1, argument2);
}
else if (operation.GetType() == typeof(Addition))
{
Addition addition = (Addition)operation;
Expression argument1 = GenerateMethodBody(addition.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(addition.Argument2, contextParameter, functionRegistry);
return Expression.Add(argument1, argument2);
}
else if (operation.GetType() == typeof(Subtraction))
{
Subtraction addition = (Subtraction)operation;
Expression argument1 = GenerateMethodBody(addition.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(addition.Argument2, contextParameter, functionRegistry);
return Expression.Subtract(argument1, argument2);
}
else if (operation.GetType() == typeof(Division))
{
Division division = (Division)operation;
Expression dividend = GenerateMethodBody(division.Dividend, contextParameter, functionRegistry);
Expression divisor = GenerateMethodBody(division.Divisor, contextParameter, functionRegistry);
return Expression.Divide(dividend, divisor);
}
else if (operation.GetType() == typeof(Modulo))
{
Modulo modulo = (Modulo)operation;
Expression dividend = GenerateMethodBody(modulo.Dividend, contextParameter, functionRegistry);
Expression divisor = GenerateMethodBody(modulo.Divisor, contextParameter, functionRegistry);
return Expression.Modulo(dividend, divisor);
}
else if (operation.GetType() == typeof(Exponentiation))
{
Exponentiation exponentation = (Exponentiation)operation;
Expression @base = GenerateMethodBody(exponentation.Base, contextParameter, functionRegistry);
Expression exponent = GenerateMethodBody(exponentation.Exponent, contextParameter, functionRegistry);
return Expression.Call(null, typeof(Math).GetRuntimeMethod("Pow", new Type[] { typeof(double), typeof(double) }), @base, exponent);
}
else if (operation.GetType() == typeof(UnaryMinus))
{
UnaryMinus unaryMinus = (UnaryMinus)operation;
Expression argument = GenerateMethodBody(unaryMinus.Argument, contextParameter, functionRegistry);
return Expression.Negate(argument);
}
else if (operation.GetType() == typeof(And))
{
And and = (And)operation;
Expression argument1 = Expression.NotEqual(GenerateMethodBody(and.Argument1, contextParameter, functionRegistry), Expression.Constant(0.0));
Expression argument2 = Expression.NotEqual(GenerateMethodBody(and.Argument2, contextParameter, functionRegistry), Expression.Constant(0.0));
return Expression.Condition(Expression.And(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(Or))
{
Or and = (Or)operation;
Expression argument1 = Expression.NotEqual(GenerateMethodBody(and.Argument1, contextParameter, functionRegistry), Expression.Constant(0.0));
Expression argument2 = Expression.NotEqual(GenerateMethodBody(and.Argument2, contextParameter, functionRegistry), Expression.Constant(0.0));
return Expression.Condition(Expression.Or(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(LessThan))
{
LessThan lessThan = (LessThan)operation;
Expression argument1 = GenerateMethodBody(lessThan.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(lessThan.Argument2, contextParameter, functionRegistry);
return Expression.Condition(Expression.LessThan(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(LessOrEqualThan))
{
LessOrEqualThan lessOrEqualThan = (LessOrEqualThan)operation;
Expression argument1 = GenerateMethodBody(lessOrEqualThan.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(lessOrEqualThan.Argument2, contextParameter, functionRegistry);
return Expression.Condition(Expression.LessThanOrEqual(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(GreaterThan))
{
GreaterThan greaterThan = (GreaterThan)operation;
Expression argument1 = GenerateMethodBody(greaterThan.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(greaterThan.Argument2, contextParameter, functionRegistry);
return Expression.Condition(Expression.GreaterThan(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(GreaterOrEqualThan))
{
GreaterOrEqualThan greaterOrEqualThan = (GreaterOrEqualThan)operation;
Expression argument1 = GenerateMethodBody(greaterOrEqualThan.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(greaterOrEqualThan.Argument2, contextParameter, functionRegistry);
return Expression.Condition(Expression.GreaterThanOrEqual(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(Equal))
{
Equal equal = (Equal)operation;
Expression argument1 = GenerateMethodBody(equal.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(equal.Argument2, contextParameter, functionRegistry);
return Expression.Condition(Expression.Equal(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(NotEqual))
{
NotEqual notEqual = (NotEqual)operation;
Expression argument1 = GenerateMethodBody(notEqual.Argument1, contextParameter, functionRegistry);
Expression argument2 = GenerateMethodBody(notEqual.Argument2, contextParameter, functionRegistry);
return Expression.Condition(Expression.NotEqual(argument1, argument2),
Expression.Constant(1.0),
Expression.Constant(0.0));
}
else if (operation.GetType() == typeof(Function))
{
Function function = (Function)operation;
FunctionInfo functionInfo = functionRegistry.GetFunctionInfo(function.FunctionName);
Type funcType;
Type[] parameterTypes;
Expression[] arguments;
if (functionInfo.IsDynamicFunc)
{
funcType = typeof(DynamicFunc<double, double>);
parameterTypes = new Type[] { typeof(double[]) };
Expression[] arrayArguments = new Expression[function.Arguments.Count];
for (int i = 0; i < function.Arguments.Count; i++)
arrayArguments[i] = GenerateMethodBody(function.Arguments[i], contextParameter, functionRegistry);
arguments = new Expression[1];
arguments[0] = NewArrayExpression.NewArrayInit(typeof(double), arrayArguments);
}
else
{
funcType = GetFuncType(functionInfo.NumberOfParameters);
parameterTypes = (from i in Enumerable.Range(0, functionInfo.NumberOfParameters)
select typeof(double)).ToArray();
arguments = new Expression[functionInfo.NumberOfParameters];
for (int i = 0; i < functionInfo.NumberOfParameters; i++)
arguments[i] = GenerateMethodBody(function.Arguments[i], contextParameter, functionRegistry);
}
Expression getFunctionRegistry = Expression.Property(contextParameter, "FunctionRegistry");
ParameterExpression functionInfoVariable = Expression.Variable(typeof(FunctionInfo));
Expression funcInstance;
if (!functionInfo.IsOverWritable)
{
funcInstance = Expression.Convert(
Expression.Property(
Expression.Call(
getFunctionRegistry,
typeof(IFunctionRegistry).GetRuntimeMethod("GetFunctionInfo", new Type[] { typeof(string) }),
Expression.Constant(function.FunctionName)),
"Function"),
funcType);
}
else
funcInstance = Expression.Constant(functionInfo.Function, funcType);
return Expression.Call(
funcInstance,
funcType.GetRuntimeMethod("Invoke", parameterTypes),
arguments);
}
else
{
throw new ArgumentException(string.Format("Unsupported operation \"{0}\".", operation.GetType().FullName), "operation");
}
}
private Type GetFuncType(int numberOfParameters)
{
string funcTypeName;
if (numberOfParameters < 9)
funcTypeName = string.Format("System.Func`{0}", numberOfParameters + 1);
else
funcTypeName = string.Format("System.Func`{0}, {1}", numberOfParameters + 1, FuncAssemblyQualifiedName);
Type funcType = Type.GetType(funcTypeName);
Type[] typeArguments = new Type[numberOfParameters + 1];
for (int i = 0; i < typeArguments.Length; i++)
typeArguments[i] = typeof(double);
return funcType.MakeGenericType(typeArguments);
}
private static class PrecompiledMethods
{
public static double GetVariableValueOrThrow(string variableName, FormulaContext context)
{
if (context.Variables.TryGetValue(variableName, out double result))
return result;
else if (context.ConstantRegistry.IsConstantName(variableName))
return context.ConstantRegistry.GetConstantInfo(variableName).Value;
else
throw new VariableNotDefinedException($"The variable \"{variableName}\" used is not defined.");
}
}
}
}
|
using UnityEngine;
using UnityEditor;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
namespace Unity.InteractiveTutorials.InternalToolsTests
{
public class ProjectModeTest
{
[Test]
public void IsAuthoringMode_Passes()
{
ProjectMode.IsAuthoringMode();
}
}
}
|
using System.Text;
using DirectoriesComparator.PathUtils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace TestProject1
{
[TestClass()]
public class PathValidatorTest
{
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
/// <summary>
///A test for ValidatePath
///</summary>
[TestMethod]
public void ValidatePathTest()
{
using (var file = new System.IO.StreamReader(@"C:\temp\TestData.txt", Encoding.GetEncoding("cp866")))
{
string dir;
while ((dir = file.ReadLine()) != null)
{
var result = Validator.ValidatePath(dir);
Assert.IsTrue(result, "error validating path: " + dir);
}
}
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Transactions;
using System;
using DAL.Repository;
using DAL.Models;
using DAL.Database;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace DAL.Test
{
[TestClass]
public class BookingRepositoryTests
{
private DbContextOptions<MyDbContext> _options =
new DbContextOptionsBuilder<MyDbContext>()
.UseSqlite(@"Data Source = [Repository Root]\Allfiles\Mod02\LabFiles\Lab2\Database\SqliteHotel.db")
.Options;
[TestMethod]
public async Task AddTwoBookingsTest()
{
Booking fristBooking;
Booking secondBooking;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, TransactionScopeAsyncFlowOption.Enabled))
{
HotelBookingRepository repository = new HotelBookingRepository(_options);
fristBooking = await repository.Add(1, 1, DateTime.Now.AddDays(6), 4);
secondBooking = await repository.Add(1, 2, DateTime.Now.AddDays(8), 3);
scope.Complete();
}
using (MyDbContext context = new MyDbContext(_options))
{
int bookingsCounter = context.Bookings.Where(booking => booking.BookingId == fristBooking.BookingId ||
booking.BookingId == secondBooking.BookingId).ToList().Count;
Assert.AreEqual(2, bookingsCounter);
}
}
[TestMethod]
public async Task AddTwoBookingsSQLLiteTest()
{
using (MyDbContext context = new MyDbContext(_options))
{
HotelBookingRepository repository = new HotelBookingRepository(_options);
Booking fristBooking = await repository.Add(1, 1, DateTime.Now.AddDays(6), 4);
Booking secondBooking = await repository.Add(1, 2, DateTime.Now.AddDays(8), 3);
int bookingsCounter = context.Bookings.Where(booking => booking.BookingId == fristBooking.BookingId ||
booking.BookingId == secondBooking.BookingId).ToList().Count;
Assert.AreEqual(2, bookingsCounter);
}
}
}
}
|
// Copyright 2014 Jacob Trimble
//
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using ModMaker.Lua.Parser;
using ModMaker.Lua.Runtime.LuaValues;
namespace ModMaker.Lua.Runtime {
static partial class LuaStaticLibraries {
static class IO {
static readonly LuaString _stream = new LuaString("Stream");
static Stream _input = null;
static Stream _output = null;
public static void Initialize(ILuaEnvironment env) {
ILuaTable io = new LuaValues.LuaTable();
io.SetItemRaw(new LuaString("close"), new close(env));
io.SetItemRaw(new LuaString("flush"), new flush(env));
io.SetItemRaw(new LuaString("input"), new input(env));
io.SetItemRaw(new LuaString("lines"), new lines(env));
io.SetItemRaw(new LuaString("open"), new open(env));
io.SetItemRaw(new LuaString("output"), new output(env));
io.SetItemRaw(new LuaString("read"), new read(env));
io.SetItemRaw(new LuaString("tmpfile"), new tmpfile(env));
io.SetItemRaw(new LuaString("type"), new type(env));
io.SetItemRaw(new LuaString("write"), new write(env));
_input = env.Settings.Stdin;
_output = env.Settings.Stdout;
var _globals = env.GlobalsTable;
_globals.SetItemRaw(new LuaString("io"), io);
_globals.SetItemRaw(new LuaString("dofile"), new dofile(env));
_globals.SetItemRaw(new LuaString("load"), new load(env));
_globals.SetItemRaw(new LuaString("loadfile"), new loadfile(env));
_globals.SetItemRaw(new LuaString("_STDIN"), _createFile(env.Settings.Stdin, env));
_globals.SetItemRaw(new LuaString("_STDOUT"), _createFile(env.Settings.Stdout, env));
}
sealed class LinesHelper : LuaFrameworkFunction {
StreamReader _stream;
readonly bool _close;
readonly int[] _ops; // -4 = *L, -3 = *l, -2 = *a, -1 = *n
public LinesHelper(ILuaEnvironment env, bool close, Stream stream, int[] ops)
: base(env, "io.lines") {
_stream = new StreamReader(stream);
_close = close;
_ops = ops;
}
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
if (_stream == null) {
return LuaMultiValue.Empty;
}
var ret = _read(_ops, _stream, _environment);
if (_stream.EndOfStream) {
if (_close) {
_stream.Close();
}
_stream = null;
}
return ret;
}
}
// io functions
sealed class close : LuaFrameworkFunction {
public close(ILuaEnvironment env) : base(env, "io.close") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
var t = _getStream(args[0], _environment, out Stream s);
if (t != null) {
return t;
}
try {
s.Close();
return new LuaMultiValue(_createFile(s, _environment));
} catch (Exception e) {
return LuaMultiValue.CreateMultiValueFromObj(null, e.Message, e);
}
}
}
sealed class flush : LuaFrameworkFunction {
public flush(ILuaEnvironment env) : base(env, "io.flush") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
var t = _getStream(args[0], _environment, out _);
if (t != null) {
return t;
}
try {
_output.Flush();
return new LuaMultiValue(_createFile(_output, _environment));
} catch (Exception e) {
return LuaMultiValue.CreateMultiValueFromObj(null, e.Message, e);
}
}
}
sealed class input : LuaFrameworkFunction {
public input(ILuaEnvironment env) : base(env, "io.input") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
ILuaValue obj = args[0];
if (obj != null) {
if (obj.ValueType == LuaValueType.String) {
Stream s = File.OpenRead(obj.GetValue() as string);
_input = s;
} else if (obj.ValueType == LuaValueType.Table) {
Stream s = ((ILuaTable)obj).GetItemRaw(_stream) as Stream;
if (s == null) {
throw new InvalidOperationException(
"First argument to function 'io.input' must be a file-stream or a string " +
"path.");
}
_input = s;
} else if (obj is Stream st) {
_input = st;
} else {
throw new InvalidOperationException(
"First argument to function 'io.input' must be a file-stream or a string path.");
}
}
return new LuaMultiValue(_createFile(_input, _environment));
}
}
sealed class lines : LuaFrameworkFunction {
public lines(ILuaEnvironment env) : base(env, "io.lines") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
ILuaValue obj = args[0];
bool close;
Stream s;
int start;
string oString = obj.GetValue() as string;
if (oString != null) {
if (oString[0] != '*') {
s = File.OpenRead(oString);
close = true;
start = 1;
} else {
s = _input;
close = false;
start = 0;
}
} else if (obj.ValueType == LuaValueType.Table) {
s = ((ILuaTable)obj).GetItemRaw(_stream) as Stream;
if (s == null) {
throw new ArgumentException("First argument to io.lines must be a file-stream or a " +
"file path, make sure to use file:lines.");
}
close = false;
start = 1;
} else if (obj.GetValue() is Stream st) {
s = st;
close = false;
start = 1;
} else {
s = _input;
close = false;
start = 0;
}
int[] a = _parse(args.Skip(start), "io.lines");
return new LuaMultiValue(new LinesHelper(_environment, close, s, a));
}
}
sealed class open : LuaFrameworkFunction {
public open(ILuaEnvironment env) : base(env, "io.open") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
string s = args[0].GetValue() as string;
string mode = args[1].GetValue() as string;
FileMode fileMode;
FileAccess access;
bool seek = false;
mode = mode?.ToLowerInvariant();
if (string.IsNullOrWhiteSpace(s)) {
return LuaMultiValue.CreateMultiValueFromObj(
null, "First argument must be a string filename.");
}
switch (mode) {
case "r":
case "rb":
case "":
case null:
fileMode = FileMode.Open;
access = FileAccess.Read;
break;
case "w":
case "wb":
fileMode = FileMode.Create;
access = FileAccess.Write;
break;
case "a":
case "ab":
fileMode = FileMode.OpenOrCreate;
access = FileAccess.ReadWrite;
seek = true;
break;
case "r+":
case "r+b":
fileMode = FileMode.Open;
access = FileAccess.ReadWrite;
break;
case "w+":
case "w+b":
fileMode = FileMode.Create;
access = FileAccess.ReadWrite;
break;
case "a+":
case "a+b":
fileMode = FileMode.OpenOrCreate;
access = FileAccess.ReadWrite;
seek = true;
break;
default:
return LuaMultiValue.CreateMultiValueFromObj(
null, "Second argument must be a valid string mode.");
}
try {
using (Stream stream = File.Open(s, fileMode, access)) {
if (seek && stream.CanSeek) {
stream.Seek(0, SeekOrigin.End);
}
return new LuaMultiValue(_createFile(stream, _environment));
}
} catch (Exception e) {
return LuaMultiValue.CreateMultiValueFromObj(null, e.Message, e);
}
}
}
sealed class output : LuaFrameworkFunction {
public output(ILuaEnvironment env) : base(env, "io.output") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
ILuaValue obj = args[0];
if (obj != LuaNil.Nil) {
if (obj.ValueType == LuaValueType.String) {
Stream s = File.OpenRead(obj.GetValue() as string);
_output = s;
} else if (obj.ValueType == LuaValueType.Table) {
Stream s = ((ILuaTable)obj).GetItemRaw(_stream) as Stream;
if (s == null) {
throw new InvalidOperationException("First argument to function 'io.output' must " +
"be a file-stream or a string path.");
}
_output = s;
} else if (obj is Stream st) {
_output = st;
} else {
throw new InvalidOperationException(
"First argument to function 'io.output' must be a file-stream or a string path.");
}
}
return new LuaMultiValue(_createFile(_output, _environment));
}
}
sealed class read : LuaFrameworkFunction {
public read(ILuaEnvironment env) : base(env, "io.read") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
ILuaValue obj = args[0];
Stream s;
int start;
if (obj.ValueType == LuaValueType.Table) {
s = ((ILuaTable)obj).GetItemRaw(_stream) as Stream;
if (s == null) {
throw new ArgumentException("First argument to io.read must be a file-stream or a " +
"file path, make sure to use file:read.");
}
start = 1;
} else if (obj.GetValue() is Stream st) {
s = st;
start = 1;
} else {
s = _input;
start = 0;
}
int[] a = _parse(args.Skip(start), "io.read");
return _read(a, new StreamReader(s), _environment);
}
}
sealed class seek : LuaFrameworkFunction {
public seek(ILuaEnvironment env) : base(env, "io.seek") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
Stream s = args[0].GetValue() as Stream;
SeekOrigin origin = SeekOrigin.Current;
long off = 0;
if (s == null) {
ILuaTable table = args[0] as ILuaTable;
if (table != null) {
s = table.GetItemRaw(_stream) as Stream;
}
if (s == null) {
throw new ArgumentException("First real argument to function file:seek must be a " +
"file-stream, make sure to use file:seek.");
}
}
if (args.Count > 1) {
string str = args[1].GetValue() as string;
if (str == "set") {
origin = SeekOrigin.Begin;
} else if (str == "cur") {
origin = SeekOrigin.Current;
} else if (str == "end") {
origin = SeekOrigin.End;
} else {
throw new ArgumentException("First argument to function file:seek must be a string.");
}
if (args.Count > 2) {
object obj = args[2].GetValue();
if (obj is double) {
off = Convert.ToInt64((double)obj);
} else {
throw new ArgumentException(
"Second argument to function file:seek must be a number.");
}
}
}
if (!s.CanSeek) {
return LuaMultiValue.CreateMultiValueFromObj(
null, "Specified stream cannot be seeked.");
}
try {
return LuaMultiValue.CreateMultiValueFromObj(
Convert.ToDouble(s.Seek(off, origin)));
} catch (Exception e) {
return LuaMultiValue.CreateMultiValueFromObj(null, e.Message, e);
}
}
}
sealed class tmpfile : LuaFrameworkFunction {
public tmpfile(ILuaEnvironment env) : base(env, "io.tmpfile") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
string str = Path.GetTempFileName();
Stream s = File.Open(str, FileMode.OpenOrCreate, FileAccess.ReadWrite);
return new LuaMultiValue(_createFile(s, _environment));
}
}
sealed class type : LuaFrameworkFunction {
public type(ILuaEnvironment env) : base(env, "io.type") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
ILuaValue obj = args[0];
if (obj.GetValue() is Stream) {
return LuaMultiValue.CreateMultiValueFromObj("file");
} else if (obj.ValueType == LuaValueType.Table) {
Stream s = ((ILuaTable)obj).GetItemRaw(_stream) as Stream;
return LuaMultiValue.CreateMultiValueFromObj(s == null ? null : "file");
} else {
return LuaMultiValue.Empty;
}
}
}
sealed class write : LuaFrameworkFunction {
public write(ILuaEnvironment env) : base(env, "io.write") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
ILuaValue obj = args[0];
Stream s;
int start;
if (obj.ValueType == LuaValueType.Table) {
s = ((ILuaTable)obj).GetItemRaw(_stream) as Stream;
if (s == null) {
return LuaMultiValue.CreateMultiValueFromObj(
null, "First argument must be a file-stream or a file path.");
}
start = 1;
} else if (obj is Stream st) {
s = st;
start = 1;
} else {
s = _output;
start = 0;
}
try {
for (int i = start; i < args.Count; i++) {
var temp = args[i].GetValue();
if (temp is double) {
var bt = (_environment.Settings.Encoding ?? Encoding.UTF8).GetBytes(
((double)temp).ToString(CultureInfo.InvariantCulture));
s.Write(bt, 0, bt.Length);
} else if (temp is string) {
var bt = (_environment.Settings.Encoding ?? Encoding.UTF8).GetBytes(temp as string);
s.Write(bt, 0, bt.Length);
} else {
throw new ArgumentException("Arguments to io.write must be a string or number.");
}
}
return new LuaMultiValue(_createFile(s, _environment));
} catch (ArgumentException) {
throw;
} catch (Exception e) {
return LuaMultiValue.CreateMultiValueFromObj(null, e.Message, e);
}
}
}
// helper functions
static int[] _parse(IEnumerable<ILuaValue> args, string func) {
List<int> v = new List<int>();
foreach (var item in args) {
object obj = item.GetValue();
if (obj is double d) {
if (d < 0) {
throw new ArgumentOutOfRangeException(
$"Arguments to {func} must be a positive integer.", (Exception)null);
}
v.Add(Convert.ToInt32(d));
} else if (obj is string st) {
if (st == "*index") {
v.Add(-1);
} else if (st == "*a") {
v.Add(-2);
} else if (st == "*l") {
v.Add(-3);
} else if (st == "*L") {
v.Add(-4);
} else {
throw new ArgumentException("Only the following strings are valid as arguments to " +
func + ": '*index', '*a', '*l', or '*L'.");
}
} else {
throw new ArgumentException(
$"Arguments to function {func} must be a number or a string.");
}
}
return v.ToArray();
}
static LuaMultiValue _read(int[] opts, StreamReader s, ILuaEnvironment env) {
List<ILuaValue> ret = new List<ILuaValue>();
foreach (var item in opts) {
switch (item) {
case -4:
ret.Add(s.EndOfStream ? (ILuaValue)LuaNil.Nil : new LuaString(s.ReadLine() + "\n"));
break;
case -3:
ret.Add(s.EndOfStream ? (ILuaValue)LuaNil.Nil : new LuaString(s.ReadLine()));
break;
case -2:
ret.Add(s.EndOfStream ? (ILuaValue)LuaNil.Nil : new LuaString(s.ReadToEnd()));
break;
case -1:
if (s.EndOfStream) {
ret.Add(null);
} else {
double? d = NetHelpers.ReadNumber(s);
if (d.HasValue) {
ret.Add(LuaNumber.Create(d.Value));
} else {
ret.Add(LuaNil.Nil);
}
}
break;
default:
if (s.EndOfStream) {
ret.Add(null);
} else {
char[] c = new char[item];
s.Read(c, 0, item);
ret.Add(new LuaString(new string(c)));
}
break;
}
}
return new LuaMultiValue(ret.ToArray());
}
static ILuaTable _createFile(Stream backing, ILuaEnvironment env) {
ILuaTable ret = new LuaTable();
ret.SetItemRaw(_stream, new LuaUserData<Stream>(backing));
ret.SetItemRaw(new LuaString("close"), new close(env));
ret.SetItemRaw(new LuaString("flush"), new flush(env));
ret.SetItemRaw(new LuaString("lines"), new lines(env));
ret.SetItemRaw(new LuaString("read"), new read(env));
ret.SetItemRaw(new LuaString("seek"), new seek(env));
ret.SetItemRaw(new LuaString("write"), new write(env));
return ret;
}
static LuaMultiValue _getStream(ILuaValue file, ILuaEnvironment env, out Stream s) {
s = null;
if (file == LuaNil.Nil) {
if (_output == null) {
return LuaMultiValue.CreateMultiValueFromObj(null, "No default output file set.");
}
s = _output;
} else {
if (file.ValueType == LuaValueType.Table) {
s = ((ILuaTable)file).GetItemRaw(_stream).GetValue() as Stream;
if (s == null) {
return LuaMultiValue.CreateMultiValueFromObj(
null, "Specified argument is not a valid file stream.");
}
} else if (file.ValueType == LuaValueType.UserData) {
s = file.GetValue() as Stream;
} else {
return LuaMultiValue.CreateMultiValueFromObj(
null, "Specified argument is not a valid file stream.");
}
}
return null;
}
// global functions
sealed class dofile : LuaFrameworkFunction {
public dofile(ILuaEnvironment env) : base(env, "io.dofile") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
if (args.Count < 1) {
throw new ArgumentException("Expecting one argument to function 'dofile'.");
}
string file = args[0].GetValue() as string;
if (string.IsNullOrEmpty(file)) {
throw new ArgumentException("First argument to 'loadfile' must be a file path.");
}
if (!File.Exists(file)) {
throw new FileNotFoundException("Unable to locate file at '" + file + "'.");
}
string chunk = File.ReadAllText(file);
var parsed = PlainParser.Parse(_environment.Parser, chunk,
Path.GetFileNameWithoutExtension(file));
var r = _environment.CodeCompiler.Compile(_environment, parsed, null);
return r.Invoke(LuaNil.Nil, false, LuaMultiValue.Empty);
}
}
sealed class load : LuaFrameworkFunction {
public load(ILuaEnvironment env) : base(env, "io.load") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
if (args.Count < 1) {
throw new ArgumentException("Expecting at least one argument to function 'load'.");
}
ILuaValue ld = args[0];
string chunk;
if (ld.ValueType == LuaValueType.Function) {
chunk = "";
while (true) {
var ret = ld.Invoke(LuaNil.Nil, false, new LuaMultiValue());
if (ret[0].ValueType == LuaValueType.String) {
if (string.IsNullOrEmpty(ret[0].GetValue() as string)) {
break;
} else {
chunk += ret[0].GetValue() as string;
}
} else {
break;
}
}
} else if (ld.ValueType == LuaValueType.String) {
chunk = ld.GetValue() as string;
} else {
throw new ArgumentException("First argument to 'load' must be a string or a method.");
}
try {
var parsed = PlainParser.Parse(_environment.Parser, chunk, null);
return new LuaMultiValue(_environment.CodeCompiler.Compile(_environment, parsed, null));
} catch (Exception e) {
return LuaMultiValue.CreateMultiValueFromObj(null, e.Message);
}
}
}
sealed class loadfile : LuaFrameworkFunction {
public loadfile(ILuaEnvironment env) : base(env, "io.loadfile") { }
protected override LuaMultiValue _invokeInternal(LuaMultiValue args) {
if (args.Count < 1) {
throw new ArgumentException("Expecting at least one argument to function 'loadfile'.");
}
string file = args[0].GetValue() as string;
string mode = args[1].GetValue() as string;
if (string.IsNullOrEmpty(file)) {
throw new ArgumentException("First argument to 'loadfile' must be a file path.");
}
if (!File.Exists(file)) {
throw new FileNotFoundException("Unable to locate file at '" + file + "'.");
}
if (string.IsNullOrEmpty(mode) && args.Count > 1) {
throw new ArgumentException("Second argument to 'loadfile' must be a string mode.");
}
if (mode != "type") {
throw new ArgumentException("The only mode supported by loadfile is 'type'.");
}
string chunk = File.ReadAllText(file);
try {
var parsed = PlainParser.Parse(_environment.Parser, chunk,
Path.GetFileNameWithoutExtension(file));
return new LuaMultiValue(_environment.CodeCompiler.Compile(_environment, parsed, null));
} catch (Exception e) {
return LuaMultiValue.CreateMultiValueFromObj(null, e.Message);
}
}
}
}
}
}
|
using System.ComponentModel;
using OMP.Connector.Domain.Schema.Base;
using OMP.Connector.Domain.Schema.Responses;
namespace OMP.Connector.Domain.Schema.Messages
{
[Description("Definition of OPC UA Command Response")]
public class CommandResponse : Message<ResponsePayload> { }
} |
using System;
using System.IO;
namespace Glacie.Data.Arc
{
internal static class TestDataUtilities
{
private static string? s_testDataPath;
public static string GetPath(string path)
{
if (s_testDataPath == null)
{
s_testDataPath = System.IO.Path.Combine(Environment.CurrentDirectory, "./test-data");
}
return System.IO.Path.Combine(s_testDataPath, path);
}
}
}
|
using AutoMapper;
using FluentAssertions;
using NSubstitute;
using NUnit.Framework;
using System.Threading;
using System.Threading.Tasks;
using ygo.application.Mappings.Profiles;
using ygo.application.Queries.BanlistById;
using ygo.core.Models.Db;
using ygo.core.Services;
using ygo.tests.core;
namespace ygo.application.unit.tests.QueriesTests
{
[TestFixture]
[Category(TestType.Unit)]
public class BanlistByIdQueryHandlerTests
{
private BanlistByIdQueryHandler _sut;
private IBanlistService _banlistService;
[SetUp]
public void SetUp()
{
var config = new MapperConfiguration
(
cfg => { cfg.AddProfile(new BanlistProfile()); }
);
var mapper = config.CreateMapper();
_banlistService = Substitute.For<IBanlistService>();
_sut = new BanlistByIdQueryHandler(_banlistService, mapper);
}
[Test]
public async Task Given_An_BanlistId_If_Not_Found_Should_Return_Null()
{
// Arrange
_banlistService.GetBanlistById(Arg.Any<long>()).Returns(null as Banlist);
// Act
var result = await _sut.Handle(new BanlistByIdQuery(), CancellationToken.None);
// Assert
result.Should().BeNull();
}
[Test]
public async Task Given_An_BanlistId_If_Found_Should_Return_Banlist()
{
// Arrange
_banlistService.GetBanlistById(Arg.Any<long>()).Returns(new Banlist());
// Act
var result = await _sut.Handle(new BanlistByIdQuery(), CancellationToken.None);
// Assert
result.Should().NotBeNull();
}
[Test]
public async Task Given_An_BanlistId_If_Found_Should_Execute_GetBanlistById_Method_Once()
{
// Arrange
_banlistService.GetBanlistById(Arg.Any<long>()).Returns(new Banlist());
// Act
await _sut.Handle(new BanlistByIdQuery(), CancellationToken.None);
// Assert
await _banlistService.Received(1).GetBanlistById(Arg.Any<long>());
}
}
} |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ShObjIdl_core.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("7E9FB0D3-919F-4307-AB2E-9B1860310C93")]
[NativeTypeName("struct IShellItem2 : IShellItem")]
[NativeInheritance("IShellItem")]
public unsafe partial struct IShellItem2
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IShellItem2*, Guid*, void**, int>)(lpVtbl[0]))((IShellItem2*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IShellItem2*, uint>)(lpVtbl[1]))((IShellItem2*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IShellItem2*, uint>)(lpVtbl[2]))((IShellItem2*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
[return: NativeTypeName("HRESULT")]
public int BindToHandler(IBindCtx* pbc, [NativeTypeName("const GUID &")] Guid* bhid, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IShellItem2*, IBindCtx*, Guid*, Guid*, void**, int>)(lpVtbl[3]))((IShellItem2*)Unsafe.AsPointer(ref this), pbc, bhid, riid, ppv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
[return: NativeTypeName("HRESULT")]
public int GetParent(IShellItem** ppsi)
{
return ((delegate* unmanaged<IShellItem2*, IShellItem**, int>)(lpVtbl[4]))((IShellItem2*)Unsafe.AsPointer(ref this), ppsi);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
[return: NativeTypeName("HRESULT")]
public int GetDisplayName(SIGDN sigdnName, [NativeTypeName("LPWSTR *")] ushort** ppszName)
{
return ((delegate* unmanaged<IShellItem2*, SIGDN, ushort**, int>)(lpVtbl[5]))((IShellItem2*)Unsafe.AsPointer(ref this), sigdnName, ppszName);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
[return: NativeTypeName("HRESULT")]
public int GetAttributes([NativeTypeName("SFGAOF")] uint sfgaoMask, [NativeTypeName("SFGAOF *")] uint* psfgaoAttribs)
{
return ((delegate* unmanaged<IShellItem2*, uint, uint*, int>)(lpVtbl[6]))((IShellItem2*)Unsafe.AsPointer(ref this), sfgaoMask, psfgaoAttribs);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(7)]
[return: NativeTypeName("HRESULT")]
public int Compare(IShellItem* psi, [NativeTypeName("SICHINTF")] uint hint, int* piOrder)
{
return ((delegate* unmanaged<IShellItem2*, IShellItem*, uint, int*, int>)(lpVtbl[7]))((IShellItem2*)Unsafe.AsPointer(ref this), psi, hint, piOrder);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(8)]
[return: NativeTypeName("HRESULT")]
public int GetPropertyStore(GETPROPERTYSTOREFLAGS flags, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IShellItem2*, GETPROPERTYSTOREFLAGS, Guid*, void**, int>)(lpVtbl[8]))((IShellItem2*)Unsafe.AsPointer(ref this), flags, riid, ppv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(9)]
[return: NativeTypeName("HRESULT")]
public int GetPropertyStoreWithCreateObject(GETPROPERTYSTOREFLAGS flags, IUnknown* punkCreateObject, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IShellItem2*, GETPROPERTYSTOREFLAGS, IUnknown*, Guid*, void**, int>)(lpVtbl[9]))((IShellItem2*)Unsafe.AsPointer(ref this), flags, punkCreateObject, riid, ppv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(10)]
[return: NativeTypeName("HRESULT")]
public int GetPropertyStoreForKeys([NativeTypeName("const PROPERTYKEY *")] PROPERTYKEY* rgKeys, [NativeTypeName("UINT")] uint cKeys, GETPROPERTYSTOREFLAGS flags, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, uint, GETPROPERTYSTOREFLAGS, Guid*, void**, int>)(lpVtbl[10]))((IShellItem2*)Unsafe.AsPointer(ref this), rgKeys, cKeys, flags, riid, ppv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(11)]
[return: NativeTypeName("HRESULT")]
public int GetPropertyDescriptionList([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* keyType, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, Guid*, void**, int>)(lpVtbl[11]))((IShellItem2*)Unsafe.AsPointer(ref this), keyType, riid, ppv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(12)]
[return: NativeTypeName("HRESULT")]
public int Update(IBindCtx* pbc)
{
return ((delegate* unmanaged<IShellItem2*, IBindCtx*, int>)(lpVtbl[12]))((IShellItem2*)Unsafe.AsPointer(ref this), pbc);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(13)]
[return: NativeTypeName("HRESULT")]
public int GetProperty([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, PROPVARIANT* ppropvar)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, PROPVARIANT*, int>)(lpVtbl[13]))((IShellItem2*)Unsafe.AsPointer(ref this), key, ppropvar);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(14)]
[return: NativeTypeName("HRESULT")]
public int GetCLSID([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, [NativeTypeName("CLSID *")] Guid* pclsid)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, Guid*, int>)(lpVtbl[14]))((IShellItem2*)Unsafe.AsPointer(ref this), key, pclsid);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(15)]
[return: NativeTypeName("HRESULT")]
public int GetFileTime([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, FILETIME* pft)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, FILETIME*, int>)(lpVtbl[15]))((IShellItem2*)Unsafe.AsPointer(ref this), key, pft);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(16)]
[return: NativeTypeName("HRESULT")]
public int GetInt32([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, int* pi)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, int*, int>)(lpVtbl[16]))((IShellItem2*)Unsafe.AsPointer(ref this), key, pi);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(17)]
[return: NativeTypeName("HRESULT")]
public int GetString([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, [NativeTypeName("LPWSTR *")] ushort** ppsz)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, ushort**, int>)(lpVtbl[17]))((IShellItem2*)Unsafe.AsPointer(ref this), key, ppsz);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(18)]
[return: NativeTypeName("HRESULT")]
public int GetUInt32([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, [NativeTypeName("ULONG *")] uint* pui)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, uint*, int>)(lpVtbl[18]))((IShellItem2*)Unsafe.AsPointer(ref this), key, pui);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(19)]
[return: NativeTypeName("HRESULT")]
public int GetUInt64([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, [NativeTypeName("ULONGLONG *")] ulong* pull)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, ulong*, int>)(lpVtbl[19]))((IShellItem2*)Unsafe.AsPointer(ref this), key, pull);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(20)]
[return: NativeTypeName("HRESULT")]
public int GetBool([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key, [NativeTypeName("BOOL *")] int* pf)
{
return ((delegate* unmanaged<IShellItem2*, PROPERTYKEY*, int*, int>)(lpVtbl[20]))((IShellItem2*)Unsafe.AsPointer(ref this), key, pf);
}
}
}
|
using System;
using UnityEngine;
/// <summary>
/// DialogueLine is a Scriptable Object that represents one line of spoken dialogue.
/// It references the Actor that speaks it.
/// </summary>
[CreateAssetMenu(fileName = "newLineOfDialogue", menuName = "Dialogues/Line of Dialogue")]
public class DialogueLineSO : ScriptableObject
{
public ActorSO Actor { get => _actor; }
public string Sentence { get => _sentence; }
[SerializeField] private ActorSO _actor = default;
[SerializeField] [TextArea(3, 3)] private string _sentence = default; //TODO: Connect this with localisation
}
|
using System;
using System.Collections.Generic;
using System.Text;
using UniversalProcessor.SDD.Common;
namespace UniversalProcessor.Processors
{
public class StringDescriber : DataDescriber
{
public override bool CanProcess(object data)
{
if (data is String)
return true;
return false;
}
public override List<SDDDataViewDefinition> GenerateViews(object data)
{
List<SDDDataViewDefinition> views = new List<SDDDataViewDefinition>();
if (data is string)
{
string strData = data as string;
views.Add(new SDDString(strData));
views.Add(new SDDListCharacters(strData.ToCharArray()));
}
return views;
}
}
}
|
// Copyright (c) Robin Boerdijk - All rights reserved - See LICENSE file for license terms
using MDSDK.BinaryIO;
using MDSDK.JPEG2000.Model;
using MDSDK.JPEG2000.Utils;
using System;
using System.Diagnostics;
namespace MDSDK.JPEG2000.CodestreamSyntax
{
class CodingStyleDefaultMarkerSegment : CodingStyleMarkerSegment
{
public ProgressionOrder SG_ProgressionOrder { get; protected set; }
public ushort SG_NumberOfLayers { get; protected set; }
public MultipleComponentTransform SG_MultipleComponentTransform { get; protected set; }
private void Read_SG_Parameters(BinaryDataReader input)
{
SG_ProgressionOrder = (ProgressionOrder)input.ReadByte();
SG_NumberOfLayers = input.Read<UInt16>();
SG_MultipleComponentTransform = (MultipleComponentTransform)input.ReadByte();
}
public override void ReadFrom(CodestreamReader input)
{
var dataReader = input.DataReader;
Read_S_CodingStyle(dataReader);
Read_SG_Parameters(dataReader);
Read_SP_Parameters(dataReader);
Debug.Assert(dataReader.Input.AtEnd);
}
}
}
|
using System.Management.Automation;
using Microsoft.Crm.Sdk.Messages;
namespace Handy.Crm.Powershell.Cmdlets
{
[Cmdlet(VerbsLifecycle.Invoke, "CRMWhoAmI")]
public class InvokeCrmWhoAmICommand : CrmCmdletBase
{
protected override void ProcessRecord()
{
base.ProcessRecord();
var whoAmI = (WhoAmIResponse)Connection.Execute(
new WhoAmIRequest());
WriteObject(whoAmI);
}
}
} |
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Notifications.ScenarioPages.Toasts.ToastNotificationManagerHistory.GetHistory.Visualizer
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ScenarioElement : UserControl
{
public ScenarioElement()
{
this.InitializeComponent();
ButtonUpdate_Click(this, null);
}
private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
{
var toasts = ToastNotificationManager.History.GetHistory();
ListViewHistory.ItemsSource = toasts;
}
}
}
|
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using Microsoft.VisualBasic;
using System.Linq;
using System;
using System.Collections;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Data.OleDb;
namespace HBRS
{
public partial class frmSeleccionarHabitacion
{
public frmSeleccionarHabitacion()
{
InitializeComponent();
}
#region Default Instance
private static frmSeleccionarHabitacion defaultInstance;
public static frmSeleccionarHabitacion Default
{
get
{
if (defaultInstance == null)
{
defaultInstance = new frmSeleccionarHabitacion();
defaultInstance.FormClosed += new FormClosedEventHandler(defaultInstance_FormClosed);
}
return defaultInstance;
}
}
static void defaultInstance_FormClosed(object sender, FormClosedEventArgs e)
{
defaultInstance = null;
}
#endregion
public void frmSelectRoom_Load(System.Object sender, System.EventArgs e)
{
display_room();
}
private void display_room()
{
Modulo1.con.Open();
DataTable Dt = new DataTable("tblRoom");
OleDbDataAdapter rs = default(OleDbDataAdapter);
rs = new OleDbDataAdapter("Select * from tblRoom WHERE Status = \'Disponible\'", Modulo1.con);
rs.Fill(Dt);
int indx = default(int);
lvRoom.Items.Clear();
for (indx = 0; indx <= Dt.Rows.Count - 1; indx++)
{
ListViewItem lv = new ListViewItem();
lv.Text = (Dt.Rows[indx]["RoomNumber"].ToString());
lv.SubItems.Add(Dt.Rows[indx]["RoomType"].ToString());
lv.SubItems.Add(Dt.Rows[indx]["RoomRate"].ToString());
lv.SubItems.Add(Dt.Rows[indx]["NoOfOccupancy"].ToString());
lvRoom.Items.Add(lv);
}
rs.Dispose();
Modulo1.con.Close();
}
public void lvRoom_DoubleClick(object sender, System.EventArgs e)
{
frmEntrada.Default.txtRoomNumber.Text = lvRoom.SelectedItems[0].Text;
frmEntrada.Default.txtRoomType.Text = lvRoom.SelectedItems[0].SubItems[1].Text;
frmEntrada.Default.txtRoomRate.Text = lvRoom.SelectedItems[0].SubItems[2].Text;
frmEntrada.Default.lblNoOfOccupancy.Text = lvRoom.SelectedItems[0].SubItems[3].Text;
frmReservar.Default.txtRoomNumber.Text = lvRoom.SelectedItems[0].Text;
frmReservar.Default.txtRoomType.Text = lvRoom.SelectedItems[0].SubItems[1].Text;
frmReservar.Default.txtRoomRate.Text = lvRoom.SelectedItems[0].SubItems[2].Text;
frmReservar.Default.lblNoOfOccupancy.Text = lvRoom.SelectedItems[0].SubItems[3].Text;
this.Close();
}
public void lvRoom_SelectedIndexChanged(System.Object sender, System.EventArgs e)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WareHouse :MonoBehaviour, IAnimalBuyEvent {
// List for items in warehouse
public static List<GameObject> ItemsInWareHouse = new List<GameObject>();
// List for animals type in warehouse
public static List<Animals> AnimalsInWareHouse = new List<Animals>();
// Prefab for warehouse item
[SerializeField]
private GameObject WareHouseItemPrefab;
// Content window for warehouse items
[SerializeField]
private GameObject WareHouseContent;
// Main menu window
[SerializeField]
private GameObject MainMenu;
// Button for close wareouse
[SerializeField]
private Button CloseWareHouse;
// Normalized scale for item in warehouse
private Vector3 NormalizedScale = new Vector3(1, 1, 1);
private void Start() {
CloseWareHouse.onClick.AddListener(CloseShopClick);
}
// Add new item in warehouse or change count one of them
private void AddWareHouseItem(Animals animal) {
if (AnimalsInWareHouse.IndexOf(animal) == -1) {
AnimalsInWareHouse.Add(animal);
GameObject newWareHouseItem = Instantiate(WareHouseItemPrefab);
newWareHouseItem.GetComponent<WareHouseItem>().SetValues(animal,1);
ItemsInWareHouse.Add(newWareHouseItem);
}
else {
ItemsInWareHouse[AnimalsInWareHouse.IndexOf(animal)].GetComponent<WareHouseItem>()._Count++;
}
}
// or event after buy animal
public void OnAnimalBuy(Animals animal) {
AddWareHouseItem(animal);
}
// Sho items from warehouse in window
public void ShowItemsInWareHouse() {
foreach (GameObject Item in ItemsInWareHouse) {
Item.transform.SetParent(WareHouseContent.transform);
Item.transform.localScale = NormalizedScale;
}
}
// Close warehouse
private void CloseShopClick() {
MainMenu.SetActive(true);
this.gameObject.SetActive(false);
}
}
|
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 System.Net;
using System.IO;
namespace Triggernometry.Forms
{
public partial class ExportForm : MemoryForm<ExportForm>
{
private string _ShownText;
internal string ShownText
{
get
{
return _ShownText;
}
set
{
_ShownText = value;
UpdateDisplay();
}
}
public ExportForm()
{
InitializeComponent();
cbxFormat.SelectedIndex = 0;
RestoredSavedDimensions();
}
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
btnSelectionToClipboard.Enabled = (rtbExportResults.SelectionLength > 0);
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
ctxSelectionToClipboard.Enabled = btnSelectionToClipboard.Enabled;
ctxEverythingToClipboard.Enabled = btnEverythingToClipboard.Enabled;
}
private void copySelectionToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
{
selectionToClipboardToolStripMenuItem_Click(sender, e);
}
private void copyAllToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
{
everythingToClipboardToolStripMenuItem_Click(sender, e);
}
private void cbxFormat_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateDisplay();
}
private void UpdateDisplay()
{
switch (cbxFormat.SelectedIndex)
{
case 0:
rtbExportResults.Text = ShownText;
break;
case 1:
rtbExportResults.Text = WebUtility.HtmlEncode(ShownText);
break;
}
}
private void selectionToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Clipboard.SetText(rtbExportResults.SelectedText);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, I18n.Translate("internal/ExportForm/exception", "Exception"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void everythingToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
Clipboard.SetText(rtbExportResults.Text);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, I18n.Translate("internal/ExportForm/exception", "Exception"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void saveToFileToolStripMenuItem_Click(object sender, EventArgs e)
{
btnSaveToFile_Click(sender, e);
}
private void btnSaveToFile_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, rtbExportResults.Text);
}
}
}
}
|
namespace LMPlatform.Models.CP
{
public class CoursePercentagesGraphToGroup
{
public int CoursePercentagesGraphToGroupId { get; set; }
public int CoursePercentagesGraphId { get; set; }
public int GroupId { get; set; }
public virtual Group Group { get; set; }
public virtual CoursePercentagesGraph CoursePercentagesGraph { get; set; }
}
}
|
/************************************************************************
AvalonDock
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at https://opensource.org/licenses/MS-PL
************************************************************************/
namespace AvalonDock.Controls
{
public enum DropTargetType
{
DockingManagerDockLeft,
DockingManagerDockTop,
DockingManagerDockRight,
DockingManagerDockBottom,
DocumentPaneDockLeft,
DocumentPaneDockTop,
DocumentPaneDockRight,
DocumentPaneDockBottom,
DocumentPaneDockInside,
DocumentPaneGroupDockInside,
AnchorablePaneDockLeft,
AnchorablePaneDockTop,
AnchorablePaneDockRight,
AnchorablePaneDockBottom,
AnchorablePaneDockInside,
DocumentPaneDockAsAnchorableLeft,
DocumentPaneDockAsAnchorableTop,
DocumentPaneDockAsAnchorableRight,
DocumentPaneDockAsAnchorableBottom,
}
}
|
using ArmiesDomain.Exceptions;
using ArmiesDomain.Repositories.Armies;
using ArmiesDomain.Services.ArmyNotifications;
namespace ArmiesDomain.ValueObjects
{
public class Quantity
{
private readonly int value;
public Quantity() : this(0)
{
}
public Quantity(int value)
{
if(value < 0)
{
throw new QuantityException();
}
this.value = value;
}
public Cost Multiply(Cost cost)
{
return cost.Multiply(value);
}
public void FillSquadData(SquadNotificationDto data)
{
data.Quantity = value;
}
public void FillSquadData(SquadRepositoryDto data)
{
data.Quantity = value;
}
public bool IsZero
{
get => value == 0;
}
public static readonly Quantity Single = new Quantity(1);
}
}
|
using System;
namespace BlaSoft.PowerShell.KnownFolders.Win32
{
[Flags]
internal enum SICHINTF : uint
{
SICHINT_DISPLAY = 0x00000000,
SICHINT_ALLFIELDS = 0x80000000,
SICHINT_CANONICAL = 0x10000000,
SICHINT_TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000
}
}
|
@using Bootstrap4._3
@namespace Bootstrap4._3.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace AGCSE
{
public class clsView : clsItemBase
{
private ActiveGanttCSECtl mp_oControl;
private clsTimeLine mp_oTimeLine;
private clsClientArea mp_oClientArea;
private String mp_sTag;
private E_INTERVAL mp_yScrollInterval;
private E_INTERVAL mp_yInterval;
private int mp_lFactor;
public clsView(ActiveGanttCSECtl Value)
{
mp_oControl = Value;
mp_yInterval = E_INTERVAL.IL_MINUTE;
mp_lFactor = 1;
mp_yScrollInterval = E_INTERVAL.IL_HOUR;
mp_oTimeLine = new clsTimeLine(mp_oControl, this);
mp_oClientArea = new clsClientArea(mp_oControl, mp_oTimeLine);
mp_sTag = "";
}
~clsView()
{
}
public String Key
{
get
{
return mp_sKey;
}
set
{
mp_oControl.Views.oCollection.mp_SetKey(ref mp_sKey, value, SYS_ERRORS.VIEWS_SET_KEY);
}
}
public clsTimeLine TimeLine
{
get
{
return mp_oTimeLine;
}
}
public clsClientArea ClientArea
{
get
{
return mp_oClientArea;
}
}
public String Tag
{
get
{
return mp_sTag;
}
set
{
mp_sTag = value;
}
}
internal E_INTERVAL f_ScrollInterval
{
get
{
return mp_yScrollInterval;
}
}
public E_INTERVAL Interval
{
get
{
return mp_yInterval;
}
set
{
mp_yInterval = value;
if (mp_yInterval == E_INTERVAL.IL_YEAR)
{
mp_yScrollInterval = E_INTERVAL.IL_YEAR;
}
else
{
mp_yScrollInterval = mp_yInterval + 1;
}
}
}
public int Factor
{
get
{
return mp_lFactor;
}
set
{
mp_lFactor = value;
}
}
public String GetXML()
{
clsXML oXML = new clsXML(mp_oControl, "View");
oXML.InitializeWriter();
oXML.WriteProperty("Interval", mp_yInterval);
oXML.WriteProperty("Factor", mp_lFactor);
oXML.WriteProperty("Key", mp_sKey);
oXML.WriteProperty("Tag", mp_sTag);
oXML.WriteObject(mp_oClientArea.GetXML());
oXML.WriteObject(mp_oTimeLine.GetXML());
return oXML.GetXML();
}
public void SetXML(String sXML)
{
clsXML oXML = new clsXML(mp_oControl, "View");
oXML.SetXML(sXML);
oXML.InitializeReader();
oXML.ReadProperty("Tag", ref mp_sTag);
oXML.ReadProperty("Interval", ref mp_yInterval);
oXML.ReadProperty("Factor", ref mp_lFactor);
mp_oClientArea.SetXML(oXML.ReadObject("ClientArea"));
mp_oTimeLine.SetXML(oXML.ReadObject("TimeLine"));
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class ItemsCollector : MonoBehaviour
{
private Dictionary<ItemData, int> _containedItems;
public event Action onContainedItemsChanged;
private void Awake()
{
_containedItems = new Dictionary<ItemData, int>();
}
public void Put(ItemData itemData)
{
if (_containedItems.ContainsKey(itemData))
{
_containedItems[itemData]++;
}
else
_containedItems[itemData] = 1;
onContainedItemsChanged?.Invoke();
}
private void RemoveCount(ItemData itemData, int count, bool canRemoveMoreThanHad = false)
{
if (GetCount(itemData) == 0)
return;
if (!canRemoveMoreThanHad && _containedItems[itemData] - count < 0)
return;
if ((_containedItems[itemData] -= count) <= 0)
_containedItems.Remove(itemData);
onContainedItemsChanged?.Invoke();
}
public void RemoveOne(ItemData itemData)
{
RemoveCount(itemData, 1);
}
public void RemoveAll(ItemData itemData)
{
RemoveCount(itemData, int.MaxValue, true);
}
public int GetCount(ItemData itemData)
{
foreach (var i in _containedItems)
{
if (i.Key == itemData)
{
return i.Value;
}
}
return 0;
}
public IEnumerable<ItemData> GetItems(Predicate<ItemData> predicate)
{
return from kvp in _containedItems
where predicate(kvp.Key)
select kvp.Key;
}
}
|
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using xe.data.service.Models;
using xe.data.service.Services.Interfaces;
namespace xe.data.service.Services
{
public class ConfigurationReader : IConfigurationReader
{
public List<ConfigurationEntry> ReadConfiguration()
{
return JsonConvert.DeserializeObject<List<ConfigurationEntry>>(File.ReadAllText("config.json"));
}
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using Xunit;
namespace Microsoft.Azure.WebJobs.Host.UnitTests.Hosting
{
public class FunctionDataCacheKeyTests
{
[Fact]
public void GetHashCode_UsesIdAndVersion()
{
string id = "foo";
string version = "bar";
FunctionDataCacheKey key = new FunctionDataCacheKey(id, version);
int hashId = id.GetHashCode();
int versionHash = version.GetHashCode();
int combinedHash = hashId ^ versionHash;
Assert.Equal(combinedHash, key.GetHashCode());
}
[Fact]
public void LookupKeyInSet_EnsureFound()
{
HashSet<FunctionDataCacheKey> set = new HashSet<FunctionDataCacheKey>();
string id = "foo";
string version = "bar";
FunctionDataCacheKey key = new FunctionDataCacheKey(id, version);
Assert.True(set.Add(key));
Assert.Contains(new FunctionDataCacheKey(id, version), set);
}
[Fact]
public void LookupKeyInSetWithEqualIdUnequalVersion_EnsureNotFound()
{
HashSet<FunctionDataCacheKey> set = new HashSet<FunctionDataCacheKey>();
string id = "foo";
string version1 = "bar1";
FunctionDataCacheKey key = new FunctionDataCacheKey(id, version1);
Assert.True(set.Add(key));
Assert.Contains(new FunctionDataCacheKey(id, version1), set);
string version2 = "bar2";
Assert.DoesNotContain(new FunctionDataCacheKey(id, version2), set);
}
[Fact]
public void LookupKeyInSetWithEqualVersionUnequalId_EnsureNotFound()
{
HashSet<FunctionDataCacheKey> set = new HashSet<FunctionDataCacheKey>();
string id1 = "foo1";
string version = "bar";
FunctionDataCacheKey key = new FunctionDataCacheKey(id1, version);
Assert.True(set.Add(key));
Assert.Contains(new FunctionDataCacheKey(id1, version), set);
string id2 = "foo2";
Assert.DoesNotContain(new FunctionDataCacheKey(id2, version), set);
}
[Fact]
public void CompareEqualKeys_EnsureEqual()
{
string id = "foo";
string version = "bar";
FunctionDataCacheKey key1 = new FunctionDataCacheKey(id, version);
FunctionDataCacheKey key2 = new FunctionDataCacheKey(id, version);
Assert.Equal(key1, key2);
}
[Fact]
public void CompareKeysWithEqualIdUnequalVersion_EnsureUnequal()
{
string id = "foo";
string version1 = "bar1";
FunctionDataCacheKey key1 = new FunctionDataCacheKey(id, version1);
string version2 = "bar2";
FunctionDataCacheKey key2 = new FunctionDataCacheKey(id, version2);
Assert.NotEqual(key1, key2);
}
[Fact]
public void CompareKeysWithEqualVersionUnequalId_EnsureUnequal()
{
string id1 = "foo1";
string version = "bar";
FunctionDataCacheKey key1 = new FunctionDataCacheKey(id1, version);
string id2 = "id2";
FunctionDataCacheKey key2 = new FunctionDataCacheKey(id2, version);
Assert.NotEqual(key1, key2);
}
}
}
|
using UnityEngine;
using System.Collections;
public class EnemyMotion : MonoBehaviour {
private float charaSizeX;
private float charaSizeY;
void Start()
{
charaSizeX = this.GetComponent<RectTransform>().sizeDelta.x;
}
void FixedUpdate()
{
charaSizeY = Mathf.PingPong(Time.time * 2, 1) * 5 + this.GetComponent<RectTransform>().sizeDelta.x;
this.GetComponent<RectTransform>().sizeDelta = new Vector2(charaSizeX, charaSizeY);
}
}
|
/*
* Copyright 2018 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : Server Shell
* Summary : The phrases used in the Server shell
*
* Author : Mikhail Shiryaev
* Created : 2018
* Modified : 2018
*/
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace Scada.Server.Shell.Code
{
/// <summary>
/// The phrases used in the Server shell.
/// <para>Фразы, используемые оболочкой Сервера.</para>
/// </summary>
public class ServerShellPhrases
{
// Scada.Server.Shell.Code.ServerShell
public static string CommonParamsNode { get; private set; }
public static string SaveParamsNode { get; private set; }
public static string ArchiveNode { get; private set; }
public static string CurDataNode { get; private set; }
public static string MinDataNode { get; private set; }
public static string HourDataNode { get; private set; }
public static string EventsNode { get; private set; }
public static string ModulesNode { get; private set; }
public static string GeneratorNode { get; private set; }
public static string StatsNode { get; private set; }
// Scada.Server.Shell.Forms
public static string ConnectionUndefined { get; private set; }
public static string Loading { get; private set; }
// Scada.Server.Shell.Forms.FrmCommonParams
public static string ChooseItfDir { get; private set; }
public static string ChooseArcDir { get; private set; }
public static string ChooseArcCopyDir { get; private set; }
// Scada.Server.Shell.Forms.FrmModules
public static string ModuleNotFound { get; private set; }
public static void Init()
{
Localization.Dict dict = Localization.GetDictionary("Scada.Server.Shell.Code.ServerShell");
CommonParamsNode = dict.GetPhrase("CommonParamsNode");
SaveParamsNode = dict.GetPhrase("SaveParamsNode");
ArchiveNode = dict.GetPhrase("ArchiveNode");
CurDataNode = dict.GetPhrase("CurDataNode");
MinDataNode = dict.GetPhrase("MinDataNode");
HourDataNode = dict.GetPhrase("HourDataNode");
EventsNode = dict.GetPhrase("EventsNode");
ModulesNode = dict.GetPhrase("ModulesNode");
GeneratorNode = dict.GetPhrase("GeneratorNode");
StatsNode = dict.GetPhrase("StatsNode");
dict = Localization.GetDictionary("Scada.Server.Shell.Forms");
ConnectionUndefined = dict.GetPhrase("ConnectionUndefined");
Loading = dict.GetPhrase("Loading");
dict = Localization.GetDictionary("Scada.Server.Shell.Forms.FrmCommonParams");
ChooseItfDir = dict.GetPhrase("ChooseItfDir");
ChooseArcDir = dict.GetPhrase("ChooseArcDir");
ChooseArcCopyDir = dict.GetPhrase("ChooseArcCopyDir");
dict = Localization.GetDictionary("Scada.Server.Shell.Forms.FrmModules");
ModuleNotFound = dict.GetPhrase("ModuleNotFound");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PenghargaanControl : MonoBehaviour
{
public GameObject penghargaanContainer;
public GameObject penghargaanContentContainer;
public GameObject penghargaanEarn;
public GameObject penghargaanEarnUI;
public GameObject penghargaanPrefab;
private bool isShown = false;
private float dx;
private float dy;
private int mod = 4;
// Use this for initialization
void Start()
{
dx = penghargaanPrefab.GetComponent<Image>().rectTransform.rect.width;
dx += dx / 2;
dy = penghargaanPrefab.GetComponent<Image>().rectTransform.rect.height;
dy += dy / 2;
layoutPenghargaan();
showPenghargaan();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && !isShown)
{
showPenghargaan();
}
}
public void open()
{
penghargaanContainer.SetActive(true);
}
public void close()
{
penghargaanContainer.SetActive(false);
}
public void showPenghargaan()
{
PenghargaanController pc = PenghargaanController.self;
Penghargaan p = pc.getEarnedPenghargaan();
if (p != null)
{
Debug.Log(p.name);
Image image = penghargaanEarnUI.GetComponent<Image>();
Sprite s = Resources.Load<Sprite>("Penghargaan/Gambar/" + p.imageName);
image.sprite = s;
penghargaanEarn.SetActive(true);
}
else
{
penghargaanEarn.SetActive(false);
Destroy(penghargaanEarn);
isShown = true;
}
}
void layoutPenghargaan()
{
PenghargaanContainer pc = PenghargaanContainer.self;
AccountContainer ac = AccountContainer.self;
int index = 0;
foreach (Penghargaan p in pc.penghargaans)
{
Transform a = Instantiate(penghargaanPrefab.transform, penghargaanContentContainer.transform);
a.localPosition += new Vector3((index % 4) * dx, (index / 4) * dy * -1, 0);
//a.localPosition = new Vector3(oriX + (index % 5) * dx, oriY + (index / 5) * dy, 0);
a.gameObject.name = p.name;
a.gameObject.SetActive(true);
index++;
if (ac.currentAccount.getPenghargaan(p))
{
a.GetComponent<Image>().sprite = Resources.Load<Sprite>("Penghargaan/Gambar/" + p.imageName);
}
}
}
}
|
using System;
using MassTransit.Azure.ServiceBus.Core;
namespace Younited.MassTransit.Trigger.Config.Infrastructure
{
public interface IServiceBusHostConfiguration
{
Uri ServiceUri { get; }
void ConfigureHost(IServiceBusHostConfigurator configurator);
}
}
|
// 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 Microsoft.Cci;
using Microsoft.Cci.Mappings;
namespace Microsoft.DotNet.AsmDiff.CSV
{
public sealed class DiffVisibiliyCsvColumn : DiffCsvColumn
{
public DiffVisibiliyCsvColumn(DiffConfiguration diffConfiguration)
: base(diffConfiguration)
{
}
public override string Name
{
get { return "Visibility"; }
}
public override string GetValue(TypeMapping mapping)
{
var visibility = TypeHelper.TypeVisibilityAsTypeMemberVisibility(mapping.Representative);
return visibility.ToString();
}
public override string GetValue(MemberMapping mapping)
{
var visibility = mapping.Representative.Visibility;
return visibility.ToString();
}
}
}
|
namespace Windows32
{
public enum SystemMetricsConst
{
SM_CXSCREEN = 0,
SM_CYSCREEN = 1,
SM_CXVSCROLL = 2,
SM_CYHSCROLL = 3,
SM_CYCAPTION = 4,
SM_CXBORDER = 5,
SM_CYBORDER = 6,
SM_CXDLGFRAME = 7,
SM_CYDLGFRAME = 8,
SM_CYVTHUMB = 9,
SM_CXHTHUMB = 10,
SM_CXICON = 11,
SM_CYICON = 12,
SM_CXCURSOR = 13,
SM_CYCURSOR = 14,
SM_CYMENU = 0xF,
SM_CXFULLSCREEN = 0x10,
SM_CYFULLSCREEN = 17,
SM_CYKANJIWINDOW = 18,
SM_MOUSEPRESENT = 19,
SM_CYVSCROLL = 20,
SM_CXHSCROLL = 21,
SM_DEBUG = 22,
SM_SWAPBUTTON = 23,
SM_RESERVED1 = 24,
SM_RESERVED2 = 25,
SM_RESERVED3 = 26,
SM_RESERVED4 = 27,
SM_CXMIN = 28,
SM_CYMIN = 29,
SM_CXSIZE = 30,
SM_CYSIZE = 0x1F,
SM_CXFRAME = 0x20,
SM_CYFRAME = 33,
SM_CXMINTRACK = 34,
SM_CYMINTRACK = 35,
SM_CXDOUBLECLK = 36,
SM_CYDOUBLECLK = 37,
SM_CXICONSPACING = 38,
SM_CYICONSPACING = 39,
SM_MENUDROPALIGNMENT = 40,
SM_PENWINDOWS = 41,
SM_DBCSENABLED = 42,
SM_CMOUSEBUTTONS = 43,
SM_SECURE = 44,
SM_CXEDGE = 45,
SM_CYEDGE = 46,
SM_CXMINSPACING = 47,
SM_CYMINSPACING = 48,
SM_CXSMICON = 49,
SM_CYSMICON = 50,
SM_CYSMCAPTION = 51,
SM_CXSMSIZE = 52,
SM_CYSMSIZE = 53,
SM_CXMENUSIZE = 54,
SM_CYMENUSIZE = 55,
SM_ARRANGE = 56,
SM_CXMINIMIZED = 57,
SM_CYMINIMIZED = 58,
SM_CXMAXTRACK = 59,
SM_CYMAXTRACK = 60,
SM_CXMAXIMIZED = 61,
SM_CYMAXIMIZED = 62,
SM_NETWORK = 0x3F,
SM_CLEANBOOT = 67,
SM_CXDRAG = 68,
SM_CYDRAG = 69,
SM_SHOWSOUNDS = 70,
SM_CXMENUCHECK = 71,
SM_CYMENUCHECK = 72,
SM_SLOWMACHINE = 73,
SM_MIDEASTENABLED = 74,
SM_MOUSEWHEELPRESENT = 75,
SM_XVIRTUALSCREEN = 76,
SM_YVIRTUALSCREEN = 77,
SM_CXVIRTUALSCREEN = 78,
SM_CYVIRTUALSCREEN = 79,
SM_CMONITORS = 80,
SM_SAMEDISPLAYFORMAT = 81,
SM_CMETRICS = 83
}
}
|
namespace PnP.Core.Model.SharePoint
{
/// <summary>
/// Statistics for a given action
/// </summary>
public interface IActivityActionStat
{
/// <summary>
/// The number of times the action took place.
/// </summary>
int ActionCount { get; }
/// <summary>
/// The number of distinct actors that performed the action.
/// </summary>
int ActorCount { get; }
/// <summary>
/// The time (seconds) spent for the performed action.
/// </summary>
int TimeSpentInSeconds { get; }
}
}
|
using System;
using System.Collections.Generic;
namespace RoadFlow.Data.Interface
{
public interface IUsersRole
{
/// <summary>
/// 新增
/// </summary>
int Add(RoadFlow.Data.Model.UsersRole model);
/// <summary>
/// 更新
/// </summary>
int Update(RoadFlow.Data.Model.UsersRole model);
/// <summary>
/// 查询所有记录
/// </summary>
List<RoadFlow.Data.Model.UsersRole> GetAll();
/// <summary>
/// 查询单条记录
/// </summary>
Model.UsersRole Get(Guid memberid, Guid roleid);
/// <summary>
/// 删除
/// </summary>
int Delete(Guid memberid, Guid roleid);
/// <summary>
/// 查询记录条数
/// </summary>
long GetCount();
/// <summary>
/// 删除一个机构所有记录
/// </summary>
int DeleteByUserID(Guid userID);
/// <summary>
/// 删除一个角色所有记录
/// </summary>
int DeleteByRoleID(Guid roleid);
/// <summary>
/// 根据一组机构ID查询记录
/// </summary>
List<RoadFlow.Data.Model.UsersRole> GetByUserIDArray(Guid[] userIDArray);
/// <summary>
/// 根据人员ID查询记录
/// </summary>
List<RoadFlow.Data.Model.UsersRole> GetByUserID(Guid userID);
}
}
|
using System.Text;
using SequelNet.Connector;
namespace SequelNet.Phrases
{
/// <summary>
/// This will return value in meters
/// </summary>
public class GeographyContains : IPhrase
{
public ValueWrapper Outer;
public ValueWrapper Inner;
#region Construcinnerrs
public GeographyContains(
ValueWrapper outer,
ValueWrapper inner)
{
this.Outer = outer;
this.Inner = inner;
}
public GeographyContains(
object outerValue, ValueObjectType outerValueType,
object innerValue, ValueObjectType innerValueType)
{
this.Outer = ValueWrapper.Make(outerValue, outerValueType);
this.Inner = ValueWrapper.Make(innerValue, innerValueType);
}
public GeographyContains(
object outerValue, ValueObjectType outerValueType,
string innerColumnName)
{
this.Outer = ValueWrapper.Make(outerValue, outerValueType);
this.Inner = ValueWrapper.Column(innerColumnName);
}
public GeographyContains(
object outerValue, ValueObjectType outerValueType,
string innerTableName, string innerColumnName)
{
this.Outer = ValueWrapper.Make(outerValue, outerValueType);
this.Inner = ValueWrapper.Column(innerTableName, innerColumnName);
}
public GeographyContains(
Geometry outerValue,
string innerColumnName)
{
this.Outer = ValueWrapper.From(outerValue);
this.Inner = ValueWrapper.Column(innerColumnName);
}
public GeographyContains(
Geometry outerValue,
string innerTableName, string innerColumnName)
{
this.Outer = ValueWrapper.From(outerValue);
this.Inner = ValueWrapper.Column(innerTableName, innerColumnName);
}
public GeographyContains(Geometry outerValue, Geometry innerValue)
{
this.Outer = ValueWrapper.From(outerValue);
this.Inner = ValueWrapper.From(innerValue);
}
public GeographyContains(
string outerColumnName,
Geometry innerObject)
{
this.Outer = ValueWrapper.Column(outerColumnName);
this.Inner = ValueWrapper.From(innerObject);
}
public GeographyContains(
string outerTableName, string outerColumnName,
Geometry innerObject)
{
this.Outer = ValueWrapper.Column(outerTableName, outerColumnName);
this.Inner = ValueWrapper.From(innerObject);
}
#endregion
public void Build(StringBuilder sb, ConnectorBase conn, Query relatedQuery = null)
{
sb.Append(conn.Language.ST_Distance_Sphere(
Outer.Build(conn, relatedQuery),
Inner.Build(conn, relatedQuery)));
}
}
}
|
using System;
using System.Collections.Generic;
namespace Statistics
{
public interface IAlerter
{
void sendAlerts();
}
} |
using System;
namespace Framework.Core
{
public static class LazyHelper
{
public static Lazy<TResult> Create<TResult>(Func<TResult> func)
{
if (func == null) throw new ArgumentNullException(nameof(func));
return new Lazy<TResult>(func);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebUI.Areas.Admin.Models.DashboardVM
{
public class IndexTwoViewModel
{
/// <summary>
/// 操作系统
/// </summary>
public string ServerVer
{
get
{
return Environment.OSVersion.ToString();
}
}
/// <summary>
/// 服务器名称
/// </summary>
public string ServerName { get; set; }
/// <summary>
/// 服务器IP
/// </summary>
public string ServerIp { get; set; }
/// <summary>
/// 服务端脚本执行超时
/// </summary>
public string ServerOutTime { get; set; }
/// <summary>
/// Application总数
/// </summary>
public int ServerApplicationTotal { get; set; }
/// <summary>
/// IIS版本
/// </summary>
public string IISVer { get; set; }
/// <summary>
/// .NET Framework 版本
/// </summary>
public string NetVer { get; set; }
/// <summary>
/// CPU 数量
/// </summary>
public int CpuNum { get; set; }
}
} |
using SendGrid;
namespace GreatIdeas.MailServices;
public interface ISendGridService
{
/// <summary>
/// Send emailModel using SendGrid API
/// </summary>
/// <param name="emailModel"><see cref="EmailModel"/></param>
/// <returns>SendGrid <see cref="Response"/></returns>
Task<Response> SendEmailAsync(EmailModel emailModel);
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BgMoving : MonoBehaviour
{
float scale;
bool up_scale;
Vector3 original_scale;
// Start is called before the first frame update
void Start()
{
up_scale = true;
scale = 1.0f;
original_scale = transform.localScale;
}
// Update is called once per frame
void Update()
{
if (up_scale)
{
scale += 0.0002f;
if (scale > 1.03f)
{
scale = 1.03f;
up_scale = false;
}
}
else
{
scale -= 0.0002f;
if (scale < 1.00f)
{
scale = 1.00f;
up_scale = true;
}
}
var tmpScale = transform.localScale;
tmpScale = original_scale * scale;
transform.localScale = tmpScale;
//transform.rotation = new Vector3(0, 0, scale * 10);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace EstouAVer.Tables
{
public class User
{
public string username { get; }
public string rep { get; }
public string salt { get; }
public User(string username, string rep, string salt)
{
this.username = username;
this.rep = rep;
this.salt = salt;
}
}
}
|
using System;
using PX.Objects;
using PX.Data;
namespace PX.SM.BoxStorageProvider
{
public class SMAccessPersonalMaint_Extension : PXGraphExtension<SMAccessPersonalMaint>
{
public PXAction<Users> redirectToBoxUserProfile;
[PXUIField(DisplayName = Messages.BoxUserProfile)]
[PXButton()]
public void RedirectToBoxUserProfile()
{
var graph = PXGraph.CreateInstance<UserProfile>();
PXRedirectHelper.TryRedirect(graph, PXRedirectHelper.WindowMode.Same);
}
}
} |
using System;
namespace _07.ExchangeVariableValues
{
class ExchangeVariableValues
{
static void Main(string[] args)
{
var a = Console.ReadLine();
var b = Console.ReadLine();
Console.WriteLine("Before:");
Console.WriteLine($"a = {a}");
Console.WriteLine($"b = {b}");
var oldA = b;
var oldB = a;
Console.WriteLine("After:");
Console.WriteLine($"a = {oldA}");
Console.WriteLine($"b = {oldB}");
}
}
}
|
namespace MVP.Api
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MADE.Networking.Http.Requests.Json;
using MVP.Api.Models.MicrosoftAccount;
using Newtonsoft.Json;
/// <summary>
/// Defines a mechanism to call into the MVP API from a client application.
/// </summary>
public partial class ApiClient
{
private const string BaseApiUri = "https://mvpapi.azure-api.net/mvp/api";
private readonly HttpClient httpClient;
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient"/> class.
/// </summary>
/// <param name="clientId">
/// The Microsoft application client ID.
/// </param>
/// <param name="clientSecret">
/// The Microsoft application client secret.
/// </param>
/// <param name="subscriptionKey">
/// The MVP API subscription key.
/// </param>
/// <param name="isLiveSdkApp">
/// A value indicating whether the client ID and secret are associated with an older Live SDK application.
/// </param>
public ApiClient(string clientId, string clientSecret, string subscriptionKey, bool isLiveSdkApp = false)
{
this.ClientId = clientId;
this.ClientSecret = clientSecret;
this.SubscriptionKey = subscriptionKey;
this.IsLiveSdkApp = isLiveSdkApp;
this.httpClient = new HttpClient();
}
/// <summary>
/// Gets a value indicating whether the client ID and secret are from an older Live SDK application.
/// </summary>
/// <remarks>
/// If you're using a newer 'Converged application', this should be false.
/// If you're using an older 'Live SDK application', this should be true.
/// Find your apps here: https://apps.dev.microsoft.com/?mkt=en-us#/appList.
/// </remarks>
public bool IsLiveSdkApp { get; }
/// <summary>
/// Gets the Microsoft application client ID.
/// </summary>
public string ClientId { get; }
/// <summary>
/// Gets the Microsoft application client secret.
/// </summary>
public string ClientSecret { get; }
/// <summary>
/// Gets the MVP API subscription key.
/// </summary>
public string SubscriptionKey { get; }
/// <summary>
/// Gets or sets the credentials associated with the logged in Microsoft account.
/// </summary>
public MSACredentials Credentials { get; set; }
private async Task<TResponse> GetAsync<TResponse>(
string endpoint,
bool useCredentials = true,
string overrideUri = null,
CancellationToken cancellationToken = default)
{
string uri = string.IsNullOrWhiteSpace(overrideUri) ? $"{BaseApiUri}/{endpoint}" : overrideUri;
JsonGetNetworkRequest getRequest = useCredentials
? new JsonGetNetworkRequest(
this.httpClient,
uri,
this.GetRequestHeaders())
: new JsonGetNetworkRequest(this.httpClient, uri);
bool retryCall = false;
try
{
return await getRequest.ExecuteAsync<TResponse>(cancellationToken);
}
catch (HttpRequestException hre) when (hre.Message.Contains("401"))
{
MSACredentials tokenRefreshed = await this.ExchangeRefreshTokenAsync(cancellationToken);
if (tokenRefreshed != null)
{
retryCall = true;
}
}
if (!retryCall)
{
return default;
}
getRequest = useCredentials
? new JsonGetNetworkRequest(this.httpClient, uri, this.GetRequestHeaders())
: new JsonGetNetworkRequest(this.httpClient, uri);
return await getRequest.ExecuteAsync<TResponse>(cancellationToken);
}
private async Task<bool> PostAsync(
string endpoint,
object data,
bool useCredentials = true,
string overrideUri = null,
CancellationToken cancellationToken = default)
{
try
{
await this.PostAsync<object>(endpoint, data, useCredentials, overrideUri, cancellationToken);
return true;
}
catch (Exception)
{
return false;
}
}
private async Task<TResponse> PostAsync<TResponse>(
string endpoint,
object data,
bool useCredentials = true,
string overrideUri = null,
CancellationToken cancellationToken = default)
{
string uri = string.IsNullOrWhiteSpace(overrideUri) ? $"{BaseApiUri}/{endpoint}" : overrideUri;
JsonPostNetworkRequest postRequest = useCredentials
? new JsonPostNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty,
this.GetRequestHeaders())
: new JsonPostNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty);
bool retryCall = false;
try
{
return await postRequest.ExecuteAsync<TResponse>(cancellationToken);
}
catch (HttpRequestException hre) when (hre.Message.Contains("401"))
{
MSACredentials tokenRefreshed = await this.ExchangeRefreshTokenAsync(cancellationToken);
if (tokenRefreshed != null)
{
retryCall = true;
}
}
if (!retryCall)
{
return default;
}
postRequest = useCredentials
? new JsonPostNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty,
this.GetRequestHeaders())
: new JsonPostNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty);
return await postRequest.ExecuteAsync<TResponse>(cancellationToken);
}
private async Task<bool> PutAsync(
string endpoint,
object data,
bool useCredentials = true,
string overrideUri = null,
CancellationToken cancellationToken = default)
{
string uri = string.IsNullOrWhiteSpace(overrideUri) ? $"{BaseApiUri}/{endpoint}" : overrideUri;
JsonPutNetworkRequest putRequest = useCredentials
? new JsonPutNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty,
this.GetRequestHeaders())
: new JsonPutNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty);
bool retryCall = false;
try
{
await putRequest.ExecuteAsync<string>(cancellationToken);
return true;
}
catch (HttpRequestException hre) when (hre.Message.Contains("401"))
{
MSACredentials tokenRefreshed = await this.ExchangeRefreshTokenAsync(cancellationToken);
if (tokenRefreshed != null)
{
retryCall = true;
}
}
if (!retryCall)
{
return false;
}
putRequest = useCredentials
? new JsonPutNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty,
this.GetRequestHeaders())
: new JsonPutNetworkRequest(
this.httpClient,
uri,
data != null ? JsonConvert.SerializeObject(data) : string.Empty);
await putRequest.ExecuteAsync<string>(cancellationToken);
return true;
}
private async Task<bool> DeleteAsync(
string endpoint,
bool useCredentials = true,
string overrideUri = null,
CancellationToken cancellationToken = default)
{
string uri = string.IsNullOrWhiteSpace(overrideUri) ? $"{BaseApiUri}/{endpoint}" : overrideUri;
JsonDeleteNetworkRequest deleteRequest = useCredentials
? new JsonDeleteNetworkRequest(
this.httpClient,
uri,
this.GetRequestHeaders())
: new JsonDeleteNetworkRequest(this.httpClient, uri);
bool retryCall = false;
try
{
await deleteRequest.ExecuteAsync<string>(cancellationToken);
return true;
}
catch (HttpRequestException hre) when (hre.Message.Contains("401"))
{
MSACredentials tokenRefreshed = await this.ExchangeRefreshTokenAsync(cancellationToken);
if (tokenRefreshed != null)
{
retryCall = true;
}
}
if (!retryCall)
{
return false;
}
deleteRequest = useCredentials
? new JsonDeleteNetworkRequest(this.httpClient, uri, this.GetRequestHeaders())
: new JsonDeleteNetworkRequest(this.httpClient, uri);
await deleteRequest.ExecuteAsync<string>(cancellationToken);
return true;
}
private Dictionary<string, string> GetRequestHeaders()
{
if (this.Credentials == null || string.IsNullOrWhiteSpace(this.Credentials.AccessToken))
{
return new Dictionary<string, string>();
}
var headers = new Dictionary<string, string>
{
{"Authorization", $"Bearer {this.Credentials.AccessToken}"},
{"Ocp-Apim-Subscription-Key", this.SubscriptionKey},
};
return headers;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StdPaint
{
internal static class Utils
{
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
public static int Mod(int x, int m)
{
int r = x % m;
return r < 0 ? r + m : r;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Macad.Core.Shapes;
using Macad.Presentation;
using Macad.Common;
using Macad.Core;
using Macad.Interaction.Panels;
namespace Macad.Interaction.Editors.Shapes
{
public partial class SketchConstraintsPropertyPanel : PropertyPanel
{
public class ConstraintData : BaseObject
{
public Sketch Sketch { get; }
public SketchConstraint Constraint { get; set; }
public string Type { get; set; }
public string Info { get; set; }
public double Parameter { get; set; }
public string ParameterName { get; set; }
public string ToggleName { get; set; }
public bool ToggleState { get; set; }
public ValueUnits Units { get; set; }
//--------------------------------------------------------------------------------------------------
public static RelayCommand<ConstraintData> ToggleCommand { get; } = new(
(constraintData) => { constraintData._Toggle(); }
);
//--------------------------------------------------------------------------------------------------
void _Toggle()
{
if (Constraint is SketchConstraintSmoothCorner smoothCornerConstraint)
{
Sketch.SaveUndo(Sketch.ElementType.Constraint);
smoothCornerConstraint.Symmetric = !smoothCornerConstraint.Symmetric;
ToggleState = smoothCornerConstraint.Symmetric;
Sketch.OnElementsChanged(Sketch.ElementType.Constraint);
Sketch.SolveConstraints(true);
Sketch.Invalidate();
InteractiveContext.Current.UndoHandler.Commit();
RaisePropertyChanged(nameof(ToggleState));
}
}
//--------------------------------------------------------------------------------------------------
internal ConstraintData(Sketch sketch, SketchConstraint constraint, bool swapOrientation)
{
Sketch = sketch;
Constraint = constraint;
Info = "";
if ((constraint.Points != null) && constraint.Points.Any())
{
Info += (constraint.Points.Length == 1 ? "Point " : "Points ") + string.Join(", ", constraint.Points);
if ((constraint.Segments != null) && constraint.Segments.Any())
{
Info += " ";
}
}
if ((constraint.Segments != null) && constraint.Segments.Any())
{
Info += (constraint.Segments.Length == 1 ? "Segment " : "Segments ") + string.Join(", ", constraint.Segments);
}
switch (constraint)
{
case SketchConstraintPerpendicular _:
Type = "Perpendicular";
break;
case SketchConstraintHorizontal _:
Type = swapOrientation ? "Vertical" : "Horizontal";
break;
case SketchConstraintVertical _:
Type = swapOrientation ? "Horizontal" : "Vertical";
break;
case SketchConstraintParallel _:
Type = "Parallel";
break;
case SketchConstraintConcentric _:
Type = "Concentric";
break;
case SketchConstraintPointOnSegment _:
Type = "Point on Segment";
break;
case SketchConstraintPointOnMidpoint _:
Type = "Point on Midpoint";
break;
case SketchConstraintFixed fixedConstraint:
switch (fixedConstraint.Target)
{
case SketchConstraintFixed.TargetType.Point:
Type = "Fix Point";
break;
case SketchConstraintFixed.TargetType.Segment:
Type = "Fix Segment";
break;
}
break;
case SketchConstraintEqual _:
Type = "Equal";
break;
case SketchConstraintAngle _:
Type = "Inner Angle";
ParameterName = "Angle";
Parameter = constraint.Parameter;
Units = ValueUnits.Degree;
break;
case SketchConstraintHorizontalDistance _:
Type = swapOrientation ? "Horiz. Distance" : "Vert. Distance";
ParameterName = "Distance";
Parameter = constraint.Parameter;
Units = ValueUnits.Length;
break;
case SketchConstraintVerticalDistance _:
Type = swapOrientation ? "Vert. Distance" : "Horiz. Distance";
ParameterName = "Distance";
Parameter = constraint.Parameter;
Units = ValueUnits.Length;
break;
case SketchConstraintLength _:
Type = "Length";
ParameterName = "Length";
Parameter = constraint.Parameter;
Units = ValueUnits.Length;
break;
case SketchConstraintRadius _:
Type = "Radius";
ParameterName = "Radius";
Parameter = constraint.Parameter;
Units = ValueUnits.Length;
break;
case SketchConstraintTangent _:
Type = "Tangent";
break;
case SketchConstraintSmoothCorner smoothCornerConstraint:
Type = "Smooth Corner";
ToggleName = "Symmetric";
ToggleState = smoothCornerConstraint.Symmetric;
break;
default:
Type = "Unknown";
break;
}
}
}
//--------------------------------------------------------------------------------------------------
public SketchEditorTool SketchEditorTool
{
get { return _SketchEditorTool; }
set
{
if (_SketchEditorTool != value)
{
_SketchEditorTool = value;
RaisePropertyChanged();
}
}
}
SketchEditorTool _SketchEditorTool;
//--------------------------------------------------------------------------------------------------
public List<ConstraintData> Constraints
{
get { return _Constraints; }
set
{
if (_Constraints != value)
{
_Constraints = value;
RaisePropertyChanged();
}
}
}
List<ConstraintData> _Constraints;
//--------------------------------------------------------------------------------------------------
void SketchEditTool_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var tool = sender as SketchEditorTool;
Debug.Assert(tool != null);
if (e.PropertyName == "SelectedConstraints")
{
UpdatePointList();
}
}
//--------------------------------------------------------------------------------------------------
void UpdatePointList()
{
bool swapOrientation = false;
if(InteractiveContext.Current?.WorkspaceController?.LockWorkingPlane ?? false)
{
swapOrientation = ((int) ((InteractiveContext.Current?.WorkspaceController?.ActiveViewport?.Twist ?? 0.0 + 45.0) / 90.0) & 0x01) == 1;
}
var newConstraints = new List<ConstraintData>();
if (SketchEditorTool.SelectedConstraints != null)
{
newConstraints.AddRange(
(from selectedConstraint in SketchEditorTool.SelectedConstraints
select new ConstraintData(_SketchEditorTool.Sketch, selectedConstraint, swapOrientation)).Take(10));
}
Constraints = newConstraints;
}
//--------------------------------------------------------------------------------------------------
protected override void OnSourceUpdated(object sender, DataTransferEventArgs e)
{
var constraintData = (e.OriginalSource as Control)?.Tag as ConstraintData;
if (constraintData == null) return;
if (constraintData.ParameterName.IsNullOrEmpty())
return;
if(SketchEditorTool.Sketch.SetConstraintParameter(constraintData.Constraint, constraintData.Parameter))
CommmitChange();
}
//--------------------------------------------------------------------------------------------------
public override void Initialize(BaseObject instance)
{
SketchEditorTool = instance as SketchEditorTool;
Debug.Assert(SketchEditorTool != null);
SketchEditorTool.PropertyChanged += SketchEditTool_PropertyChanged;
WorkspaceController.ActiveViewport.PropertyChanged += _ActiveViewport_OnPropertyChanged;
InitializeComponent();
}
void _ActiveViewport_OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Viewport.Twist))
{
UpdatePointList();
}
}
//--------------------------------------------------------------------------------------------------
public override void Cleanup()
{
if (SketchEditorTool != null)
{
SketchEditorTool.PropertyChanged -= SketchEditTool_PropertyChanged;
}
WorkspaceController.ActiveViewport.PropertyChanged -= _ActiveViewport_OnPropertyChanged;
}
//--------------------------------------------------------------------------------------------------
}
}
|
using InsuranceAdvisor.Domain.Models;
using InsuranceAdvisor.WebApi.Models;
namespace InsuranceAdvisor.WebApi.Mappers
{
public static class VehicleProfileMapper
{
public static VehicleProfile ToDomain(this VehicleProfileDto dto)
=> new VehicleProfile(dto.Year);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace MocksSourceGeneratorTests
{
public class DefaultIfNotMockedTests : TestsBase
{
public DefaultIfNotMockedTests(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void ShouldGenerateWhenFlagIsSet()
{
string source = @"using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Example
{
public abstract class IExternalSystemService
{
public abstract int Add(int operand1, int operand2);
public abstract IEnumerable<bool> GetList();
public abstract bool GetBool();
public virtual async Task<decimal> GetAsync(int i)
{
await Task.Delay(2);
return 20;
}
}
class Test
{
public static string RunTest()
{
var mock = (IExternalSystemService) new MyMock()
{
ReturnDefaultIfNotMocked = true
};
var task = Task.Run<decimal>(async () => await mock.GetAsync(0));
return $""{mock.Add(5, 7)}-{mock.GetList()}-{mock.GetBool()}-{task.Result}"";
}
}
}";
var compilation = GetGeneratedOutput(source);
Assert.Equal("0--False-0", RunTest(compilation));
}
}
}
|
using Ryujinx.Common.Logging;
namespace Ryujinx.HLE.HOS.Services.Am.AppletAE.AllSystemAppletProxiesService.SystemAppletProxy
{
class IAudioController : IpcService
{
public IAudioController() { }
[Command(0)]
// SetExpectedMasterVolume(f32, f32)
public ResultCode SetExpectedMasterVolume(ServiceCtx context)
{
float appletVolume = context.RequestData.ReadSingle();
float libraryAppletVolume = context.RequestData.ReadSingle();
Logger.Stub?.PrintStub(LogClass.ServiceAm);
return ResultCode.Success;
}
[Command(1)]
// GetMainAppletExpectedMasterVolume() -> f32
public ResultCode GetMainAppletExpectedMasterVolume(ServiceCtx context)
{
context.ResponseData.Write(1f);
Logger.Stub?.PrintStub(LogClass.ServiceAm);
return ResultCode.Success;
}
[Command(2)]
// GetLibraryAppletExpectedMasterVolume() -> f32
public ResultCode GetLibraryAppletExpectedMasterVolume(ServiceCtx context)
{
context.ResponseData.Write(1f);
Logger.Stub?.PrintStub(LogClass.ServiceAm);
return ResultCode.Success;
}
[Command(3)]
// ChangeMainAppletMasterVolume(f32, u64)
public ResultCode ChangeMainAppletMasterVolume(ServiceCtx context)
{
float unknown0 = context.RequestData.ReadSingle();
long unknown1 = context.RequestData.ReadInt64();
Logger.Stub?.PrintStub(LogClass.ServiceAm);
return ResultCode.Success;
}
[Command(4)]
// SetTransparentVolumeRate(f32)
public ResultCode SetTransparentVolumeRate(ServiceCtx context)
{
float unknown0 = context.RequestData.ReadSingle();
Logger.Stub?.PrintStub(LogClass.ServiceAm);
return ResultCode.Success;
}
}
} |
/// <summary>
/// Client v2.
/// Разработанно командой Sky Games
/// sgteam.ru
/// </summary>
using UnityEngine;
using System.Collections;
public class Client: MonoBehaviour {
public Camera cam; // ссылка на нашу камеру
private Vector3 moveDirection; // вектор передвижения
private float speed = 6.0F; // скорость для внутренних расчетов
public float speedStep = 6.0f; // скорость ходьбы
public float speedShift = 9.0f; // скорость бега
public float gravity = 20.0F; // скорость падения
public float speedRotate = 4; // скорость поворота
public float jumpSpeed = 8; // высота прыжка
// Анимации
public AnimationClip a_Idle;
public float a_IdleSpeed = 1;
public AnimationClip a_Walk;
public float a_WalkSpeed = 1;
public AnimationClip a_Run;
public float a_RunSpeed = 1;
public AnimationClip a_Jump;
public float a_JumpSpeed = 1;
private string s_anim;
private CharacterController controller; // ссылка на контроллер
private float lastSynchronizationTime = 0f;
private float syncDelay = 0f;
private float syncTime = 0f;
private Vector3 syncStartPosition = Vector3.zero;
private Vector3 syncEndPosition = Vector3.zero;
private Quaternion rot; // поворот
private int numCurAnim; // номер анимации для сереализации 0 ожидание 1 ходьба 2 бег 3 прыжок
// При создании объекта со скриптом
void Awake () {
cam = transform.GetComponentInChildren<Camera>().GetComponent<Camera>();
controller = GetComponent<CharacterController>();
GetComponent<Animation>()[a_Idle.name].speed = a_IdleSpeed;
GetComponent<Animation>()[a_Walk.name].speed = a_WalkSpeed;
GetComponent<Animation>()[a_Run.name].speed = a_RunSpeed;
GetComponent<Animation>()[a_Jump.name].speed = a_JumpSpeed;
GetComponent<Animation>()[a_Idle.name].wrapMode = WrapMode.Loop;
GetComponent<Animation>()[a_Walk.name].wrapMode = WrapMode.Loop;
GetComponent<Animation>()[a_Run.name].wrapMode = WrapMode.Loop;
GetComponent<Animation>()[a_Jump.name].wrapMode = WrapMode.ClampForever;
s_anim = a_Idle.name;
numCurAnim = 0;
}
// на каждый кадр
void Update () {
if(GetComponent<NetworkView>().isMine) {
GetComponent<Animation>().CrossFade(s_anim);
if (controller.isGrounded) {
moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetKey(KeyCode.LeftShift))
speed = speedShift;
else speed = speedStep;
// Анимация ходьбы
if(Input.GetAxis("Vertical") > 0) {
if(speed == speedShift) {
s_anim = a_Run.name;
GetComponent<Animation>()[a_Run.name].speed = a_RunSpeed;
numCurAnim = 2;
} else {
s_anim = a_Walk.name;
GetComponent<Animation>()[a_Walk.name].speed = a_WalkSpeed;
numCurAnim = 1;
}
} else
if(Input.GetAxis("Vertical") < 0) {
if(speed == speedShift) {
s_anim = a_Run.name;
GetComponent<Animation>()[a_Run.name].speed = a_RunSpeed * -1;
numCurAnim = 2;
} else {
s_anim = a_Walk.name;
GetComponent<Animation>()[a_Walk.name].speed = a_WalkSpeed * -1;
numCurAnim = 1;
}
} else
if(Input.GetAxis("Vertical") == 0) {
s_anim = a_Idle.name;
numCurAnim = 0;
}
if(Input.GetKeyDown(KeyCode.Space)) {
moveDirection.y = jumpSpeed;
s_anim = a_Jump.name;
numCurAnim = 3;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
transform.Rotate(Vector3.down * speedRotate * Input.GetAxis("Horizontal") * -1, Space.World);
} else {
if(cam.enabled) {
cam.enabled = false;
cam.gameObject.GetComponent<AudioListener>().enabled = false;
}
SyncedMovement();
}
}
// Вызывается с определенной частотой. Отвечает за сереализицию переменных
void OnSerializeNetworkView (BitStream stream, NetworkMessageInfo info) {
Vector3 syncPosition = Vector3.zero;
if (stream.isWriting) {
rot = transform.rotation;
syncPosition = transform.position;
stream.Serialize(ref syncPosition);
stream.Serialize(ref rot);
stream.Serialize(ref numCurAnim);
} else {
stream.Serialize(ref syncPosition);
stream.Serialize(ref rot);
stream.Serialize(ref numCurAnim);
PlayNameAnim();
GetComponent<Animation>().CrossFade(s_anim);
transform.rotation = rot;
// Расчеты для интерполяции
// Находим время между текущим моментом и последней интерполяцией
syncTime = 0f;
syncDelay = Time.time - lastSynchronizationTime;
lastSynchronizationTime = Time.time;
syncStartPosition = transform.position;
syncEndPosition = syncPosition;
Debug.Log(GetComponent<NetworkView>().viewID + " " + syncStartPosition + " " + syncEndPosition);
}
}
// Интерполяция
private void SyncedMovement() {
syncTime += Time.deltaTime;
transform.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
}
// Определение анимации по номеру
public void PlayNameAnim () {
switch (numCurAnim) {
case 0:
s_anim = a_Idle.name;
break;
case 1:
s_anim = a_Walk.name;
break;
case 2:
s_anim = a_Run.name;
break;
case 3:
s_anim = a_Jump.name;
GetComponent<Animation>()[a_Jump.name].wrapMode = WrapMode.ClampForever;
break;
}
}
}
|
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using GitHub.DistributedTask.Expressions2.Sdk;
using GitHub.Services.WebApi.Internal;
using Newtonsoft.Json.Linq;
namespace GitHub.DistributedTask.Pipelines.ContextData
{
[DataContract]
[ClientIgnore]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class StringContextData : PipelineContextData, IString
{
public StringContextData(String value)
: base(PipelineContextDataType.String)
{
m_value = value;
}
public String Value
{
get
{
if (m_value == null)
{
m_value = String.Empty;
}
return m_value;
}
}
public override PipelineContextData Clone()
{
return new StringContextData(m_value);
}
public override JToken ToJToken()
{
return (JToken)m_value;
}
String IString.GetString()
{
return Value;
}
public override String ToString()
{
return Value;
}
public static implicit operator String(StringContextData data)
{
return data.Value;
}
public static implicit operator StringContextData(String data)
{
return new StringContextData(data);
}
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
if (m_value?.Length == 0)
{
m_value = null;
}
}
[DataMember(Name = "s", EmitDefaultValue = false)]
private String m_value;
}
}
|
using Domain.Entities;
using System.Threading.Tasks;
using Domain.Interfaces.Abstractions;
using System.Collections.Generic;
namespace Domain.Interfaces.Read
{
public interface ITaskReadRepository : IReadRepository<ToDoTask>
{
Task<ToDoTask> GetTaskWithTeamMembersByIdAsync(string id);
Task<List<ToDoTask>> GetTasksWithTeamMembersAsync();
Task<List<ToDoTask>> GetTasksWithTeamMembersByUserAsync(string userId);
}
}
|
using Microsoft.EntityFrameworkCore;
using QbQuestionsAPI.Domain.Models;
namespace QbQuestionsAPI.Persistence.Contexts
{
public class AppDbContext : DbContext
{
public DbSet<QbQuestion> QbQuestions { get; set; }
public DbSet<User> Users { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<QbQuestion>().ToTable("QbQuestions");
builder.Entity<QbQuestion>().HasKey(q => q.Id);
builder.Entity<QbQuestion>().Property(q => q.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<QbQuestion>().Property(q => q.Level).IsRequired();
builder.Entity<QbQuestion>().Property(q => q.Tournament).IsRequired().HasMaxLength(50);
builder.Entity<QbQuestion>().Property(q => q.Year).IsRequired();
builder.Entity<QbQuestion>().Property(q => q.Power).IsRequired(false);
builder.Entity<QbQuestion>().Property(q => q.Body).IsRequired();
builder.Entity<QbQuestion>().Property(q => q.Answer).IsRequired().HasMaxLength(50);
builder.Entity<QbQuestion>().Property(q => q.Notes).IsRequired(false).HasMaxLength(250);
builder.Entity<User>().ToTable("Users");
builder.Entity<User>().HasKey(u => u.Id);
builder.Entity<User>().Property(u => u.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<User>().Property(u => u.Username).IsRequired().HasMaxLength(30);
// Hashed passwords using SHA256 always have length 64
builder.Entity<User>().Property(u => u.Password).IsRequired().HasMaxLength(64);
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace Kentico.Kontent.Statiq.Lumen.Models
{
public partial class Author
{
public IEnumerable<Contact> ContactsTyped => Contacts.OfType<Contact>();
}
} |
using System;
using System.IO;
using AElf.Kernel.Blockchain.Infrastructure;
using AElf.Types;
using Google.Protobuf;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;
namespace AElf.Kernel.SmartContract.Infrastructure
{
public interface IDefaultContractZeroCodeProvider
{
SmartContractRegistration DefaultContractZeroRegistration { get; set; }
Address ContractZeroAddress { get; }
void SetDefaultContractZeroRegistrationByType(Type defaultZero);
Address GetZeroSmartContractAddress(int chainId);
}
public class DefaultContractZeroCodeProvider : IDefaultContractZeroCodeProvider, ISingletonDependency
{
private readonly IStaticChainInformationProvider _staticChainInformationProvider;
private readonly ContractOptions _contractOptions;
public DefaultContractZeroCodeProvider(IStaticChainInformationProvider staticChainInformationProvider,
IOptionsSnapshot<ContractOptions> contractOptions)
{
_staticChainInformationProvider = staticChainInformationProvider;
_contractOptions = contractOptions.Value;
}
public SmartContractRegistration DefaultContractZeroRegistration { get; set; }
public Address ContractZeroAddress => _staticChainInformationProvider.ZeroSmartContractAddress;
public void SetDefaultContractZeroRegistrationByType(Type defaultZero)
{
var dllPath = Directory.Exists(_contractOptions.GenesisContractDir)
? Path.Combine(_contractOptions.GenesisContractDir, $"{defaultZero.Assembly.GetName().Name}.dll")
: defaultZero.Assembly.Location;
var code = File.ReadAllBytes(dllPath);
DefaultContractZeroRegistration = new SmartContractRegistration()
{
Category = GetCategory(),
Code = ByteString.CopyFrom(code),
CodeHash = HashHelper.ComputeFromByteArray(code)
};
}
protected virtual int GetCategory()
{
return KernelConstants.DefaultRunnerCategory;
}
public Address GetZeroSmartContractAddress(int chainId)
{
return _staticChainInformationProvider.GetZeroSmartContractAddress(chainId);
}
}
} |
using AbhsChinese.Domain.Dto.Request.School;
using AbhsChinese.Domain.Dto.Response.School;
using AbhsChinese.Domain.Entity.School;
using AbhsChinese.Repository.RepositoryBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbhsChinese.Repository.IRepository.School
{
public interface ISchoolClassRepository : IRepositoryBase<Yw_SchoolClass>
{
List<DtoSchoolClass> GetSchoolClassList(DtoSchoolClassSearch search);
List<Yw_SchoolClass> GetSchoolClassByCourseId(int courseId, int schoolId);
Yw_SchoolClass Get(int id);
bool Update(Yw_SchoolClass entity);
int Insert(Yw_SchoolClass obj);
bool IncrementStudentCount(int classId, int count,int oper);
}
}
|
namespace SecondMonitor.F12019Connector.Datamodel.enums
{
internal enum DriverResultKind
{
Na, Inactive, Active, Finished, Disqualified, NotClassified,
}
} |
using System.Collections.Generic;
using TencentAd.Model.Enums;
namespace TencentAd.Model.UserData
{
/// <summary>
/// 上传用户行为数据
/// </summary>
public class UserActionsAddReq : TencentAdRequest
{
public UserActionsAddReq(long accountId, long userActionSetId, List<UserActionsAdd_Action> actions)
{
account_id = accountId;
user_action_set_id = userActionSetId;
this.actions = actions;
}
/// <summary>
/// 推广帐号 id,有操作权限的帐号 id,包括代理商和广告主帐号 id
/// </summary>
public long account_id { get; set; }
/// <summary>
/// 用户行为源 id
/// </summary>
public long user_action_set_id { get; set; }
public List<UserActionsAdd_Action> actions { get; set; }
}
public class UserActionsAdd_UserId
{
public string hash_imei { get; set; }
public string md5_sha256_imei { get; set; }
public string hash_idfa { get; set; }
public string md5_sha256_idfa { get; set; }
public string gdt_openid { get; set; }
public string hash_phone { get; set; }
public string sha256_phone { get; set; }
public string hash_android_id { get; set; }
public string hash_mac { get; set; }
public string oaid { get; set; }
public string md5_sha256_oaid { get; set; }
public string wechat_openid { get; set; }
public string wechat_unionid { get; set; }
public string wechat_app_id { get; set; }
}
public class UserActionsAdd_ProductInform
{
/// <summary>
/// 商品库行业
/// </summary>
public action_product_inform_type? content_type { get; set; }
public string product_catalog_id { get; set; }
public string[] product_id { get; set; }
public List<string> category_path { get; set; }
}
public class UserActionsAdd_Action
{
/// <summary>
/// 用户自定义的行为 id 标识
/// </summary>
public string external_action_id { get; set; }
/// <summary>
/// 行为发生时,客户端的时间点。UNIX 时间,单位为秒
/// </summary>
public long action_time { get; set; }
/// <summary>
/// 用户标识,app 数据上报时必填,web 数据上报时可以不填 user_id,但建议填写,方便后续优化
/// </summary>
public UserActionsAdd_UserId user_id { get; set; }
/// <summary>
/// 标准行为类型,当值为 'CUSTOM' 时表示自定义行为类型
/// </summary>
public api_action_type? action_type { get; set; }
/// <summary>
/// 自定义行为类型,当 action_type=CUSTOM 时必填
/// </summary>
public string custom_action { get; set; }
/// <summary>
/// 行为所带的参数,
/// action_param是一个Map,key 类型为 string,value 的类型支持以下几种:
/// int 或 int[] : 64位整数;
/// float 或 float[]: 最大值100000000000 (一千亿),保留3位小数精度,超过的截断,而非四舍五入;
/// boolean 或 boolean[]: 支持字面值为:true,false;
/// string 或 string[]: 字符串;
/// </summary>
public object action_param { get; set; }
/// <summary>
/// 商品信息
/// </summary>
public UserActionsAdd_ProductInform product_inform { get; set; }
/// <summary>
/// 渠道信息,标识该条行为发生在何渠道上
/// </summary>
public action_channel_type? channel { get; set; }
/// <summary>
/// url,网页回传时必须要填写 url,请填写效果数据发生 h5 页面 URL 地址
/// </summary>
public string url { get; set; }
/// <summary>
/// 跟踪信息
/// </summary>
public UserActionsAdd_Trace trace { get; set; }
}
public class UserActionsAdd_Trace
{
public string click_id { get; set; }
}
} |
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Phema.RabbitMQ.ProducerOverrides
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddRabbitMQ()
.AddConnection("connection", connection =>
{
var exchange = connection.AddDirectExchange<string>("exchange")
.AutoDelete();
var queue1 = connection.AddQueue<string>("queue1")
.AutoDelete()
.BoundTo(exchange);
var queue2 = connection.AddQueue<string>("queue2")
.AutoDelete()
.BoundTo(exchange);
connection.AddConsumer(queue1, queue2)
.Subscribe(async payload => await Console.Out.WriteLineAsync(payload));
connection.AddProducer(exchange);
});
services.AddHostedService<Worker>();
});
}
} |
using System.Collections.Generic;
using System.Net.Mail;
using Cluster.System.Api;
namespace Cluster.System.Api
{
// Role interface implemented by any class that can return one or more PostalAddresses
public interface IEmailAddressProvider : IDomainInterface
{
MailAddress DefaultEmailAddress();
}
}
|
using System;
using System.Collections.Generic;
namespace Agugu.Editor
{
public class PsdLayerConfig
{
private readonly Dictionary<string, string> _config = new Dictionary<string, string>();
public PsdLayerConfig() { }
public PsdLayerConfig(Dictionary<string, string> config)
{
_config = config;
}
public string GetValueOrDefault(string tag)
{
return _config.GetValueOrDefault(tag);
}
public bool GetLayerConfigAsBool(string tag)
{
string tagValue = _config.GetValueOrDefault(tag);
return string.Equals(tagValue, "true", StringComparison.OrdinalIgnoreCase);
}
public float GetLayerConfigAsFloat(string tag, float defaultValue)
{
string tagValue = _config.GetValueOrDefault(tag);
return !string.IsNullOrEmpty(tagValue) ? float.Parse(tagValue) : defaultValue;
}
public WidgetType GetLayerConfigAsWidgetType(string tag)
{
string taggedStringValue = GetValueOrDefault(tag);
switch (taggedStringValue)
{
case "image": return WidgetType.Image;
case "text": return WidgetType.Text;
case "empty": return WidgetType.EmptyGraphic;
default: return WidgetType.None;
}
}
public XAnchorType GetLayerConfigAsXAnchorType(string tag)
{
string taggedStringValue = GetValueOrDefault(tag);
switch (taggedStringValue)
{
case "left": return XAnchorType.Left;
case "center": return XAnchorType.Center;
case "right": return XAnchorType.Right;
case "stretch": return XAnchorType.Stretch;
default: return XAnchorType.None;
}
}
public YAnchorType GetLayerConfigAsYAnchorType(string tag)
{
string taggedStringValue = GetValueOrDefault(tag);
switch (taggedStringValue)
{
case "top": return YAnchorType.Top;
case "middle": return YAnchorType.Middle;
case "bottom": return YAnchorType.Bottom;
case "stretch": return YAnchorType.Stretch;
default: return YAnchorType.None;
}
}
}
} |
namespace Fabricdot.Domain.Core.Auditing
{
public interface IHasModifierId
{
string LastModifierId { get; }
}
} |
/*
* Copyright 2013 ThirdMotion, Inc.
*
* 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.
*/
/**
* @class strange.extensions.sequencer.impl.Sequencer
*
* @deprecated
*/
using System;
using strange.extensions.dispatcher.api;
using strange.extensions.sequencer.api;
using strange.extensions.command.impl;
using strange.framework.api;
namespace strange.extensions.sequencer.impl
{
public class Sequencer : CommandBinder, ISequencer, ITriggerable
{
public Sequencer ()
{
}
override public IBinding GetRawBinding()
{
return new SequenceBinding (resolver);
}
override public void ReactTo(object key, object data)
{
var binding = GetBinding (key) as ISequenceBinding;
if (binding != null)
{
nextInSequence (binding, data, 0);
}
}
private void removeSequence(ISequenceCommand command)
{
if (activeSequences.ContainsKey (command))
{
command.Cancel();
activeSequences.Remove (command);
}
}
private void invokeCommand(Type cmd, ISequenceBinding binding, object data, int depth)
{
var command = createCommand (cmd, data);
command.sequenceId = depth;
trackCommand (command, binding);
executeCommand (command);
ReleaseCommand (command);
}
/// Instantiate and Inject the ISequenceCommand.
new virtual protected ISequenceCommand createCommand(object cmd, object data)
{
injectionBinder.Bind<ISequenceCommand> ().To (cmd);
var command = injectionBinder.GetInstance<ISequenceCommand> ();
command.data = data;
injectionBinder.Unbind<ISequenceCommand> ();
return command;
}
private void trackCommand (ISequenceCommand command, ISequenceBinding binding)
{
activeSequences [command] = binding;
}
private void executeCommand(ISequenceCommand command)
{
if (command == null)
{
return;
}
command.Execute ();
}
public void ReleaseCommand (ISequenceCommand command)
{
if (command.retain == false)
{
if (activeSequences.ContainsKey(command))
{
var binding = activeSequences [command] as ISequenceBinding;
var data = command.data;
activeSequences.Remove (command);
nextInSequence (binding, data, command.sequenceId + 1);
}
}
}
private void nextInSequence(ISequenceBinding binding, object data, int depth)
{
var values = binding.value as object[];
if (depth < values.Length)
{
var cmd = values [depth] as Type;
invokeCommand (cmd, binding, data, depth);
}
else
{
if (binding.isOneOff)
{
Unbind (binding);
}
}
}
private void failIf(bool condition, string message, SequencerExceptionType type)
{
if (condition)
{
throw new SequencerException(message, type);
}
}
new public virtual ISequenceBinding Bind<T> ()
{
return base.Bind<T> () as ISequenceBinding;
}
new public virtual ISequenceBinding Bind (object value)
{
return base.Bind (value) as ISequenceBinding;
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace ET.WebAPI.Database.Migrations
{
public partial class latlondecimalprec : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<decimal>(
name: "Longitude",
table: "Devices",
type: "decimal(8,5)",
precision: 8,
scale: 5,
nullable: false,
oldClrType: typeof(decimal),
oldType: "decimal(9,5)",
oldPrecision: 9,
oldScale: 5);
migrationBuilder.AlterColumn<decimal>(
name: "Latitude",
table: "Devices",
type: "decimal(7,5)",
precision: 7,
scale: 5,
nullable: false,
oldClrType: typeof(decimal),
oldType: "decimal(8,5)",
oldPrecision: 8,
oldScale: 5);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<decimal>(
name: "Longitude",
table: "Devices",
type: "decimal(9,5)",
precision: 9,
scale: 5,
nullable: false,
oldClrType: typeof(decimal),
oldType: "decimal(8,5)",
oldPrecision: 8,
oldScale: 5);
migrationBuilder.AlterColumn<decimal>(
name: "Latitude",
table: "Devices",
type: "decimal(8,5)",
precision: 8,
scale: 5,
nullable: false,
oldClrType: typeof(decimal),
oldType: "decimal(7,5)",
oldPrecision: 7,
oldScale: 5);
}
}
}
|
using ExaminationSystem.Models;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace ExaminationSystem.Utils
{
/// <summary>
/// Excel帮助类
/// </summary>
public static class ExcelHelper
{
public static MemoryStream ExportExcel(List<ExportExcelInfo> exportExcelList)
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
//Excel文件的摘要信息
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "blog.csdn.net";
hssfworkbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "Export Excel";
hssfworkbook.SummaryInformation = si;
//下面代码输出的Excel有三列(姓名、年龄、性别)
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
int i = 0;
IRow row0 = sheet1.CreateRow(i++);
row0.CreateCell(0).SetCellValue("编号");
row0.CreateCell(1).SetCellValue("姓名");
row0.CreateCell(2).SetCellValue("日期");
row0.CreateCell(3).SetCellValue("场次");
row0.CreateCell(4).SetCellValue("试卷");
row0.CreateCell(5).SetCellValue("分数");
row0.CreateCell(6).SetCellValue("是否提交");
foreach (ExportExcelInfo excelInfo in exportExcelList)
{
IRow row = sheet1.CreateRow(i++);
row.CreateCell(0).SetCellValue($"{excelInfo.LogId}");
row.CreateCell(1).SetCellValue($"{excelInfo.UserName}");
row.CreateCell(2).SetCellValue($"{excelInfo.Date}");
row.CreateCell(3).SetCellValue($"{excelInfo.Part}");
row.CreateCell(4).SetCellValue($"{excelInfo.Title}");
row.CreateCell(5).SetCellValue($"{excelInfo.Score}");
row.CreateCell(6).SetCellValue($"{(excelInfo.IsSubmit ? "是" : "否")}");
}
MemoryStream ms = new MemoryStream();
hssfworkbook.Write(ms);
return ms;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.