text stringlengths 13 6.01M |
|---|
using System;
using System.Threading;
using System.Web.Mvc;
namespace DevExpress.Web.Demos {
public partial class DataViewController : DemoController {
public ActionResult CustomCallback() {
Session["SortCommand"] = String.Empty;
return DemoView("CustomCallback", Cameras.GetData());
}
public ActionResult CustomCallbackPartial() {
// Intentionally pauses server-side processing,
// to demonstrate the Loading Panel functionality.
Thread.Sleep(500);
return PartialView("CustomCallbackPartial", Cameras.GetData((string)Session["SortCommand"]));
}
public ActionResult SortData(string sortCommand) {
// Intentionally pauses server-side processing,
// to demonstrate the Loading Panel functionality.
Thread.Sleep(500);
Session["SortCommand"] = sortCommand;
return PartialView("CustomCallbackPartial", Cameras.GetData(sortCommand));
}
}
}
|
using Sentry.Extensibility;
using Sentry.Integrations;
namespace Sentry.Internal.DiagnosticSource;
internal class SentryDiagnosticListenerIntegration : ISdkIntegration
{
public void Register(IHub hub, SentryOptions options)
{
if (!options.IsPerformanceMonitoringEnabled)
{
options.Log(SentryLevel.Info, "DiagnosticSource Integration is disabled because tracing is disabled.");
options.DisableDiagnosticSourceIntegration();
return;
}
var subscriber = new SentryDiagnosticSubscriber(hub, options);
DiagnosticListener.AllListeners.Subscribe(subscriber);
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace MinecraftToolsBoxSDK
{
/// <summary>
/// JsonSelectorEditor.xaml 的交互逻辑
/// </summary>
public partial class JsonSelectorEditor : Grid
{
public Button Apply { get { return apply; } }
public Button Cancel { get { return cancel; } }
public TextBox Selector { get { return selector; } }
public JsonEditor Editor { get; set; }
public static ImageBrush SelectorBrush = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/MinecraftToolsBoxSDK;component/Controls/JsonEditor/selector.png")));
public JsonSelectorEditor()
{
InitializeComponent();
}
public void Clear()
{
selector.Text = "";
}
private void Apply_Click(object sender, RoutedEventArgs e)
{
if (Editor.Selection.Text != "")
{
Span ss = new Span(Editor.Selection.Start, Editor.Selection.End);
(ss.Parent as Paragraph).Inlines.Remove(ss);
}
TextPointer start = Editor.Selection.Start;
InlineUIContainer container = new InlineUIContainer(new TextBlock { Text = selector.Text, Background = SelectorBrush, SnapsToDevicePixels = true, ToolTip = "Selector" }, start);
Span s = new Span(container, start);
}
}
}
|
namespace BoatRacingSimulator.Interfaces
{
using Enumerations;
public interface IBoat : IModelable
{
int Weight { get; }
bool IsMotorBoat { get; }
BoatType BoatType { get; }
double CalculateRaceSpeed(IRace race);
}
} |
namespace Alabo.Extensions {
public static class BoolExtensions {
public static string GetHtmlName(this bool value) {
var result = string.Empty;
if (value) {
result = @"<span class='m-badge m-badge--wide m-badge--success'>是</span>";
} else {
result = @"<span class='m-badge m-badge--wide m-badge--danger'>否</span>";
}
return result;
}
public static string GetDisplayName(this bool value) {
var result = string.Empty;
if (value) {
result = @"是";
} else {
result = @"否";
}
return result;
}
}
} |
using System.ComponentModel.DataAnnotations;
using HiLoSocket.Builder.Server;
using NUnit.Framework;
using Shouldly;
namespace HiLoSocketTests.Builder.Server
{
[TestFixture]
[Category( "ServerBuilderTests" )]
public class ServerBuilderTests
{
[Test]
public void Build_NullLocalIpEndPoint_ThrowsValidationException( )
{
Should.Throw<ValidationException>(
( ) => ServerBuilder<string>.CreateNew( )
.SetLocalIpEndPoint( null )
.SetFormatterType( null )
.SetCompressType( null )
.SetLogger( null )
.Build( ) );
}
}
} |
using ISE.SM.Common.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecurityClient
{
public class TokenContainer
{
private static IdentityToken Token = null;
public static void SetToken(IdentityToken token)
{
Token = token;
}
public static IdentityToken CurrentToken
{
get
{
return Token;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Task_01_2
{
class A
{
public void GetA()
{
Console.WriteLine("This is type A.");
}
}
class B : A
{
new public void GetA()
{
Console.WriteLine("This is type B.");
}
}
}
|
namespace ReproBox.Tests
{
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestStack.White;
using TestStack.White.UIItems;
using TestStack.White.WindowsAPI;
[TestClass]
public class UnitTest
{
[TestMethod]
public void Hangs()
{
using (var application = Application.AttachOrLaunch(CreateStartInfo()))
{
var window = application.GetWindow("MainWindow");
window.Get<TextBox>("TextBox")
.Text = "foo";
window.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.TAB);
window.Get<TextBox>("Button").Click();
}
}
private static ProcessStartInfo CreateStartInfo()
{
var testAssembly = new Uri(typeof(UnitTest).Assembly.Location).LocalPath;
var fileName = Path.Combine(Path.GetDirectoryName(testAssembly), Path.GetFileNameWithoutExtension(testAssembly).Replace(".Tests", "") + ".exe");
Assert.AreEqual(true, File.Exists(fileName));
var processStartInfo = new ProcessStartInfo { FileName = fileName };
return processStartInfo;
}
}
}
|
using System;
using System.IO;
using System.Threading;
// using System.Threading.Tasks;
using Cysharp.Threading.Tasks; // System.Threading.Tasks の代わりにこちらをusingする
using UnityEngine;
namespace UniTaskSample
{
public class UniTaskSample : MonoBehaviour
{
[SerializeField] private string _path;
// キャンセルに用いるCancellationTokenSource
private CancellationTokenSource _cancellationTokenSource;
private void Start()
{
_cancellationTokenSource = new CancellationTokenSource();
// 非同期読み込み開始
// Forget()を呼び出すことで、awaitしてない時に発生する警告を抑制できる
WaitForReadAsync(_path, _cancellationTokenSource.Token).Forget(); }
private void OnDestroy()
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource?.Dispose();
}
// ファイルの読み込みを待機してログに出す
private async UniTask WaitForReadAsync(string path, CancellationToken token)
{
try
{
var result = await ReadFileAsync(path, token);
Debug.Log(result);
}
catch (Exception e) when (!(e is OperationCanceledException))
{
Debug.LogException(e);
}
}
// ファイルを非同期に読み取る
private async UniTask<string> ReadFileAsync(string path, CancellationToken token)
{
// UniTask.Run でも動くがObsoleteなので
// UniTask.RunOnThreadPool を推奨
return await UniTask.RunOnThreadPool(() => File.ReadAllText(path), cancellationToken: token);
}
}
} |
using System;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace gView.Server.AppCode
{
public class TaskQueue_old<T>
{
public delegate Task QueuedTask(T parameter);
private long ProcessId = 0;
private long ProcessedTasks = 0;
private int RunningTasks = 0;
private int MaxParallelTasks = 50;
private object locker = new object();
public TaskQueue_old(int maxParallelTask, int maxQueueLength)
{
this.MaxParallelTasks = maxParallelTask;
}
public long CurrentProccessId => ProcessId;
public long CurrentProcessedTasks => ProcessedTasks;
public long CurrentQueuedTasks => CurrentProccessId - CurrentProcessedTasks;
public int CurrentRunningTasks => RunningTasks;
private long NextProcessId()
{
lock (locker)
{
/*
if(ProcessId>100)
{
ProcessId -= ProcessedTasks;
ProcessedTasks = 0;
}
*/
return ++ProcessId;
}
}
private void IncreaseProcessedTasks()
{
lock (locker)
{
ProcessedTasks = ++ProcessedTasks;
}
}
private void IncreaseRunningTasks()
{
lock(locker)
{
RunningTasks = ++RunningTasks;
}
}
public void DecreaseRunningTasks()
{
lock (locker)
{
RunningTasks = --RunningTasks;
}
}
private bool IsReadyToRumble(long currentProcessId)
{
lock (locker)
{
return currentProcessId - ProcessedTasks <= MaxParallelTasks;
}
}
async public Task<bool> AwaitRequest(TaskQueue<T>.QueuedTask method, T parameter)
{
try
{
long currentProcessId = NextProcessId();
while (true)
{
if (IsReadyToRumble(currentProcessId))
{
break;
}
await Task.Delay(10);
//return false;
}
IncreaseRunningTasks();
await method?.Invoke(parameter);
return true;
}
catch (Exception /*ex*/)
{
//await Logger.LogAsync(
// parameter as IServiceRequestContext,
// Framework.system.loggingMethod.error,
// "Thread Error: " + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
return false;
}
finally
{
DecreaseRunningTasks();
IncreaseProcessedTasks();
}
}
}
}
|
using Api.Daos;
using Api.Models;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
namespace Api.Controllers
{
public class PedidosController : ApiController
{
// GET: Pedidos
public async Task<IHttpActionResult> Get()
{
try
{
var pedidos = await new PedidosDao().Listar();
return Ok(pedidos);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
// GET: api/Pedidos/5
public async Task<IHttpActionResult> Get(int id)
{
var pedido = await new PedidosDao().Buscar(id);
if (pedido == null)
{
return NotFound();
}
return Ok(new
{
pedido.Id,
pedido.Data,
itensDoPedido = pedido.ItensDoPedido.Select(x => new
{
x.ProdutoId,
x.Quantidade,
x.Produto?.Descricao
}).ToList()
});
}
// POST: Pedidos
[HttpPost]
public async Task<IHttpActionResult> Post([FromBody] Pedido pedido)
{
try
{
await new PedidosDao().Salvar(pedido);
return Ok(new { mensagem = "Pedido salvo com sucesso!" });
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
} |
using System.Collections.Generic;
// ReSharper disable InconsistentNaming
namespace Properties.Infrastructure.Rightmove.Objects
{
public class RmrtdfBranchPropertyList
{
public string request_id { get; set; }
public string message { get; set; }
public bool success { get; set; }
public string request_timestamp { get; set; }
public string response_timestamp { get; set; }
public RmrtdfBranch branch { get; set; }
public IEnumerable<RmrtdfBranchProperty> property { get; set; }
public IEnumerable<RmrtdfResponseError> errors { get; set; }
public IEnumerable<RmrtdfResponseWarning> warnings { get; set; }
}
}
|
using gView.Framework.Data;
using gView.Framework.Data.Metadata;
using gView.Framework.FDB;
using gView.Framework.Geometry;
using gView.Framework.IO;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace gView.DataSources.Fdb.SQLite
{
[gView.Framework.system.RegisterPlugIn("36DEB6AC-EA0C-4B37-91F1-B2E397351555")]
public class SQLiteFDBDataset : DatasetMetadata, IFeatureDataset2, IRasterDataset, IFDBDataset
{
internal int _dsID = -1;
private List<IDatasetElement> _layers;
private string _errMsg = String.Empty;
private string _dsname = String.Empty;
internal SQLiteFDB _fdb = null;
private string _connStr = String.Empty;
private List<string> _addedLayers;
private ISpatialReference _sRef = null;
private DatasetState _state = DatasetState.unknown;
private ISpatialIndexDef _sIndexDef = new gViewSpatialIndexDef();
public SQLiteFDBDataset()
{
_addedLayers = new List<string>();
_fdb = new SQLiteFDB();
}
async static internal Task<SQLiteFDBDataset> Create(SQLiteFDB fdb, string dsname)
{
var ds = new SQLiteFDBDataset();
ds._dsname = dsname;
string connStr = fdb.DatabaseConnectionString;
if (!connStr.Contains(";dsname=" + dsname))
{
connStr += ";dsname=" + dsname;
}
await ds.SetConnectionString(connStr);
await ds.Open();
return ds;
}
~SQLiteFDBDataset()
{
this.Dispose();
}
public void Dispose()
{
if (_fdb != null)
{
_fdb.Dispose();
_fdb = null;
}
}
#region IFeatureDataset Member
async public Task<IEnvelope> Envelope()
{
if (_layers == null)
{
return null;
}
bool first = true;
IEnvelope env = null;
foreach (IDatasetElement layer in _layers)
{
IEnvelope envelope = null;
if (layer.Class is IFeatureClass)
{
envelope = ((IFeatureClass)layer.Class).Envelope;
if (envelope.Width > 1e10 && await ((IFeatureClass)layer.Class).CountFeatures() == 0)
{
envelope = null;
}
}
else if (layer.Class is IRasterClass)
{
if (((IRasterClass)layer.Class).Polygon == null)
{
continue;
}
envelope = ((IRasterClass)layer.Class).Polygon.Envelope;
}
if (gView.Framework.Geometry.Envelope.IsNull(envelope))
{
continue;
}
if (first)
{
first = false;
env = new Envelope(envelope);
}
else
{
env.Union(envelope);
}
}
return env;
}
async public Task<ISpatialReference> GetSpatialReference()
{
if (_sRef != null)
{
return _sRef;
}
if (_fdb == null)
{
return null;
}
return _sRef = await _fdb.SpatialReference(_dsname);
}
public void SetSpatialReference(ISpatialReference sRef)
{
// Nicht in Databank übernehmen !!!
_sRef = sRef;
}
#endregion
#region IDataset Member
public string DatasetName
{
get
{
return _dsname;
}
}
public string ConnectionString
{
get
{
if (_fdb == null)
{
return String.Empty;
}
string c = _fdb._conn.ConnectionString;
if (!c.Contains(";dsname=" + ConfigTextStream.ExtractValue(_connStr, "dsname")))
{
c += ";dsname=" + ConfigTextStream.ExtractValue(_connStr, "dsname") + ";";
}
while (c.IndexOf(";;") != -1)
{
c = c.Replace(";;", ";");
}
return c;
}
}
async public Task<bool> SetConnectionString(string value)
{
_connStr = value;
if (value == null)
{
return false;
}
while (_connStr.IndexOf(";;") != -1)
{
_connStr = _connStr.Replace(";;", ";");
}
_dsname = ConfigTextStream.ExtractValue(value, "dsname");
_addedLayers.Clear();
foreach (string layername in ConfigTextStream.ExtractValue(value, "layers").Split('@'))
{
if (layername == "")
{
continue;
}
if (_addedLayers.IndexOf(layername) != -1)
{
continue;
}
_addedLayers.Add(layername);
}
if (_fdb == null)
{
_fdb = new SQLiteFDB();
}
_fdb.DatasetRenamed += new gView.DataSources.Fdb.MSAccess.AccessFDB.DatasetRenamedEventHandler(SqlFDB_DatasetRenamed);
_fdb.FeatureClassRenamed += new gView.DataSources.Fdb.MSAccess.AccessFDB.FeatureClassRenamedEventHandler(SqlFDB_FeatureClassRenamed);
_fdb.TableAltered += new gView.DataSources.Fdb.MSAccess.AccessFDB.AlterTableEventHandler(SqlFDB_TableAltered);
await _fdb.Open(_connStr);
return true;
}
public DatasetState State
{
get { return _state; }
}
public string DatasetGroupName
{
get
{
return "SQLite FDB";
}
}
public string ProviderName
{
get
{
return "SQLite Feature Database";
}
}
async public Task<bool> Open()
{
if (_fdb == null)
{
return false;
}
_dsID = await _fdb.DatasetID(_dsname);
if (_dsID < 0)
{
return false;
}
_sRef = await this.GetSpatialReference();
_state = DatasetState.opened;
_sIndexDef = await _fdb.SpatialIndexDef(_dsID);
return true;
}
public string LastErrorMessage
{
get
{
return _errMsg;
}
set { _errMsg = value; }
}
async public Task<List<IDatasetElement>> Elements()
{
if (_layers == null || _layers.Count == 0)
{
_layers = await _fdb.DatasetLayers(this);
if (_layers != null && _addedLayers.Count != 0)
{
List<IDatasetElement> list = new List<IDatasetElement>();
foreach (IDatasetElement element in _layers)
{
if (element is IFeatureLayer)
{
if (_addedLayers.Contains(((IFeatureLayer)element).FeatureClass.Name))
{
list.Add(element);
}
}
else if (element is IRasterLayer)
{
if (_addedLayers.Contains(((IRasterLayer)element).Title))
{
list.Add(element);
}
}
else
{
if (_addedLayers.Contains(element.Title))
{
list.Add(element);
}
}
}
_layers = list;
}
}
if (_layers == null)
{
return new List<IDatasetElement>();
}
return _layers;
}
public string Query_FieldPrefix
{
get { return "\""; }
}
public string Query_FieldPostfix
{
get { return "\""; }
}
public IDatabase Database
{
get { return _fdb; }
}
async public Task<IDatasetElement> Element(string title)
{
if (_fdb == null)
{
return null;
}
IDatasetElement element = await _fdb.DatasetElement(this, title);
if (element != null && element.Class is SQLiteFDBFeatureClass)
{
((SQLiteFDBFeatureClass)element.Class).SpatialReference = _sRef;
}
return element;
}
async public Task RefreshClasses()
{
if (_fdb != null)
{
await _fdb.RefreshClasses(this);
}
}
#endregion
#region IDataset2 Member
async public Task<IDataset2> EmptyCopy()
{
SQLiteFDBDataset dataset = new SQLiteFDBDataset();
await dataset.SetConnectionString(ConnectionString);
await dataset.Open();
return dataset;
}
async public Task AppendElement(string elementName)
{
if (_layers == null)
{
_layers = new List<IDatasetElement>();
}
foreach (IDatasetElement e in _layers)
{
if (e.Title == elementName)
{
return;
}
}
IDatasetElement element = await _fdb.DatasetElement(this, elementName);
if (element != null)
{
_layers.Add(element);
}
}
#endregion
#region IFDBDataset Member
public ISpatialIndexDef SpatialIndexDef
{
get { return _sIndexDef; }
}
#endregion
#region IConnectionStringDialog Member
public string ShowConnectionStringDialog(string initConnectionString)
{
//string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
//Assembly uiAssembly = Assembly.LoadFrom(appPath + @"/FDB.dll");
//gView.Framework.UI.IConnectionStringDialog p = uiAssembly.CreateInstance("gView.FDB.SqlFdbConnectionStringDialog") as gView.Framework.UI.IConnectionStringDialog;
//if (p != null)
// return p.ShowConnectionStringDialog(initConnectionString);
//return null;
return null;
}
#endregion
#region IPersistable Member
public string PersistID
{
get
{
return null;
}
}
async public Task<bool> LoadAsync(IPersistStream stream)
{
string connectionString = (string)stream.Load("connectionstring", "");
if (_fdb != null)
{
_fdb.Dispose();
_fdb = null;
}
await this.SetConnectionString(connectionString);
return await this.Open();
}
public void Save(IPersistStream stream)
{
stream.SaveEncrypted("connectionstring", this.ConnectionString);
}
#endregion
void SqlFDB_FeatureClassRenamed(string oldName, string newName)
{
if (_layers == null)
{
return;
}
foreach (IDatasetElement element in _layers)
{
if (element.Class is SQLiteFDBFeatureClass &&
((SQLiteFDBFeatureClass)element.Class).Name == oldName)
{
((SQLiteFDBFeatureClass)element.Class).Name = newName;
}
}
}
async void SqlFDB_TableAltered(string table)
{
if (_layers == null)
{
return;
}
foreach (IDatasetElement element in _layers)
{
if (element.Class is SQLiteFDBFeatureClass &&
((SQLiteFDBFeatureClass)element.Class).Name == table)
{
var fields = await _fdb.FeatureClassFields(this._dsID, table);
SQLiteFDBFeatureClass fc = element.Class as SQLiteFDBFeatureClass;
((FieldCollection)fc.Fields).Clear();
foreach (IField field in fields)
{
((FieldCollection)fc.Fields).Add(field);
}
}
}
}
void SqlFDB_DatasetRenamed(string oldName, string newName)
{
if (_dsname == oldName)
{
_dsname = newName;
}
}
}
}
|
using System;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
using Xamarin.UITest.Android;
using System.Reflection;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace Devneval.UITest.AppElement
{
internal abstract class Element
{
protected readonly IApp _app;
internal Element()
{
var app = AppContainer.App;
if(app == null)
throw new NullReferenceException("For parameterless Build() in ElementBuilder you must pass a valid instance" +
"of IApp (AndroidApp or iOSApp) in the AppContainer<T>.App property");
_app = app;
}
internal Element(IApp app)
{
_app = app;
}
protected virtual Platform ResolvePlatform()
{
return _app.GetType() == typeof(AndroidApp) ? Platform.Android : Platform.iOS;
}
}
}
|
using UnityEngine;
using Unity.Entities;
using Unity.Mathematics;
using System.Collections.Generic;
[RequiresEntityConversion]
public class WeaponPickupAuthoring : MonoBehaviour, IConvertGameObjectToEntity, IDeclareReferencedPrefabs
{
[SerializeField] private int damage = 0;
[SerializeField] private int ammoCount = 0;
[SerializeField] private float fireRate = 0f;
[SerializeField] private float minSpread = 0f;
[SerializeField] private float maxSpread = 0f;
[SerializeField] private float3 bulletPositionOffset = float3.zero;
[SerializeField] private float3 positionOffset = float3.zero;
[SerializeField] private bool singleFire = false;
[SerializeField] private bool withMelee = false;
[SerializeField] private GameObject bulletPrefab;
[SerializeField] private float bulletSpeed = 0f;
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
referencedPrefabs.Add(bulletPrefab);
}
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new WeaponComponent
{
Damage = damage,
AmmoCount = ammoCount,
FireInterval = 1f / fireRate,
FireTimer = 0f,
MinSpread = math.radians(minSpread),
MaxSpread = math.radians(maxSpread),
SpreadFactor = 0f,
LastPosition = float3.zero,
BulletEntity = conversionSystem.GetPrimaryEntity(bulletPrefab),
BulletPositionOffset = bulletPositionOffset,
BulletSpeed = bulletSpeed
});
dstManager.AddComponentData(entity, new WeaponFireInput { Firing = false });
dstManager.AddComponentData(entity, new WeaponPositionOffset { Value = positionOffset });
dstManager.AddComponentData(entity, new Lifetime { Value = 10f });
if (singleFire) dstManager.AddComponent(entity, typeof(SingleFire));
if (withMelee) dstManager.AddComponent(entity, typeof(WithMelee));
}
} |
using Abp.Domain.Services;
using System;
using System.Collections.Generic;
using System.Text;
namespace Dg.KMS.People
{
public class PersonManger:IDomainService
{
}
}
|
using System;
using System.IO;
namespace ComplexLib
{
public static class Ex
{
public static void WriteBin(this Complex c, string fileName)
{
using (BinaryWriter binaryWriter = new BinaryWriter(File.Create(fileName)))
{
binaryWriter.Write(c.Real);
binaryWriter.Write(c.Imaginary);
}
}
}
public struct Complex : IFormattable, IEquatable<Complex>
{
/// <summary>
/// Хранит мнимую единицу.
/// </summary>
public static readonly Complex imaginaryOne = new Complex(0, 1);
#region Properties (свойства)
/// <summary>
/// Возвращает вещественную часть комплексного числа.
/// </summary>
public double Real
{ get; }
/// <summary>
/// Возвращает мнимую часть комплексного числа.
/// </summary>
public double Imaginary
{ get; }
/// <summary>
/// Возвращает значение модуля комплексного числа.
/// </summary>
public double Magnitude => Math.Sqrt(Real * Real + Imaginary * Imaginary);
/// <summary>
/// Возвращает фазу комплексного числа.
/// </summary>
public double Phase => Math.Atan2(Imaginary, Real);
#endregion
/// <summary>
/// Конструктор. Инициализирует поля структуры.
/// </summary>
/// <param name="re">Вещественная часть.</param>
/// <param name="im">Мнимая часть.</param>
public Complex(double re, double im)
{
Real = re; Imaginary = im;
}
#region Operators
/// <summary>
/// Неявно преобразует число типа double в число типа Complex.
/// </summary>
/// <param name="d">Значение числа типа double.</param>
public static implicit operator Complex(double d) => new Complex(d, 0);
public static Complex operator +(Complex c1, Complex c2) => new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
public static Complex operator -(Complex c) => new Complex(-c.Real, -c.Imaginary);
public static Complex operator -(Complex c1, Complex c2) => c1 + (-c2);
public static Complex operator *(Complex c1, Complex c2) => new Complex(c1.Real * c2.Real - c1.Imaginary * c2.Imaginary,
c1.Real * c2.Imaginary + c1.Imaginary * c2.Real);
/// <summary>
/// Определяет сопряженное число.
/// </summary>
/// <param name="c">Исходное число.</param>
/// <returns>Сопряженное исходному.</returns>
public static Complex operator ~(Complex c) => new Complex(c.Real, -c.Imaginary);
public static Complex operator /(Complex c1, Complex c2)
{
double temp = 1 / c2.Magnitude;
return temp * temp * c1 * ~c2;
}
public static bool operator ==(Complex c1, Complex c2) => c1.Equals(c2);
public static bool operator !=(Complex c1, Complex c2) => !(c1 == c2);
#endregion
#region Methods
/// <summary>
/// Создает комплексное число по заданному модулю и фазе.
/// </summary>
/// <param name="magnitude">Модуль.</param>
/// <param name="phase">Фаза.</param>
/// <returns>Комплексное число.</returns>
public static Complex FromPolarCoordinates(double magnitude, double phase) =>
new Complex(magnitude * Math.Cos(phase), magnitude * Math.Sin(phase));
#region Элементарные функции
/// <summary>
/// Извлекает квадратный корень из комплексного числа.
/// </summary>
/// <param name="c">Заданное число.</param>
/// <returns></returns>
public static Complex Sqrt(Complex c) => FromPolarCoordinates(Math.Sqrt(c.Magnitude), .5 * c.Phase);
public static Complex Exp(Complex c) => FromPolarCoordinates(Math.Exp(c.Real), c.Imaginary);
public static Complex Pow(Complex value, Complex power) =>
value.Magnitude == 0 ? 0 : Exp((Math.Log(value.Magnitude) + value.Phase * imaginaryOne) * power);
public static Complex Log(Complex c) => Math.Log(c.Magnitude) + imaginaryOne * c.Phase;
public static Complex Cos(Complex c)
{
Complex exp = Exp(imaginaryOne * c);
return .5 * (exp + 1 / exp);
}
public static Complex Acos(Complex c)
{
Complex exp = c + Sqrt(c * c - 1);
return Log(exp) / imaginaryOne;
}
#endregion
public static Complex Parse(string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentNullException();
if (!s.EndsWith(">") || !s.StartsWith("<") || !s.Contains(";"))
throw new FormatException();
int indx = s.IndexOf(';');
return double.Parse(s.Substring(1, indx - 1)) +
imaginaryOne * double.Parse(s.Substring(indx + 1, s.IndexOf('>') - indx - 1));
}
public static bool TryParse(string s, out Complex c)
{
c = double.NaN;
try
{
c = Parse(s);
}
catch
{
return false;
}
return true;
}
public void WriteToFile(string fileName)
{
using (BinaryWriter bw = new BinaryWriter(File.Create(fileName)))
bw.Write(this);
}
#region Переопределенные методы предков
public override bool Equals(object obj) => base.Equals(obj);
public override int GetHashCode() => base.GetHashCode();
#endregion
#region Методы, реализующие интерфейсы
public bool Equals(Complex other) => Equals(other as object);
public string ToString(string format = null, IFormatProvider formatProvider = null)
=> "<" + Real.ToString(format, formatProvider) + ";" + Imaginary.ToString(format, formatProvider) + ">";
#endregion
#endregion
class BinaryWriter : System.IO.BinaryWriter
{
internal BinaryWriter(Stream stream) : base(stream)
{ }
internal void Write(Complex c)
{
base.Write(c.Real);
base.Write(c.Imaginary);
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Zlib;
using Zlib.Core;
namespace Zlib.Combat
{
public class GunHandler : MonoBehaviour
{
[SerializeField] Weapon CurrentWeapon = null;
[SerializeField] Transform GunHolster = null;
[SerializeField] Transform playerCamera = null;
[SerializeField] LayerMask shootLayer = 0;
public Action OnShoot;
Controls controls;
void Start()
{
controls = GetComponent<Controls>();
OnShoot += FireShootRay;
EqiupWeapon(CurrentWeapon);
}
void Update()
{
if (Input.GetKeyDown(controls.fire))
{
OnShoot?.Invoke();
}
}
void FireShootRay()
{
// creates a ray from the camera
Ray shootRay = new Ray(playerCamera.position, playerCamera.forward);
RaycastHit hit = new RaycastHit();
// shoots the ray
Physics.Raycast(shootRay, out hit, 100, shootLayer);
// gives the name of the object that you hit
Debug.Log(hit.collider.gameObject.name);
}
private void EqiupWeapon(Weapon gun)
{
GameObject spawnedGun = Instantiate(gun.gunPrefab, GunHolster);
spawnedGun.GetComponent<ShootHandler>().gunHandler = this;
}
}
} |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace Tools
{
[Serializable]
public class Fraction : IEquatable<Fraction>, ISerializable
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GCD(int a, int b)
{
if (a % b == 0)
{
return b;
}
bool aIsEven = (a & 1) == 0;
bool bIsEven = (b & 1) == 0;
if (aIsEven && bIsEven)
{
return 2 * GCD(a >> 1, b >> 1);
}
else if (aIsEven)
{
return GCD(a >> 1, b);
}
else if (bIsEven)
{
return GCD(a, b >> 1);
}
else if (a > b)
{
return GCD((a - b) >> 1, b);
}
else
{
return GCD((b - a) >> 1, a);
}
}
private int[] _decimalDigits;
private int _cycleStart;
private readonly int _originalNumerator;
private readonly int _originalDenominator;
public int IntegerPart { get; private set; }
public int Numerator { get; private set; }
public int Denominator { get; private set; }
public int PeriodLength
{
get
{
return _decimalDigits.Length - _cycleStart;
}
}
public Fraction(int numerator, int denominator)
{
_originalDenominator = denominator;
_originalNumerator = numerator;
SetProps(numerator, denominator);
}
private void SetProps(int numerator, int denominator)
{
IntegerPart = numerator / denominator;
numerator -= denominator * IntegerPart;
int gcd = numerator < 2 ? 1 : GCD(numerator, denominator);
Numerator = numerator / gcd;
Denominator = denominator / gcd;
ComputeDecimalForm();
}
private Fraction(SerializationInfo info, StreamingContext context)
{
_originalDenominator = info.GetInt32("denominator");
_originalNumerator = info.GetInt32("numerator");
SetProps(_originalNumerator, _originalDenominator);
}
private void ComputeDecimalForm()
{
var numerators = new HashSet<int>();
var decimalDigits = new List<int>();
int numerator = Numerator;
int denominator = Denominator;
while (numerator % denominator != 0)
{
if (numerator < denominator)
{
numerator *= 10;
while (numerator < denominator)
{
numerators.Add(numerator);
decimalDigits.Add(0);
numerator *= 10;
}
}
if (!numerators.Add(numerator))
{
int cycleStart = 0;
foreach (var item in numerators)
{
if (numerator == item)
{
break;
}
cycleStart++;
}
_cycleStart = cycleStart;
_decimalDigits = decimalDigits.ToArray();
return;
}
decimalDigits.Add(numerator / denominator);
numerator = numerator % denominator;
}
if (numerator > 0) { decimalDigits.Add(numerator / denominator); }
_decimalDigits = decimalDigits.ToArray();
_cycleStart = _decimalDigits.Length;
}
public override string ToString()
{
var sb = new System.Text.StringBuilder(_decimalDigits.Length + 4);
sb.Append(IntegerPart);
if (_decimalDigits.Length > 0)
{
sb.Append('.');
for (int i = 0; i < _cycleStart; i++)
{
sb.Append(_decimalDigits[i]);
}
if (_cycleStart < _decimalDigits.Length)
{
sb.Append('(');
for (int i = _cycleStart; i < _decimalDigits.Length; i++)
{
sb.Append(_decimalDigits[i]);
}
sb.Append(')');
}
}
return String.Format("{0}/{1} == {2}", Numerator + IntegerPart * Denominator, Denominator, sb);
}
public bool Equals(Fraction other)
{
return IntegerPart == other.IntegerPart &&
Numerator == other.Numerator &&
Denominator == other.Denominator;
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Equals(obj as Fraction);
}
public override int GetHashCode()
{
return _originalDenominator.GetHashCode() ^ _originalNumerator.GetHashCode();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("numerator", _originalNumerator);
info.AddValue("denominator", _originalDenominator);
}
public static bool operator ==(Fraction f1, Fraction f2)
{
return f1.Equals(f2);
}
public static bool operator !=(Fraction f1, Fraction f2)
{
return !f1.Equals(f2);
}
public static Fraction operator +(Fraction f1, Fraction f2)
{
int lcm = (f1.Denominator * f2.Denominator) / GCD(f1.Denominator, f2.Denominator);
int numerator = f1.Numerator * (lcm / f1.Denominator) +
f2.Numerator * (lcm / f2.Denominator) +
f1.IntegerPart * lcm +
f2.IntegerPart * lcm;
return new Fraction(numerator, lcm);
}
public static Fraction operator *(Fraction f1, Fraction f2)
{
return new Fraction(f1._originalNumerator * f2._originalNumerator,
f1._originalDenominator * f2._originalDenominator);
}
}
}
|
using System;
using aairvid.Utils;
using Android.App;
using Android.Graphics;
using Android.OS;
using Android.Views;
using Android.Widget;
using Java.IO;
using libairvidproto.model;
using System.Linq;
namespace aairvid.History
{
public class RecentlyViewedFragment : ListFragment
{
private RecentlyItemListAdapter _adp;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
HistoryMaiten.Load();
_adp = new RecentlyItemListAdapter(inflater.Context);
foreach (var item in HistoryMaiten.HistoryItems)
{
_adp.AddItem(item.Key, item.Value);
}
ListAdapter = _adp;
var view = base.OnCreateView(inflater, container, savedInstanceState);
return view;
}
public override void OnCreateContextMenu(IContextMenu menu, View v, IContextMenuContextMenuInfo menuInfo)
{
var info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.SetHeaderTitle(_adp.GetVideoName(info.Position));
var menuItems = Resources.GetStringArray(Resource.Array.recentitems_ctx_menu);
for (var i = 0; i < menuItems.Length; i++)
{
menu.Add(Menu.None, i, i, menuItems[i]);
}
base.OnCreateContextMenu(menu, v, menuInfo);
}
public override bool OnContextItemSelected(IMenuItem item)
{
var info = (AdapterView.AdapterContextMenuInfo)item.MenuInfo;
var selectedItem = item.TitleFormatted.ToString();
if (selectedItem == Resources.GetString(Resource.String.DeleteFromHistory))
{
_adp.RemoveItem(info.Position);
}
else if (selectedItem == Resources.GetString(Resource.String.ViewVideoInfo))
{
var player = Activity as IResourceSelectedListener;
var historyItem = _adp[info.Position];
var server = player.GetServerById(historyItem.Details.ServerId);
if (server == null)
{
Toast.MakeText(Activity, Resource.String.CannotFindServer, ToastLength.Short).Show();
return true;
}
var parent = new AirVidResource.NodeInfo()
{
Id = historyItem.Details.FolderId,
Path = historyItem.Details.FolderPath,
Name = historyItem.Details.FolderPath.Split('\\').LastOrDefault()
};
var v = new Video(server,
historyItem.Details.VideoName,
historyItem.Details.VideoId, parent);
player.ReqDisplayMediaViaMediaFragment(v);
}
else if (selectedItem == Resources.GetString(Resource.String.ViewFolderInfo))
{
var player = Activity as IResourceSelectedListener;
var historyItem = _adp[info.Position];
var server = player.GetServerById(historyItem.Details.ServerId);
if (server == null)
{
Toast.MakeText(Activity, Resource.String.CannotFindServer, ToastLength.Short).Show();
return true;
}
var parentFolderPath = historyItem.Details.FolderPath.Substring(0,
historyItem.Details.FolderPath.LastIndexOf("\\", StringComparison.Ordinal));
var parent = new AirVidResource.NodeInfo()
{
Id = Guid.Empty.ToString(),
Path = parentFolderPath,
Name = parentFolderPath.Split('\\').LastOrDefault()
};
var v = new Folder(server,
historyItem.Details.FolderPath.Split('\\').LastOrDefault(),
historyItem.Details.FolderId,
parent);
player.OnFolderSelected(v);
}
return true;
}
public override void OnListItemClick(ListView l, View v, int position, long id)
{
RegisterForContextMenu(l);
l.ShowContextMenuForChild(v);
}
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
base.OnCreateOptionsMenu(menu, inflater);
for (var i = 0; i < menu.Size(); ++i)
{
var item = menu.GetItem(i);
if (item != null && item.ItemId != Resource.Id.menu_exit)
{
item.SetVisible(false);
}
}
}
public override void OnCreate(Bundle savedInstanceState)
{
SetHasOptionsMenu(true);
base.OnCreate(savedInstanceState);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
/*
* tags: adhoc
* Time(n^2), Space(1)
*/
namespace leetcode
{
public class Lc782_Transform_to_Chessboard
{
/// <summary>
/// 1. The 4 corners of any rectangle inside a chessboard must be 4 ones, or 4 zeroes, or 2 ones and 2 zeroes, that is NW^NE^SW^SE==0
/// 2. Given a row, any other row must be identical to it or its mirror.
/// so we only need to count the total swap to make first row and first column to 01010... or 10101..., which one should we make?
/// In case of n even, take the minimum one, because both are possible.
/// In case of n odd, take the even swaps. Because when we make a swap, we move two rows or two columns at the same time.
/// </summary>
public int MovesToChessboard(int[,] board)
{
int n = board.GetLength(0);
for (int r = 0; r < n; r++)
{
for (int c = 0; c < n; c++)
if ((board[0, 0] ^ board[0, c] ^ board[r, 0] ^ board[r, c]) == 1)
return -1;
}
int rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0;
for (int i = 0; i < n; i++)
{
rowSum += board[i, 0];
colSum += board[0, i];
if (board[i, 0] == i % 2) rowSwap++;
if (board[0, i] == i % 2) colSwap++;
}
if (rowSum != n / 2 && rowSum != (n + 1) / 2) return -1;
if (colSum != n / 2 && colSum != (n + 1) / 2) return -1;
if (n % 2 == 1)
{
if (rowSwap % 2 == 1) rowSwap = n - rowSwap;
if (colSwap % 2 == 1) colSwap = n - colSwap;
}
else
{
rowSwap = Math.Min(rowSwap, n - rowSwap);
colSwap = Math.Min(colSwap, n - colSwap);
}
return (rowSwap + colSwap) / 2;
}
public void Test()
{
var board = new int[,] { { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 } };
Console.WriteLine(MovesToChessboard(board) == 2);
board = new int[,] { { 0, 1 }, { 1, 0 } };
Console.WriteLine(MovesToChessboard(board) == 0);
board = new int[,] { { 1, 0 }, { 0, 1 } };
Console.WriteLine(MovesToChessboard(board) == 0);
board = new int[,] { { 1, 0 }, { 1, 0 } };
Console.WriteLine(MovesToChessboard(board) == -1);
board = new int[,] { { 1, 1, 0 }, { 0, 0, 1 }, { 0, 0, 1 } };
Console.WriteLine(MovesToChessboard(board) == 2);
board = new int[,] { { 1, 0, 0 }, { 0, 1, 1 }, { 1, 0, 0 } };
Console.WriteLine(MovesToChessboard(board) == 1);
board = new int[,] { { 0, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 1 } };
Console.WriteLine(MovesToChessboard(board) == 2);
}
}
}
|
namespace Exercises.Models.Queries
{
using System;
using System.Data.Entity;
using System.Linq;
using CodeFirstFromDatabase;
/// <summary>
/// Problem05 - Employees from Seattle
/// </summary>
public class EmployeesFromSeattle : Query<SoftuniContext>
{
public override string QueryResult(SoftuniContext context)
{
var employees = context
.Employees
.Include(e => e.Department)
.Where(e => e.Department.Name == "Research and Development")
.OrderBy(e => e.Salary)
.ThenByDescending(e => e.FirstName)
.Select(e => new
{
e.FirstName, e.LastName,
DepartmentName = e.Department.Name, e.Salary
});
foreach (var employee in employees)
{
this.Result.AppendFormat(
"{0} {1} from {2} - ${3:F2}{4}",
employee.FirstName,
employee.LastName,
employee.DepartmentName,
employee.Salary,
Environment.NewLine);
}
return this.Result.ToString();
}
}
} |
using System;
namespace Meetup.Sagas.Contracts
{
public interface ItemAdded
{
string Username { get; }
DateTime Timestamp { get; }
}
public interface CheckedOut
{
string Username { get; }
DateTime Timestamp { get; }
}
public interface ShowSadPuppy
{
string Username { get; }
}
}
|
using ND.FluentTaskScheduling.Command.asyncrequest;
using ND.FluentTaskScheduling.Model;
using ND.FluentTaskScheduling.Model.enums;
using ND.FluentTaskScheduling.Model.request;
using ND.FluentTaskScheduling.Model.response;
using ND.FluentTaskScheduling.TaskInterface;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//**********************************************************************
//
// 文件名称(File Name):TaskJob.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-04-06 15:07:06
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-04-06 15:07:06
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.Core.TaskHandler
{
/// <summary>
/// 任务回调Job
/// </summary>
public class TaskJob :IJob//MarshalByRefObject, IJob
{
// private static object lockobj = new object();
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void Execute(JobExecutionContext context)
{
//lock (lockobj)
//{
int taskid = Convert.ToInt32(context.JobDetail.Name);
try
{
var taskruntimeinfo = TaskPoolManager.CreateInstance().Get(taskid.ToString());
taskruntimeinfo.DllTask.ClearLog();
if (taskruntimeinfo == null || taskruntimeinfo.DllTask == null)
{
// LogHelper.AddTaskError("当前任务信息为空引用", taskid, new Exception());
return;
}
taskruntimeinfo.TaskLock.Invoke(() =>
{
// int runCount = 0;
try
{
int taskid2 = taskruntimeinfo.TaskModel.id;
int taskversionid = taskruntimeinfo.TaskVersionModel.id;
string nextrunTime = Convert.ToDateTime(context.NextFireTimeUtc).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
nextrunTime = nextrunTime.IndexOf("0001-01") > -1 ? "2099-12-30" : nextrunTime;
if (taskruntimeinfo.TaskModel.ispauseschedule == 0)//等于0 说明没有停止调度,否则停止调度
{
taskruntimeinfo.DllTask.TryRunTask(nextrunTime, taskruntimeinfo);//执行完,判断是否需要释放
try
{
if (taskruntimeinfo.TaskModel.tasktype == (int)TaskType.OnceTask)
{
bool disposeflag= TaskDisposer.DisposeTask(taskid2, taskruntimeinfo, false, null);
if (disposeflag)//如果释放成功则上报
{
var req = new UpdateTaskScheduleStatusRequest() { NodeId = GlobalNodeConfig.NodeID, Source = Source.Node, ScheduleStatus = Model.enums.TaskScheduleStatus.StopSchedule, TaskId = taskid2, TaskVersionId = taskversionid };
var r2 = NodeProxy.PostToServer<EmptyResponse, UpdateTaskScheduleStatusRequest>(ProxyUrl.UpdateTaskScheduleStatus_Url, req);
if (r2.Status != ResponesStatus.Success)
{
LogProxy.AddTaskErrorLog("更新任务调度状态(停止调度)失败,请求Url:" + ProxyUrl.UpdateTaskScheduleStatus_Url + ",请求参数:" + JsonConvert.SerializeObject(req) + ",返回参数:" + JsonConvert.SerializeObject(r2), taskid);
}
}else
{
LogProxy.AddTaskErrorLog("taskid=" + taskid + ",释放单次执行任务资源失败", taskid);
}
}
}
catch(Exception ex)
{
LogProxy.AddTaskErrorLog("taskid=" + taskid + ",释放单次执行任务资源异常:" + JsonConvert.SerializeObject(ex), taskid);
}
}
}
catch (Exception exp)
{
LogProxy.AddTaskErrorLog("任务:" + taskid + ",TaskJob回调时执行异常,异常信息:" + JsonConvert.SerializeObject(exp), taskid);
}
});
}
catch (Exception exp)
{
LogProxy.AddTaskErrorLog("任务调度组件回调时发生严重异常,异常信息:" + JsonConvert.SerializeObject(exp), taskid);
}
}
//public override object InitializeLifetimeService()
//{
// //Remoting对象 无限生存期
// return null;
//}
//}
}
}
|
namespace WindowsFormsApp1
{
class ConfirmData
{
public bool Res { get; set; }
}
} |
using System;
using System.Numerics;
namespace Algorithms.HackerRank.ExtraLongFactorials
{
class ExtraLongFactorials
{
static BigInteger Factorial(int n)
{
if (n > 1)
{
return n * Factorial(n - 1);
}
return n;
}
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(Factorial(n));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MergeLists
{
class Program
{
static void Main(string[] args)
{
int []a = {10,9,8,3,1,-10,-15,-20,-25,-30,-35};
int []b = {20,15,4,2,-1 ,-2,-3};
int[] c = merge(a,b);
Console.WriteLine("a is ");
print(a);
Console.WriteLine("b is ");
print(b);
Console.WriteLine("c is ");
print(c);
Console.ReadKey();
}
static int[] merge(int []a, int []b )
{
int[] c= new int[18];
int indexA = 0;
int indexB = 0;
int indexC = -1;
while (indexA < a.Length && indexB < b.Length)
{
int topA = a[indexA];
int topB = b[indexB];
if (topA > topB)
{
c[++indexC] = topA;
indexA++;
}
else {
c[++indexC] = topB;
indexB++;
}
}
Console.WriteLine("index b is {0}",indexB);
if (indexA < a.Length )
{
for (int k = indexA; k < a.Length ; k++)
{
c[++indexC] = a[k];
}
}
if (indexB < b.Length )
{
for (int k = indexB; k < b.Length ; k++)
{
c[++indexC] = b[k];
}
}
return c;
}
static void print(int[] a)
{
foreach (int x in a)
{
Console.Write("[{0:D2}] ", x);
}
Console.WriteLine();
for (int i = 0; i < a.Length; i++)
{
Console.Write("|{0:D2}| ", i);
}
Console.WriteLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace InventoryControl.Models
{
public class Supplier
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int SupplierNum { get; set; }
public virtual ICollection<Item> Items { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public static implicit operator Supplier(int v)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Management_Plus
{
public partial class CompenyList : Form
{
public CompenyList()
{
InitializeComponent();
ShowCompeny.TabStop = true;
/*********Demo***********/
displaycompanydata("");
/**********************Edit Grid View*************/
ShowCompeny.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(235, 235, 235);
ShowCompeny.CellBorderStyle = DataGridViewCellBorderStyle.SingleVertical;
ShowCompeny.EnableHeadersVisualStyles = false;
ShowCompeny.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
ShowCompeny.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(20, 25, 72);
ShowCompeny.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
/***************************************************/
}
static CompenyList Clist = null;
public static CompenyList ListCompeny
{
get {
if (Clist == null)
{
Clist = new CompenyList();
Clist.FormClosed += new FormClosedEventHandler(Clist_FormClosed);
}
else {
Clist.Activate();
Clist.BringToFront();
}
return Clist;
}
}
static void Clist_FormClosed(object sender, FormClosedEventArgs e)
{
Clist = null;
}
//When Click On Close Button
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
int INDEX = 0;
private void btn_new_Click(object sender, EventArgs e)
{
if (ShowCompeny.Rows.Count > 0)
{
INDEX = ShowCompeny.CurrentCell.RowIndex;
}
AddCompeny AC = AddCompeny.CreateCompeny;
AC.FormTitle.Text = "ADD Compeny";
AC.FormClosed += new FormClosedEventHandler(AC_FormClosed);
AC.btn_update.Visible = false;
AC.btn_submit.Visible = true;
AC.MdiParent = this.MdiParent;
AC.Show();
}
void AC_FormClosed(object sender, FormClosedEventArgs e)
{
CompenyList_Load(this, null);
if (ShowCompeny.Rows.Count > 0)
{
if (INDEX > 0)
ShowCompeny.Rows[INDEX].Selected = true;
}
}
public static string company;
private void btn_edit_Click(object sender, EventArgs e)
{
if (ShowCompeny.Rows.Count != 0)
{
if (ShowCompeny.Rows.Count > 0)
{
INDEX = ShowCompeny.CurrentCell.RowIndex;
}
OleDbConnection con1 = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\project database\Management Plus.mdb");
con1.Open();
AddCompeny AC = AddCompeny.CreateCompeny;
AC.FormTitle.Text = "Edit Compeny";
AC.FormClosed+=new FormClosedEventHandler(AC_FormClosed);
AC.name_txt.Text = this.ShowCompeny.CurrentRow.Cells[0].Value.ToString();
OleDbCommand cmd = new OleDbCommand("select * from companyregistration where Name='" + AC.name_txt.Text + "'", con1);
OleDbDataReader dr = cmd.ExecuteReader();
dr.Read();
AC.name_txt.Text = dr[0].ToString();
company = dr[0].ToString();
AC.StateBox.Text = dr[1].ToString();
AC.CityBox.Text = dr[2].ToString();
AC.pin_txt.Text = dr[3].ToString();
AC.address_txt.Text = dr[4].ToString();
AC.mobile_txt1.Text = dr[5].ToString();
AC.mobile_txt2.Text = dr[6].ToString();
AC.email_txt.Text = dr[7].ToString();
AC.website_txt.Text = dr[8].ToString();
AC.gstinno.Text = dr[9].ToString();
AC.panno.Text = dr[10].ToString();
AC.txtdate.Text = dr[11].ToString();
AC.btn_submit.Visible = false;
AC.btn_update.Visible = true;
AC.MdiParent = this.MdiParent;
AC.Show();
dr.Close();
con1.Close();
this.Close();
}
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
public void displaycompanydata(String value)
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\project database\Management Plus.mdb");
OleDbDataAdapter da = new OleDbDataAdapter("select Name,Dates,mobileno1 from companyregistration where Name LIKE '" + value + "%'", con);
DataTable dt = new DataTable();
da.Fill(dt);
ShowCompeny.DataSource = dt;
}
private void CompenyList_Load(object sender, EventArgs e)
{
this.ShowCompeny.Focus();
displaycompanydata("");
}
private void ShowCompeny_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (ShowCompeny.Rows.Count != 0)
{
if (ShowCompeny.Rows.Count > 0)
{
INDEX = ShowCompeny.CurrentCell.RowIndex;
}
OleDbConnection con1 = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\project database\Management Plus.mdb");
con1.Open();
AddCompeny AC = AddCompeny.CreateCompeny;
AC.FormTitle.Text = "Edit Compeny";
AC.FormClosed += new FormClosedEventHandler(AC_FormClosed);
AC.name_txt.Text = this.ShowCompeny.CurrentRow.Cells[0].Value.ToString();
OleDbCommand cmd = new OleDbCommand("select * from companyregistration where Name='" + AC.name_txt.Text + "'", con1);
OleDbDataReader dr = cmd.ExecuteReader();
dr.Read();
AC.name_txt.Text = dr[0].ToString();
company = dr[0].ToString();
AC.StateBox.Text = dr[1].ToString();
AC.CityBox.Text = dr[2].ToString();
AC.pin_txt.Text = dr[3].ToString();
AC.address_txt.Text = dr[4].ToString();
AC.mobile_txt1.Text = dr[5].ToString();
AC.mobile_txt2.Text = dr[6].ToString();
AC.email_txt.Text = dr[7].ToString();
AC.website_txt.Text = dr[8].ToString();
AC.gstinno.Text = dr[9].ToString();
AC.panno.Text = dr[10].ToString();
AC.txtdate.Text = dr[11].ToString();
AC.btn_submit.Visible = false;
AC.btn_update.Visible = true;
AC.MdiParent = this.MdiParent;
AC.Show();
dr.Close();
con1.Close();
this.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (ShowCompeny.Rows.Count != 0)
{
DialogResult DR = MessageBox.Show("Can You Deleta this Recoed...", "Delete", MessageBoxButtons.YesNo);
if (DR == DialogResult.Yes)
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\project database\Management Plus.mdb");
if (con.State == ConnectionState.Closed)
con.Open();
OleDbCommand com = new OleDbCommand("select Company_Name from addproduct where Company_Name='" + this.ShowCompeny.CurrentRow.Cells[0].Value + "' ", con);
OleDbDataReader drr = com.ExecuteReader();
drr.Read();
if (drr.HasRows)
{
MessageBox.Show("This Compeny Product Add In Your Stock You Can't Delete this...", "Info", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
else
{
OleDbDataAdapter DA = new OleDbDataAdapter("Delete from companyregistration where Name='" + this.ShowCompeny.CurrentRow.Cells[0].Value + "'", con);
DataTable DT = new DataTable();
DA.Fill(DT);
CompenyList_Load(this, null);
}
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
else { MessageBox.Show("All Data is Deleted..."); }
}
}
private void ShowCompeny_KeyDown(object sender, KeyEventArgs e)
{
if (ShowCompeny.Rows.Count != 0)
{
if(e.KeyCode==Keys.Delete )
{
DialogResult DR = MessageBox.Show("Can You Deleta this Recoed...", "Delete", MessageBoxButtons.YesNo);
if(DR==DialogResult.Yes)
{
if (ShowCompeny.Rows.Count > 0)
{
INDEX = ShowCompeny.CurrentCell.RowIndex;
}
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\project database\Management Plus.mdb");
OleDbDataAdapter DA = new OleDbDataAdapter("Delete from companyregistration where ID=" + this.ShowCompeny.CurrentRow.Cells[0].Value + "", con);
DataTable DT = new DataTable();
DA.Fill(DT);
CompenyList_Load(this, null);
if (INDEX > 0)
{
ShowCompeny.Rows[INDEX - 1].Selected = true;
}
}
}
}
else { MessageBox.Show("All Data is Deleted..."); }
}
private void ShowCompeny_SelectionChanged(object sender, EventArgs e)
{
try
{
this.TitleText.Text = this.ShowCompeny.CurrentRow.Cells[0].Value.ToString();
TitleText.Left = (this.groupBox2.Width - TitleText.Width) / 2;
}
catch (NullReferenceException)
{
}
}
private void txt_search_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
}
}
private void txt_search_TextChanged(object sender, EventArgs e)
{
displaycompanydata(txt_search.Text.ToString());
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Mvc.ViewComponents;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
namespace SciVacancies.WebApp
{
[HtmlTargetElement("checkboxing", Attributes = "items, values, property, onchange")]
public class CheckboxingTagHelper : TagHelper
{
[HtmlAttributeName("items")]
public IEnumerable<SelectListItem> Items { get; set; }
[HtmlAttributeName("values")]
public IEnumerable<int> Values { get; set; }
[HtmlAttributeName("property")]
public string Property { get; set; }
[HtmlAttributeName("onchange")]
public string OnChange { get; set; }
/// <summary>
/// количество отображаемых значений для выбора (список ComboBox'ов), где (-1) - показывать все значения, (0) - значение по-умолчанию, (n) - показать минимум 'n'-значений, или все выбранные значения.
/// </summary>
[HtmlAttributeName("showcount")]
public int Showcount { get; set; }
[HtmlAttributeName("labelforindex")]
public int LabelForIndex { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (Items == null) return;
var i = LabelForIndex;
if (Values != null)
{
var valuesString = Values.Select(c => c.ToString());
var selectedCount = Items.Count(c => valuesString.Contains(c.Value));
if (Showcount != -1) //если не указано "показывать все значения"
Showcount = selectedCount > Showcount ? selectedCount : Showcount; //показать минимум Showcount значений, или все выбранные значения
foreach (var item in Items.Where(c => valuesString.Contains(c.Value)))
{
i++;
AppendItem(output, i, item, true);
}
foreach (var item in Items.Where(c => !valuesString.Contains(c.Value)))
{
i++;
AppendItem(output, i, item, false);
}
}
else
{
foreach (var item in Items)
{
i++;
AppendItem(output, i, item, false);
}
}
}
private void AppendItem(TagHelperOutput output, int i, SelectListItem item, bool itemIsChecked)
{
var input = new TagBuilder("input");
var span = new TagBuilder("span");
input.Attributes.Add("type", "checkbox");
input.Attributes.Add("name", Property);
input.Attributes.Add("id", Property + i);
input.Attributes.Add("value", item.Value);
if(!string.IsNullOrEmpty(OnChange))
{
input.Attributes.Add("onchange", OnChange);
}
if (itemIsChecked)
{
input.Attributes.Add("checked", string.Empty);
span.AddCssClass("checked");
}
span.AddCssClass("checkbox");
if(!string.IsNullOrEmpty(OnChange))
{
span.Attributes.Add("onclick", OnChange);
}
span.InnerHtml.Append(input);
var label = new TagBuilder("label");
label.Attributes.Add("for", input.Attributes["id"]);
label.InnerHtml.AppendEncoded(item.Text);
var li = new TagBuilder("li");
li.InnerHtml.Append(span).Append(label);
li.AddCssClass("li-checkbox");
if (Showcount > 0 && i > Showcount)
{
li.Attributes.Add("style", "display: none;");
}
var t = new StringBuilder();
output.Content.Append(li);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Panel_LevelFailed : BasePanel
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample.Commands
{
public class AddTwoNumbers : ICommand<int>
{
public int A { get; private set; }
public int B { get; private set; }
public AddTwoNumbers(int a, int b)
{
this.A = a;
this.B = b;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClipModels
{
static class ServiceLayer
{
//converts HH:MM:SS string format to (int) number of actual seconds.
internal static int stringToSecondsRounded(string duration)
{
int hours;
int minutes;
int seconds;
int.TryParse(duration.Substring(0, 2), out hours);
int.TryParse(duration.Substring(3, 2), out minutes);
int.TryParse(duration.Substring(6, 2), out seconds);
return 3600 * hours + 60 * minutes + seconds;
}
/// <summary>
/// Return exact second representation, including milliseconds
/// </summary>
/// <param name="frames"></param>
/// <param name="frameRate"></param>
/// <returns></returns>
internal static double framesToSecondsExact(double frames, double frameRate)
{
if (frameRate != 0)
return frames / frameRate;
else return 0;
}
/// <summary>
/// Return frames
/// </summary>
/// <param name="exactSeconds"></param>
/// <param name="frameRate"></param>
/// <returns></returns>
internal static int secondsToFramesExact(double exactSeconds, double frameRate)
{
return (int)(exactSeconds * frameRate);
}
/// <summary>
/// Check if HH:MM:SS duration field format is valid
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
internal static bool durationIsValidHHMMSS(string duration)
{
string[] tempStr = duration.Split(':');
int n;
//Check if format HH:MM:SS:FF
if (tempStr.Length != 3)
return false;
//Check if each segment is number and its in range
for (int i = 0; i < tempStr.Length; i++)
{
if (!(int.TryParse(tempStr[i], out n)))
return false;
else
{
switch (i)
{
case 1:
if (!(n >= 0 && n <= 59))
return false;
break;
case 2:
if (!(n >= 0 && n <= 59))
return false;
break;
}
}
}
//If passed all above - return TRUE
return true;
}
/// <summary>
/// Check if HH:MM:SS:FF duration field format is valid
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
internal static bool durationIsValidHHMMSSFF(string duration)
{
string[] tempStr = duration.Split(':');
int n;
//Check if format HH:MM:SS:FF
if (tempStr.Length != 4)
return false;
//Check if each segment is number and its in range
for (int i = 0; i < tempStr.Length; i++)
{
if (!(int.TryParse(tempStr[i], out n)))
return false;
else
{
switch (i)
{
case 1:
if (!(n >= 0 && n <= 59))
return false;
break;
case 2:
if (!(n >= 0 && n <= 59))
return false;
break;
}
}
}
//If passed all above - return TRUE
return true;
}
}
}
|
using UnityEngine;
using VRTK;
using System.Collections;
/// <summary>
/// Fix the coal spawner by "hitting" it 3 times
/// </summary>
public class FixCoalSpawner : MonoBehaviour
{
private int count = 0;
private const int countNeeded = 3;
/// <summary>
/// Create the custom event
/// </summary>
void Start()
{
CreateTouchEvent();
}
/// <summary>
/// Add a new custom event to the VRTK interaction event handler.
/// </summary>
/// <remarks>
/// This code is my adaptation of a github issue which can be seen here https://github.com/thestonefox/VRTK/issues/643
/// My work is transformative but not wholly original.
/// </remarks>
private void CreateTouchEvent()
{
//make sure the object has the VRTK script attached.
if (GetComponent<VRTK_InteractableObject>() == null)
{
Debug.LogError("VRTK_InteractableObject needed");
return;
}
//hook into event
GetComponent<VRTK_InteractableObject>().InteractableObjectTouched += new InteractableObjectEventHandler(ObjectTouched);
}
/// <summary>
/// Count number of times coal spawner is hit.
/// Once it has been hit the required number of times, begin spawning coal again
/// </summary>
/// <param name="sender"> The Object being touched </param>
/// <param name="e"> Information regarding the touch event </param>
private void ObjectTouched(object sender, InteractableObjectEventArgs e)
{
count += 1;
if (count == countNeeded)
{
count = 0;
//turn on coal spawner script
(GetComponent("RandomCoalSpawning") as MonoBehaviour).enabled = true;
//turn off this script
(GetComponent("FixCoalSpawner") as MonoBehaviour).enabled = false;
//Turn off smoke effect
transform.Find("WhiteSmoke").gameObject.SetActive(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using POSServices.Data;
using POSServices.PosMsgModels;
namespace POSServices.WebAPIBackendController
{
[Route("api/TableSync")]
[ApiController]
public class TableSyncController : Controller
{
private readonly HO_MsgContext _context;
public TableSyncController(HO_MsgContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> getTableSync()
{
try
{
var jobList = (from TableToSynch in _context.TableToSynch
select new
{
TableName = TableToSynch.TableName
}).ToList();
return Json(jobList);
}
catch (Exception ex)
{
return StatusCode(500, new
{
status = "500",
message = ex.ToString()
});
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TECF;
[CreateAssetMenu(menuName = "FSM/States/ActionPhase")]
public class SActionPhase : IState
{
public override void Initialise(StateManager a_controller)
{
// Show dialog panel
//ReferenceManager.Instance.dialogPanel.SetActive(true);
// Hide action panel
ReferenceManager.Instance.actionPanel.SetActive(false);
// Identify enemy actions for this turn
BattleManager.Instance.DecideEnemyTurns();
// Run through command list
EventManager.TriggerEvent("RunThroughCommands");
}
public override void Shutdown(StateManager a_controller)
{
// Hide dialog panel
//ReferenceManager.Instance.dialogPanel.SetActive(false);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SendClippingPlaneInfo : MonoBehaviour
{
public string PositionKeyword;
public string PlaneNormalKeyword;
public string ClipPlaneEnableKeyword;
public bool jobON = false;
// Update is called once per frame
void Update()
{
if (jobON)
{
Shader.SetGlobalVector(PositionKeyword, this.transform.position);
Shader.SetGlobalVector(PlaneNormalKeyword, this.transform.forward);
//Shader.EnableKeyword(Keyword3);
}
}
public void enableClippingPlane()
{
Shader.EnableKeyword(ClipPlaneEnableKeyword);
jobON = true;
}
void OnDisable()
{
if (gameObject.activeInHierarchy == false)
{
Shader.DisableKeyword(ClipPlaneEnableKeyword);
jobON = false;
}
}
void OnEnable()
{
if (gameObject.activeInHierarchy == true)
{
Shader.EnableKeyword(ClipPlaneEnableKeyword);
jobON = true;
}
}
void OnDestroy()
{
//Shader.DisableKeyword(Keyword3);
jobON = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using Kingdee.CAPP.Model;
namespace Kingdee.CAPP.UI.Common
{
/// <summary>
/// 排序的逻辑
/// </summary>
public class NodeSorter: IComparer
{
/// <summary>
/// Comparer PlanningCardRelation 'Sort
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(object x, object y)
{
TreeNode tnX = x as TreeNode;
TreeNode tnY = y as TreeNode;
int x1 = Convert.ToInt32(tnX.Name);
int y1 = Convert.ToInt32(tnY.Name);
if (x1 > y1)
{
return 1;
}
else
{
return 0;
}
}
}
}
|
namespace ServerCommonLibrary
{
/// <summary>
/// RawRequest holds the informations about a request
/// </summary>
public class RawRequest
{
//#### Client connection
public SocketConnection Connection { get; set; }
//#### the request data
public byte[] RawData { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace WindowsFormsApplication1
{
public partial class Consulta : Form
{
string IP = "192.168.25.132";
int puerto = 9230;
Socket server;
public Consulta()
{
InitializeComponent();
}
public void SetPuerto(int p)
{
this.puerto = p;
}
public void SetIP(string ip)
{
this.IP = ip;
}
public void Consulta2()
{
//Preparamos el mensaje que queremos consultar
string mensaje = "2/";
//Enviamos la consulta al servidor
byte[] msg = System.Text.Encoding.ASCII.GetBytes(mensaje);
server.Send(msg);
//Recibimos la respuesta del servidor
byte[] msg2 = new byte[80];
server.Receive(msg2);
mensaje = Encoding.ASCII.GetString(msg2).Split('\0')[0];
MessageBox.Show("La experiencia del jugador que ganó la última partida es: " + mensaje + " puntos");
}
public void Consulta1()
{
//Preparamos el mensaje que queremos consultar
string mensaje = "1/" + textBox1.Text + "/" + textBox2.Text;
//Enviamos la consulta al servidor
byte[] msg = System.Text.Encoding.ASCII.GetBytes(mensaje);
server.Send(msg);
//Recibimos la respuesta del servidor
byte[] msg2 = new byte[80];
server.Receive(msg2);
mensaje = Encoding.ASCII.GetString(msg2).Split('\0')[0];
MessageBox.Show("La primera vez que jugaron fue: " + mensaje);
}
public void Consulta3()
{
//Preparamos el mensaje que queremos consultar
string mensaje = "3/" + textBox1.Text;
//Enviamos la consulta al servidor
byte[] msg = System.Text.Encoding.ASCII.GetBytes(mensaje);
server.Send(msg);
//Recibimos la respuesta del servidor
byte[] msg2 = new byte[80];
server.Receive(msg2);
mensaje = Encoding.ASCII.GetString(msg2).Split('\0')[0];
MessageBox.Show("El jugador " + textBox1.Text + " ha ganado " + mensaje + " partidas");
}
private void enviar_Click(object sender, EventArgs e)
{
//Creamos la conexión
IPAddress direc = IPAddress.Parse(IP);
IPEndPoint ipep = new IPEndPoint(direc, puerto);
//Creamos el socket
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Intentamos conectar con el servidor
try
{
server.Connect(ipep);
}
catch (SocketException)
{
//Mensaje de error en caso de no poder establecer la conexión
MessageBox.Show("No he podido conectar con el servidor");
return;
}
if (consulta1.Checked)
{
Consulta1();
}
if (consulta2.Checked)
{
Consulta2();
}
if (consulta3.Checked)
{
Consulta3();
}
}
private void Consulta_Load(object sender, EventArgs e)
{
}
private void desconectar_Click(object sender, EventArgs e)
{
//Creamos un IPEndPoint con el ip del servidor y puerto del servidor
//al que deseamos conectarnos
IPAddress direc = IPAddress.Parse(IP);
IPEndPoint ipep = new IPEndPoint(direc, puerto);
//Creamos el socket
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ipep);//Intentamos conectar el socket
}
catch (SocketException)
{
//Si hay excepcion imprimimos error y salimos del programa con return
MessageBox.Show("No he podido conectar con el servidor");
return;
}
// Quiere saber la longitud
string mensaje = "5/" + "Desconectar";
// Enviamos al servidor el nombre tecleado
byte[] msg = System.Text.Encoding.ASCII.GetBytes(mensaje);
server.Send(msg);
////Recibimos la respuesta del servidor
//byte[] msg2 = new byte[80];
//server.Receive(msg2);
//mensaje = Encoding.ASCII.GetString(msg2).Split('\0')[0];
//MessageBox.Show("La longitud de tu nombre es: " + mensaje);
// Se terminó el servicio.
// Nos desconectamos
server.Shutdown(SocketShutdown.Both);
server.Close();
this.Close();
Inicio form2 = new Inicio();
form2.ShowDialog();
}
}
}
|
using DAL;
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
public class IntercapiManager
{
public static DemandeIntercapi SendRequestIntercapi(int IdIntercapi, String Name, String Firstname, String Email, String Type, String Group, String Message)
{
return IntercapiDB.SendRequestIntercapi(IdIntercapi, Name, Firstname, Email, Type, Group, Message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
namespace Algorithm_Prim
{
class Program
{
static void Main(string[] args)
{
Initialization();
Prim();
Output();
Console.ReadLine();
}
struct Edge
{
public int u, v;
};
static int[,] graph; //
static List<int> MST; // Minimum spanning tree или минимален път
static List<Edge> EDGE;
static List<int> Values;
static void Prim()
{
int u = -1, ///съществуващ възел
v = -1; ///нов възел
int min;
int n = graph.GetLength(0);
int x = 0; //стартов възел
MST.Add(x);
while (MST.Count != n)
{
min = int.MaxValue;
foreach (int i in MST)
{
for (int j = 0; j < n; j++)
{
if (MST.Contains(j)) continue;
if (graph[i, j] != 0 && graph[i, j] < min)
{
min = graph[i, j];
u = i; v = j;
}
}
}
MST.Add(v);
Values.Add(min);
Edge e = new Edge();
e.u = u; e.v = v;
EDGE.Add(e);
}
}
static void Initialization()
{
graph = new int[,]
{
{0,17,0,26,0,0,0},
{17,0,5,10,0,0,0},
{0,5,0,3,2,20,0},
{26,10,3,0,8,0,0},
{0,0,2,8,0,8,0},
{0,0,20,0,8,0,9},
{0,0,0,0,0,9,0}
};
MST = new List<int>();
EDGE = new List<Edge>();
Values = new List<int>();
}
static void Output()
{
Console.Write("Minimum path: ");
foreach (int i in MST)
{
Console.Write("{0} ", i + 1);
}
Console.WriteLine();
Console.Write("Edges: ");
foreach (Edge e in EDGE)
{
Console.Write("({0}, {1}) ", e.u+1, e.v+1);
}
Console.WriteLine();
int F = 0;
foreach (var item in Values)
{
F += item;
}
Console.WriteLine("Fmin= {0}", F);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class SceneData
{
private List<string> _name;
private List<Vector3> _position;
private List<Vector3> _rotation;
private List<Vector3> _scale;
private List<int> _layer;
private List<string> _tag;
private GameObjectData _gameObjectData;
private List<bool> _has_Collider;
private List<Vector3> _collider_Center;
private List<Vector3> _collider_Size;
/// <summary>
/// 数据个数
/// </summary>
public int Count
{
get { return _name.Count; }
}
public SceneData()
{
_name = new List<string>();
_position = new List<Vector3>();
_rotation = new List<Vector3>();
_scale = new List<Vector3>();
_layer = new List<int>();
_tag = new List<string>();
_has_Collider = new List<bool>();
_collider_Center = new List<Vector3>();
_collider_Size = new List<Vector3>();
}
public void SaveData(string name, Vector3 pos, Vector3 rot, Vector3 sca, int layer, string tag)
{
_name.Add(name);
_position.Add(pos);
_rotation.Add(rot);
_scale.Add(sca);
_layer.Add(layer);
_tag.Add(tag);
_has_Collider.Add(false);
}
public void SaveData(string name, Vector3 pos, Vector3 rot, Vector3 sca, int layer, string tag,Vector3 collider_Center, Vector3 collider_Size)
{
_name.Add(name);
_position.Add(pos);
_rotation.Add(rot);
_scale.Add(sca);
_layer.Add(layer);
_tag.Add(tag);
_has_Collider.Add(true);
_collider_Center.Add(collider_Center);
_collider_Size.Add(collider_Size);
}
public GameObjectData GetData(int i)
{
if (i >= Count)
{
Debug.Log("超出数据大小");
return default(GameObjectData);
}
else
{
if (_has_Collider[i])
{
_gameObjectData = new GameObjectData(_name[i], _position[i], _rotation[i], _scale[i], _layer[i], _tag[i],_collider_Center[i],_collider_Size[i]);
}
else
{
_gameObjectData = new GameObjectData(_name[i], _position[i], _rotation[i], _scale[i], _layer[i], _tag[i]);
}
return _gameObjectData;
}
}
}
public struct GameObjectData
{
public string _name { get; private set; }
public Vector3 _position { get; private set; }
public Vector3 _rotation { get; private set; }
public Vector3 _scale { get; private set; }
public int _layer { get; private set; }
public string _tag { get; private set; }
public Vector3 _collider_Center { get; private set; }
public Vector3 _collider_Size { get; private set; }
public GameObjectData(string name, Vector3 pos, Vector3 rot, Vector3 sca, int layer, string tag):this()
{
_name = name;
_position = pos;
_rotation = rot;
_scale = sca;
_layer = layer;
_tag = tag;
}
public GameObjectData(string name, Vector3 pos, Vector3 rot, Vector3 sca, int layer, string tag, Vector3 collider_Center, Vector3 collider_Size) : this()
{
_name = name;
_position = pos;
_rotation = rot;
_scale = sca;
_layer = layer;
_tag = tag;
_collider_Center = collider_Center;
_collider_Size = collider_Size;
}
}
|
using EE;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using DAL;
namespace MPP
{
public class MPPObjetivo
{
public bool Alta_Objetivo(EEObjetivo objetivo)
{
Acceso Datos = new Acceso();
Hashtable Hdatos = new Hashtable();
bool Resultado;
string consulta = "SP_Objetivo_Alta";
Hdatos.Add("@Nombre", objetivo.Nombre);
Hdatos.Add("@Distancia", objetivo.Distancia);
Hdatos.Add("@ProbabilidadAcierto", objetivo.ProbabilidadAcierto);
Hdatos.Add("@Activo", objetivo.Activo);
Resultado = Datos.Escribir(consulta, Hdatos);
return Resultado;
}
public bool BajaObjetivo(EEObjetivo objetivo)
{
Acceso Datos = new Acceso();
Hashtable Hdatos = new Hashtable();
bool Resultado;
Hdatos.Add("@Id", objetivo.Id);
string consulta = "SP_Objetivo_Baja";
return Resultado = Datos.Escribir(consulta, Hdatos);
}
public BindingList<EEObjetivo> ListarObjetivo()
{
Acceso Datos = new Acceso();
DataSet ds = new DataSet();
BindingList<EEObjetivo> LObjetivos = new BindingList<EEObjetivo>();
ds = Datos.Leer("SP_Objetivo_Leer", null);
if (ds.Tables[0].Rows.Count > 0)
{
EEObjetivo eObjetivo;
foreach (DataRow fila in ds.Tables[0].Rows)
{
eObjetivo = new(
Convert.ToInt16(fila["Id"]),
fila["Nombre"].ToString(),
Convert.ToInt16(fila["Distancia"]),
Convert.ToInt16(fila["ProbabilidadAcierto"]),
Convert.ToBoolean(fila["Activo"]));
LObjetivos.Add(eObjetivo);
}
}
return LObjetivos;
}
}
}
|
using System.Linq;
using Mastermind;
using Mastermind.NET.Models;
using NUnit.Framework;
namespace MastermindTests
{
public class GameStateTests
{
[Test]
public void RandomNumbersGeneratedCorrectly()
{
var state = new GameState();
Assert.AreEqual(state.Numbers.Count, 4, "Game state should have four random numbers.");
Assert.IsTrue(state.Numbers.All(n => n >= 0 && n <= 6), "Randomly generated numbers should be between 1 and 6.");
}
[Test]
public void StateShouldReportMaxAttemptsReachedAt10()
{
var state = new GameState();
Assert.IsFalse(state.MaxAttemptsReached);
for (int i = 0; i < 10; i++)
{
state.IncrementAttempts();
}
Assert.IsTrue(state.MaxAttemptsReached);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using Sind.BLL;
using Sind.BLL.Excel;
using Sind.Model;
using Sind.Web.Publico.Controles;
using Sind.Web.Publico.Helpers;
namespace Sind.Web.Cadastros
{
public partial class ImportarPlanilhaValores : System.Web.UI.Page
{
#region [ PROPRIEDADES ]
private IList<ImportaPlanilha> listaImportacaoErros
{
get { return SessionHelper.listaImportacaoErros; }
set { SessionHelper.listaImportacaoErros = value; }
}
private IList<Filial> listaFiliais
{
get { return SessionHelper.ListFiliais; }
set { SessionHelper.ListFiliais = value; }
}
#endregion
#region [ EVENTOS ]
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
CarregarPrimeiroAcesso();
}
catch (Exception ex)
{
ExceptionHelper.PresentationErrorTreatment(ex);
}
}
protected void btnImportar_Click(object sender, EventArgs e)
{
try
{
ImportarExcel();
}
catch (Exception ex)
{
ExceptionHelper.PresentationErrorTreatment(ex);
}
}
protected void btnVoltar_Click(object sender, EventArgs e)
{
}
protected void grdCritica_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdCritica.PageIndex = e.NewPageIndex;
grdCritica.DataSource = this.listaImportacaoErros;
grdCritica.DataBind();
}
#endregion
#region [ MÉTODOS ]
private void CarregarPrimeiroAcesso()
{
SessionHelper.ListIndicadores = new ManterIndicador().GetAll();
SessionHelper.ListFiliais = new ManterFilial().GetAll();
}
public bool ValidarData(string DataImportacao)
{
bool teste = true;
string mes, ano;
string aux;
aux = DataImportacao;
mes = aux.Substring(3, 2);
ano = aux.Substring(6, 4);
var anoInteiro = Convert.ToInt32(ano);
if (mes != "01" && mes != "02" && mes != "03" && mes != "04" && mes != "05" && mes != "06"
&& mes != "07" && mes != "08" && mes != "09" && mes != "10" && mes != "11" && mes != "12")
{
teste = false;
}
if ((anoInteiro < 1900) || (anoInteiro > 3000))
{
teste = false;
}
return teste;
}
private void ImportarExcel()
{
if (!fluImportar.HasFile)
{
GerenciadorMensagens.IncluirMensagemAlerta("Selecione um arquivo.");
return;
}
if (!fluImportar.FileName.Contains(".xls"))
{
if (!fluImportar.FileName.Contains(".xlsx"))
{
GerenciadorMensagens.IncluirMensagemAlerta("Formato do arquivo selecionado é inválido. Selecione arquivos do microsoft excel (xls/xlsx).");
return;
}
}
DataTable dt = XlsxToDataSet(fluImportar.PostedFile.FileName);
// 0 ->idIndicador
// 1 ->idFilial,
// 2 -> mesAno
// 3 -> tipoBase
// 4 -> valor
Func<object[], bool> camposEstaoVazios = itens => itens.Select(x => x.ToString()).Where(x => string.IsNullOrWhiteSpace(x)).Count() == itens.Count();
var listaImportacao = (from row in dt.Rows.Cast<DataRow>()
where !camposEstaoVazios(row.ItemArray)
let colunas = row.ItemArray.Select(x => x.ToString()).ToArray()
select ValidarItensExcel(colunas[0], colunas[1], colunas[2], colunas[3], colunas[4])).ToList();
//Carrega lista de itens na grid de erros.
this.listaImportacaoErros = listaImportacao.Where(l => l.Mensagem != null).ToList();
if (this.listaImportacaoErros.Count > 0)
{
grdCritica.DataSource = this.listaImportacaoErros;
grdCritica.DataBind();
foreach (ImportaPlanilha importar in this.listaImportacaoErros)
{
listaImportacao.Remove(importar);
}
}
if (listaImportacao.Count > 0)
{
//SALVAR ITENS DA LISTA.
SalvarMovimentacao(listaImportacao);
GerenciadorMensagens.IncluirMensagemSucesso("Importação de Planilha de Valores ocorreu com sucesso.");
}
}
private void SalvarMovimentacao(List<ImportaPlanilha> listaImportacao)
{
ManterMovimentacao manterMovimentacao = new ManterMovimentacao();
foreach (ImportaPlanilha importaPlanilha in listaImportacao)
{
// manterMovimentacao.Insert(GetMovimentacao(importaPlanilha));
}
}
private Movimentacao GetMovimentacao(ImportaPlanilha importaPlanilha)
{
Movimentacao movimentacao = new Movimentacao();
movimentacao.Indicador = new Indicador();
movimentacao.Indicador.Id = Convert.ToInt32(importaPlanilha.IdIndicador);
movimentacao.Filial = new Filial();
movimentacao.Filial.Id = importaPlanilha.Filial.Id;
movimentacao.Status = StatusMovimentacaoEnum.EmAndamento;
movimentacao.TipoBase = TipoBaseEnum.ORC;
movimentacao.Valor = Convert.ToInt32(importaPlanilha.Valor);
return movimentacao;
}
private ImportaPlanilha ValidarItensExcel(string idIndicador, string idFilial, string mesAno, string tipoBase, string valor)
{
ImportaPlanilha importar = new ImportaPlanilha();
importar.Mensagem = new System.Text.StringBuilder();
#region [ Validar Indicador ]
if (!String.IsNullOrWhiteSpace(idIndicador))
{
var listaIndicadores = SessionHelper.ListIndicadores;
var totIndicadores = listaIndicadores.Where(l => l.Id == Convert.ToInt32(idIndicador)).Count();
if (totIndicadores == 0)
{
importar.Mensagem.Append("- Indicador informado, não existe na base de dados.");
importar.Mensagem.AppendLine();
}
importar.IdIndicador = Convert.ToInt32(idIndicador);
}
#endregion
#region [ Validar Filial ]
if (!String.IsNullOrWhiteSpace(idFilial))
{
//if (SessionHelper.UsuarioLogado.Perfil == PerfilEnum.GestorFabrica)
//{
var idUsuarioLogado = SessionHelper.UsuarioLogado.Id;
var listaFiliaisUsuarioLogado = new List<Filial>();
foreach (Filial filial in listaFiliais)
{
var totalUsuario = filial.Usuarios.Where(u => u.Id == idUsuarioLogado).Count();
if (totalUsuario > 0)
listaFiliaisUsuarioLogado.Add(filial);
}
//verificar se a filial informada esta na lista de filiais, se nao estiver enviar msg de erro!
var filialUsuario = listaFiliaisUsuarioLogado.Where(l => l.Id == Convert.ToInt32(idFilial)).SingleOrDefault();
if (filialUsuario != null)
{
importar.Filial = new Filial();
importar.Filial = filialUsuario;
}
else
{
importar.Mensagem.Append("- Filial informada não existe.");
importar.Mensagem.AppendLine();
}
// }
}
else
{
importar.Mensagem.Append("- Filial não foi informada.");
importar.Mensagem.AppendLine();
}
#endregion
#region [ VALIDAR TIPO BASE ]
if (!String.IsNullOrWhiteSpace(tipoBase))
{
if (!tipoBase.Contains("REA") && tipoBase.Contains("ORC") && tipoBase.Contains("RP1") && tipoBase.Contains("RP2") && tipoBase.Contains("RP3"))
{
importar.Mensagem.Append("- Tipo base informado inválido.");
importar.Mensagem.AppendLine();
}
else
{
importar.TipoBase = tipoBase;
}
}
else
{
importar.Mensagem.Append("- Tipo base não informado.");
importar.Mensagem.AppendLine();
}
#endregion
#region [ VALIDAR MES / ANO ]
//VALIDAR MES/ANO
if (String.IsNullOrWhiteSpace(mesAno))
{
importar.Mensagem.Append("- Mes/Ano não foi informado.");
importar.Mensagem.AppendLine();
}
else
{
if (!ValidarData(mesAno))
{
importar.Mensagem.Append("- Mes/Ano informado inválido.");
importar.Mensagem.AppendLine();
}
importar.MesAno = Convert.ToDateTime(mesAno).ToString("MM/yyyy");
}
#endregion
#region[ VALIDAR VALOR ]
if (!String.IsNullOrWhiteSpace(valor))
{
var valorConvertido = Convert.ToInt32(valor);
if (valorConvertido > 0 && valorConvertido < 99)
importar.Valor = valorConvertido;
else
{
importar.Mensagem.Append("- Valor informado inválido.");
importar.Mensagem.AppendLine();
}
}
else
{
importar.Mensagem.Append("- Valor não foi informado.");
importar.Mensagem.AppendLine();
}
#endregion
return importar;
}
public static DataTable XlsxToDataSet(string sFile)
{
DataTable dt = new DataTable();
OleDbDataAdapter MyCommand;
OleDbConnection MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFile + ";Extended Properties=Excel 12.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [Plan1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Table");
MyCommand.Fill(dt);
MyConnection.Close();
return dt;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebUI.Entity;
namespace WebUI.Data.Abstract
{
public interface IAbilityRepository
{
Ability GetById(int abilityId);
IQueryable<Ability> GetAll();
void AddAbility(Ability ability);
void DeleteAbility(int abilityId);
void SaveAbility(Ability ability);
}
}
|
using System;
using Xunit;
using System.Collections.Generic;
using System.Collections;
using ImagoCore.Models.Strategies;
using ImagoCore.Models;
namespace ImagoCore.Tests.Models.Strategies
{
public class FertigkeitVeraendernServiceTest
{
private readonly FertigkeitVeraendernService _service;
public FertigkeitVeraendernServiceTest()
{
_service = new FertigkeitVeraendernService();
}
[Theory]
[ClassData(typeof(FertigkeitSteigernGenugEpTestData))]
public void SteigereFertigkeit_FertigkeitHasGenugEp_SteigerungWertInc(int aktuellerSteigerungsWert, int verfuegbareEp, int erwarteterSteigerungsWert)
{
SteigerbareFertigkeitBase fertigkeit = new Fertigkeit() { SteigerungsWert = aktuellerSteigerungsWert, Erfahrung = verfuegbareEp };
_service.SteigereFertigkeit(ref fertigkeit);
var result = (fertigkeit).SteigerungsWert;
Assert.Equal(erwarteterSteigerungsWert, result);
}
[Theory]
[ClassData(typeof(FertigkeitSteigernNichtGenugEpTestData))]
public void SteigereFertigkeit_FertigkeitHasNotGenugEp_SteigerungWertNoInc(int aktuellerSteigerungsWert, int verfuegbareEp, int erwarteterSteigerungsWert)
{
SteigerbareFertigkeitBase fertigkeit = new Fertigkeit() { SteigerungsWert = aktuellerSteigerungsWert, Erfahrung = verfuegbareEp };
_service.SteigereFertigkeit(ref fertigkeit);
var result = (fertigkeit).SteigerungsWert;
Assert.Equal(erwarteterSteigerungsWert, result);
}
[Theory]
[ClassData(typeof(AttributSteigernGenugEpTestData))]
public void SteigereFertigkeit_AttributHasGenugEp_SteigerungWertInc(int aktuellerNw, int verfuegbareEp, int erwarteterNw)
{
SteigerbareFertigkeitBase fertigkeit = new Attribut() { SteigerungsWert = aktuellerNw, Erfahrung = verfuegbareEp };
_service.SteigereFertigkeit(ref fertigkeit);
var result = fertigkeit.SteigerungsWert;
Assert.Equal(erwarteterNw, result);
}
[Theory]
[ClassData(typeof(AttributSteigernNichtGenugEpTestData))]
public void SteigereFertigkeit_AttributHasNotGenugEp_SteigerungWertNoInc(int aktuellerNw, int verfuegbareEp, int erwarteterNw)
{
SteigerbareFertigkeitBase fertigkeit = new Attribut() { SteigerungsWert = aktuellerNw, Erfahrung = verfuegbareEp };
_service.SteigereFertigkeit(ref fertigkeit);
var result = fertigkeit.SteigerungsWert;
Assert.Equal(erwarteterNw, result);
}
[Theory]
[ClassData(typeof(FertigkeitsKategorieSteigernGenugEpTestData))]
public void SteigereFertigkeit_FertigkeitsKategorieHasGenugEp_SteigerungWertInc(int aktuellerSteigerungsWert, int verfuegbareEp, int erwarteterSteigerungsWert)
{
SteigerbareFertigkeitBase fertigkeit = new FertigkeitsKategorie() { SteigerungsWert = aktuellerSteigerungsWert, Erfahrung = verfuegbareEp };
_service.SteigereFertigkeit(ref fertigkeit);
var result = fertigkeit.SteigerungsWert;
Assert.Equal(erwarteterSteigerungsWert, result);
}
[Theory]
[ClassData(typeof(FertigkeitsKategorieSteigernNichtGenugEpTestData))]
public void SteigereFertigkeit_FertigkeitsKategorieHasNotGenugEp_SteigerungWertNoInc(int aktuellerSteigerungsWert, int verfuegbareEp, int erwarteterSteigerungsWert)
{
SteigerbareFertigkeitBase fertigkeit = new FertigkeitsKategorie() { SteigerungsWert = aktuellerSteigerungsWert, Erfahrung = verfuegbareEp };
_service.SteigereFertigkeit(ref fertigkeit);
var result = fertigkeit.SteigerungsWert;
Assert.Equal(erwarteterSteigerungsWert, result);
}
}
public class FertigkeitSteigernGenugEpTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 100; i++)
{
if (0 <= i && i <= 14)
{
var random = new Random();
yield return new object[] { i, random.Next(2, 10), i + 1 };
}
if (15 <= i && i <= 29)
{
var random = new Random();
yield return new object[] { i, random.Next(3, 11), i + 1 };
}
if (30 <= i && i <= 44)
{
var random = new Random();
yield return new object[] { i, random.Next(5, 13), i + 1 };
}
if (45 <= i && i <= 59)
{
var random = new Random();
yield return new object[] { i, random.Next(8, 16), i + 1 };
}
if (60 <= i && i <= 74)
{
var random = new Random();
yield return new object[] { i, random.Next(12, 21), i + 1 };
}
if (75 <= i && i <= 89)
{
var random = new Random();
yield return new object[] { i, random.Next(17, 30), i + 1 };
}
if (90 <= i)
{
var random = new Random();
yield return new object[] { i, random.Next(23, 38), i + 1 };
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class FertigkeitSteigernNichtGenugEpTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 100; i++)
{
if (0 <= i && i <= 14)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 2), i };
}
if (15 <= i && i <= 29)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 3), i };
}
if (30 <= i && i <= 44)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 5), i };
}
if (45 <= i && i <= 59)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 8), i };
}
if (60 <= i && i <= 74)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 12), i };
}
if (75 <= i && i <= 89)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 17), i };
}
if (90 <= i)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 23), i };
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class AttributSteigernGenugEpTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 99; i++)
{
if (0 <= i && i <= 39)
{
var random = new Random();
yield return new object[] { i, random.Next(2, 10), i + 1 };
}
if (40 <= i && i <= 49)
{
var random = new Random();
yield return new object[] { i, random.Next(3, 11), i + 1 };
}
if (50 <= i && i <= 59)
{
var random = new Random();
yield return new object[] { i, random.Next(5, 13), i + 1 };
}
if (60 <= i && i <= 69)
{
var random = new Random();
yield return new object[] { i, random.Next(8, 16), i + 1 };
}
if (70 <= i && i <= 79)
{
var random = new Random();
yield return new object[] { i, random.Next(12, 21), i + 1 };
}
if (80 <= i && i <= 89)
{
var random = new Random();
yield return new object[] { i, random.Next(17, 30), i + 1 };
}
if (90 <= i)
{
var random = new Random();
yield return new object[] { i, random.Next(23, 38), i + 1 };
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class AttributSteigernNichtGenugEpTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 100; i++)
{
if (0 <= i && i <= 39)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 2), i };
}
if (40 <= i && i <= 49)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 3), i };
}
if (50 <= i && i <= 59)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 5), i };
}
if (60 <= i && i <= 69)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 8), i };
}
if (70 <= i && i <= 79)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 12), i };
}
if (80 <= i && i <= 89)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 17), i };
}
if (90 <= i)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 23), i };
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class FertigkeitsKategorieSteigernGenugEpTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 100; i++)
{
if (0 <= i && i <= 4)
{
var random = new Random();
yield return new object[] { i, random.Next(5, 10), i + 1 };
}
if (5 <= i && i <= 9)
{
var random = new Random();
yield return new object[] { i, random.Next(8, 12), i + 1 };
}
if (10 <= i && i <= 14)
{
var random = new Random();
yield return new object[] { i, random.Next(12, 15), i + 1 };
}
if (15 <= i && i <= 19)
{
var random = new Random();
yield return new object[] { i, random.Next(17, 25), i + 1 };
}
if (20 <= i && i <= 24)
{
var random = new Random();
yield return new object[] { i, random.Next(23, 30), i + 1 };
}
if (25 <= i && i <= 29)
{
var random = new Random();
yield return new object[] { i, random.Next(30, 40), i + 1 };
}
if (30 <= i && i <= 34)
{
var random = new Random();
yield return new object[] { i, random.Next(38, 50), i + 1 };
}
if (35 <= i && i <= 39)
{
var random = new Random();
yield return new object[] { i, random.Next(47, 60), i + 1 };
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class FertigkeitsKategorieSteigernNichtGenugEpTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 100; i++)
{
if (0 <= i && i <= 4)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 5), i };
}
if (5 <= i && i <= 9)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 8), i };
}
if (10 <= i && i <= 14)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 12), i };
}
if (15 <= i && i <= 19)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 17), i };
}
if (20 <= i && i <= 24)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 23), i };
}
if (25 <= i && i <= 29)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 30), i };
}
if (30 <= i && i <= 34)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 38), i };
}
if (35 <= i && i <= 39)
{
var random = new Random();
yield return new object[] { i, random.Next(0, 47), i };
}
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
using System.Collections.Generic;
namespace NBatch.Main.Readers.FileReader.Services
{
public interface IFileService
{
IEnumerable<string> ReadLines(long startIndex, int chunkSize);
}
} |
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Dominio.Interfaces.Servicos
{
public interface IServicoNacionalidadesOnu: IServicoBase<NacionalidadesOnu>
{
NacionalidadesOnu ObterNacionalidadeOnuPorCodigoPais(int codigo);
}
}
|
/* Menu.cs
* Author: Agustin Rodriguez
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace DinoDiner.Menu
{
/// <summary>
/// this class contains properties for menu items such as entrees, drinks, and sides.
/// </summary>
public class Menu
{
/// <summary>
/// property that gets each menu item at dino diner
/// </summary>
public List<IMenuItem> AvailableMenuItems
{
get
{
List<IMenuItem> list = new List<IMenuItem>();
Fryceritops fry = new Fryceritops();
MeteorMacAndCheese mac = new MeteorMacAndCheese();
MezzorellaSticks sticks = new MezzorellaSticks();
Triceritots tots = new Triceritots();
list.Add(fry);
list.Add(mac);
list.Add(sticks);
list.Add(tots);
JurrasicJava jj = new JurrasicJava();
Sodasaurus soda = new Sodasaurus();
Tyrannotea tea = new Tyrannotea();
Water agua = new Water();
list.Add(jj);
list.Add(soda);
list.Add(tea);
list.Add(agua);
Brontowurst wurst = new Brontowurst();
DinoNuggets nuggs = new DinoNuggets();
PrehistoricPBJ sandwich = new PrehistoricPBJ();
PterodactylWings wings = new PterodactylWings();
SteakosaurusBurger burger = new SteakosaurusBurger();
TRexKingBurger king = new TRexKingBurger();
VelociWrap wrap = new VelociWrap();
list.Add(wurst);
list.Add(nuggs);
list.Add(sandwich);
list.Add(wings);
list.Add(burger);
list.Add(king);
list.Add(wrap);
return list;
}
}
/// <summary>
/// property that gets the available entrees at Dino DIner
/// </summary>
public List<IMenuItem> AvailableEntrees
{
get
{
List<IMenuItem> list = new List<IMenuItem>();
Brontowurst wurst = new Brontowurst();
DinoNuggets nuggs = new DinoNuggets();
PrehistoricPBJ sandwich = new PrehistoricPBJ();
PterodactylWings wings = new PterodactylWings();
SteakosaurusBurger burger = new SteakosaurusBurger();
TRexKingBurger king = new TRexKingBurger();
VelociWrap wrap = new VelociWrap();
list.Add(wurst);
list.Add(nuggs);
list.Add(sandwich);
list.Add(wings);
list.Add(burger);
list.Add(king);
list.Add(wrap);
return list;
}
}
/// <summary>
/// Property that gets the available sides at dino diner
/// </summary>
public List<IMenuItem> AvailableSides
{
get
{
List<IMenuItem> list = new List<IMenuItem>();
Fryceritops fry = new Fryceritops();
MeteorMacAndCheese mac = new MeteorMacAndCheese();
MezzorellaSticks sticks = new MezzorellaSticks();
Triceritots tots = new Triceritots();
list.Add(fry);
list.Add(mac);
list.Add(sticks);
list.Add(tots);
return list;
}
}
/// <summary>
/// property that gets the available drinks at dino diner
/// </summary>
public List<IMenuItem> AvailableDrinks
{
get
{
List<IMenuItem> list = new List<IMenuItem>();
JurrasicJava jj = new JurrasicJava();
Sodasaurus soda = new Sodasaurus();
Tyrannotea tea = new Tyrannotea();
Water agua = new Water();
list.Add(jj);
list.Add(soda);
list.Add(tea);
list.Add(agua);
return list;
}
}
/// <summary>
/// property that gets all available combos at dino diner and returns them in a list
/// </summary>
public List<IMenuItem> AvailableCombos
{
get
{
List<IMenuItem> list = new List<IMenuItem>();
Brontowurst wurst = new Brontowurst();
DinoNuggets nuggs = new DinoNuggets();
PrehistoricPBJ sandwich = new PrehistoricPBJ();
PterodactylWings wings = new PterodactylWings();
SteakosaurusBurger burger = new SteakosaurusBurger();
TRexKingBurger king = new TRexKingBurger();
VelociWrap wrap = new VelociWrap();
CretaceousCombo combo1 = new CretaceousCombo(wurst);
CretaceousCombo combo2 = new CretaceousCombo(nuggs);
CretaceousCombo combo3 = new CretaceousCombo(sandwich);
CretaceousCombo combo4 = new CretaceousCombo(wings);
CretaceousCombo combo5 = new CretaceousCombo(burger);
CretaceousCombo combo6 = new CretaceousCombo(king);
CretaceousCombo combo7 = new CretaceousCombo(wrap);
list.Add(combo1);
list.Add(combo2);
list.Add(combo3);
list.Add(combo4);
list.Add(combo5);
list.Add(combo6);
list.Add(combo7);
return list;
}
}
/// <summary>
/// overrides the ToString method to show every menu item seperated by new lines
/// </summary>
/// <returns></returns> returns every menu item as a string
public override string ToString()
{
return $"Jurassic Java \n Cola Sodasaurus \n Orange Sodasaurus \n Vanilla Sodasaurus \n Chocolate Sodasaurus \n RootBeet Sodasaurus \n Cherry Sodasaurus \n Lime Sodasaurus \n Decaf Jurassic Java \n Sweet Tyrannotea \n Tyrannotea Water \n Brontowurst \n Dino-Nuggets \n Prehistoric PB&J \n Pterodactyl Wings \n Steakosaurus Burger \n T-Rex King Burger \n Veloci-Wrap \n Friceritops \n Meteor Mac and Cheese \n Mezzorella Sticks \n Triceritots";
}
/// <summary>
/// adding every ingredient from every item into a list. No repeats
/// </summary>
public List<string> Ingredients
{
get
{
List<string> ingredients = new List<string>();
foreach (IMenuItem item in AvailableMenuItems)
{
for (int i = 0; i < item.Ingredients.Count; i++)
{
if (!ingredients.Contains(item.Ingredients[i]))
{
ingredients.Add(item.Ingredients[i]);
}
}
}
return ingredients;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeaklySmartUMLMaker.Fabrics;
namespace WeaklySmartUMLMaker
{
public static class FigureFabricCreator
{
private static Dictionary<ActionType, Type> _operations = new Dictionary<ActionType, Type>()
{
{ActionType.Aggregation, typeof( AggregationPolygonFabric) },
{ActionType.Association, typeof( AssociationFabric) },
{ActionType.Composition, typeof( CompositionFabric) },
{ActionType.CreateNewClass, typeof( CreateNewClassFabric) },
{ActionType.Inheritance, typeof( InheritanceFabric) },
{ActionType.Realization, typeof( RealizationFabric) },
{ActionType.Rectangle, typeof( RectangleFabric) },
};
public static FigureFabric GetFabric(ActionType type)
{
return (FigureFabric)Activator.CreateInstance(_operations[type]);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
public class RoomEffectEditor : EditorWindow
{
#region Exemples
//Exemple
/*
string myString = "Hello World";
bool groupEnabled;
bool myBool = true;
float myFloat = 1.23f;
*/
#endregion
public RoomEffect effect = RoomEffect.EMPTY;
public RoomEffect selectedEffect;
private RoomEffectManager _roomEffectManager = null;
// The variable to control where the scrollview 'looks' into its child elements.
Vector2 scrollPosition;
private static GUIStyle _selectedButton = null;
private static GUIStyle selectedButton
{
get
{
if (_selectedButton == null)
{
_selectedButton = new GUIStyle(GUI.skin.button); //Nouveau skin de button
_selectedButton.normal.background = _selectedButton.active.background; //On active le background de button appuyé
_selectedButton.normal.textColor = _selectedButton.active.textColor; //On active la couleur de texte de button appuyé
}
return _selectedButton; //On applique le nouveau skin de button appuyé
}
}
//Ajoute le RoomEffectEditor au menu Window
[MenuItem("Window/Room Effect Editor")]
static void Init()
{
//Récupère la window existante, et si elle n'existe pas, on en créé une nouvelle
RoomEffectEditor window = (RoomEffectEditor)EditorWindow.GetWindow(typeof(RoomEffectEditor));
window.Show();
}
//Fonction d'affichage sur la window
void OnGUI()
{
if (null == _roomEffectManager)
{
_roomEffectManager = GetRoomEffectManagerInScene(); //On récupère le RoomEffectManager sur la scène
}
if (null == _roomEffectManager)
{
//No Room Effect Manager in Scene
GUILayout.Label("Create a room effect manager on scene to continue.", EditorStyles.boldLabel);
return;
}
GUILayout.Label("Room Grid", EditorStyles.boldLabel);
int newSizeX = EditorGUILayout.IntField("Size X", _roomEffectManager.sizeX); //Champ int correspondant au nombre de room en largeur
int newSizeY = EditorGUILayout.IntField("Size Y", _roomEffectManager.sizeY); //Champ int correspondant au nombre de room en longueur
if (_roomEffectManager.sizeX != newSizeX || _roomEffectManager.sizeY != newSizeY)
{
_roomEffectManager.sizeX = newSizeX;
_roomEffectManager.sizeY = newSizeY;
RoomData[] roomDataArr = _roomEffectManager.roomsDataArr;
Array.Resize(ref roomDataArr, _roomEffectManager.sizeX * _roomEffectManager.sizeY);
for (int i = 0; i < roomDataArr.Length; ++i)
{
if (roomDataArr[i] == null)
roomDataArr[i] = new RoomData();
roomDataArr[i].x = i % newSizeX;
roomDataArr[i].y = i / newSizeX;
}
_roomEffectManager.roomsDataArr = roomDataArr;
}
//Affiche en ligne un button par effet de room, button qu'on devra sélectionner pour set un effet à une room
EditorGUILayout.BeginHorizontal();
foreach (RoomEffect effect in Enum.GetValues(typeof(RoomEffect)))
{
//Button créé directement dans le if, et ce if gère le click du button
if (GUILayout.Button(effect.ToString(), (effect == selectedEffect ? selectedButton : GUI.skin.button))) //Si on clique sur un button de choix d'effet
{
selectedEffect = effect; //On set selectedEffect à l'effet du button cliqué
}
}
EditorGUILayout.EndHorizontal();
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
//Affiche le tableau de room avec une room = un button
EditorGUILayout.BeginHorizontal(GUILayout.Width(_roomEffectManager.sizeX * 50));
for (int x = _roomEffectManager.sizeY - 1; x >= 0; x--)
{
EditorGUILayout.BeginVertical(GUILayout.Height(_roomEffectManager.sizeY * 50));
for (int y = _roomEffectManager.sizeX - 1; y >= 0; y--)
{
RoomData roomData = _GetRoomData(_roomEffectManager.roomsDataArr, y, x);
if (null != roomData)
{
if (GUILayout.Button(roomData.roomEffect.ToString(), GUILayout.Width(50), GUILayout.Height(50))) //Créé le button
{
roomData.roomEffect = selectedEffect;
}
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
if (GUILayout.Button("Generate map view")) //Si on clique sur le bouton generate
{
_roomEffectManager.GenerateRoomsView(); //On affiche le nouveau tableau sur la room tilemap
}
#region Exemple
//Exemples
/*
myString = EditorGUILayout.TextField("Text Field", myString);
groupEnabled = EditorGUILayout.BeginToggleGroup("Optional Settings", groupEnabled);
myBool = EditorGUILayout.Toggle("Toggle", myBool);
myFloat = EditorGUILayout.Slider("Slider", myFloat, -3, 3);
EditorGUILayout.EndToggleGroup();
*/
#endregion
}
private RoomData _GetRoomData(RoomData[] datasArr, int x, int y)
{
foreach (RoomData roomData in datasArr)
{
if (roomData.x == x && roomData.y == y)
{
return roomData;
}
}
return null;
}
public RoomEffectManager GetRoomEffectManagerInScene()
{
Scene scene = SceneManager.GetActiveScene();
GameObject[] rootGameObjects = scene.GetRootGameObjects();
foreach (GameObject rootGameObject in rootGameObjects)
{
RoomEffectManager roomEffectManager = rootGameObject.GetComponentInChildren<RoomEffectManager>();
if (null != roomEffectManager)
{
return roomEffectManager;
}
}
return null;
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Threading.Tasks;
namespace WebTest
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using ConsoleApp1.SqlConn;
namespace ConsoleApp1
{
class InsertData
{
public static void Insert()
{
SqlConnection connection = DBUtils.GetDBConnection();
connection.Open();
try
{
// Команда Insert.
string sql = "Insert into Person (PersonID, FirstName, LastName, ModifiedDate) "
+ " values (@personid, @firstname, @lastname, @modifieddate) ";
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = sql;
// Создать объект Parameter.
SqlParameter personID = new SqlParameter("@personid", SqlDbType.Int);
personID.Value = 4;
cmd.Parameters.Add(personID);
// Добавить параметр @firstname
SqlParameter firstname = cmd.Parameters.Add("@firstname", SqlDbType.Text);
firstname.Value = "nadya";
// Добавить параметр @lastname
cmd.Parameters.Add("@lastname", SqlDbType.Text).Value = "sakharova";
cmd.Parameters.Add("@modifieddate", SqlDbType.Date).Value = "12.12.2012";
// Выполнить Command (Используется для delete, insert, update).
int rowCount = cmd.ExecuteNonQuery();
Console.WriteLine("Row Count affected = " + rowCount);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
Console.WriteLine(e.StackTrace);
}
finally
{
connection.Close();
connection.Dispose();
connection = null;
}
}
}
}
|
using System.Web.Mvc;
using System;
using Foundry.Security;
using Foundry.Website.Extensions;
namespace Foundry.Website.Controllers
{
[UserFilter, ViewModelUserFilter]
public abstract partial class FoundryController : Controller
{
public const string VIEW_MESSAGE_KEY = "Message";
public IAuthorizationService AuthorizationService { get; set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
ProcessViewMessage();
}
private void ProcessViewMessage()
{
if (TempData.ContainsKey(VIEW_MESSAGE_KEY))
ViewData[VIEW_MESSAGE_KEY] = TempData[VIEW_MESSAGE_KEY];
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Engine.Events;
public class BaseGameUIPanelResultsBase : MonoBehaviour {
public UILabel totalScore;
public UILabel totalScoreSmarts;
public UILabel totalScores;
public UILabel totalCoins;
public UILabel totalTime;
public UILabel totalKills;
public virtual void OnEnable() {
Messenger<string>.AddListener(ButtonEvents.EVENT_BUTTON_CLICK, OnButtonClickEventHandler);
}
public virtual void OnDisable() {
Messenger<string>.RemoveListener(ButtonEvents.EVENT_BUTTON_CLICK, OnButtonClickEventHandler);
}
public virtual void Start() {
Init();
}
public virtual void Init() {
loadData();
}
public virtual void OnButtonClickEventHandler(string buttonName) {
//Debug.Log("OnButtonClickEventHandler: " + buttonName);
}
public virtual void UpdateDisplay(GamePlayerRuntimeData runtimeData, float timeTotal) {
double totalScoreValue = runtimeData.totalScoreValue;
UIUtil.SetLabelValue(totalTime, FormatUtil.GetFormattedTimeHoursMinutesSecondsMs((double)timeTotal));
UIUtil.SetLabelValue(totalCoins, runtimeData.coins.ToString("N0"));
UIUtil.SetLabelValue(totalScores, runtimeData.scores.ToString("N0"));
UIUtil.SetLabelValue(totalScoreSmarts, runtimeData.score.ToString("N0"));
UIUtil.SetLabelValue(totalScore, totalScoreValue.ToString("N0"));
UIUtil.SetLabelValue(totalKills, runtimeData.kills.ToString("N0"));
}
public virtual void loadData() {
//StartCoroutine(loadDataCo());
}
public virtual IEnumerator loadDataCo() {
yield return new WaitForSeconds(1f);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* Class for fixing the aspect ratio of the screen to 1:1 (for gameplay reasons: map is squared).
* For now, since the game doesn't allow resizing of the window, we only need to fix the ratio on Start.
*/
[RequireComponent(typeof(Camera))]
public class CameraAspectRatio : MonoBehaviour
{
private Camera mCamera;
void Start()
{
mCamera = GetComponent<Camera>();
FixAspectRatio();
}
void FixAspectRatio()
{
int width = Screen.width;
int height = Screen.height;
if (width != 0 && height != 0)
{
float ratio = (float)height / width;
if (ratio < 1.0f)
{
mCamera.rect = new Rect((1.0f - ratio) * 0.5f, 0.0f, ratio, 1.0f);
}
else if (ratio > 1.0f)
{
mCamera.rect = new Rect(0.0f, (1.0f - 1.0f / ratio) * 0.5f, 1.0f, 1.0f / ratio);
}
}
}
}
|
namespace ParkingSystem.Tests
{
using NUnit.Framework;
using System;
using System.Linq;
public class SoftParkTest
{
[SetUp]
public void Setup()
{
}
[Test]
public void TestPropertyGettersWorkCorrectly()
{
Car car = new Car("Vw", "8596");
string make = car.Make;
string registrationNumber = car.RegistrationNumber;
string expectedMake = "Vw";
string expectedRegistrationNumber = "8596";
Assert.AreEqual(expectedMake, make);
Assert.AreEqual(expectedRegistrationNumber, registrationNumber);
}
[Test]
public void TestSoftParksParkingWorkCorrectly()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
var expectedCar = "A1";
var carFromParking = softpark.Parking.FirstOrDefault(x => x.Key == "A1").Key;
Assert.AreEqual(expectedCar, carFromParking);
}
[Test]
public void TestParkCarMethodWorkCorrectly()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
string message=softpark.ParkCar("A1", car);
string expectedMessage= $"Car:8596 parked successfully!";
Assert.AreEqual(expectedMessage, message);
}
[Test]
public void TestParkCarMethodShouldThrowsException()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
//softpark.ParkCar("Volkswagen", car);
Assert.Throws<ArgumentException>(() => softpark.ParkCar("Volkswagen",car));
}
[Test]
public void TestParkCarMethodShouldThrowArgumentException()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
string message = "";
softpark.ParkCar("A1", car);
if(softpark.Parking["A1"] != null)
{
message = "Parking spot is already taken!";
}
string expectedMessage = "Parking spot is already taken!";
Assert.AreEqual(expectedMessage, message);
}
[Test]
public void TestParkCarExistCar()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
softpark.ParkCar("A1", car);
string message = "";
if(softpark.Parking.Values.Any(x => x?.RegistrationNumber == car.RegistrationNumber))
{
message = "Car is already parked!";
}
string expectedMessage = "Car is already parked!";
Assert.AreEqual(expectedMessage, message);
}
[Test]
public void TestRemoveCarMethodWorkCorrectly()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
softpark.ParkCar("A1", car);
string message= softpark.RemoveCar("A1", car);
string expectedMessage= "Remove car:8596 successfully!";
Assert.AreEqual(expectedMessage, message);
}
[Test]
public void TestRemoveCarMethodShouldThrowsException()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
Assert.Throws<ArgumentException>(() => softpark.RemoveCar("Volkswagen", car));
}
[Test]
public void TestRemoveCarMethodShouldThrowsArgumentException()
{
Car car = new Car("Audi", "8596");
SoftPark softpark = new SoftPark();
softpark.ParkCar("A1", car);
Assert.Throws<ArgumentException>(() => softpark.RemoveCar("A1", null));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Euler_Logic.Problems.AdventOfCode.Y2021 {
public class Problem23 : AdventOfCodeBase {
private List<Pod> _pods;
private Pod[] _locations;
private Dictionary<string, ulong> _hash;
private ulong _best = ulong.MaxValue;
private HomeBucket[] _homeBuckets;
private List<Route> _routes;
private char[] _key;
private enum enumRouteType {
HomeToHome,
HomeToHallway,
HallwayToHome
}
public override string ProblemName {
get { return "Advent of Code 2021: 23"; }
}
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private ulong Answer1(List<string> input) {
_locations = new Pod[7];
_hash = new Dictionary<string, ulong>();
SetHomeBuckets(false);
GetPods(input, false);
SetRoutes2();
SetKey();
return GetRecursiveCount(new string(_key), 0, 1);
}
private ulong Answer2(List<string> input) {
_locations = new Pod[7];
_hash = new Dictionary<string, ulong>();
SetHomeBuckets(true);
GetPods(input, true);
SetRoutes2();
SetKey();
return GetRecursiveCount(new string(_key), 0, 1);
}
private ulong GetRecursiveCount(string key, ulong prior, int moveCount) {
ulong best = ulong.MaxValue;
_hash.Add(key, 0);
foreach (var route in _routes) {
Action undo = null;
bool didPerform = false;
Pod pod = null;
ulong additionalSteps = 0;
switch (route.RouteType) {
case enumRouteType.HallwayToHome:
if (CanPerformHallwayToHome(route)) {
additionalSteps = (ulong)_homeBuckets[route.End].MaxIndex - (ulong)(_homeBuckets[route.End].NextOpen);
didPerform = true;
pod = PerformHallwayToHome(route.Start, route.End);
undo = () => PerformHomeToHallway(route.End, route.Start);
}
break;
case enumRouteType.HomeToHallway:
if (CanPerformHomeToHallway(route)) {
additionalSteps = (ulong)_homeBuckets[route.Start].MaxIndex - (ulong)(_homeBuckets[route.Start].NextOpen - 1);
didPerform = true;
pod = PerformHomeToHallway(route.Start, route.End);
undo = () => PerformHallwayToHome(route.End, route.Start);
}
break;
case enumRouteType.HomeToHome:
if (CanPerformHomeToHome(route)) {
additionalSteps = ((ulong)_homeBuckets[route.Start].MaxIndex - (ulong)(_homeBuckets[route.Start].NextOpen - 1)) + ((ulong)_homeBuckets[route.Start].MaxIndex - (ulong)(_homeBuckets[route.End].NextOpen));
didPerform = true;
pod = PerformHomeToHome(route.Start, route.End);
undo = () => PerformHomeToHome(route.End, route.Start);
}
break;
}
if (didPerform) {
ulong sub = pod.Energy * (route.Steps + additionalSteps);
var nextKey = new string(_key);
if (IsSolved()) {
if (sub < best) {
best = sub;
}
if (sub + prior < _best) {
_best = sub + prior;
}
} else {
ulong next = 0;
if (!_hash.ContainsKey(nextKey)) {
next = GetRecursiveCount(nextKey, sub + prior, moveCount + 1);
} else {
next = _hash[nextKey];
}
if (next != 0 && next != ulong.MaxValue && sub + next < best) {
best = sub + next;
if (prior + best < _best) {
_best = prior + best;
}
}
}
undo();
}
}
_hash[key] = best;
return _hash[key];
}
private bool IsSolved() {
return _homeBuckets[0].IsComplete && _homeBuckets[1].IsComplete && _homeBuckets[2].IsComplete && _homeBuckets[3].IsComplete;
}
private bool CanPerformHallwayToHome(Route route) {
var end = _homeBuckets[route.End];
Pod pod = _locations[route.Start];
// No pod at position
if (pod == null) return false;
// End bucket is not home bucket for pod
if (route.End != pod.HomeBucket) return false;
// End bucket has pods that don't belong in that bucket
foreach (var endPod in end.Pods) {
if (endPod != null && endPod.HomeBucket != route.End) return false;
}
// End bucket is already complete
if (end.IsComplete) return false;
// Route is blocked
foreach (var space in route.SpacesCovered) {
if (_locations[space] != null) return false;
}
return true;
}
private bool CanPerformHomeToHallway(Route route) {
var start = _homeBuckets[route.Start];
// Start bucket is complete
if (start.IsComplete) return false;
// Start bucket is empty
if (start.NextOpen == 0) return false;
// Start bucket is not complete, but has all home pods
int homeCount = 0;
foreach (var pod in start.Pods) {
if (pod != null && pod.HomeBucket == route.Start) homeCount++;
}
if (homeCount == start.NextOpen) return false;
// route is blocked
foreach (var space in route.SpacesCovered) {
if (_locations[space] != null) return false;
}
return true;
}
private bool CanPerformHomeToHome(Route route) {
var start = _homeBuckets[route.Start];
var end = _homeBuckets[route.End];
Pod pod = null;
// Start bucket is empty
if (_homeBuckets[route.Start].NextOpen == 0) return false;
pod = start.Pods[start.NextOpen - 1];
// End bucket is not home bucket for pod
if (route.End != pod.HomeBucket) return false;
// End bucket has pods that don't belong in that bucket
foreach (var endPod in end.Pods) {
if (endPod != null && endPod.HomeBucket != route.End) return false;
}
// End bucket is already complete
if (end.IsComplete) return false;
// Route is blocked
foreach (var space in route.SpacesCovered) {
if (_locations[space] != null) return false;
}
return true;
}
private Pod PerformHallwayToHome(int hallwayStart, int homeEnd) {
var end = _homeBuckets[homeEnd];
var pod = _locations[hallwayStart];
_locations[hallwayStart] = null;
end.Pods[end.NextOpen] = pod;
end.NextOpen++;
end.IsComplete = IsComplete(end, homeEnd);
_key[pod.Position] = '-';
pod.Position = end.Positions[end.NextOpen - 1];
_key[pod.Position] = pod.Name;
return pod;
}
private Pod PerformHomeToHome(int homeStart, int homeEnd) {
var start = _homeBuckets[homeStart];
var end = _homeBuckets[homeEnd];
end.Pods[end.NextOpen] = start.Pods[start.NextOpen - 1];
end.NextOpen++;
start.NextOpen--;
start.Pods[start.NextOpen] = null;
start.IsComplete = false;
end.IsComplete = IsComplete(end, homeEnd);
_key[end.Pods[end.NextOpen - 1].Position] = '-';
end.Pods[end.NextOpen - 1].Position = end.Positions[end.NextOpen - 1];
_key[end.Pods[end.NextOpen - 1].Position] = end.Pods[end.NextOpen - 1].Name;
return end.Pods[end.NextOpen - 1];
}
private Pod PerformHomeToHallway(int homeStart, int hallwayEnd) {
var start = _homeBuckets[homeStart];
_locations[hallwayEnd] = start.Pods[start.NextOpen - 1];
start.NextOpen--;
start.Pods[start.NextOpen] = null;
_key[_locations[hallwayEnd].Position] = '-';
_locations[hallwayEnd].Position = (ulong)hallwayEnd;
_key[_locations[hallwayEnd].Position] = _locations[hallwayEnd].Name;
start.IsComplete = false;
return _locations[hallwayEnd];
}
private bool IsComplete(HomeBucket bucket, int homeIndex) {
bool isComplete = bucket.NextOpen > bucket.MaxIndex;
if (isComplete) {
foreach (var pod in bucket.Pods) {
if (pod.HomeBucket != homeIndex) {
return false;
}
}
return true;
}
return false;
}
private void SetRoutes2() {
_routes = new List<Route>();
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 0, End = 1, SpacesCovered = new List<ulong>() { 2 }, Steps = 4 }); // Start & End are Homebucket indexes
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 0, End = 2, SpacesCovered = new List<ulong>() { 2, 3 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 0, End = 3, SpacesCovered = new List<ulong>() { 2, 3, 4 }, Steps = 8 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 1, End = 0, SpacesCovered = new List<ulong>() { 2 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 1, End = 2, SpacesCovered = new List<ulong>() { 3 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 1, End = 3, SpacesCovered = new List<ulong>() { 3, 4 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 2, End = 0, SpacesCovered = new List<ulong>() { 3, 2 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 2, End = 1, SpacesCovered = new List<ulong>() { 3 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 2, End = 3, SpacesCovered = new List<ulong>() { 4 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 3, End = 0, SpacesCovered = new List<ulong>() { 4, 3, 2 }, Steps = 8 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 3, End = 1, SpacesCovered = new List<ulong>() { 4, 3 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHome, Start = 3, End = 2, SpacesCovered = new List<ulong>() { 4 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 0, End = 0, SpacesCovered = new List<ulong>() { 1, 0 }, Steps = 3 }); // Start is HomeBucket index, End is position
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 0, End = 1, SpacesCovered = new List<ulong>() { 1 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 0, End = 2, SpacesCovered = new List<ulong>() { 2 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 0, End = 3, SpacesCovered = new List<ulong>() { 2, 3 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 0, End = 4, SpacesCovered = new List<ulong>() { 2, 3, 4 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 0, End = 5, SpacesCovered = new List<ulong>() { 2, 3, 4, 5 }, Steps = 8 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 0, End = 6, SpacesCovered = new List<ulong>() { 2, 3, 4, 5, 6 }, Steps = 9 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 1, End = 0, SpacesCovered = new List<ulong>() { 2, 1, 0 }, Steps = 5 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 1, End = 1, SpacesCovered = new List<ulong>() { 2, 1 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 1, End = 2, SpacesCovered = new List<ulong>() { 2 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 1, End = 3, SpacesCovered = new List<ulong>() { 3 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 1, End = 4, SpacesCovered = new List<ulong>() { 3, 4 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 1, End = 5, SpacesCovered = new List<ulong>() { 3, 4, 5 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 1, End = 6, SpacesCovered = new List<ulong>() { 3, 4, 5, 6 }, Steps = 7 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 2, End = 0, SpacesCovered = new List<ulong>() { 3, 2, 1, 0 }, Steps = 7 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 2, End = 1, SpacesCovered = new List<ulong>() { 3, 2, 1 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 2, End = 2, SpacesCovered = new List<ulong>() { 3, 2 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 2, End = 3, SpacesCovered = new List<ulong>() { 3 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 2, End = 4, SpacesCovered = new List<ulong>() { 4 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 2, End = 5, SpacesCovered = new List<ulong>() { 4, 5 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 2, End = 6, SpacesCovered = new List<ulong>() { 4, 5, 6 }, Steps = 5 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 3, End = 0, SpacesCovered = new List<ulong>() { 4, 3, 2, 1, 0 }, Steps = 9 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 3, End = 1, SpacesCovered = new List<ulong>() { 4, 3, 2, 1 }, Steps = 8 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 3, End = 2, SpacesCovered = new List<ulong>() { 4, 3, 2 }, Steps = 6 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 3, End = 3, SpacesCovered = new List<ulong>() { 4, 3 }, Steps = 4 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 3, End = 4, SpacesCovered = new List<ulong>() { 4 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 3, End = 5, SpacesCovered = new List<ulong>() { 5 }, Steps = 2 });
_routes.Add(new Route() { RouteType = enumRouteType.HomeToHallway, Start = 3, End = 6, SpacesCovered = new List<ulong>() { 5, 6 }, Steps = 3 });
foreach (var route in _routes.Where(x => x.RouteType == enumRouteType.HomeToHallway).ToList()) { // Start is position, End is HomeBucket Index
var routeToAdd = new Route() { RouteType = enumRouteType.HallwayToHome, Start = route.End, End = route.Start, SpacesCovered = new List<ulong>(route.SpacesCovered), Steps = route.Steps };
routeToAdd.SpacesCovered.Remove((ulong)routeToAdd.Start);
_routes.Add(routeToAdd);
}
for (int index = 0; index < _routes.Count; index++) {
_routes[index].Id = index;
}
_routes = _routes.OrderBy(x => {
if (x.RouteType == enumRouteType.HomeToHome) {
return 0;
} else if (x.RouteType == enumRouteType.HallwayToHome) {
return 1;
} else {
return 2;
}
}).ToList();
}
private void SetHomeBuckets(bool insertMiddle) {
int count = (insertMiddle ? 4 : 2);
_homeBuckets = new HomeBucket[4];
for (int index = 0; index < 4; index++) {
_homeBuckets[index] = new HomeBucket() { Pods = new Pod[count], Positions = new ulong[count], NextOpen = count, MaxIndex = count - 1 };
}
}
private void GetPods(List<string> input, bool insertMiddle) {
_pods = new List<Pod>();
if (!insertMiddle) {
_pods.Add(new Pod() { BitShift = 0, Name = input[2][3], Position = 7 });
_pods.Add(new Pod() { BitShift = 4, Name = input[2][5], Position = 9 });
_pods.Add(new Pod() { BitShift = 8, Name = input[2][7], Position = 11 });
_pods.Add(new Pod() { BitShift = 12, Name = input[2][9], Position = 13 });
_pods.Add(new Pod() { BitShift = 16, Name = input[3][3], Position = 8 });
_pods.Add(new Pod() { BitShift = 20, Name = input[3][5], Position = 10 });
_pods.Add(new Pod() { BitShift = 24, Name = input[3][7], Position = 12 });
_pods.Add(new Pod() { BitShift = 28, Name = input[3][9], Position = 14 });
} else {
_pods.Add(new Pod() { BitShift = 0, Name = input[2][3], Position = 7 });
_pods.Add(new Pod() { BitShift = 4, Name = input[2][5], Position = 11 });
_pods.Add(new Pod() { BitShift = 8, Name = input[2][7], Position = 15 });
_pods.Add(new Pod() { BitShift = 12, Name = input[2][9], Position = 19 });
_pods.Add(new Pod() { BitShift = 16, Name = input[3][3], Position = 10 });
_pods.Add(new Pod() { BitShift = 20, Name = input[3][5], Position = 14 });
_pods.Add(new Pod() { BitShift = 24, Name = input[3][7], Position = 18 });
_pods.Add(new Pod() { BitShift = 28, Name = input[3][9], Position = 22 });
_pods.Add(new Pod() { BitShift = 32, Name = 'D', Position = 8 });
_pods.Add(new Pod() { BitShift = 36, Name = 'D', Position = 9 });
_pods.Add(new Pod() { BitShift = 40, Name = 'C', Position = 12 });
_pods.Add(new Pod() { BitShift = 44, Name = 'B', Position = 13 });
_pods.Add(new Pod() { BitShift = 48, Name = 'B', Position = 16 });
_pods.Add(new Pod() { BitShift = 52, Name = 'A', Position = 17 });
_pods.Add(new Pod() { BitShift = 56, Name = 'A', Position = 20 });
_pods.Add(new Pod() { BitShift = 60, Name = 'C', Position = 21 });
}
foreach (var pod in _pods) {
SetPodSpecifics(pod);
if (insertMiddle) {
if (pod.Position <= 10) {
_homeBuckets[0].Pods[3 - (pod.Position - 7)] = pod;
_homeBuckets[0].Positions[3 - (pod.Position - 7)] = pod.Position;
} else if (pod.Position <= 14) {
_homeBuckets[1].Pods[3 - (pod.Position - 11)] = pod;
_homeBuckets[1].Positions[3 - (pod.Position - 11)] = pod.Position;
} else if (pod.Position <= 18) {
_homeBuckets[2].Pods[3 - (pod.Position - 15)] = pod;
_homeBuckets[2].Positions[3 - (pod.Position - 15)] = pod.Position;
} else {
_homeBuckets[3].Pods[3 - (pod.Position - 19)] = pod;
_homeBuckets[3].Positions[3 - (pod.Position - 19)] = pod.Position;
}
} else {
if (pod.Position <= 8) {
_homeBuckets[0].Pods[1 - (pod.Position - 7)] = pod;
_homeBuckets[0].Positions[1 - (pod.Position - 7)] = pod.Position;
} else if (pod.Position <= 10) {
_homeBuckets[1].Pods[1 - (pod.Position - 9)] = pod;
_homeBuckets[1].Positions[1 - (pod.Position - 9)] = pod.Position;
} else if (pod.Position <= 12) {
_homeBuckets[2].Pods[1 - (pod.Position - 11)] = pod;
_homeBuckets[2].Positions[1 - (pod.Position - 11)] = pod.Position;
} else {
_homeBuckets[3].Pods[1 - (pod.Position - 13)] = pod;
_homeBuckets[3].Positions[1 - (pod.Position - 13)] = pod.Position;
}
}
}
}
private void SetKey() {
var max = _pods.Select(x => x.Position).Max();
_key = new char[max + 1];
for (ulong count = 0; count < max; count++) {
_key[count] = '-';
}
foreach (var pod in _pods) {
_key[pod.Position] = pod.Name;
}
}
private void SetPodSpecifics(Pod pod) {
switch (pod.Name) {
case 'A':
pod.Energy = 1;
pod.HomeBucket = 0;
break;
case 'B':
pod.Energy = 10;
pod.HomeBucket = 1;
break;
case 'C':
pod.Energy = 100;
pod.HomeBucket = 2;
break;
case 'D':
pod.Energy = 1000;
pod.HomeBucket = 3;
break;
}
}
private string Output() {
var text = new StringBuilder();
text.AppendLine("#############");
text.Append("#");
if (_locations[0] != null) {
text.Append(_locations[0].Name);
} else {
text.Append(".");
}
if (_locations[1] != null) {
text.Append(_locations[1].Name);
} else {
text.Append(".");
}
text.Append(".");
if (_locations[2] != null) {
text.Append(_locations[2].Name);
} else {
text.Append(".");
}
text.Append(".");
if (_locations[3] != null) {
text.Append(_locations[3].Name);
} else {
text.Append(".");
}
text.Append(".");
if (_locations[4] != null) {
text.Append(_locations[4].Name);
} else {
text.Append(".");
}
text.Append(".");
if (_locations[5] != null) {
text.Append(_locations[5].Name);
} else {
text.Append(".");
}
if (_locations[6] != null) {
text.Append(_locations[6].Name);
} else {
text.Append(".");
}
text.AppendLine("#");
text.Append("###");
for (int index = 0; index < 4; index++) {
if (_homeBuckets[index].Pods[3] != null) {
text.Append(_homeBuckets[index].Pods[3].Name);
} else {
text.Append(".");
}
text.Append("#");
}
text.AppendLine("##");
for (int count = 2; count >= 0; count--) {
text.Append(" #");
for (int index = 0; index < 4; index++) {
if (_homeBuckets[index].Pods[count] != null) {
text.Append(_homeBuckets[index].Pods[count].Name);
} else {
text.Append(".");
}
text.Append("#");
}
text.AppendLine();
}
text.AppendLine(" #########");
return text.ToString();
}
private class HomeBucket {
public Pod[] Pods { get; set; }
public ulong[] Positions { get; set; }
public int NextOpen { get; set; }
public bool IsComplete { get; set; }
public int MaxIndex { get; set; }
}
private class Pod {
public char Name { get; set; }
public ulong Position { get; set; }
public int BitShift { get; set; }
public ulong Energy { get; set; }
public bool IsHome { get; set; }
public int HomeBucket { get; set; }
}
private class Route {
public int Start { get; set; }
public int End { get; set; }
public ulong Steps { get; set; }
public List<ulong> SpacesCovered { get; set; }
public enumRouteType RouteType { get; set; }
public int Id { get; set; }
}
}
}
|
using iSukces.Code.Interfaces;
namespace iSukces.Code.Irony
{
public class SimpleCodeExpression : ICsExpression
{
public SimpleCodeExpression(string code) => Code = code;
public string GetCode(ITypeNameResolver resolver) => Code;
public string Code { get; }
}
} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArkSavegameToolkitNet
{
public class ArkStringCache
{
private ConcurrentDictionary<string, string> _items;
public ArkStringCache()
{
_items = new ConcurrentDictionary<string, string>();
}
public string Add(string value)
{
if (value == null) return null;
try
{
string result;
if (!_items.TryGetValue(value, out result))
{
if (!_items.TryAdd(value, value))
{
_items.TryGetValue(value, out result);
return result;
}
return value;
}
return result;
}
catch { }
return value;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
[RequireComponent(typeof(Panel))]
public class UIPlayerPointsList : MonoBehaviour
{
public static UIPlayerPointsList instance;
public VerticalLayoutGroup playerList;
private Panel _panel;
//Flag
bool eventHappened = false;
private void Awake()
{
if(instance)
return;
instance = this;
_panel = GetComponent<Panel>();
}
public void UpdatePoints(Action onComplete)
{
StartCoroutine(UpdatePointsAnimation(onComplete));
}
IEnumerator UpdatePointsAnimation(Action onComplete)
{
yield return new WaitForSeconds(0.5f);
_panel.Open();
yield return new WaitForSeconds(0.5f);
UIPlayerPoints[] uiPlayers = GetComponentsInChildren<UIPlayerPoints>();
foreach (var uiPlayer in uiPlayers)
{
uiPlayer.UpdatePoints(OnEvent);
yield return WaitForEvent();
}
onComplete?.Invoke();
}
//Event subscriber that sets the flag
void OnEvent(){
eventHappened=true;
}
//Coroutine that waits until the flag is set
IEnumerator WaitForEvent() {
yield return new WaitUntil(()=> eventHappened);
eventHappened=false;
}
}
|
using DChild.Gameplay;
using DChild.Gameplay.Objects;
using Sirenix.OdinInspector;
using UnityEngine;
public class AutoStep : MonoBehaviour
{
[SerializeField]
[TabGroup("Sensors")]
private RaycastSensor m_upperSensor;
[SerializeField]
[TabGroup("Sensors")]
private RaycastSensor m_lowerSensor;
[SerializeField]
[TabGroup("Step Config")]
private float m_tolerableHeight;
[SerializeField]
[TabGroup("Step Config")]
private float m_stepDistance;
[SerializeField]
[TabGroup("Step Config")]
private float m_stepSpeed;
private bool m_isRight;
private float m_flipDirection;
private Transform m_player;
private void Update()
{
var stepUp = false;
var targetPos = m_player.position;
var input = Input.GetAxis("Horizontal");
if (input != 0)
{
var scale = m_player.localScale;
if (input > 0)
{
scale.x = m_flipDirection;
m_isRight = true;
}
else if (input < 0)
{
scale.x = -m_flipDirection;
m_isRight = false;
}
m_player.localScale = scale;
}
if (m_upperSensor.isDetecting && m_lowerSensor.isDetecting)
{
var collider = m_upperSensor.GetPriorityHit(Direction.Right).collider;
if (collider != null)
{
var step = collider.GetComponentInParent<Transform>();
var stepHeight = step.GetComponent<Collider2D>().bounds.extents.y + 5;
if ((stepHeight) <= m_tolerableHeight)
{
targetPos.y = step.position.y + stepHeight + 10;
stepUp = true;
if (m_isRight)
targetPos.x += m_stepDistance;
else
targetPos.x -= m_stepDistance;
}
}
if (stepUp)
{
if (input != 0)
{
if (m_isRight)// && input > 0)
{
m_player.position = Vector3.Lerp(m_player.position, targetPos, Time.deltaTime * m_stepSpeed);
}
else if (!m_isRight)// && input < 0)
{
m_player.position = Vector3.Lerp(m_player.position, targetPos, Time.deltaTime * m_stepSpeed);
}
}
}
}
}
private void Start()
{
m_player = GetComponentInParent<Transform>();
m_flipDirection = m_player.localScale.x;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Overall
{
public class MenuController : MonoBehaviour
{
public static MenuController instance;
// Outlets
public GameObject welcomeMenu;
public GameObject levelMenu;
// State Tracking
public string level1;
public string level2;
public string level3;
public string level4;
//Methods
void Awake()
{
instance = this;
Hide();
Show();
}
public void Show()
{
ShowWelcomeMenu();
gameObject.SetActive(true);
Time.timeScale = 0;
}
public void Hide()
{
gameObject.SetActive(false);
Time.timeScale = 1;
}
void SwitchMenu(GameObject someMenu)
{
//Turn off all menus
welcomeMenu.SetActive(false);
levelMenu.SetActive(false);
//Turn on requested menu
someMenu.SetActive(true);
}
public void ShowWelcomeMenu()
{
SwitchMenu(welcomeMenu);
}
public void ShowLevelMenu()
{
SwitchMenu(levelMenu);
}
public void LoadLevel1()
{
Time.timeScale = 1;
SceneManager.LoadScene(level1);
}
public void LoadLevel2()
{
Time.timeScale = 1;
SceneManager.LoadScene(level2);
}
public void LoadLevel3()
{
Time.timeScale = 1;
SceneManager.LoadScene(level3);
}
public void LoadLevel4()
{
Time.timeScale = 1;
SceneManager.LoadScene(level4);
}
public void ExitGame()
{
Application.Quit();
}
}
}
|
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Instances;
namespace Profiling2.Infrastructure.NHibernateMaps.Conventions
{
public class StringClobColumnConvention : IPropertyConvention, IPropertyConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType == typeof(string)).Expect(x => x.Length == 0);
}
public void Apply(IPropertyInstance instance)
{
instance.CustomType("StringClob");
instance.CustomSqlType("nvarchar(max)");
}
}
}
|
using DChild.Gameplay.Objects.Characters;
using UnityEngine;
namespace DChild.Gameplay.Player
{
public class PlayerDoubleJump : CharacterJump, IDoubleJump, IPlayerBehaviour
{
[SerializeField]
private bool m_isEnabled;
private bool m_canDoubleJump;
private bool m_restrictHighJump;
public bool isEnabled => m_isEnabled;
public bool canDoubleJump => m_canDoubleJump;
public void EnableSkill(bool value) => m_isEnabled = value;
public void Initialize(IPlayer player) => m_characterPhysics2D = player.physics;
public bool Jump(bool isPressed)
{
if (m_isEnabled)
{
if (m_canDoubleJump && isPressed)
{
Jump();
m_canDoubleJump = false;
return true;
}
}
return false;
}
public void ResetSkill()
{
m_canDoubleJump = true;
}
}
}
|
using gView.Framework.Geometry;
using System.Collections.Generic;
using System.Data;
namespace gView.Framework.FDB
{
public interface ISpatialIndex
{
bool InitIndex(string FCName);
bool InsertNodes(string FCName, List<SpatialIndexNode> nodes);
DataTable QueryIDs(IEnvelope env);
}
}
|
using Cs_Gerencial.Dominio.Entities;
using Cs_Gerencial.Dominio.Interfaces.Repositorios;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Infra.Data.Repositorios
{
public class RepositorioTabelaCustas : RepositorioBase<TabelaCustas>, IRepositorioTabelaCustas
{
public List<TabelaCustas> CalcularItensCustasComValor(decimal baseCalculo, int ano)
{
var listaItens = new List<TabelaCustas>();
var listaCustas = Db.TabelaCustas.Where(p => p.Tabela == "22" && p.Tabela == "16" && p.Ano == ano).ToList();
if (baseCalculo <= 15000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "1").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
if (baseCalculo > 15000.00M && baseCalculo <= 30000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "2").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
if (baseCalculo > 30000.00M && baseCalculo <= 45000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "3").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
if (baseCalculo > 45000.00M && baseCalculo <= 60000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
if (baseCalculo > 60000.00M && baseCalculo <= 80000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "5").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
if (baseCalculo > 80000.00M && baseCalculo <= 100000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "6").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
if (baseCalculo > 100000.00M && baseCalculo <= 200000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "7").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
if (baseCalculo > 200000.00M && baseCalculo <= 400000.00M)
{
listaItens.Add(listaCustas.Where(p => p.SubItem == "8").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
}
return listaItens;
}
public List<TabelaCustas> CalcularItensCustas(string tipo, int ano)
{
var listaItens = new List<TabelaCustas>();
var listaCustas = Db.TabelaCustas.Where(p => (p.Tabela == "22" || p.Tabela == "16") && p.Ano == ano).ToList();
tipo = tipo.ToUpper();
listaItens.Add(listaCustas.Where(p => p.Descricao == tipo).FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "4").FirstOrDefault());
listaItens.Add(listaCustas.Where(p => p.Tabela == "16" && p.Item == "5").FirstOrDefault());
return listaItens;
}
public bool AtualizarCustas(int ano)
{
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodingTest
{
/// <summary>
/// Class that wraps a dictionary of string and Record and provides functionality
/// to Add to dict if a key is not already present, elsewise the 'Added' and the
/// existing Record instances PatchRequired properties are set to false to represent
/// two Records with the same hostname or IP address being present within the data set.
/// -----------------------------------------------------------------------------------
/// This method works as .NET passes object types by reference, meaning the dictionary
/// contains references to the original object instead of new instances each time.
/// </summary>
public class DictionaryWrapper
{
private Dictionary<string, Record> _dictionary;
public DictionaryWrapper()
{
_dictionary = new Dictionary<string, Record>();
}
/// <summary>
/// Function to add to the dictionary or set PatchRequired
/// property to false.
/// </summary>
/// <param name="key">Key value (IP address or hostname)</param>
/// <param name="val">Record instance associated with that key.</param>
public void Add(string key, Record val)
{
if (key != string.Empty) //Don't consider invalid values with empty properties.
{
Record current = GetKeyValue(key); //Attempt to retrieve value from dictionary with provided key
//If no record is associated then add the record to the dictionary
if (current == null)
{
_dictionary.Add(key, val);
}
//Elsewise set both patchrequired values to false (so neither are printed)
else
{
val.PatchRequired = false;
current.PatchRequired = false;
}
}
}
/// <summary>
/// Method to attempt to retieve a Value from dictionary
/// based on a provided key. Returns null if no value is
/// found.
/// </summary>
/// <param name="key">Key to find in dictionary</param>
/// <returns>Null or valid record.</returns>
private Record GetKeyValue(string key)
{
Record retVal = null;
_dictionary.TryGetValue(key, out retVal);
return retVal;
}
}
}
|
using Genesys.WebServicesClient.Components;
using Genesys.WebServicesClient.Sample.Agent.WPF.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Genesys.WebServicesClient.Sample.Agent.WPF
{
public partial class MainWindow : Window
{
readonly GenesysConnection genesysConnection;
readonly GenesysUser genesysUser;
readonly GenesysDevice genesysDevice;
readonly GenesysInteractionManager genesysInteractionManager;
readonly GenesysChannelManager genesysChannelManager;
public MainWindow()
{
InitializeComponent();
genesysConnection = new GenesysConnection();
genesysUser = new GenesysUser()
{
Connection = genesysConnection,
};
genesysDevice = new GenesysDevice()
{
User = genesysUser,
};
genesysInteractionManager = new GenesysInteractionManager()
{
User = genesysUser,
};
genesysChannelManager = new GenesysChannelManager()
{
User = genesysUser,
};
ConnectionPanel.DataContext = genesysConnection;
UserPanel.DataContext = genesysUser;
DevicePanel.DataContext = genesysDevice;
CallsPanel.DataContext = genesysInteractionManager;
ActiveCallPanel.DataContext = genesysInteractionManager;
CallDataGrid.ItemsSource = genesysInteractionManager.Calls;
ChannelsPanel.DataContext = genesysChannelManager;
ChatDataGrid.ItemsSource = genesysInteractionManager.Chats;
ActiveChatPanel.DataContext = genesysInteractionManager;
genesysUser.Updated += (s, e) =>
{
UpdateUserDataGrid();
};
genesysInteractionManager.Calls.ListChanged += Calls_ListChanged;
genesysInteractionManager.Chats.ListChanged += Chats_ListChanged;
}
void Calls_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
new ToastWindow(genesysInteractionManager.Calls[e.NewIndex]).Show();
}
}
void Chats_ListChanged(object sender, ListChangedEventArgs e)
{
ChatMessagesDataGrid.ItemsSource = genesysInteractionManager.ActiveChatMessages;
}
void UpdateUserDataGrid()
{
if (genesysInteractionManager.ActiveCall != null)
{
userDataPropertyGrid.SelectedObject = null;
userDataPropertyGrid.SelectedObject = genesysInteractionManager.ActiveCall.UserData;
userDataPropertyGrid.Refresh();
}
}
async void OpenConnection_Click(object sender, RoutedEventArgs e)
{
genesysConnection.ServerUri = ServerUri.Text;
genesysConnection.UserName = Username.Text;
genesysConnection.Password = Password.Text;
genesysConnection.OpenTimeoutMs = Settings.Default.OpenConnectionTimeoutMs;
try
{
await genesysConnection.StartAsync();
await genesysUser.StartAsync();
}
catch (Exception ex)
{
genesysConnection.Stop();
// OperationCanceledException is thrown if Close was requested while Opening. That's OK
if (!(ex is OperationCanceledException))
throw;
}
}
void CloseConnection_Click(object sender, RoutedEventArgs e)
{
genesysConnection.Dispose();
}
void SetReady_Click(object sender, RoutedEventArgs e)
{
genesysUser.DoOperation("Ready");
}
void SetNotReady_Click(object sender, RoutedEventArgs e)
{
genesysUser.DoOperation("NotReady");
}
void StartSessionChat_Click(object sender, RoutedEventArgs e)
{
genesysUser.StartContactCenterSession(new string[] { "chat" }, null, null, null, null);
}
void AnswerButton_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveCall.Answer();
}
void HangupButton_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveCall.Hangup();
}
void AttachUserData_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveCall.AttachUserData(new Dictionary<string, string>()
{
{ UserDataKey.Text, UserDataValue.Text },
});
}
void UpdateUserData_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveCall.UpdateUserData(new Dictionary<string, string>()
{
{ UserDataKey.Text, UserDataValue.Text },
});
}
void TestToast_Click(object sender, RoutedEventArgs e)
{
ToastWindow toast = new ToastWindow();
toast.Show();
}
void StartSession_Click(object sender, RoutedEventArgs e)
{
var channels = new List<string>();
if (ChatChannelCheckBox.IsChecked.Value)
channels.Add("chat");
if (TwitterChannelCheckBox.IsChecked.Value)
channels.Add("twitter");
genesysUser.StartContactCenterSession(channels);
}
void EndSession_Click(object sender, RoutedEventArgs e)
{
genesysUser.EndContactCenterSession();
}
void AcceptChat_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveChat.Accept(Username.Text);
}
void RejectChat_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveChat.Reject();
}
void CompleteChat_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveChat.Complete();
}
void SendMessageChat_Click(object sender, RoutedEventArgs e)
{
SendMessage();
}
void ChatMessageTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
SendMessage();
}
void SendMessage()
{
genesysInteractionManager.ActiveChat.SendMessage(ChatMessageTextBox.Text);
ChatMessageTextBox.Clear();
}
void LeaveChat_Click(object sender, RoutedEventArgs e)
{
genesysInteractionManager.ActiveChat.Leave();
}
}
}
|
using System.Net;
namespace AxiEndPoint.EndPointClient
{
public interface IEndPoint
{
/// <summary>
/// Отправляет данные на сервер и возвращает ответ
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
ResponseData Send(RequestData data);
ResponseData Send(RequestData data, IPEndPoint ipEndPoint);
}
} |
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
using Sentry.Protocol.Envelopes;
namespace Sentry.Internal.Http;
internal class CachingTransport : ITransport, IAsyncDisposable, IDisposable
{
private const string EnvelopeFileExt = "envelope";
private readonly ITransport _innerTransport;
private readonly SentryOptions _options;
private readonly bool _failStorage;
private readonly string _isolatedCacheDirectoryPath;
private readonly int _keepCount;
// When a file is getting processed, it's moved to a child directory
// to avoid getting picked up by other threads.
private readonly string _processingDirectoryPath;
// Signal that tells the worker whether there's work it can do.
// Pre-released because the directory might already have files from previous sessions.
private readonly Signal _workerSignal = new(true);
// Signal that ensures only one thread can process items from the cache at a time
private readonly Signal _processingSignal = new(true);
// Lock to synchronize file system operations inside the cache directory.
// It's required because there are multiple threads that may attempt to both read
// and write from/to the cache directory.
// Lock usage is minimized by moving files that are being processed to a special directory
// where collisions are not expected.
private readonly Lock _cacheDirectoryLock = new();
private readonly CancellationTokenSource _workerCts = new();
private Task _worker = null!;
private ManualResetEventSlim? _initCacheResetEvent = new();
private ManualResetEventSlim? _preInitCacheResetEvent = new();
// Inner transport exposed internally primarily for testing
internal ITransport InnerTransport => _innerTransport;
private readonly IFileSystem _fileSystem;
public static CachingTransport Create(ITransport innerTransport, SentryOptions options,
bool startWorker = true,
bool failStorage = false)
{
var transport = new CachingTransport(innerTransport, options, failStorage);
transport.Initialize(startWorker);
return transport;
}
private CachingTransport(ITransport innerTransport, SentryOptions options, bool failStorage)
{
_innerTransport = innerTransport;
_options = options;
_failStorage = failStorage; // For testing
_fileSystem = options.FileSystem;
_keepCount = _options.MaxCacheItems >= 1
? _options.MaxCacheItems - 1
: 0; // just in case MaxCacheItems is set to an invalid value somehow (shouldn't happen)
_isolatedCacheDirectoryPath =
options.TryGetProcessSpecificCacheDirectoryPath() ??
throw new InvalidOperationException("Cache directory or DSN is not set.");
_processingDirectoryPath = Path.Combine(_isolatedCacheDirectoryPath, "__processing");
}
private void Initialize(bool startWorker)
{
// Restore any abandoned files from a previous session
MoveUnprocessedFilesBackToCache();
// Ensure directories exist
_fileSystem.CreateDirectory(_isolatedCacheDirectoryPath);
_fileSystem.CreateDirectory(_processingDirectoryPath);
// Start a worker, if one is needed
if (startWorker)
{
_options.LogDebug("Starting CachingTransport worker.");
_worker = Task.Run(CachedTransportBackgroundTaskAsync);
}
else
{
_worker = Task.CompletedTask;
}
// Wait for init timeout, if configured. (Can't do this without a worker.)
if (startWorker && _options.InitCacheFlushTimeout > TimeSpan.Zero)
{
_options.LogDebug("Blocking initialization to flush the cache.");
try
{
// This will complete just before processing starts in the worker.
// It ensures that we don't start the timeout period prematurely.
_preInitCacheResetEvent!.Wait(_workerCts.Token);
// This will complete either when the first round of processing is done,
// or on timeout, whichever comes first.
var completed = _initCacheResetEvent!.Wait(_options.InitCacheFlushTimeout, _workerCts.Token);
if (completed)
{
_options.LogDebug("Completed flushing the cache. Resuming initialization.");
}
else
{
_options.LogDebug(
$"InitCacheFlushTimeout of {_options.InitCacheFlushTimeout} reached. " +
"Resuming initialization. Cache will continue flushing in the background.");
}
}
finally
{
// We're done with these. Dispose them.
_preInitCacheResetEvent!.Dispose();
_initCacheResetEvent!.Dispose();
//Set null to avoid object disposed exceptions on future processing calls.
_preInitCacheResetEvent = null;
_initCacheResetEvent = null;
}
}
}
private async Task CachedTransportBackgroundTaskAsync()
{
_options.LogDebug("CachingTransport worker has started.");
while (!_workerCts.IsCancellationRequested)
{
try
{
await _workerSignal.WaitAsync(_workerCts.Token).ConfigureAwait(false);
_options.LogDebug("CachingTransport worker signal triggered.");
await ProcessCacheAsync(_workerCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (_workerCts.IsCancellationRequested)
{
// Swallow if IsCancellationRequested as it'll get out of the loop
break;
}
catch (Exception ex)
{
_options.LogError("Exception in CachingTransport worker.", ex);
try
{
// Wait a bit before retrying
await Task.Delay(500, _workerCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break; // Shutting down triggered while waiting
}
}
}
_options.LogDebug("CachingTransport worker stopped.");
}
private void MoveUnprocessedFilesBackToCache()
{
// Processing directory may already contain some files left from previous session
// if the cache was working when the process terminated unexpectedly.
// Move everything from that directory back to cache directory.
if (!_fileSystem.DirectoryExists(_processingDirectoryPath))
{
// nothing to do
return;
}
foreach (var filePath in _fileSystem.EnumerateFiles(_processingDirectoryPath))
{
var destinationPath = Path.Combine(_isolatedCacheDirectoryPath, Path.GetFileName(filePath));
_options.LogDebug("Moving unprocessed file back to cache: {0} to {1}.", filePath, destinationPath);
const int maxAttempts = 3;
for (var attempt = 1; attempt <= maxAttempts; attempt++)
{
try
{
_fileSystem.MoveFile(filePath, destinationPath);
break;
}
catch (Exception ex)
{
if (!_fileSystem.FileExists(filePath))
{
_options.LogDebug(
"Failed to move unprocessed file back to cache (attempt {0}), " +
"but the file no longer exists so it must have been handled by another process: {1}",
attempt, filePath);
break;
}
if (attempt < maxAttempts)
{
_options.LogDebug(
"Failed to move unprocessed file back to cache (attempt {0}, retrying.): {1}",
attempt, filePath);
Thread.Sleep(200); // give a small bit of time before retry
}
else
{
_options.LogError(
"Failed to move unprocessed file back to cache (attempt {0}, done.): {1}", ex,
attempt, filePath);
}
// note: we do *not* want to re-throw the exception
}
}
}
}
private void EnsureFreeSpaceInCache()
{
// Trim files, leaving only (X - 1) of the newest ones.
// X-1 because we need at least 1 empty space for an envelope we're about to add.
// Example:
// Limit: 3
// [f1] [f2] [f3] [f4] [f5]
// |-------| <- keep these ones
// |------------| <- delete these ones
var excessCacheFilePaths = GetCacheFilePaths().SkipLast(_keepCount).ToArray();
foreach (var filePath in excessCacheFilePaths)
{
try
{
_fileSystem.DeleteFile(filePath);
_options.LogDebug("Deleted cached file {0}.", filePath);
}
catch (FileNotFoundException)
{
// File has already been deleted (unexpected but not critical)
_options.LogWarning(
"Cached envelope '{0}' has already been deleted.",
filePath);
}
}
}
private IEnumerable<string> GetCacheFilePaths() =>
_fileSystem.EnumerateFiles(_isolatedCacheDirectoryPath, $"*.{EnvelopeFileExt}")
.OrderBy(f => _fileSystem.GetFileCreationTime(f));
private async Task ProcessCacheAsync(CancellationToken cancellation)
{
try
{
// Make sure we're the only thread processing items
await _processingSignal.WaitAsync(cancellation).ConfigureAwait(false);
// Signal that we can start waiting for _options.InitCacheFlushTimeout
_preInitCacheResetEvent?.Set();
// Process the cache
_options.LogDebug("Flushing cached envelopes.");
while (await TryPrepareNextCacheFileAsync(cancellation).ConfigureAwait(false) is { } file)
{
await InnerProcessCacheAsync(file, cancellation).ConfigureAwait(false);
}
// Signal that we can continue with initialization, if we're using _options.InitCacheFlushTimeout
_initCacheResetEvent?.Set();
}
finally
{
// Release the signal so the next pass or another thread can enter
_processingSignal.Release();
}
}
private async Task InnerProcessCacheAsync(string file, CancellationToken cancellation)
{
if (_options.NetworkStatusListener is { Online: false } listener)
{
_options.LogDebug("The network is offline. Pausing processing.");
await listener.WaitForNetworkOnlineAsync(cancellation).ConfigureAwait(false);
_options.LogDebug("The network is back online. Resuming processing.");
}
_options.LogDebug("Reading cached envelope: {0}", file);
try
{
var stream = _fileSystem.OpenFileForReading(file);
#if NETFRAMEWORK || NETSTANDARD2_0
using (stream)
#else
await using (stream.ConfigureAwait(false))
#endif
{
using (var envelope = await Envelope.DeserializeAsync(stream, cancellation).ConfigureAwait(false))
{
// Don't even try to send it if we are requesting cancellation.
cancellation.ThrowIfCancellationRequested();
try
{
_options.LogDebug("Sending cached envelope: {0}",
envelope.TryGetEventId(_options.DiagnosticLogger));
await _innerTransport.SendEnvelopeAsync(envelope, cancellation).ConfigureAwait(false);
}
// OperationCancel should not log an error
catch (OperationCanceledException ex)
{
_options.LogDebug("Canceled sending cached envelope: {0}, retrying after a delay.", ex, file);
// Let the worker catch, log, wait a bit and retry.
throw;
}
catch (Exception ex) when (ex is HttpRequestException or WebException or SocketException
or IOException)
{
_options.LogError("Failed to send cached envelope: {0}, retrying after a delay.", ex, file);
// Let the worker catch, log, wait a bit and retry.
throw;
}
catch (Exception ex) when (ex.Source == "FakeFailingTransport")
{
// HACK: Deliberately sent from unit tests to avoid deleting the file from processing
return;
}
catch (Exception ex)
{
_options.ClientReportRecorder.RecordDiscardedEvents(DiscardReason.CacheOverflow, envelope);
LogFailureWithDiscard(file, ex);
}
}
}
}
catch (JsonException ex)
{
// Log deserialization errors
LogFailureWithDiscard(file, ex);
}
// Envelope & file stream must be disposed prior to reaching this point
// Delete the envelope file and move on to the next one
_fileSystem.DeleteFile(file);
}
private void LogFailureWithDiscard(string file, Exception ex)
{
string? envelopeContents = null;
try
{
if (_fileSystem.FileExists(file))
{
envelopeContents = _fileSystem.ReadAllTextFromFile(file);
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{
}
if (envelopeContents == null)
{
_options.LogError("Failed to send cached envelope: {0}, discarding cached envelope.", ex, file);
}
else
{
_options.LogError("Failed to send cached envelope: {0}, discarding cached envelope. Envelope contents: {1}", ex, file, envelopeContents);
}
}
// Gets the next cache file and moves it to "processing"
private async Task<string?> TryPrepareNextCacheFileAsync(CancellationToken cancellationToken = default)
{
using var lockClaim = await _cacheDirectoryLock.AcquireAsync(cancellationToken).ConfigureAwait(false);
var filePath = GetCacheFilePaths().FirstOrDefault();
if (string.IsNullOrWhiteSpace(filePath))
{
_options.LogDebug("No cached file to process.");
return null;
}
var targetFilePath = Path.Combine(_processingDirectoryPath, Path.GetFileName(filePath));
// Move the file to processing.
// We move with overwrite just in case a file with the same name already exists in the output directory.
// That should never happen under normal workflows because the filenames have high variance.
_fileSystem.MoveFile(filePath, targetFilePath, overwrite: true);
return targetFilePath;
}
private async Task StoreToCacheAsync(
Envelope envelope,
CancellationToken cancellationToken = default)
{
if (_failStorage)
{
throw new("Simulated failure writing to storage (for testing).");
}
// Envelope file name can be either:
// 1604679692_2035_b2495755f67e4bb8a75504e5ce91d6c1_17754019.envelope
// 1604679692_2035__17754019_2035660868.envelope
// (depending on whether event ID is present or not)
var envelopeFilePath = Path.Combine(
_isolatedCacheDirectoryPath,
$"{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_" + // timestamp for variance & sorting
$"{Guid.NewGuid().GetHashCode() % 1_0000}_" + // random 1-4 digits for extra variance
$"{envelope.TryGetEventId(_options.DiagnosticLogger)}_" + // event ID (may be empty)
$"{envelope.GetHashCode()}" + // envelope hash code
$".{EnvelopeFileExt}");
_options.LogDebug("Storing file {0}.", envelopeFilePath);
using var lockClaim = await _cacheDirectoryLock.AcquireAsync(cancellationToken).ConfigureAwait(false);
EnsureFreeSpaceInCache();
var stream = _fileSystem.CreateFileForWriting(envelopeFilePath);
#if NETFRAMEWORK || NETSTANDARD2_0
using(stream)
#else
await using (stream.ConfigureAwait(false))
#endif
{
await envelope.SerializeAsync(stream, _options.DiagnosticLogger, cancellationToken).ConfigureAwait(false);
}
// Tell the worker that there is work available
// (file stream MUST BE DISPOSED prior to this)
_workerSignal.Release();
}
// Used locally and in tests
internal int GetCacheLength() => GetCacheFilePaths().Count();
// This method asynchronously blocks until the envelope is written to cache, but not until it's sent
public async Task SendEnvelopeAsync(
Envelope envelope,
CancellationToken cancellationToken = default)
{
// Client reports should be generated here so they get included in the cached data
var clientReport = _options.ClientReportRecorder.GenerateClientReport();
if (clientReport != null)
{
envelope = envelope.WithItem(EnvelopeItem.FromClientReport(clientReport));
_options.LogDebug("Attached client report to envelope {0}.", envelope.TryGetEventId(_options.DiagnosticLogger));
}
try
{
// Store the envelope in a file without actually sending it anywhere.
// The envelope will get picked up by the background thread eventually.
await StoreToCacheAsync(envelope, cancellationToken).ConfigureAwait(false);
}
catch
{
// On any failure writing to the cache, recover the client report.
if (clientReport != null)
{
_options.ClientReportRecorder.Load(clientReport);
}
throw;
}
}
public Task StopWorkerAsync()
{
if (_worker.IsCompleted)
{
// already stopped
return Task.CompletedTask;
}
// Stop worker and wait until it finishes
_options.LogDebug("Stopping CachingTransport worker.");
_workerCts.Cancel();
return _worker;
}
public Task FlushAsync(CancellationToken cancellationToken = default)
{
_options.LogDebug("CachingTransport received request to flush the cache.");
return ProcessCacheAsync(cancellationToken);
}
public async ValueTask DisposeAsync()
{
try
{
await StopWorkerAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
// Don't throw inside dispose
_options.LogError(
"Error stopping worker during dispose.",
ex);
}
_workerSignal.Dispose();
_workerCts.Dispose();
_worker.Dispose();
_cacheDirectoryLock.Dispose();
_preInitCacheResetEvent?.Dispose();
_initCacheResetEvent?.Dispose();
(_innerTransport as IDisposable)?.Dispose();
}
public void Dispose() => DisposeAsync().GetAwaiter().GetResult();
}
|
using Sales.ViewModels;
using System.Windows.Controls;
namespace Sales.Views.SaleViews
{
public partial class SaleOfferDisplayUserControl : UserControl
{
public SaleOfferDisplayUserControl()
{
InitializeComponent();
Unloaded += (s, e) => ViewModelLocator.Cleanup("SaleOfferDisplay");
}
}
}
|
using UnityEngine;
using System.Collections;
namespace Game.UI.Component
{
[RequireComponent(typeof(Canvas))]
/// <summary>
/// 游戏中的主要画布,用于游戏play时的主界面服务;
/// </summary>
/// <remarks>挂载在主Canvas上即可实现单例获取</remarks>
public class MainGameCanvas : MonoBehaviour
{
//如果有指定UIContainer,则此将作为Canvas的RectTransform,否则Canvas根为Canvas
[SerializeField] RectTransform m_uiContainner;
static RectTransform g_UIContainer;
internal static RectTransform canvasRectTransform
{
get
{
#if UNITY_EDITOR
if (g_UIContainer == null)
{
Debug.LogError("NO GAME CAVAS ASSIGNED IN CURRENT SCENE!");
}
#endif
return g_UIContainer;
}
}
void Awake ()
{
//如果指定Canvas的Container为另外物体,则指定之为其他UI悬挂的Parent
if (m_uiContainner == null)
{
Debug.Log("No contain panel specifyed.So Canvas used as panel.");
g_UIContainer = this.GetComponent<RectTransform>();
}
else
{
g_UIContainer = m_uiContainner;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using CEMAPI.BAL;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CEMAPI.Models;
using System.Net.Mail;
using System.Reflection;
using CEMAPI.DAL;
namespace CEMAPI.Controllers
{
public class TEGeneralNotesAPIController : ApiController
{
TETechuvaDBContext context = new TETechuvaDBContext();
RecordExceptions exception = new RecordExceptions();
public TEGeneralNotesAPIController()
{
context.Configuration.ProxyCreationEnabled = false;
}
[HttpPost]
public HttpResponseMessage GetGeneralNotesAPI(JObject json)
{
HttpResponseMessage hrm = new HttpResponseMessage();
SuccessInfo sinfo = new SuccessInfo();
FailInfo finfo = new FailInfo();
context.Configuration.ProxyCreationEnabled = false;
try
{
int? ReferenceID = json["ReferenceID"].ToObject<int>();
string ModuleName = json["ModuleName"].ToObject<string>();
List<TEGenaralNoteView> offernotes = new List<TEGenaralNoteView>();
offernotes = (from inv in context.TEGenaralNotes
join up in context.UserProfiles on inv.LastModifiedByID equals up.UserId
where inv.ReferenceID == ReferenceID && inv.IsDeleted == false
&& inv.ModuleName.Equals(ModuleName)
select new TEGenaralNoteView
{
NotesID = inv.NotesID,
ReferenceID = inv.ReferenceID,
ModuleName = inv.ModuleName,
Notes = inv.Notes,
LastModifiedByID = inv.LastModifiedByID,
LastModifiedDate = inv.LastModifiedDate,
LastModifiedBy=up.UserName
}).ToList().OrderByDescending(x => x.LastModifiedDate).ToList();
if (offernotes.Count > 0)
{
finfo.errorcode = 0;
finfo.errormessage = "Success";
}
else
{
finfo.errorcode = 1;
finfo.errormessage = "No Records";
}
hrm.Content = new JsonContent(new { result = offernotes, info = finfo });
}
catch (Exception ex)
{
ApplicationErrorLog errorlog = new ApplicationErrorLog();
if (ex.InnerException != null)
errorlog.InnerException = ex.InnerException.ToString();
if (ex.StackTrace != null)
errorlog.Stacktrace = ex.StackTrace.ToString();
if (ex.Source != null)
errorlog.Source = ex.Source.ToString();
if (ex.Message != null)
errorlog.Error = ex.Message.ToString();
errorlog.ExceptionDateTime = DateTime.Now;
context.ApplicationErrorLogs.Add(errorlog);
context.SaveChanges();
finfo.errorcode = 1;
//finfo.errormessage = "You are not Authorised User";
finfo.errormessage = "error";
hrm.Content = new JsonContent(new { info = finfo });
}
//
return hrm;
}
[HttpPost]
public HttpResponseMessage SaveGeneralNotesAPI(TEGenaralNote Data)
{
int authuser = 0;
var headers = Request.Headers;
if (headers.Contains("authUser"))
{
authuser = Convert.ToInt32(headers.GetValues("authUser").First());
}
HttpResponseMessage hrm = new HttpResponseMessage();
SuccessInfo sinfo = new SuccessInfo();
FailInfo finfo = new FailInfo();
context.Configuration.ProxyCreationEnabled = false;
try
{
Data.IsDeleted = false;
Data.LastModifiedByID = authuser;
Data.LastModifiedDate = DateTime.Now;
context.TEGenaralNotes.Add(Data);
context.SaveChanges();
if (Data.NotesID > 0)
{
finfo.errorcode = 0;
finfo.errormessage = "Notes Saved Successfully";
}
else
{
finfo.errorcode = 1;
finfo.errormessage = "Notes Cannot be Saved";
}
hrm.Content = new JsonContent(new { result = Data.NotesID, info = finfo });
}
catch (Exception ex)
{
ApplicationErrorLog errorlog = new ApplicationErrorLog();
if (ex.InnerException != null)
errorlog.InnerException = ex.InnerException.ToString();
if (ex.StackTrace != null)
errorlog.Stacktrace = ex.StackTrace.ToString();
if (ex.Source != null)
errorlog.Source = ex.Source.ToString();
if (ex.Message != null)
errorlog.Error = ex.Message.ToString();
errorlog.ExceptionDateTime = DateTime.Now;
context.ApplicationErrorLogs.Add(errorlog);
context.SaveChanges();
finfo.errorcode = 1;
//finfo.errormessage = "You are not Authorised User";
finfo.errormessage = "Error";
hrm.Content = new JsonContent(new { info = finfo });
}
//
return hrm;
}
}
public partial class TEGenaralNoteView
{
public int NotesID { get; set; }
public Nullable<int> ReferenceID { get; set; }
public string ModuleName { get; set; }
public string Notes { get; set; }
public Nullable<bool> IsDeleted { get; set; }
public Nullable<int> LastModifiedByID { get; set; }
public Nullable<System.DateTime> LastModifiedDate { get; set; }
public string LastModifiedBy { get; set; }
}
}
|
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.Data.SqlClient;
namespace movie_guide_module_3
{
public partial class Form13 : Form
{
public Form13()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
this.Hide();
Form6 f = new Form6();
f.Show();
}
private void button1_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(@"Data Source=LAPTOP-VOK8FTS3;Initial Catalog=MOVIE GUIDE MODULE 1;Integrated Security=True");
//con.Open();
//if (radioButton1.Checked)
//{
// string r = "insert into Username(comment) values(@comment)";
// SqlParameter comment = new SqlParameter("@comment", textBox1.Text);
// SqlCommand cmd = new SqlCommand(r, con);
// cmd.Parameters.Add(comment);
// cmd.ExecuteNonQuery();
//}
//else if (radioButton2.Checked)
//{
// string r = "insert into admin(comment) values(@comment)";
// SqlParameter comment = new SqlParameter("@rate", textBox1.Text);
// SqlCommand cmd = new SqlCommand(r, con);
// cmd.Parameters.Add(comment);
// cmd.ExecuteNonQuery();
//}
//con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(@"Data Source=LAPTOP-VOK8FTS3;Initial Catalog=MOVIE GUIDE MODULE 1;Integrated Security=True");
//con.Open();
//if (radioButton1.Checked)
//{
// string r = "insert into Username(rate) values(@rate)";
// SqlParameter rate = new SqlParameter("@rate", textBox2.Text);
// SqlCommand cmd = new SqlCommand(r, con);
// cmd.Parameters.Add(rate);
// cmd.ExecuteNonQuery();
//}
//else if (radioButton2.Checked)
//{
// string r = "insert into admin(rate) values(@rate)";
// SqlParameter rate = new SqlParameter("@rate", textBox2.Text);
// SqlCommand cmd = new SqlCommand(r, con);
// cmd.Parameters.Add(rate);
// cmd.ExecuteNonQuery();
//}
//con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=LAPTOP-VOK8FTS3;Initial Catalog=MOVIE GUIDE MODULE 1;Integrated Security=True");
con.Open();
if (radioButton1.Checked)
{
string r = "insert into Username(comment) values(@comment)";
SqlParameter comment = new SqlParameter("@comment", textBox1.Text);
SqlCommand cmd = new SqlCommand(r, con);
cmd.Parameters.Add(comment);
cmd.ExecuteNonQuery();
}
else if (radioButton2.Checked)
{
string r = "insert into admin(comment) values(@comment)";
SqlParameter comment = new SqlParameter("@rate", textBox1.Text);
SqlCommand cmd = new SqlCommand(r, con);
cmd.Parameters.Add(comment);
cmd.ExecuteNonQuery();
}
if (radioButton1.Checked)
{
string r = "insert into Username(rate) values(@rate)";
SqlParameter rate = new SqlParameter("@rate", textBox2.Text);
SqlCommand cmd = new SqlCommand(r, con);
cmd.Parameters.Add(rate);
cmd.ExecuteNonQuery();
}
else if (radioButton2.Checked)
{
string r = "insert into admin(rate) values(@rate)";
SqlParameter rate = new SqlParameter("@rate", textBox2.Text);
SqlCommand cmd = new SqlCommand(r, con);
cmd.Parameters.Add(rate);
cmd.ExecuteNonQuery();
}
if (radioButton1.Checked)
{
string r = "insert into Username([movie name]) values(@movie_name)";
SqlParameter rate = new SqlParameter("@movie_name", textBox2.Text);
SqlCommand cmd = new SqlCommand(r, con);
cmd.Parameters.Add(rate);
cmd.ExecuteNonQuery();
}
else if (radioButton2.Checked)
{
string r = "insert into admin([movie name]) values(@movie_name)";
SqlParameter rate = new SqlParameter("@movie_name", textBox2.Text);
SqlCommand cmd = new SqlCommand(r, con);
cmd.Parameters.Add(rate);
cmd.ExecuteNonQuery();
}
con.Close();
MessageBox.Show("successfully");
}
private void pictureBox7_Click(object sender, EventArgs e)
{
this.Hide();
Form6 f = new Form6();
f.Show();
}
private void textBox3_Click(object sender, EventArgs e)
{
textBox3.Text = "";
}
private void textBox2_Click(object sender, EventArgs e)
{
textBox2.Text = "";
}
private void textBox1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
}
}
|
namespace E
{
/// <summary>
/// 列转换类型
/// </summary>
public enum ColumnNameCaseType
{
/// <summary>
/// 默认不做处理
/// </summary>
Default = 0,
/// <summary>
/// 转大写
/// </summary>
Upper = 1,
/// <summary>
/// 转小写
/// </summary>
Lower = 2,
}
}
|
using Tools;
namespace _039
{
static class Program
{
static void Main(string[] args)
{
Decorators.TimeItAccurate(Solve, 2000, 100);
}
private static int Solve(int upperLimit)
{
var solutions = new int[upperLimit + 1];
for (int perimeter = 2; perimeter <= upperLimit; perimeter += 2)
{
int solution = CountPureSolutions(perimeter);
solutions[perimeter] += solution;
for (int j = 2; j * perimeter < upperLimit; j++)
{
solutions[j * perimeter] += solution;
}
}
int res = 0;
int max = 0;
for (int i = 0; i < upperLimit; i++)
{
if (solutions[i] > max)
{
res = i;
max = solutions[i];
}
}
return res;
}
private static int CountPureSolutions(int perimeter)
{
int count = 0;
int halfPerimeter = perimeter >> 1;
for (int a = 3; a <= halfPerimeter; a += 2)
{
for (int b = (halfPerimeter - a) & (int.MaxValue - 3); b <= halfPerimeter; b += 4)
{
int c = perimeter - (a + b);
if (a * a + b * b == c * c)
{
count++;
}
}
}
return count;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneTrans : BasePanel
{
public void HideOver()
{
UIManager.GetInstance().HidePanel("SceneTrans");
Destroy(gameObject);
}
}
|
using System;
using StardewValley;
using StardewValley.Locations;
using StardewModdingAPI;
using System.Linq;
namespace StardewNotification
{
public class GeneralNotification
{
public void DoNewDayNotifications(ITranslationHelper Trans)
{
CheckForBirthday(Trans);
CheckForFestival(Trans);
CheckForMaxLuck(Trans);
CheckForQueenOfSauce(Trans);
CheckForToolUpgrade(Trans);
CheckForTravelingMerchant(Trans);
CheckForHayLevel(Trans);
}
public void CheckForHayLevel(ITranslationHelper Trans)
{
if (!StardewNotification.Config.NotifyHay || Game1.getFarm().buildings.Count(b => b.buildingType.Value == "Silo") == 0)
return;
int hayAmt = Game1.getFarm().piecesOfHay.Value;
if (hayAmt > 0)
Util.ShowMessage(Trans.Get("hayMessage", new { hayAmt = Game1.getFarm().piecesOfHay.Value}));
else if (StardewNotification.Config.ShowEmptyhay)
Util.ShowMessage(Trans.Get("noHayMessage"));
}
public void DoBirthdayReminder(ITranslationHelper Trans)
{
var character = Utility.getTodaysBirthdayNPC(Game1.currentSeason, Game1.dayOfMonth);
if (!(character is null) && Game1.player.friendshipData[character.Name].GiftsToday != 1)
{
Util.ShowMessage(Trans.Get("birthdayReminder", new { charName = character.displayName }));
}
}
private void CheckForBirthday(ITranslationHelper Trans)
{
if (StardewNotification.Config.NotifyBirthdays)
{
var character = Utility.getTodaysBirthdayNPC(Game1.currentSeason, Game1.dayOfMonth);
if (character is null) return;
Util.ShowMessage(Trans.Get("birthday", new { charName = character.displayName }));
}
}
private void CheckForTravelingMerchant(ITranslationHelper Trans)
{
Forest f = Game1.getLocationFromName("Forest") as Forest;
if (!StardewNotification.Config.NotifyTravelingMerchant || !f.travelingMerchantDay)
{
return;
}
Util.ShowMessage(Trans.Get("travelingMerchant"));
}
private void CheckForToolUpgrade(ITranslationHelper Trans)
{
if (!StardewNotification.Config.NotifyToolUpgrade) return;
if (!(Game1.player.toolBeingUpgraded.Value is null) && Game1.player.daysLeftForToolUpgrade.Value <= 0)
Util.ShowMessage(Trans.Get("toolPickup", new { toolName = Game1.player.toolBeingUpgraded.Value.Name }));
}
private void CheckForMaxLuck(ITranslationHelper Trans)
{
if (StardewNotification.Config.NotifyMaxLuck && Game1.dailyLuck > 0.07)
Util.ShowMessage(Trans.Get("luckyDay"));
else if (StardewNotification.Config.NotifyMinLuck && Game1.dailyLuck < -.07)
Util.ShowMessage(Trans.Get("unluckyDay"));
}
private void CheckForQueenOfSauce(ITranslationHelper Trans)
{
if (!StardewNotification.Config.NotifyQueenOfSauce) return;
var dayName = Game1.shortDayNameFromDayOfSeason(Game1.dayOfMonth);
if (!dayName.Equals("Sun")) return;
Util.ShowMessage(Trans.Get("queenSauce"));
}
private void CheckForFestival(ITranslationHelper Trans)
{
if (!StardewNotification.Config.NotifyFestivals || !Utility.isFestivalDay(Game1.dayOfMonth, Game1.currentSeason)) return;
var festivalName = GetFestivalName(Trans);
Util.ShowMessage(Trans.Get("fMsg", new { fest = festivalName }));
if (!festivalName.Equals(Trans.Get("WinterStar"))) return;
Random r = new Random((int)(Game1.uniqueIDForThisGame / 2uL) ^ Game1.year ^ (int)Game1.player.UniqueMultiplayerID);
var santa = Utility.getRandomTownNPC(r).displayName;
Util.ShowMessage(Trans.Get("SecretSantaReminder", new { charName = santa }));
}
private string GetFestivalName(ITranslationHelper Trans)
{
var season = Game1.currentSeason;
var day = Game1.dayOfMonth;
switch (season)
{
case "spring":
if (day == 13) return Trans.Get("EggFestival");
if (day == 24) return Trans.Get("FlowerDance");
break;
case "summer":
if (day == 11) return Trans.Get("Luau");
if (day == 28) return Trans.Get("MoonlightJellies");
break;
case "fall":
if (day == 16) return Trans.Get("ValleyFair");
if (day == 27) return Trans.Get("SpiritsEve");
break;
case "winter":
if (day == 8) return Trans.Get("IceFestival");
if (day == 14) return Trans.Get("NightFestival");
if (day == 15) return Trans.Get("NightFestival");
if (day == 16) return Trans.Get("NightFestival");
if (day == 25) return Trans.Get("WinterStar");
break;
default:
break;
}
return Trans.Get("festival");
}
}
}
|
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using SolarSystemWeb.Models.Identity;
namespace SolarSystemWeb
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// настраиваем контекст и менеджер
app.CreatePerOwinContext<ApplicationContext>(ApplicationContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// регистрация менеджера ролей
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
});
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using System.ComponentModel;
namespace Supermarket.API.Extensions
{
public static class EnumExtensions
{
/*First we define a generic method(a method that can receive more than onc
* type of arguement, in this case,represented by the TEnum declaration) that
*receives a given enum as an arguement
Since enum is a reserved keyword in C#, we added an @ in front of Parameters name
` The first execution step of this method is to get the type information(the class,
interface,enum or struct def) of the parameter using the GetType method
Then the method gets the specific enum value(for instance Kilogram) using
GetField(@enum.ToString())
The next line finds all the Description attribute applied over the enumeration
value and stores their data into an array ( we can specify multiple attribute
for a same property in some cases)
The last line uses a short syntax to check if we have at least one description attribute
for the enum type. If we have, we return the Description value provided by this attribute.
if not we return the enumeration as a string using the defult casting.
?. -> a null conditional operator checks if the value is null before accessing its property
?? -> a null coalescing operator, tells the applicaiton to return the value at the left if its
not empty, or the value at the right otherwise.
*/
public static string ToDescriptionString<TEnum>(this TEnum @enum)
{
FieldInfo info = @enum.GetType().GetField(@enum.ToString());
var attribute = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attribute?[0].Description ?? @enum.ToString();
}
}
}
|
using System;
namespace MainTool.Exceptions
{
public class FlowImpossibleException : Exception
{
public FlowImpossibleException(string message)
: base(message)
{
}
}
} |
namespace Ach.Fulfillment.Business
{
using System.Collections.Generic;
using Data;
public interface IAchTransactionManager : IManager<AchTransactionEntity>
{
void ChangeAchTransactionStatus(List<AchTransactionEntity> transactions, AchTransactionStatus status);
void SendAchTransactionNotification(List<AchTransactionEntity> transactions);
List<AchTransactionEntity> GetAllInQueue(bool toLock = true);
List<AchTransactionEntity> GetAllInQueueForPartner(PartnerEntity partner, bool toLock = true);
void UnLock(List<AchTransactionEntity> transactions);
}
} |
using System.Net;
namespace Org.Common.Exception
{
public class DuplicateEtityException : OperationException
{
public DuplicateEtityException(string message) : base(message, (int)HttpStatusCode.Conflict)
{
}
}
}
|
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Web.Security;
using System.Web.UI.WebControls;
public class Dashboard
{
public bool success { get; set; }
public Chart[] chartDonut { get; set; }
public Chart[] chartBar { get; set; }
public Table[] tableUsers { get; set; }
}
public class Chart
{
public string name { get; set; }
public string value { get; set; }
}
public class Table
{
public string firstName { get; set; }
public string lastName { get; set; }
public string userName { get; set; }
}
public partial class _Default : System.Web.UI.Page
{
private static HttpClient httpClient = new HttpClient();
private const string URLAEMEnersol = "http://test-demo.aem-enersol.com/api/dashboard";
private SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalDBConn"].ConnectionString);
string myUsername;
string myToken;
protected void Page_Load(object sender, EventArgs e)
{
// Make sure user is logged in to access other features
if (Session["username"] != null && Session["token"] != null)
{
myUsername = Session["username"].ToString();
myToken = Session["token"].ToString();
if (!this.IsPostBack)
{
GetDashboard();
}
}
// Else, redirect to Login page
else
{
// Redirect to Login page
Response.Redirect("Login.aspx", true);
}
}
private async void GetDashboard()
{
var request = new HttpRequestMessage(HttpMethod.Get, URLAEMEnersol);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", myToken);
var responseTask = httpClient.SendAsync(request, CancellationToken.None);
responseTask.Wait();
var response = responseTask.Result;
if (response.IsSuccessStatusCode)
{
// Get response body
string responseBody = await response.Content.ReadAsStringAsync();
// Deserialize responsebody JSON in string to Employee (array) object
Dashboard dashboard = Newtonsoft.Json.JsonConvert.DeserializeObject<Dashboard>(responseBody);
if (dashboard.success == true)
{
// Show success message
//lblStatus.Text += "<br>SUCCESS" + dashboard.tableUsers.Length;
////Building an HTML string.
//StringBuilder html1 = new StringBuilder();
//int no1 = 1;
//foreach (Chart c1 in dashboard.chartDonut)
//{
// html1.Append("<tr>" +
// "<th scope=\"row\">" + no1 + "</th>" +
// "<td>" + c1.name + "</td>" +
// "<td>" + c1.value + "</td>" +
// "<td></td>" +
// "</tr>");
// //phTable.Controls.Add(new Literal { Text = html.ToString() });
// chartDonutScript.InnerHtml = html1.ToString();
// no1++;
//}
////Building an HTML string.
//StringBuilder html2 = new StringBuilder();
//int no2 = 1;
//foreach (Chart c2 in dashboard.chartBar)
//{
// html2.Append("<tr>" +
// "<th scope=\"row\">" + no2 + "</th>" +
// "<td>" + c2.name + "</td>" +
// "<td>" + c2.value + "</td>" +
// "<td></td>" +
// "</tr>");
// //phTable.Controls.Add(new Literal { Text = html.ToString() });
// chartBarScript.InnerHtml = html2.ToString();
// no2++;
//}
//Building an HTML string.
StringBuilder html3 = new StringBuilder();
int no3 = 1;
foreach (Table t in dashboard.tableUsers)
{
html3.Append("<tr>" +
"<th scope=\"row\">" + no3 + "</th>" +
"<td>" + t.firstName + "</td>" +
"<td>" + t.lastName + "</td>" +
"<td>" + t.userName + "</td>" +
"</tr>");
//phTable.Controls.Add(new Literal { Text = html.ToString() });
tblUser.InnerHtml = html3.ToString();
no3++;
//}
}
}
else
{
// Show success message
//lblStatus.Text += "<br>ERROR";
}
//foreach (Platform p in platform)
//{
// lblStatus.Text += "<br>" + p.UniqueName;
// if (p.Well != null && p.Well.Length > 0)
// {
// foreach (Well w in p.Well)
// {
// lblStatus.Text += "<br> " + w.UniqueName;
// }
// }
//}
}
else
{
// Show failed message
//lblStatus.Text = "Synchronization from API to localDB failed";
//lblStatus.Text = "FAILED<br>"+response.ToString();
}
}
}
|
namespace Application.Views.Admin
{
using System.Collections.Generic;
using System.Text;
using Common;
using Common.Utilities;
using Models.ViewModels;
using SimpleMVC.Interfaces.Generic;
public class Games : IRenderable<IEnumerable<AdminGamesViewModel>>
{
private readonly string header = Constants.HeaderHtml.GetContentByName();
private readonly string navbar = Constants.NavHtml;
private readonly string footer = Constants.FooterHtml.GetContentByName();
private readonly string cell = Constants.AdminGameCellHtml.GetContentByName();
public IEnumerable<AdminGamesViewModel> Model { get; set; }
public string Render()
{
return $"{this.header}{this.navbar}{this.GetAllGamesInCells()}{this.footer}";
}
private string GetAllGamesInCells()
{
var gamesOutput = new StringBuilder();
foreach (var gamesViewModel in this.Model)
{
gamesOutput.AppendLine(string.Format(
this.cell,
gamesViewModel.Title,
gamesViewModel.Price,
gamesViewModel.Size,
gamesViewModel.GameId,
gamesViewModel.GameId));
}
return string.Format(Constants.AdminGamesHtml.GetContentByName(), gamesOutput);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace SplitGroupie
{
public partial class Form1 : Form
{
private BetterRandom random = new BetterRandom();
private DiscordWebhook discordWebhook = new DiscordWebhook();
private Defaults _Def = new Defaults();
private WebClient _WC = new WebClient();
private int rechecks = 0;
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
discordWebhook.WebHook = "your discord webhook here";
backgroundWorker1.RunWorkerAsync();
}
public string GetProxy()
{
/*MatchCollection _MC = _Def._REGEX.Matches(TB_ScrapeInput.Text);
foreach (Match Match in _MC)
{
MessageBox.Show(Match.ToString());
return Match.ToString();
}
return null;*/
try
{
foreach (string PageToScrape in _Def.sources)
{
string PageSource = _WC.DownloadString(PageToScrape);
MatchCollection _MC = _Def._REGEX.Matches(PageSource);
foreach (Match Match in _MC)
{
return Match.ToString();
}
}
return string.Empty;
}
catch
{
return string.Empty;
}
}
public GroupData GetGroupData(int groupId)
{
GroupData gData = new GroupData();
try
{
gData.groupId = groupId;
string groupUrl = string.Format("https://groups.roblox.com/v1/groups/{0}", groupId);
string rbxUrl = string.Format("https://economy.roblox.com/v1/groups/{0}/currency", groupId);
string robuxData = string.Empty;
// Webclient
WebClient client = new WebClient();
/*string sProxy = string.Empty;
while (true)
{
sProxy = GetProxy();
if (sProxy == string.Empty)
{
continue;
}
break;
}
WebProxy proxy = new WebProxy(sProxy);
client.Proxy = proxy;*/
client.Headers[HttpRequestHeader.ContentType] = "application/json;charset=UTF-8";
string ownershipData = client.DownloadString(groupUrl);
client.Dispose();
/*if (!robuxData.Contains("{\"robux\":0}"))
{
int temp = 0;
gData.gotRobux = true;
//gData.robux = int.TryParse(Regex.Match(robuxData, @"\d+").Value, out int temp);
}-*/
if (ownershipData.Contains("\"publicEntryAllowed\":true"))
{
gData.canJoin = true;
}
if (ownershipData.Contains("\"owner\":null"))
{
gData.hasOwner = false;
}
richTextBox1.Text = "Returning " + gData.groupId + '\n' + richTextBox1.Text;
return gData;
}
catch
{
gData.failed = true;
return gData;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
GroupData groupData = new GroupData();
while (true)
{
if (rechecks >= 1)
{
groupData.failed = false;
}
if (richTextBox1.Text.Length > 1000)
{
richTextBox1.Text = string.Empty;
}
if (groupData.failed)
{
richTextBox1.Text = "Rechecking " + groupData.groupId + '\n' + richTextBox1.Text;
rechecks += 1;
groupData = GetGroupData(groupData.groupId);
}
else
{
rechecks = 0;
groupData = GetGroupData(random.NextInteger(100, 9097478));
}
if (groupData.hasOwner == false && groupData.failed == false && groupData.canJoin == true)
{
discordWebhook.SendMessage(groupData.groupId.ToString());
}
}
}
}
public class GroupData
{
public int groupId = 0;
public bool canJoin = false;
public bool hasOwner = true;
public bool gotRobux = false;
public int robux = 0;
public bool failed = false;
}
public class BetterRandom
{
private Random random = new Random();
private List<int> usedRandoms = new List<int>();
public int NextInteger(int min, int max)
{
int value;
while (true)
{
value = random.Next(min, max);
if (!usedRandoms.Contains(value))
{
break;
}
Thread.Sleep(1);
}
return value;
}
}
public class CustomTimer
{
private int time = 0;
public void Do(int ms)
{
while (time < ms)
{
Application.DoEvents();
time++;
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Upgrader.SqlServer;
namespace Upgrader.Test.SqlServer
{
[TestClass]
public class IndexInfoSqlServerTest : IndexInfoTest
{
public IndexInfoSqlServerTest() : base(new SqlServerDatabase(AssemblyInitialize.SqlServerConnectionString))
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.AspNetCore.Components.WebAssembly.Http;
using Microsoft.JSInterop;
using CMartCV_Shell;
using CMartCV_Shell.Shared;
namespace CMartCV_Shell.Pages
{
public partial class Counter
{
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace BanjoBotCore.persistence
{
//TODO: Refactor DatabaseController
//Also https://stackoverflow.com/questions/46010003/asp-net-core-2-0-value-cannot-be-null-parameter-name-connectionstring
public interface IDataStorage
{
Task Delete(IPersistentObject toDelete);
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Orleans.Hosting;
using Orleans.TestingHost;
using StackExchange.Redis;
namespace Orleans.Reminders.Redis.Tests
{
public class ClusterFixture : IDisposable
{
private readonly ConnectionMultiplexer _redis;
public ClusterFixture()
{
string redisHost = Environment.GetEnvironmentVariable("REDIS_HOST") ?? "127.0.0.1";
string redisPort = Environment.GetEnvironmentVariable("REDIS_PORT") ?? "6379";
string redisConnectionString = $"{redisHost}:{redisPort}, allowAdmin=true";
TestClusterBuilder builder = new TestClusterBuilder(1);
builder.Options.ServiceId = "Service";
builder.Options.ClusterId = "TestCluster";
builder.AddSiloBuilderConfigurator<SiloConfigurator>();
Cluster = builder.Build();
Cluster.Deploy();
Cluster.InitializeClientAsync();
Client = Cluster.Client;
ConfigurationOptions redisOptions = ConfigurationOptions.Parse(redisConnectionString);
_redis = ConnectionMultiplexer.ConnectAsync(redisOptions).Result;
Database = _redis.GetDatabase();
}
public TestCluster Cluster { get; }
public IGrainFactory GrainFactory => Cluster.GrainFactory;
public IClusterClient Client { get; }
public IDatabase Database { get; }
public class SiloConfigurator : ISiloConfigurator
{
public void Configure(ISiloBuilder builder)
{
builder.UseRedisReminderService(options =>
{
string redisHost = Environment.GetEnvironmentVariable("REDIS_HOST") ?? "127.0.0.1";
string redisPort = Environment.GetEnvironmentVariable("REDIS_PORT") ?? "6379";
string redisConnectionString = $"{redisHost}:{redisPort}, allowAdmin=true";
options.ConnectionString = redisConnectionString;
});
}
}
public void Dispose()
{
Database.ExecuteAsync("FLUSHALL").Wait();
//Client.Dispose();
Cluster.StopAllSilos();
_redis?.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Рекурс.С_из_n_по_k
{
class Program
{
static int Cnk(int n, int k)
{
if (k == 0)
{return 1;}
if (n == k)
{ return 1; }
else { return (Cnk(n - 1, k - 1) + Cnk(n - 1, k)); }
}
static void Main(string[] args)
{//Random m = new Random();
int n=40;
int k =20;
Stopwatch sWatch = new Stopwatch();
sWatch.Start();
Cnk(10,5);
sWatch.Stop();
TimeSpan tSpan;
tSpan = sWatch.Elapsed;
Console.WriteLine(tSpan.ToString());
Console.WriteLine("n=" + n + " k=" + k + " c=" + Cnk(n, k));
}
}
}
//T(n)=(3^n) |
using System;
using System.Xml;
namespace pjank.BossaAPI.Fixml
{
public enum OrdRejectReason
{
/*
BrokerOption = 0,
UnknownSymbol = 1,
ExchangeClosed = 2,
OrderExceedsLimit = 3,
TooLateToEnter = 4,
UnknownOrder = 5,
DuplicateOrder = 6,
DuplicateVerbOrder = 7,
StaleOrder = 8,
TradeAlongRequired = 9,
InvalidInvestorID = 10,
UnsupportedOrder = 11,
SurveillenceOption = 12,
IncorrectQuantity = 13,
IncorrectAllocQty = 14,
UnknownAccount = 15,
PriceExceedsBand = 16,
InvalidPriceInc = 18,
*/
Other = 99
}
internal static class OrderRejRsnUtil
{
public static OrdRejectReason? Read(XmlElement xml, string name, bool optional)
{
int? number = FixmlUtil.ReadInt(xml, name, optional);
if (number == null) return null;
if (!Enum.IsDefined(typeof(OrdRejectReason), (OrdRejectReason)number))
FixmlUtil.Error(xml, name, number, "- unknown OrderRejectReason");
return (OrdRejectReason)number;
}
}
}
|
using System.Reflection;
namespace Mapper.Utils
{
public class PropertyMap
{
public PropertyInfo SourceProperty { get; set; }
public PropertyInfo TargetProperty { get; set; }
}
} |
public class Solution {
public int Rob(int[] nums) {
if (nums.Length == 1) return nums[0];
return Math.Max(Rob(nums, 0, nums.Length - 2), Rob(nums, 1, nums.Length - 1));
}
public int Rob(int[] nums, int start, int end) {
if (start == end) return nums[start];
int prev1 = nums[start], prev2 = Math.Max(prev1, nums[start+1]), curr = prev2;
for (int i = start+2; i <= end; i ++) {
curr = Math.Max(prev1 + nums[i], prev2);
prev1 = prev2;
prev2 = curr;
}
return curr;
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class SlotManager : MonoBehaviour, IPointerClickHandler
{
[Header("Slot UI")]
public Text StackText;
private Stack<ItemDatabase> ItemStack;
public Stack<ItemDatabase> SlotItemStack
{
get { return ItemStack; }
set { ItemStack = value; }
}
void Start()
{
//instantiates the items stack
ItemStack = new Stack<ItemDatabase>();
}
// get the current item on the slot
public ItemDatabase CurrentItemOnSlot
{
get { return ItemStack.Peek(); }
}
// show if there is nothing inside the slot
public bool SlotStackIsEmpty
{
get { return ItemStack.Count == 0; }
}
// show the slot stack is full
public bool SlotNotStackable
{
get { return CurrentItemOnSlot.ItemMaxStack == ItemStack.Count; }
}
// Add item into slot stack
public void AddItemToSlotStack(ItemDatabase item)
{
// Add item into stack
ItemStack.Push(item);
// when there is more than 1 item in same stack/slot
if (ItemStack.Count >= 1)
{
// print out the stack count
StackText.text = ItemStack.Count.ToString();
}
// Set the item icon
SetItemIcon(item);
}
// Remove item from the slot stack
private void UseItem()
{
// if there is any item in the slot
if(!SlotStackIsEmpty)
{
// take out the item
ItemStack.Pop().UseItem();
// when there is 1 or more item in stack/slot
if(ItemStack.Count >= 1)
{
// print out the stack count
StackText.text = ItemStack.Count.ToString();
}
else
{
// else make the text empty
StackText.text = string.Empty;
}
// when we remove the item, the slot becomes empty
if(SlotStackIsEmpty)
{
// change the icon back to empty slot sprite
RemoveItemIcon();
// add another new empty slot
InventoryManager.EmptySlots++;
}
}
}
// Set the item icon when looted into an empty slot
private void SetItemIcon(ItemDatabase item)
{
this.transform.Find("Icon").gameObject.active = true;
this.transform.Find("Icon").GetComponentInChildren<Image>().enabled = true;
this.transform.Find("Icon").GetComponentInChildren<Image>().sprite = item.ItemSprite;
}
// Remove the item icon when slot becomes empty
private void RemoveItemIcon()
{
this.transform.Find("Icon").GetComponentInChildren<Image>().sprite = null;
this.transform.Find("Icon").GetComponentInChildren<Image>().enabled = false;
this.transform.Find("Icon").gameObject.active = false;
}
// Use this when replace occupied stack with another stack
public void ReplaceAddItems(Stack<ItemDatabase> items)
{
// instantiate a new ItemStack
this.ItemStack = new Stack<ItemDatabase>(items);
// when there is 1 or more item in stack/slot
if (ItemStack.Count >= 1)
{
// print out the stack count
StackText.text = ItemStack.Count.ToString();
}
else
{
// else make the text empty
StackText.text = string.Empty;
}
// Change icon to current item
SetItemIcon(CurrentItemOnSlot);
}
// Clear everything in the slot
public void ClearSlot()
{
// Remove item stack
ItemStack.Clear();
// Remove icon
RemoveItemIcon();
// Remove stack text
StackText.text = string.Empty;
}
// When the slot is clicked
public void OnPointerClick(PointerEventData eventData)
{
if(eventData.button == PointerEventData.InputButton.Right)
{
UseItem();
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
public class HotbarController : MonoBehaviour {
public int HotbarSlotSize => gameObject.transform.childCount;
private List<ItemSlot> hotbarSlots = new List<ItemSlot>();
KeyCode[] hotbarKeys = new KeyCode[] { KeyCode.Alpha1, KeyCode.Alpha2, KeyCode.Alpha3, KeyCode.Alpha4, KeyCode.Alpha5, KeyCode.Alpha6 };
private void Start() {
SetUpHotbarSlots();
Inventory.instance.onItemChange += UpdateHotbarUI;
}
private void Update() {
for (int i = 0; i < hotbarKeys.Length; i++) {
if (Input.GetKeyDown(hotbarKeys[i])) {
//use item
hotbarSlots[i].UseItem();
return;
}
}
}
private void UpdateHotbarUI() {
int currentUsedSlotCount = Inventory.instance.hotbarItemList.Count;
for (int i = 0; i < HotbarSlotSize; i++) {
if (i < currentUsedSlotCount) {
hotbarSlots[i].AddItem(Inventory.instance.hotbarItemList[i]);
} else {
hotbarSlots[i].ClearSlot();
}
}
}
private void SetUpHotbarSlots() {
for (int i = 0; i < HotbarSlotSize; i++) {
ItemSlot slot = gameObject.transform.GetChild(i).GetComponent<ItemSlot>();
hotbarSlots.Add(slot);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.