text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using MoreLinq;
using System.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace GraphDisplay
{
public class EvolutionMgr
{
public int popSize { get; set; }
private int evolvePopSize;
public int iterations { get; set; }
public double mutationRate { get; set; }
public double crossoverRate { get; set; }
private List<MLP> mlps;
private string file;
private int minWeight;
private int maxWeight;
private bool evolveWeights;
private bool evolveFunction;
private bool useGraph;
Random r = new Random();
PerfGraph graph;
public EvolutionMgr(PerfGraph graph, string file, bool evolveWeights, bool evolveFunction, int popSize, int iterations, double mutationRate, double crossoverRate, int minWeight, int maxWeight, bool useGraph)
{
this.file = file;
this.popSize = popSize;
this.iterations = iterations;
this.mutationRate = mutationRate;
this.crossoverRate = crossoverRate;
this.minWeight = minWeight;
this.maxWeight = maxWeight;
this.evolveFunction = evolveFunction;
this.evolveWeights = evolveWeights;
this.graph = graph;
this.useGraph = useGraph;
initMLP();
calculatePopToEvolve();
}
private void initMLP()
{
mlps = new List<MLP>();
for(int i = 0; i<popSize; i++)
{
mlps.Add(new MLP(file, minWeight, maxWeight));
System.Threading.Thread.Sleep(20);
}
Console.WriteLine("done");
}
private void calculatePopToEvolve()
{
evolvePopSize = (popSize / 4) * 2;
}
public void run()
{
int iteration = 0;
while (iteration < iterations)
{
graph.updateLabel_evolutionary("EA on iteration " + iteration);
double[] fitness = new double[mlps.Count];
//double[,] outputs =
int i = 0;
foreach (MLP mlp in mlps)
{
graph.updateLabel_evolutionary("EA on iteration " + iteration+" training MLP:"+(i+1));
mlp.run(50, graph, useGraph);
fitness[i] = mlp.meanSquaredError();
mlp.resetMLP();
i++;
}
bool converged = true;
double minSquaredError = 9999;
foreach(double error in fitness)
{
if (error < minSquaredError)
{
minSquaredError = error;
}
if (error != fitness[0])
{
converged = false;
}
}
graph.updateLabel_evolutionary("EA on iteration " + iteration+ " min MSE:" + minSquaredError);
if (converged)
{
graph.updateLabel_evolutionary("CONVERGED after :" +iteration+ " iterations with MSE:" + minSquaredError);
graph.updateLabel_individual("");
break;
}
if (evolvePopSize > 0)
{
//get the top and bottom population
List<KeyValuePair<double, MLP>> evolvingMLP = new List<KeyValuePair<double, MLP>>();
List<KeyValuePair<double, MLP>> removingMLP = new List<KeyValuePair<double, MLP>>();
for (i = 0; i < evolvePopSize; i++)
{
evolvingMLP.Add(new KeyValuePair<double, MLP>(fitness[i], mlps[i]));
removingMLP.Add(new KeyValuePair<double, MLP>(fitness[i], mlps[i]));
}
for (i = evolvePopSize; i < popSize; i++)
{
var maxBestFitness = evolvingMLP.MaxBy(kvp => kvp.Key).Key;
var maxBestFitnessPair = evolvingMLP.MaxBy(kvp => kvp.Key);
var minWorstFitness = removingMLP.MinBy(kpv => kpv.Key).Key;
var minWorstFitnessPair = removingMLP.MinBy(kpv => kpv.Key);
if (fitness[i] < maxBestFitness)
{
evolvingMLP.Remove(maxBestFitnessPair);
evolvingMLP.Add(new KeyValuePair<double, MLP>(fitness[i], mlps[i]));
}
if (fitness[i] > minWorstFitness)
{
removingMLP.Remove(minWorstFitnessPair);
removingMLP.Add(new KeyValuePair<double, MLP>(fitness[i], mlps[i]));
}
}
//evolve the top population
List<MLP> temp = new List<MLP>();
foreach (KeyValuePair<double, MLP> kvp in removingMLP)
{
temp.Add(kvp.Value);
}
//remove the population with the bottom fitness
foreach (MLP m in temp)
{
mlps.Remove(m);
}
temp.Clear();
foreach (KeyValuePair<double, MLP> kvp in evolvingMLP)
{
temp.Add(DeepClone(kvp.Value));
}
//add the evolved mlps to the population
List<MLP> evolved = evolvePop(temp);
foreach (MLP m in evolved)
{
mlps.Add(m);
}
}
iteration++;
}
}
public static MLP DeepClone<MLP>(MLP obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (MLP)formatter.Deserialize(ms);
}
}
private List<MLP> evolvePop(List<MLP> population)
{
MLP m1;
MLP m2;
int index;
List<MLP> newPop = new List<MLP>();
while (population.Count > 0)
{
index = r.Next(0, population.Count);
m1 = population[index];
population.RemoveAt(index);
index = r.Next(0, population.Count);
m2 = population[index];
population.RemoveAt(index);
doCrossover(m1, m2, out m1, out m2);
doMutation(m1, out m1);
doMutation(m2, out m2);
newPop.Add(m1);
newPop.Add(m2);
}
return newPop;
}
private void doCrossover(MLP m1, MLP m2, out MLP m1Out, out MLP m2Out)
{
double probability = r.NextDouble();
if (probability <= crossoverRate)
{
if (evolveWeights)
{
int nodeIndex = r.Next(0, 5);
//test swap
Node n = m1.nodes[nodeIndex];
m1.nodes[nodeIndex] = m2.nodes[nodeIndex];
m2.nodes[nodeIndex] = n;
double weight = m1.getWeight(nodeIndex);
m1.setWeight(nodeIndex, m2.getWeight(nodeIndex));
m1.setWeight(nodeIndex, weight);
int nodeIndex2 = r.Next(0, 5);
while (nodeIndex2 == nodeIndex)
{
nodeIndex2 = r.Next(0, 5);
}
nodeIndex = nodeIndex2;
//test swap
n = m1.nodes[nodeIndex];
m1.nodes[nodeIndex] = m2.nodes[nodeIndex];
m2.nodes[nodeIndex] = n;
weight = m1.getWeight(nodeIndex);
m1.setWeight(nodeIndex, m2.getWeight(nodeIndex));
m1.setWeight(nodeIndex, weight);
}
if(evolveFunction)
{
MLP.Activation a = m1.activation;
m1.activation = m2.activation;
m2.activation = a;
}
}
m1Out = m1;
m2Out = m2;
}
private void doMutation(MLP m, out MLP mOut)
{
double probability = r.NextDouble();
if (probability <= mutationRate)
{
if (evolveWeights)
{
m.mutateWeights();
}
if(evolveFunction)
{
m.mutateFunction();
}
}
mOut = m;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using ZXing.Net.Mobile.Forms;
namespace App1
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public static string result;
public static String message;
public static Button scanner;
public static String GUID;
public string guid;
public MainPage()
{
InitializeComponent();
result = "123";
Guid id;
guid = "";
string returnedvalue = "";
MessagingCenter.Subscribe<giris, string>(this, "Entry value", (sender, value) => {
returnedvalue = value;
MessagingCenter.Unsubscribe<giris, string>(this, "Entry value");
});
if (returnedvalue != "")
{
id = Guid.NewGuid();
using (StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine(id.ToString());
}
}
if (!File.Exists("write.txt")){
MessagingCenter.Send<MainPage, string> (this, "Entry value", null);
Navigation.PushAsync(new giris());
}
else
{
using (StreamReader readtext = new StreamReader("write.txt"))
{
guid = readtext.ReadLine();
}
}
}
// SCANNING
private async void btn_scanClick(object sender, EventArgs e)
{
try
{
var scanner = DependencyService.Get<Interface1>();
var result = await scanner.ScanAsync();
if (result != null)
{
lbl2.Text = result;
string url = "https://web.bilist.com.tr:1512/dv_test_qr/tr_TR/";
posting(url);
}
}
catch (Exception ex)
{
throw;
}
}
public void posting(string url)
{
string myXMLstring2 = "";
String str = "";
Task task2 = new Task(() => {
str = lbl2.Text;
string[] strAr = str.Split(',');
string[] post = new String[strAr.Length+1];
string[] post_name = new String[strAr.Length+1];
string[] temp;
for (int i = 0; i < strAr.Length; i++)
{
temp = strAr[i].Split(':');
post_name[i] = temp[0].Substring(3, temp[0].Length - 1);
post[i] = temp[1].Substring(0, temp[1].Length - 1);
}
post_name[0] = post_name[0].Substring(1, post_name[0].Length);
post[post.Length - 2] = post[post.Length - 2].Substring(0, post[post.Length - 2].Length - 3);
post[post.Length-1] = guid;
post_name[post_name.Length-1] = "GUID";
string top = "";
for(int i=0; i<post.Length; i++)
{
top += post[i];
}
l1.Text = top;
Post_request pr = new Post_request();
myXMLstring2 = pr.AccessTheWebAsync(url, post_name, post).Result;
});
if (str != "")
{
task2.Start();
task2.Wait();
lbl.Text = myXMLstring2;
}
}
}
}
|
using System.Windows.Controls;
namespace Demo.HelloEventAggregator
{
/// <summary>
/// Interaction logic for PublisherView.xaml
/// </summary>
public partial class PublisherView : UserControl
{
public PublisherView()
{
InitializeComponent();
}
}
}
|
using Assets.Modules.Utility;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory("Camera")]
public class SetCameraToFollowPlayer : FsmStateAction
{
// QuestVM vm;
public override void OnEnter()
{
/* CameraController2D cam = FsmVariables.GlobalVariables.GetFsmGameObject(GlobalNames.Camera ).Value.GetComponent<CameraController2D>();
GameObject Target = FsmVariables.GlobalVariables.GetFsmGameObject(GlobalNames.Character ).Value;
// cam.initialTarget = Target.transform;
if (Target != null)
{
cam.AddTarget(Target.transform);
}
// cam.heightFromTarget = 5;
Finish();
} */
}
}
[ActionCategory("Camera")]
public class AlignMenuOptionWithPlayer : FsmStateAction
{
// QuestVM vm;
public override void OnEnter()
{
/* Camera cam = FsmVariables.GlobalVariables.GetFsmGameObject(GlobalNames.Camera).Value.GetComponent<Camera>();
GameObject Target = FsmVariables.GlobalVariables.GetFsmGameObject(GlobalNames.Character).Value;
Vector3 vec= cam.camera.WorldToScreenPoint(Target.transform.position);
FsmVariables.GlobalVariables.GetFsmGameObject(GlobalNames.QuestChoicesGUI).Value.transform.localPosition = vec;
Finish(); */
}
}
} |
using LearningEnglishWeb.Areas.Training.Models.CollectWord;
using LearningEnglishWeb.Areas.Training.Models.Shared;
using LearningEnglishWeb.Areas.Training.ViewModels.ChooseTranslate;
using LearningEnglishWeb.Areas.Training.ViewModels.CollectWord;
namespace LearningEnglishWeb.Areas.Training.ViewModels.Abstractions
{
public class QuestionViewModel
{
public QuestionViewModel(string word, int number, string imgSrc)
{
Word = word;
QuestionNumber = number.ToString();
ImageSrc = imgSrc;
}
public QuestionViewModel(Question question, string imgSrc) : this(question.Word, question.Number, imgSrc)
{
}
public string Word { get; set; }
public string QuestionNumber { get; set; }
public string ImageSrc { get; set; }
private static CollectWordQuestionViewModel CreateImpl(CollectWordQuestion question, string src)
{
return new CollectWordQuestionViewModel(question, src);
}
private static QuestionViewModel CreateImpl(Question question, string src)
{
return new QuestionViewModel(question, src);
}
private static ChooseTranslateQuestionViewModel CreateImpl(QuestionWithOptions question, string src)
{
return new ChooseTranslateQuestionViewModel(question, src);
}
public static dynamic Create(Question question, string src)
{
dynamic dQuestion = question;
return CreateImpl(dQuestion, src);
}
}
}
|
using System;
using System.Collections.Generic;
namespace DeckOfCard
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Deck of Cards Problem");
ShuffleCard shuffleCard = new ShuffleCard();
shuffleCard.ShufflingAndDistributing();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
/// <summary>
/// 公文紧急程度
/// </summary>
public enum EArchiveUrgency
{
普通 = 0,
急件 = 1,
特急 = 2
}
/// <summary>
/// 风险处置等级
/// </summary>
public enum EArchiveRiskLevel
{
一级 = 1,
二级 = 2,
三级 = 3
} |
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using JetBrains.Util;
using KaVE.Commons.Model.Events;
using KaVE.Commons.Model.Events.VisualStudio;
using KaVE.Commons.TestUtils.Model.Events;
using KaVE.Commons.Utils.Assertion;
using KaVE.VS.Commons;
using KaVE.VS.FeedbackGenerator.Generators;
using KaVE.VS.FeedbackGenerator.Utils.Logging;
using Moq;
using NUnit.Framework;
namespace KaVE.VS.FeedbackGenerator.Tests.Generators
{
internal class EventLoggerTest
{
private Mock<IMessageBus> _mockMessageBus;
private Mock<ILogManager> _mockLogManager;
private Action<IDEEvent> _logHandler;
private AutoResetEvent _logAppendSignal;
private List<IDEEvent> _loggedEvents;
private EventLogger _uut;
[SetUp]
public void SetUp()
{
_loggedEvents = new List<IDEEvent>();
_mockMessageBus = new Mock<IMessageBus>();
_mockMessageBus.Setup(mb => mb.Subscribe(It.IsAny<Action<IDEEvent>>(), null))
.Callback<Action<IDEEvent>, Func<IDEEvent, bool>>(
(logHandler, dc) => _logHandler = logHandler);
_logAppendSignal = new AutoResetEvent(false);
_mockLogManager = new Mock<ILogManager>();
OnCurrentLogAppend(
e =>
{
_loggedEvents.Add(e);
_logAppendSignal.Set();
});
_uut = new EventLogger(_mockMessageBus.Object, _mockLogManager.Object, null);
}
private void OnCurrentLogAppend(Action<IDEEvent> action)
{
_mockLogManager.Setup(lm => lm.CurrentLog.Append(It.IsAny<IDEEvent>())).Callback(action);
}
[Test]
public void LogsEvent()
{
var someEvent = TestEventFactory.SomeEvent();
WhenLoggerReceives(someEvent);
AssertAppendToCurrentLog(someEvent);
}
[Test]
public void SupressesNullEvents()
{
WhenLoggerReceives((IDEEvent) null);
AssertNoAppendToCurrentLog();
}
[Test]
public void ShouldNotFailIfLoggingFails()
{
var failingEvent = TestEventFactory.SomeEvent();
var someEvent = TestEventFactory.SomeEvent();
OnCurrentLogAppend(
e =>
{
Asserts.Not(failingEvent.Equals(e));
_loggedEvents.Add(e);
_logAppendSignal.Set();
});
WhenLoggerReceives(failingEvent, someEvent);
AssertAppendToCurrentLog(someEvent);
}
[Test, Ignore]
// RS9 TODO: this tests regularly fails during the build... what's going on here?
public void ShouldFlushOnShutdown()
{
var anEvent = TestEventFactory.SomeEvent();
var shutdownEvent = new IDEStateEvent {IDELifecyclePhase = IDELifecyclePhase.Shutdown};
WhenLoggerReceives(anEvent);
_uut.Shutdown(shutdownEvent);
CollectionAssert.AreEqual(new IDEEvent[] {anEvent, shutdownEvent}, _loggedEvents);
}
// TODO add tests for event merging logic
private void WhenLoggerReceives(params IDEEvent[] events)
{
events.ForEach(_logHandler);
}
private void AssertNoAppendToCurrentLog()
{
_logHandler(TestEventFactory.SomeEvent()); // send another event to flush buffer
Assert.IsFalse(_logAppendSignal.WaitOne(1000), "nothing appended");
}
private void AssertAppendToCurrentLog(params IDEEvent[] events)
{
_logHandler(TestEventFactory.SomeEvent()); // send another event to flush buffer
WaitForLogAppend();
CollectionAssert.AreEqual(events, _loggedEvents);
}
private void WaitForLogAppend()
{
Assert.IsTrue(_logAppendSignal.WaitOne(5000), "append was not invoked");
}
}
} |
using System;
using System.Threading.Tasks;
using Domain.Entities;
using Common.Repository;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Common.SensorListenerAPI;
using Microsoft.Extensions.Logging;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace SensorService.Controllers
{
[Route("api/[controller]")]
public class SensorsController : Controller
{
private readonly IHomeRepository repository;
private readonly ISensorListenerAPI listenerClient;
private readonly ILogger<SensorsController> logger;
public SensorsController(IHomeRepository repository, ISensorListenerAPI listenerClient, ILogger<SensorsController> logger)
{
this.repository = repository;
this.listenerClient = listenerClient;
this.logger = logger;
}
// POST api/sensor
[HttpPost]
public async Task<IActionResult> Post([FromBody]Sensor sensor)
{
var insertedSensor = await this.repository.AddSensor(sensor);
if (insertedSensor == null)
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
if (insertedSensor.RoomId != Guid.Empty)
{
var s = await listenerClient.NotifySensorUpdate(insertedSensor);
if (s == null)
{
this.logger.LogWarning("Failed to notify sensor change on queue client");
}
}
return Ok(insertedSensor);
}
// PUT api/sensor
[HttpPut]
public async Task<IActionResult> Put([FromBody]Sensor sensor)
{
var resultOk = await this.repository.EditSensor(sensor);
if (!resultOk)
{
return BadRequest();
}
var s = await this.listenerClient.NotifySensorUpdate(sensor);
return Ok(s);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var sensor = await this.repository.GetSensor(Guid.Parse(id));
if (sensor == null)
{
return NotFound();
}
return Ok(sensor);
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var sensors = await this.repository.GetSensors();
return Ok(sensors);
}
// DELETE api/sensor/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
var sensor = await this.repository.GetSensor(Guid.Parse(id));
if (sensor == null)
{
return NotFound();
}
var resultOk = await this.repository.DeleteSensor(Guid.Parse(id));
if (!resultOk)
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
return Ok(sensor);
}
[HttpGet("{id}/homeymapping")]
public async Task<IActionResult> GetHomeyMapping(string id)
{
var sensor = await this.repository.GetSensor(Guid.Parse(id));
if (sensor == null)
{
return NotFound();
}
var homeyMapping = await this.repository.GetHomeyMapping(sensor);
return Ok(homeyMapping);
}
[HttpPost("{id}/homeymapping")]
public async Task<IActionResult> PostHomeyMapping(string id, [FromBody] HomeyMapping mapping)
{
var sensor = await this.repository.GetSensor(Guid.Parse(id));
if (sensor == null)
{
return NotFound();
}
var insertedMapping = await this.repository.AddHomeyMapping(Guid.Parse(id), mapping);
if (insertedMapping == null)
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
return Ok(insertedMapping);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MOSC
{
class ServiceController
{
static System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("ServiceVPT");
public static bool GetStatus()
{
service = new System.ServiceProcess.ServiceController("ServiceVPT");
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Остановить службу
/// </summary>
public static void ServiceStop()
{
service.Stop();
}
/// <summary>
/// Запустить службу
/// </summary>
public static void ServiceStart()
{
service.Start();
}
/// <summary>
/// Проверить наличие службы
/// </summary>
/// <returns></returns>
public static bool CheckAvailability()
{
System.ServiceProcess.ServiceController servCheck = System.ServiceProcess.ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "ServiceVPT");
if (servCheck != null) return true;
else return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utility;
using Model.DataEntity;
using Uxnet.Web.Module.Common;
using System.Linq.Expressions;
namespace eIVOGo.Module.EIVO
{
public partial class InvoiceItemSellerGroupList : System.Web.UI.UserControl
{
protected IQueryable<SellerGroupList> _queryItems;
protected internal Dictionary<String, SortDirection> _sortExpression
{
get
{
if (ViewState["sort"] == null)
{
ViewState["sort"] = new Dictionary<String, SortDirection>();
}
return (Dictionary<String, SortDirection>)ViewState["sort"];
}
set
{
ViewState["sort"] = value;
}
}
public DateTime? DateFrom
{
get
{
return (DateTime?)ViewState["from"];
}
set
{
ViewState["from"] = value;
}
}
public DateTime? DateTo
{
get
{
return (DateTime?)ViewState["to"];
}
set
{
ViewState["to"] = value;
}
}
//min-yu add 2011-05-26
public int? RecordCount
{
get
{
if (_queryItems == null)
return 0;
else
return _queryItems.Count();
}
}
public int? SellerID
{
get
{
return (int?)ViewState["seller"];
}
set
{
ViewState["seller"] = value;
}
}
internal GridView DataList
{
get
{
return gvEntity;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void gvInvoice_Sorting(object sender, GridViewSortEventArgs e)
{
_sortExpression.AddSortExpression(e, true);
}
protected void bindData()
{
buildQueryItem();
if (this.ViewState["sort"] != null)
{
_queryItems = _sortExpression.QueryOrderBy(_queryItems, gvEntity.Columns[0].SortExpression, b => b.Seller.ReceiptNo);
_queryItems = _sortExpression.QueryOrderBy(_queryItems, gvEntity.Columns[1].SortExpression, b => b.Seller.CompanyName);
_queryItems = _sortExpression.QueryOrderBy(_queryItems, gvEntity.Columns[2].SortExpression, b => b.Seller.Addr);
_queryItems = _sortExpression.QueryOrderBy(_queryItems, gvEntity.Columns[3].SortExpression, b => b.TotalCount);
_queryItems = _sortExpression.QueryOrderBy(_queryItems, gvEntity.Columns[4].SortExpression, b => b.Summary);
}
if (gvEntity.AllowPaging)
{
gvEntity.PageIndex = PagingControl.GetCurrentPageIndex(gvEntity, 0);
gvEntity.DataSource = _queryItems.Skip(gvEntity.PageSize * gvEntity.PageIndex).Take(gvEntity.PageSize);
gvEntity.DataBind();
gvEntity.SetPageIndex("pagingList",_queryItems.Count());
}
else
{
gvEntity.DataSource = _queryItems;
gvEntity.DataBind();
}
}
protected virtual void buildQueryItem()
{
Expression<Func<InvoiceItem, bool>> queryExpr = i => i.InvoiceCancellation == null;
if (SellerID.HasValue)
{
queryExpr = queryExpr.And(o => o.SellerID == SellerID);
}
if (DateFrom.HasValue)
queryExpr = queryExpr.And(i => i.InvoiceDate >= DateFrom);
if (DateTo.HasValue)
queryExpr = queryExpr.And(i => i.InvoiceDate < DateTo.Value.AddDays(1));
//minyu-0701
//queryExpr = queryExpr.And(o => o.InvoiceItems.Where(i => i.InvoiceCancellation == null).Count() > 0);
var mgr = dsOrg.CreateDataManager();
_queryItems = mgr.GetTable<InvoiceItem>().Where(queryExpr).GroupBy(i => i.SellerID).Select(g =>
new SellerGroupList
{
Seller = mgr.EntityList.Where(o => o.CompanyID == g.Key).First(),
TotalCount = g.Count(),
Summary = g.Sum(i => i.InvoiceAmountType.TotalAmount)
});
}
public void BindData()
{
bindData();
}
}
public class SellerGroupList
{
public Organization Seller { get; set; }
public int TotalCount { get; set; }
public decimal? Summary { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Toy
{
class Toy
{
public string Manufacturer { get; set; }
public string Name { get; set; }
public double Price { get; set; }
private string Notes;
public Toy()
{
Manufacturer = string.Empty;
Name = string.Empty;
Price = 0;
}
public Toy(string notes)
{
Notes = notes;
}
public void GettingNotes(string note)
{
Notes += note;
}
public string ReturningNotes()
{
return Notes;
}
public string GetAisle()
{
Random rand = new Random();
int randomNum = rand.Next(1, 25);
string aisleNumber = $"{Manufacturer[0]}{randomNum}";
return aisleNumber;
}
}
}
|
using System;
using Android.Widget;
using Android.Animation;
using Android.Views.Animations;
using Android.Views;
namespace Ts.Core
{
public class Tag : Java.Lang.Object
{
public string key;
public Object value;
}
public static partial class ExpandAnimation
{
private static string LAYER_EXPAND = "LAYER_EXPAND_ANIMATION";
private static bool IsExpandFrame(ViewGroup view)
{
if (view is FrameLayout)
{
var tag = view.Tag;
if (tag != null)
{
Tag a = (Tag)tag;
if(a != null)
return true;
}
}
return false;
}
public static void ExpandFrameLayoutRight(this View view, int distance, int width, bool isExpand = true, long duration = 500, Action animationStart = null, Action animationEnd = null)
{
int startWidth = width;
int endWidth = isExpand ? startWidth + distance : startWidth - distance;
ExpandFrameLayoutRight(view, startWidth, endWidth, duration, animationStart, animationEnd);
}
public static void ExpandFrameLayoutRight(this View view, int widthBeginning, int widthEnd, long duration = 500, Action animationStart = null, Action animationEnd = null)
{
ViewGroup rootView = (ViewGroup)view.Parent;
ViewGroup.LayoutParams layoutParams = view.LayoutParameters;
bool isExpandFrameLayout = IsExpandFrame(rootView);
FrameLayout viewlayer = null;
if (!isExpandFrameLayout)
{
viewlayer = new FrameLayout(view.Context);
viewlayer.Tag = new Tag()
{
key = LAYER_EXPAND,
value = layoutParams,
};
viewlayer.SetBackgroundColor(Android.Graphics.Color.Transparent);
rootView.RemoveView(view);
rootView.AddView(viewlayer);
viewlayer.LayoutParameters = layoutParams;
viewlayer.SetClipChildren(true);
FrameLayout.LayoutParams paras = new FrameLayout.LayoutParams(view.Width, view.Height, GravityFlags.Left);
view.LayoutParameters = paras;
viewlayer.AddView(view);
}
else
{
viewlayer = rootView as FrameLayout;
view.SetLayoutParams(view.Width, view.Height);
viewlayer.LayoutTransition = null;
}
ValueAnimator animation = ValueAnimator.OfInt((int)widthBeginning, (int)widthEnd);
animation.SetDuration(duration);
animation.SetInterpolator(new LinearInterpolator());
animation.Update += (object sender, ValueAnimator.AnimatorUpdateEventArgs e) =>
{
int value = (int) e.Animation.AnimatedValue;
viewlayer.LayoutParameters.Width = value;
viewlayer.RequestLayout();
};
animation.AnimationEnd += (object sender, EventArgs e) =>
{
viewlayer.LayoutParameters.Height = view.Height;
viewlayer.LayoutParameters.Width = widthEnd;
viewlayer.RequestLayout();
if(animationEnd != null)
{
animationEnd.Invoke();
}
};
animation.AnimationStart += (object sender, EventArgs e) =>
{
if(animationStart != null)
{
animationStart.Invoke();
}
};
animation.Start();
}
public static void ExpandFrameLayoutRightX(this View view, int widthBeginning, int widthEnd, long duration = 500, Action animationStart = null, Action animationEnd = null)
{
ViewGroup rootView = (ViewGroup)view.Parent;
ViewGroup.LayoutParams layoutParams = view.LayoutParameters;
bool isExpandFrameLayout = IsExpandFrame(rootView);
FrameLayout viewlayer = null;
if (!isExpandFrameLayout)
{
viewlayer = new FrameLayout(view.Context);
viewlayer.Tag = new Tag()
{
key = LAYER_EXPAND,
value = layoutParams,
};
viewlayer.SetBackgroundColor(Android.Graphics.Color.Red);
rootView.RemoveView(view);
rootView.AddView(viewlayer);
viewlayer.LayoutParameters = layoutParams;
viewlayer.SetClipChildren(true);
FrameLayout.LayoutParams paras = new FrameLayout.LayoutParams(view.Width, view.Height, GravityFlags.Left);
view.LayoutParameters = paras;
viewlayer.AddView(view);
}
else
{
// Tag tag = (Tag)viewlayer.Tag;
viewlayer = rootView as FrameLayout;
// viewlayer.LayoutTransition.SetDuration(3000);
view.SetLayoutParams(view.Width, view.Height);
viewlayer.LayoutTransition = null;
// viewlayer.LayoutParameters = (ViewGroup.LayoutParams) tag.value;
// viewlayer.LayoutAnimation = null;
}
// if (viewlayer.Width == widthEnd)
// {
// if(animationStart != null)
// {
// animationStart.Invoke();
// }
//
// if(animationEnd != null)
// {
// animationEnd.Invoke();
// }
// return;
// }
ValueAnimator animation = ValueAnimator.OfInt((int)widthBeginning, (int)widthEnd);
animation.SetDuration(0);
animation.SetInterpolator(new LinearInterpolator());
animation.Update += (object sender, ValueAnimator.AnimatorUpdateEventArgs e) =>
{
// int value = (int) e.Animation.AnimatedValue;
// Console.WriteLine("Value:{0}",value);
// viewlayer.SetLayoutParams(value,view.Height);
};
animation.AnimationEnd += (object sender, EventArgs e) =>
{
viewlayer.SetLayoutParams(widthEnd,view.Height);
if(animationEnd != null)
{
animationEnd.Invoke();
}
};
animation.AnimationStart += (object sender, EventArgs e) =>
{
if(animationStart != null)
{
animationStart.Invoke();
}
};
animation.Start();
}
public static void ExpandRightWidthAnimation(this View view, int widthBeginning, int widthView, bool isExpand = true, long duration = 3000, Action animationStart = null, Action animationEnd = null, bool isKeepState = true)
{
int end = -((int)widthView - (int)widthBeginning);
ViewGroup rootView = (ViewGroup)view.Parent;
ViewGroup.LayoutParams layoutParams = view.LayoutParameters;
bool isExpandFrameLayout = IsExpandFrame(rootView);
FrameLayout viewlayer = null;
if (!isExpandFrameLayout)
{
viewlayer = new FrameLayout(view.Context);
// viewlayer.SetTag(1, layoutParams);
viewlayer.Tag = new Tag()
{
key = LAYER_EXPAND,
value = layoutParams,
};
viewlayer.SetBackgroundColor(Android.Graphics.Color.Red);
rootView.RemoveView(view);
rootView.AddView(viewlayer);
viewlayer.LayoutParameters = layoutParams;
viewlayer.SetClipChildren(true);
viewlayer.AddView(view);
viewlayer.LayoutAnimation = null;
}
else
{
viewlayer = rootView as FrameLayout;
viewlayer.LayoutParameters = (ViewGroup.LayoutParams)((Tag) viewlayer.Tag).value ;
view.SetX(0);
viewlayer.LayoutAnimation = null;
viewlayer.LayoutTransition = null;
}
ValueAnimator animation = ValueAnimator.OfInt((int)0, (int)end);
animation.SetDuration(duration);
animation.SetInterpolator(new LinearInterpolator());
animation.Update += (object sender, ValueAnimator.AnimatorUpdateEventArgs e) =>
{
int value = (int) e.Animation.AnimatedValue;
int dentaX = 0;
if(!isExpand)
{
dentaX = end - value;
}
else
{
dentaX = value;
}
viewlayer.SetX(dentaX);
view.SetX(-dentaX);
Console.WriteLine("DetaX : {0}",dentaX);
};
animation.AnimationEnd += (object sender, EventArgs e) =>
{
// viewlayer.RemoveView(view);
// rootView.RemoveView(viewlayer);
// rootView.AddView(view);
//TODO: setView layer again.
// viewlayer.SetLayoutParams
int width = isExpand ? widthBeginning : widthView;
viewlayer.SetX(0);
view.SetX(0);
view.SetLayoutParams(view.Width,view.Height);
viewlayer.SetLayoutParams(width,view.Height);
viewlayer.LayoutAnimation = null;
viewlayer.LayoutTransition = null;
(viewlayer.Parent as ViewGroup).LayoutTransition = null;
(viewlayer.Parent as ViewGroup).LayoutAnimation = null;
if(animationEnd != null)
{
animationEnd.Invoke();
}
};
animation.AnimationStart += (object sender, EventArgs e) =>
{
if(animationStart != null)
{
animationStart.Invoke();
}
};
animation.Start();
}
}
}
|
using homework_2.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace homework_2.Validation
{
public class ExamTitle: ValidationAttribute
{
private int _maxLength;
public ExamTitle(int maxLength)
{
_maxLength = maxLength;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ExamDto examDto = (ExamDto)validationContext.ObjectInstance;
if (examDto.Title.Length > _maxLength)
{
return new ValidationResult(FormatErrorMessage(validationContext.MemberName));
}
return ValidationResult.Success;
}
}
}
|
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;
namespace WindowsFormsApp1
{
public partial class frmSignupHelp : Form
{
public frmSignupHelp()
{
InitializeComponent();
lblHelp.Text = "Fill out all fields on the form to create your profile.";
lblCode.Text = "Your redemption code is automatically generated.";
lblInfo.Text = "Information can be viewed in the report once you have created your profile.";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using Newtonsoft.Json;
using QuestomAssets.AssetsChanger;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace QuestomAssets
{
/// <summary>
/// Keeps track of the status of mods relative to committed changes to the asset files
/// </summary>
internal class ModConfig
{
public List<string> InstalledModIDs { get; set; } = new List<string>();
public static ModConfig Load(QaeConfig config)
{
try
{
if (config.ModsStatusFile != null && config.RootFileProvider.FileExists(config.ModsStatusFile))
{
string modCfgTxt = System.Text.Encoding.UTF8.GetString(config.RootFileProvider.Read(config.ModsStatusFile));
return JsonConvert.DeserializeObject<ModConfig>(modCfgTxt);
}
else
{
return new ModConfig();
}
}
catch (Exception ex)
{
Log.LogErr($"Unable to read/parse mod status file from {config.ModsStatusFile}! Mod statuses will be lost!", ex);
return new ModConfig();
}
}
public void Save(QaeConfig config)
{
try
{
byte[] cfgBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(this));
config.RootFileProvider.Write(config.ModsStatusFile, cfgBytes, true);
}
catch (Exception ex)
{
Log.LogErr($"Failed to write mod status file to {config.ModsStatusFile}! Mod statuses will be lost!", ex);
throw;
}
}
public ModConfig Clone()
{
return new ModConfig() { InstalledModIDs = InstalledModIDs.ToList() };
}
public bool Matches( ModConfig y)
{
if (this == y)
return true;
if (this == null)
return false;
if (this.InstalledModIDs.Count != y.InstalledModIDs.Count)
return false;
if (this.InstalledModIDs.Any(a => !y.InstalledModIDs.Exists(b => b == a)))
return false;
return true;
}
}
}
|
// SemanticActions.cs
// Author:
// Stephen Shaw <sshaw@decriptor.com>
// Copyright (c) 2011 sshaw
using System;
using System.Collections.Generic;
using Compiler.Parser;
using Compiler.Symbols;
namespace Compiler.Semantics
{
public class SemanticActions
{
readonly Stack<Operator> _opStack;
readonly Stack<SemanticActionRecord> _saStack;
readonly Dictionary<string, int> _opWeight;
int _tid = 1000;
string _soc1Exists;
string _soc4Exists;
public SemanticActions ()
{
_opStack = new Stack<Operator> ();
_saStack = new Stack<SemanticActionRecord> ();
_opWeight = new Dictionary<string, int> ();
BuildOpWeight ();
}
public int SAStackCount ()
{
return _saStack.Count;
}
public void iPush (string name, string scope)
{
if (string.IsNullOrEmpty (name)) throw new ArgumentNullException ("name");
if (string.IsNullOrEmpty (scope)) throw new ArgumentNullException ("scope");
var sar = new SemanticActionRecord(SARType.IdSar) {Name = name, Scope = scope};
_saStack.Push (sar);
}
public void lPush (string name, string type)
{
if (string.IsNullOrEmpty(type)) throw new ArgumentNullException("type");
if (string.IsNullOrEmpty (name)) throw new ArgumentNullException ("name");
var id = SymbolsTable.Table.GetGlobal (name);
if (string.IsNullOrEmpty (id))
ERROR ("lPush", String.Format ("[Semantics][lPush]Global: {0} doesn't exist", name));
var sar = new SemanticActionRecord(SARType.LitSar, id) {Name = name, Type = type, Scope = "g."};
_saStack.Push (sar);
}
public void oPush (string op)
{
if (string.IsNullOrEmpty (op)) throw new ArgumentNullException ("op");
var weight = _opWeight [op];
if (_opStack.Count > 0) {
var top = _opStack.Peek ();
if (op == "=" && top.Name == "=")
ERROR ("oPush", "Nested assignments are not supported");
var top_weight = top.Weight;
// TODO: What about top != opWeight["["]?
while (top_weight >= weight && top_weight != _opWeight["("]) {
HandleOpStack ();
top_weight = _opStack.Peek ().Weight;
}
}
_opStack.Push (new Operator (op, weight));
}
public void tPush (string type)
{
if (string.IsNullOrEmpty (type)) throw new ArgumentNullException ("type");
var sar = new SemanticActionRecord(SARType.TypeSar) {Name = type, Type = type};
_saStack.Push (sar);
}
public void iExist (string currentScope)
{
if (string.IsNullOrEmpty(currentScope)) throw new ArgumentNullException("currentScope");
var top_sar = _saStack.Pop ();
var id_sar = new SemanticActionRecord (SARType.VarSar);
var scope = currentScope;
var identifier = FindObject (top_sar, ref scope);
if (identifier == null)
ERROR("iExist", string.Format("No symbol found for '{0}' in scope '{1}'", top_sar.Name, scope));
switch (top_sar.SAType)
{
case SARType.IdSar:
id_sar = new SemanticActionRecord(SARType.IdSar, identifier.Id)
{Scope = identifier.Scope, Name = identifier.Value, Type = identifier.data.Type};
break;
case SARType.FuncSar:
CheckArgList ("iExist", identifier.Id, top_sar.Parameters ());
id_sar = new SemanticActionRecord(SARType.FuncSar)
{Scope = currentScope, Name = identifier.Value + "()", Type = identifier.data.Type};
id_sar.ParameterAdd (top_sar.Parameters ());
id_sar.SymbolId = CreateTempSymbol (id_sar);
Core.ICode.FuncInvocInstr ("FRAME", identifier.Id, "this");
id_sar.Parameters();
foreach (var p in id_sar.Parameters()) {
Core.ICode.FuncInvocInstr ("PUSH", p, null);
}
Core.ICode.FuncInvocInstr ("CALL", identifier.Id, null);
if (GetReturnType (id_sar.SymbolId) != "void")
Core.ICode.FuncInvocInstr ("PEEK", id_sar.SymbolId, null);
break;
case SARType.ArrSar:
{
id_sar = new SemanticActionRecord(SARType.ArrSar, top_sar) {Type = identifier.data.Type};
id_sar.Type = id_sar.Type.Replace ("[]", "");
if (!identifier.data.Type.EndsWith ("[]"))
throw new ArgumentException (id_sar.Name + " is not an array");
var arrayId = identifier.Id;
// Always an int? Should this also be a 'byte' iff the type is a char?
var offsetId = CreateTempSymbol (new SemanticActionRecord (SARType.ArrSar, id_sar.Scope, "offset" + id_sar.Name, "int"), "R");
Core.ICode.MathInstr ("ADD", arrayId, id_sar.SymbolId, offsetId);
id_sar.SymbolId = offsetId;
}
break;
}
_saStack.Push (id_sar);
}
public void vPush (string scope, string name)
{
if (string.IsNullOrEmpty(scope)) throw new ArgumentNullException("scope");
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
var symbol = SymbolsTable.Table.GetSymbol (scope, name);
if (symbol == null)
ERROR ("vPush", String.Format("Symbol for {0} in scope {1} not found", name, scope));
var variable = new SemanticActionRecord(SARType.VarSar, symbol.Id)
{Name = symbol.Value, Scope = symbol.Scope, Type = symbol.Kind};
_saStack.Push (variable);
}
public void tExist ()
{
var typeSAR = _saStack.Pop ();
if (!(Lexeme.IsType (typeSAR.Type)) && !(Lexeme.IsClass (typeSAR.Type)))
ERROR ("tExist", typeSAR);
}
public void rExists (string currentScope)
{
// Pop top 2 SARs off stack Obj.member
var member_sar = _saStack.Pop ();
var obj_sar = _saStack.Pop ();
// Create a new ref_sar that we'll push onto the SAStack
var ref_sar = new SemanticActionRecord (SARType.RefSar);
var scope = "g." + SymbolsTable.Table.GetSymbolType (obj_sar.SymbolId);
// TODO: What is this for?
if (currentScope.Contains ("main"))
scope = scope + scope.Substring (scope.LastIndexOf ("."));
// Get symbol
var identifier = FindObject (member_sar, ref scope);
if (identifier == null)
ERROR ("rExists", String.Format ("{0} does not have a method for {1}", obj_sar.Name, member_sar.Name));
ref_sar.Scope = scope;
if (identifier.data.AccessModifier != "public")
ERROR ("rExists", identifier.Value + " is not accessible");
switch (member_sar.SAType)
{
case SARType.IdSar:
member_sar.SymbolId = identifier.Id;
ref_sar.Name = obj_sar.Name + "." + member_sar.Name;
ref_sar.Type = identifier.data.Type;
ref_sar.SymbolId = CreateTempSymbol (ref_sar, "R");
Core.ICode.RefInstr ("REF", obj_sar.SymbolId, member_sar.SymbolId, ref_sar.SymbolId);
break;
case SARType.FuncSar:
member_sar.SymbolId = identifier.Id;
ref_sar.Name = obj_sar.Name + "." + member_sar.Name;
ref_sar.Scope = currentScope;
ref_sar.Type = identifier.data.Type;
ref_sar.ParameterAdd (member_sar.Parameters ());
ref_sar.SymbolId = CreateTempSymbol (ref_sar);
CheckArgList ("rExist", ref_sar.SymbolId, identifier.data.Parameters ());
Core.ICode.FuncInvocInstr ("FRAME", member_sar.SymbolId, obj_sar.SymbolId);
member_sar.Parameters();
foreach (var p in member_sar.Parameters()) {
Core.ICode.FuncInvocInstr ("PUSH", p, null);
}
Core.ICode.FuncInvocInstr ("CALL", member_sar.SymbolId, null);
if (GetReturnType (ref_sar.SymbolId) != "void")
Core.ICode.FuncInvocInstr ("PEEK", ref_sar.SymbolId, null);
break;
case SARType.ArrSar:
{
ref_sar = new SemanticActionRecord(SARType.ArrSar, member_sar)
{Name = obj_sar.Name + "." + member_sar.Name + "[]", Type = identifier.data.Type};
ref_sar.Type = ref_sar.Type.Replace ("[]", "");
if (!identifier.data.Type.EndsWith ("[]"))
throw new ArgumentException (ref_sar.Name + " is not an array");
var arrayId = identifier.Id;
// Always an int? Should this also be a 'byte' iff the type is a char?
var offsetId = CreateTempSymbol (new SemanticActionRecord (SARType.ArrSar, ref_sar.Scope, "offset" + ref_sar.Name, "int"), "R");
Core.ICode.MathInstr ("ADD", arrayId, ref_sar.SymbolId, offsetId);
ref_sar.SymbolId = offsetId;
}
break;
}
_saStack.Push (ref_sar);
}
public void CD (string scope, string constructor)
{
if (ScopeUtils.Top (scope) != constructor)
ERROR ("CtorDecleration", String.Format ("Ctor not found for {0}", ScopeUtils.Top(scope)));
}
public void oComma ()
{
while ((_opStack.Peek()).Name != "," && (_opStack.Peek()).Name != "(") {
HandleOpStack ();
}
}
public void BAL ()
{
_saStack.Push (new SemanticActionRecord (SARType.BalSar));
}
public void EAL ()
{
var argSAR = new SemanticActionRecord (SARType.AlSar);
while ((_saStack.Peek()).SAType != SARType.BalSar) {
var sar = _saStack.Pop ();
argSAR.ParameterAdd (sar.SymbolId);
}
_saStack.Pop ();
_saStack.Push (argSAR);
}
public void Func ()
{
var alSAR = _saStack.Pop ();
var idSAR = _saStack.Pop ();
var funcSAR = new SemanticActionRecord(SARType.FuncSar) {Name = idSAR.Name};
funcSAR.ParameterAdd (alSAR.Parameters ());
// Add scope - This will likely be overwritten with rExist, but needed for iExist
funcSAR.Scope = idSAR.Scope;
_saStack.Push (funcSAR);
}
public void IfAction ()
{
if (_saStack.Count <= 0)
ERROR ("IfAction", "nothing", "bool");
var boolSAR = _saStack.Pop ();
boolSAR.Type = GetType (boolSAR);
if (boolSAR.Type != "bool")
ERROR ("IfAction: Expression is not a bool expression", boolSAR);
Core.ICode.IfControlFlowInstr ("BF", boolSAR.SymbolId, "SKIPIF");
}
public void WhileAction ()
{
if (_saStack.Count <= 0)
ERROR ("WhileAction", "nothing", "bool");
var boolSAR = _saStack.Pop ();
boolSAR.Type = GetType (boolSAR);
if (boolSAR.Type != "bool")
ERROR ("WhileAction", boolSAR);
Core.ICode.WhileControlFlowInstr ("BF", boolSAR.SymbolId, "ENDWHILE");
}
public void ReturnAction (string scope, bool funcEnd = false)
{
var methodScope = ScopeUtils.Pop (scope);
var method = ScopeUtils.Top (scope);
var returnSymbol = SymbolsTable.Table.GetSymbol (methodScope, method);
if (returnSymbol == null)
ERROR ("ReturnAction", String.Format("No return found for method {0}", method));
var returnType = returnSymbol.data.Type;
if (_saStack.Count == 0) {
switch (returnType)
{
case "this":
Core.ICode.ReturnInstr("RETURN", "this");
break;
case "void":
Core.ICode.ReturnInstr ("RTN", null);
break;
default:
if (funcEnd)
Core.ICode.ReturnInstr("RTN", null);
else
ERROR ("ReturnAction", String.Format ("[ReturnAction] {0} is missing a return statement of type '{1}'", method, returnType));
break;
}
} else {
var ret_sar = _saStack.Pop ();
ret_sar.Type = GetType (ret_sar);
if (returnType == "void")
ERROR ("ReturnAction", String.Format("Return type is 'void', but found return type '{0}'", ret_sar.Type));
if (returnType != ret_sar.Type)
ERROR ("ReturnAction", "Return types don't match");
Core.ICode.ReturnInstr ("RETURN", ret_sar.SymbolId);
}
EOE ();
}
public void CoutAction ()
{
var type_sar = _saStack.Pop ();
var type = GetType (type_sar);
if (type != "int" && type != "char")
ERROR ("CoutAction: Not printable type", type_sar);
Core.ICode.WriteInstr (type_sar.SymbolId, type);
EOE ();
}
public void CinAction ()
{
var typeSAR = _saStack.Pop ();
var type = GetType (typeSAR);
if (type != "int" && type != "char")
ERROR ("CinAction: Not valid type", typeSAR);
Core.ICode.ReadInstr (typeSAR.SymbolId, type);
EOE ();
}
public void ArrAction ()
{
var index = _saStack.Pop ();
var arrayName = _saStack.Pop ();
arrayName.SAType = SARType.ArrSar;
if (index.Type != "int")
ERROR("ArrAction", "Array index must be an int");
// Should this be a reference? If set to ', "R"), it only shows the same address each time.
// FIXME: What's going on here?
var socId = CreateTempSymbol (new SemanticActionRecord (SARType.ArrSar, index.Scope, "SOC" + arrayName.Name, "int"));
Core.ICode.MathInstr ("MUL", index.SymbolId, CreateSocSymbol (), socId);
arrayName.SymbolId = socId;
_saStack.Push (arrayName);
}
public void AtoiAction ()
{
var exp = _saStack.Pop ();
if (exp.Name.Length == 1 && char.IsNumber (exp.Name [0])) {
var intSAR = new SemanticActionRecord(SARType.LitSar) {Type = "int", Name = exp.Name};
_saStack.Push (intSAR);
} else
ERROR ("AtoiAction: ", exp);
}
public void ItoaAction ()
{
var exp = _saStack.Pop ();
var result = Convert.ToInt32 (exp.Name);
if (result != 0) {
var charSAR = new SemanticActionRecord(SARType.LitSar) {Type = "char"};
var num = Convert.ToChar (result);
charSAR.Name = num.ToString ();
_saStack.Push (charSAR);
} else
ERROR ("ItoaAction: ", exp);
}
public void NewObjAction ()
{
var alSAR = _saStack.Pop ();
var typeSAR = _saStack.Pop ();
var ctor = SymbolsTable.Table.GetConstructor ("g." + typeSAR.Name, typeSAR.Name);
if (ctor == null)
ERROR ("NewObj", "No ctor declared");
CheckArgList ("NewObj", ctor.Id, alSAR.Parameters ());
var newSAR = new SemanticActionRecord(SARType.NewSar, ctor.Id)
{Name = "ctor", Scope = ctor.Scope, Type = typeSAR.Name};
newSAR.ParameterAdd (alSAR.Parameters ());
newSAR.SymbolId = CreateTempSymbol (newSAR);
var size = SymbolsTable.Table.ClassSize (typeSAR.Name);
// NEWI #, A (A holds the starting address on the heap for this object
var heapAddress = CreateTempSymbol (new SemanticActionRecord (SARType.NewSar, newSAR.Scope, "sizeof" + newSAR.Name, "int"));
// NEWI size, temp ; malloc(sizeof(type)) -> temp
Core.ICode.MemoryAllocInstr ("NEWI", size.ToString (), heapAddress, null);
// Debug statement
//Console.WriteLine ("{0} size is {1}", typeSAR.Name, size.ToString ());
//
// Check some table for any Initialized Instance variable
// * Determined by the field_declaration section
//
// Put together ClassStaticInit()
// * Initialize each variable in its memory space
//
// Frame Class Type(ctor), temp
Core.ICode.FuncInvocInstr ("FRAME", ctor.Id, heapAddress);
// Add the parameters
newSAR.Parameters();
foreach (var p in newSAR.Parameters()) {
Core.ICode.RunTimeStackInstr ("PUSH", p);
}
// Call ctor
Core.ICode.FuncInvocInstr ("CALL", ctor.Id, null);
// Get the return value
Core.ICode.RunTimeStackInstr("PEEK", newSAR.SymbolId);
_saStack.Push (newSAR);
}
public void NewBracketAction (string scope)
{
var intSAR = _saStack.Pop ();
if (GetType (intSAR) != "int")
throw new ArgumentException ("NewArray: Invalid type: " + intSAR.Type);
var typeSAR = _saStack.Pop ();
var type = typeSAR.Type;
if ((type != "char") && (type != "int") &&
(type != "bool") && !(Lexeme.IsClass (type)))
throw new ArgumentException ("NewArray: Invalid array type " + typeSAR.Name);
var newSAR = new SemanticActionRecord(SARType.NewSar)
{Name = typeSAR.Name + "[" + intSAR.Name + "]", Type = type + "[]", Scope = scope};
var sizeOfArray = CreateTempSymbol (new SemanticActionRecord (SARType.NewSar, newSAR.Scope, "sizeof" + newSAR.Name, "int"));
Core.ICode.MathInstr ("MUL", CreateSocSymbol (), intSAR.SymbolId, sizeOfArray);
newSAR.SymbolId = CreateTempSymbol (newSAR);
Core.ICode.MemoryAllocInstr ("NEW", sizeOfArray, newSAR.SymbolId, null);
_saStack.Push (newSAR);
}
#region Infix to Postfix Conversion
public void OpCParen ()
{
while ((_opStack.Peek()).Name != "(") {
HandleOpStack ();
}
_opStack.Pop ();
}
public void OpCBracket ()
{
while ((_opStack.Peek()).Name != "[") {
HandleOpStack ();
}
_opStack.Pop ();
}
public void EOE (bool clean = true)
{
while (_opStack.Count > 0)
HandleOpStack ();
if (clean)
_saStack.Clear ();
}
void HandleOpStack ()
{
if (_saStack.Count < 2)
ERROR ("HandleOp", "Less than 2 actions", "At least 2 actions");
var op = _opStack.Pop ();
var rval = _saStack.Pop ();
var lval = _saStack.Pop ();
string tmpId;
string oper = op.Name;
switch (op.Name) {
case "+":
case "-":
case "*":
case "/":
case "%":
if (!CheckTypes (lval, rval))
ERROR ("HandleOpStack", op.Name);
tmpId = CreateTemp (lval, lval.Name + op.Name + rval.Name);
if (op.Name == "+" && string.IsNullOrEmpty (rval.SymbolId))
oper = "ADI";
Core.ICode.MathInstr (oper, lval.SymbolId, rval.SymbolId, tmpId);
break;
case "=":
if (!CheckTypes (lval, rval))
ERROR ("HandleOpStack", lval);
if (Lexeme.IsKeyword (lval.Name) && !(Lexeme.IsClass (lval.Name))) {
ERROR ("HandleOpStack", String.Format ("CheckTypes: Can't assign a value to keyword: {0}", lval.Name));
}
oper = "MOV";
var rvalOp = rval.SymbolId;
if (string.IsNullOrEmpty (rval.SymbolId))
rvalOp = rval.Name;
int val; // we don't care what this is
if (Int32.TryParse (rval.Name, out val))
oper = "MOVI";
Core.ICode.MiscInstr (oper, lval.SymbolId, rvalOp);
break;
case "<":
case ">":
case "==":
case "<=":
case ">=":
case "!=":
if (!CheckTypes (lval, rval))
ERROR ("HandleOpStack", String.Format ("{0}. Type mismatch", op.Name));
// Reusing lval and since the result of the temp variable will be bool we set it here
lval.Type = "bool";
tmpId = CreateTemp (lval, lval.Name + op.Name + rval.Name);
Core.ICode.BooleanInstr (op.Name, lval.SymbolId, rval.SymbolId, tmpId);
break;
case "&&":
case "||":
if (GetType (rval) != "bool" || GetType (lval) != "bool")
ERROR ("HandleOpStack", op.Name);
tmpId = CreateTemp (lval, lval.Name + op.Name + rval.Name);
Core.ICode.LogicalInstr (op.Name, lval.SymbolId, rval.SymbolId, tmpId);
break;
default:
ERROR ("HandleOpStack", op.Name);
break;
}
}
#endregion
#region Helpers
static Symbol FindObject (SemanticActionRecord sar, ref string scope)
{
if (sar.SAType == SARType.FuncSar)
scope = ScopeUtils.Pop (scope);
var obj = SymbolsTable.Table.GetSymbol (scope, sar.Name);
if (obj == null) {
if (sar.SAType == SARType.IdSar || sar.SAType == SARType.ArrSar) {
scope = ScopeUtils.Pop (scope);
obj = SymbolsTable.Table.GetSymbol (scope, sar.Name);
if (obj == null)
ERROR ("Find Obj: No value found", sar);
}
}
return obj;
}
static string GetReturnType (string id)
{
Symbol s = SymbolsTable.Table.GetSymbol (id);
return s.data.Type;
}
static bool CheckTypes (SemanticActionRecord lval, SemanticActionRecord rval)
{
string ltype = GetType (lval);
string rtype = GetType (rval);
if (Lexeme.IsClass (ltype) && rtype == "null")
return true;
if (ltype != rtype) {
ERROR ("CheckTypes", String.Format ("Found: {0}, Expect: {1}", rtype, ltype));
return false;
}
return true;
}
static void CheckArgList (string caller, string symbolID, List<string> parameters)
{
parameters.Reverse ();
var func = SymbolsTable.Table.GetSymbol (symbolID);
var funcParams = func.data.Parameters ();
if (func.data.Parameters ().Count != parameters.Count)
ERROR ("CheckArgList", String.Format ("{0}: Parameter count doesn't match\n Expected: {1}\n Found: {2}", caller, func.data.Parameters().Count, parameters.Count));
for (var i = 0; i < func.data.Parameters().Count; ++i) {
if (SymbolsTable.Table.GetSymbolType(funcParams[i]) != SymbolsTable.Table.GetSymbolType(parameters[i]))
{
var param = SymbolsTable.Table.GetSymbol(funcParams[i]);
if (param == null)
ERROR("CheckArgList", String.Format("{0}: Parameter doesn't exist", funcParams[i]));
ERROR("CheckArgList", String.Format("{0}: Wrong Parameter, {1}: {2}", caller, i + 1, param.Value));
}
}
}
static string GetType (SemanticActionRecord sar)
{
if (string.IsNullOrEmpty (sar.SymbolId))
throw new ArgumentNullException ("sar.SymbolId");
if (!string.IsNullOrEmpty (sar.Type))
return sar.Type;
return SymbolsTable.Table.GetSymbolType (sar.SymbolId);
}
string CreateTemp (SemanticActionRecord lval, string name)
{
var tvar = new SemanticActionRecord (SARType.TvarSar, lval.Scope, name, GetType (lval));
tvar.SymbolId = CreateTempSymbol (tvar);
_saStack.Push (tvar);
return tvar.SymbolId;
}
string CreateTempSymbol (SemanticActionRecord sar, string prefix = "T")
{
if (string.IsNullOrEmpty (sar.Scope))
throw new ArgumentException (sar.Name + " has no scope specified");
var id = prefix + _tid++;
var tmp = new Symbol(id, sar.Scope)
{data = {AccessModifier = "private"}, Scope = Parser.Parser.Scope.CurrentScope(), Kind = "lvar"};
tmp.data.Type = sar.Type;
tmp.data.ParameterAdd (sar.Parameters ());
tmp.Value = sar.Name;
SymbolsTable.Table.Add (tmp);
return id;
}
string CreateSocSymbol (bool sizeInt = true)
{
if (!string.IsNullOrEmpty (_soc4Exists) && sizeInt)
return _soc4Exists;
if (!string.IsNullOrEmpty (_soc1Exists) && !sizeInt)
return _soc1Exists;
string id = string.Empty;
if (sizeInt) {
id = "G" + _tid++;
var tmp = new Symbol(id, "g.") {Kind = "SOE4", data = {Type = "int"}, Value = "4"};
id = SymbolsTable.Table.AddGlobal (tmp);
_soc4Exists = id;
}
if (!sizeInt) {
id = "G" + _tid++;
var tmp = new Symbol(id, "g.") {Kind = "SOE1", data = {Type = "char"}, Value = "1"};
id = SymbolsTable.Table.AddGlobal (tmp);
_soc1Exists = id;
}
return id;
}
void BuildOpWeight ()
{
_opWeight.Add ("=", 1);
_opWeight.Add ("||", 3);
_opWeight.Add ("&&", 5);
_opWeight.Add ("==", 7);
_opWeight.Add ("!=", 7);
_opWeight.Add ("<", 9);
_opWeight.Add (">", 9);
_opWeight.Add ("<=", 9);
_opWeight.Add (">=", 9);
_opWeight.Add ("+", 11);
_opWeight.Add ("-", 11);
_opWeight.Add ("*", 13);
_opWeight.Add ("/", 13);
_opWeight.Add ("%", 13);
_opWeight.Add (")", 0);
_opWeight.Add ("]", 0);
_opWeight.Add (".", 15);
_opWeight.Add ("(", 15);
_opWeight.Add ("[", 15);
}
static void ERROR (string func, string message)
{
Console.WriteLine ("[SAError][{0}:{1}]\n Message: {2}", func, Parser.Parser.Line, message);
Core.Kill ();
}
static void ERROR (string func, string found, string expect)
{
Console.WriteLine ("[SAError][{0}:{1}]\n Expected: {2}\n Found: {3}\n", func, Parser.Parser.Line, expect, found);
Core.Kill ();
}
static void ERROR (string func, SemanticActionRecord sar)
{
Console.WriteLine ("[SAError][{0}:{1}]\n ({2})", func, Parser.Parser.Line, sar.Name);
Core.Kill ();
}
#endregion
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace API.Controllers
{
public class OrdersController : BaseApiController
{
private readonly DataContext _context;
public OrdersController(DataContext context)
{
this._context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Order>>> GetOrders()
{
return await _context.Order.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Order>> GetOrder(int id)
{
return await _context.Order.FindAsync(id);
}
}
} |
using bank_account_ddd_studies.domain.query;
namespace bank_account_ddd_studies.domain.queryHandler
{
public interface IQueryHandler
{
public string Operation { get; }
T Search<T>(IQuery query);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
public class AnimTest : MonoBehaviour {
public Animator ac;
private int ani = 0;
// Use this for initialization
void Start () {
StartCoroutine(SwitchAnim());
}
// Update is called once per frame
void Update ()
{
}
public IEnumerator SwitchAnim()
{
while (true)
{
yield return new WaitForSeconds(5);
Debug.Log("State:" + ani);
ani++;
if (ani > 6)
{
ani = 0;
}
ac.SetInteger("AnimState", ani);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankClassLib
{
public class OverdraftException : Exception
{
public OverdraftException(string str) : base(str)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using WS_PosData_PMKT.Models.Base;
namespace WS_PosData_PMKT.Models.Object
{
[DataContract]
public class DetailEventsPromo
{
[DataMember]
public List<NoVisitMotive> ListNoVisitMotive { get; set; }
[DataMember]
public List<Survey> ListSurvey { get; set; }
[DataMember]
public List<PhotographicEvidence> ListTypeEvidence { get; set; }
[DataMember]
public List<Products> ListProductsByCategory { get; set; }
[DataMember]
public List<TypeMaterial> ListTypeMaterial { get; set; }
[DataMember]
public List<UbicationProduct> ListUbication { get; set; }
[DataMember]
public List<KPI> ListKPI { get; set; }
}
public class Modules
{
public string IdModule { get; set; }
public string NameModule { get; set; }
}
public class NoVisitMotive
{
public string IdMotive { get; set; }
public string NameMotive { get; set; }
}
public class Survey
{
public string IdSurvey { get; set; }
public string NameSurvey { get; set; }
public string Question1 { get; set; }
public string Question2 { get; set; }
public string Question3 { get; set; }
public string Question4 { get; set; }
public string Question5 { get; set; }
public string Question6 { get; set; }
public string Question7 { get; set; }
public string Question8 { get; set; }
public string Question9 { get; set; }
public string Question10 { get; set; }
public string Question11 { get; set; }
public string Question12 { get; set; }
public string Question13 { get; set; }
public string Question14 { get; set; }
public string Question15 { get; set; }
}
public class PhotographicEvidence
{
public string IdTypeEvidence { get; set; }
public string NameTypeEvidence { get; set; }
}
public class ProductsCategories
{
public string IdCategory { get; set; }
public string NameCategory { get; set; }
public List<Products> ListProducts {get; set;}
}
public class Products
{
public string IdProduct { get; set; }
public string NameProduct { get; set; }
public string IdCategory { get; set; }
public string NameCategory { get; set; }
}
public class TypeMaterial
{
public string IdTypeMaterial { get; set; }
public string NameTypeMaterial { get; set; }
}
public class UbicationProduct
{
public string IdUbication { get; set; }
public string NameUbication { get; set; }
}
public class KPI
{
public string IdKPI { get; set; }
public string NameKPI { get; set; }
}
} |
using Dashboard.API.Application.Persistence.Repositories;
using Dashboard.API.Domain.Models;
using Dashboard.API.Persistence.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Dashboard.API.Persistence.Repositories
{
public class ClientServicesRepository : IClientServicesRepository
{
private readonly SeviiContext _context;
public ClientServicesRepository(SeviiContext context)
{
_context = context;
}
public Task<List<ClientServiceModel>> GetClientServicesForUserAsync(Guid userId)
{
return _context.ClientServices
.Where(d => d.ClientId == userId).Where(d => !d.IsDeleted)
.Select(d => ClientServiceModel.Create(d)).ToListAsync();
}
public async Task AddClientServiceAsync(ClientServiceModel model, Guid userId)
{
var client = await _context.Clients.FindAsync(userId);
if (client == null)
await _context.Clients.AddAsync(new Client { Id = userId, Name = "" });
var clientService = new ClientService
{
Id = model.Id == Guid.Empty ? Guid.NewGuid() : model.Id,
Name = model.Name,
ClientId = userId,
Description = model.Description,
Key = model.Key,
DefaultValue = model.DefaultValue
};
await _context.AddAsync(clientService);
await _context.SaveChangesAsync();
}
public async Task<ClientProfileAndServicesModel> GetClientProfileAndServicesOrNullAsync(Guid userId, Guid clientId)
{
var profile = await _context.Clients.FindAsync(clientId);
if (profile == null)
return null;
var services = await _context.ClientServices
.Where(d => d.ClientId == clientId).Where(d => !d.IsDeleted)
.Select(d => ClientServiceModel.Create(d)).ToListAsync();
var servicesWithSubscribedStatus = new List<ClientServiceModel>();
foreach (var service in services)
{
service.Subscribed =
await _context.UserSubscriptions.FirstOrDefaultAsync(d =>
d.UserId == userId && d.ClientServiceId == service.Id) != null;
servicesWithSubscribedStatus.Add(service);
}
var result = new ClientProfileAndServicesModel
{
Profile = ClientProfileModel.Create(profile),
Services = servicesWithSubscribedStatus
};
return result;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using TouchScript;
public class ftlTouch
{
private int _id;
private int _pointId;
private float _time;
private Dictionary<int, List<ftlTouch>> _dictionary;
private int _numberOfSamplePoints = 3;
private Vector2 _screenPosition;
private Vector3 _worldPosition;
private Vector2 _rawVelocity;
private Vector2 _averageVelocity;
private float _speed;
private bool _active;
private bool _lineDown;
private ITouch _iTouch;
private bool _discard = false;
private GameObject camObject;
public GameObject CamObject
{
get{return camObject;}
set{camObject = value;}
}
public ITouch iTouch
{
get{return _iTouch;}
set{_iTouch = value;}
}
public int Id
{
get { return _id;}
set { _id = value;}
}
public int PointId
{
get {return _pointId;}
set { _pointId = value;}
}
public Dictionary<int, List<ftlTouch>> SetDictionary
{
set{_dictionary = value;}
}
public void Add(bool HasTV)
{
_id = _iTouch.Id;
if (!_dictionary.ContainsKey(Id))
{
_dictionary.Add (Id, new List<ftlTouch>());
}
_pointId = _dictionary [_id].Count;
_screenPosition = _iTouch.Position;
var window = CamObject.GetComponent<ftlManager> ().GetWindow ();
if (!HasTV)
_worldPosition = CamObject.GetComponent<ftlManager> ().transformToWindow (_screenPosition, window);
else
_worldPosition = CamObject.GetComponent<Camera>().ScreenToWorldPoint (_screenPosition);
_worldPosition.z = 0;
if (_dictionary[_id].Count > 1)
{
var lastPoint = _dictionary[_id][_pointId - 1];
var deltaTime = _time - lastPoint.EventTime;
var deltaPosition = _worldPosition - lastPoint.WorldPosition;
_rawVelocity = deltaPosition / deltaTime;
var samplesToTake = 0;
if (_pointId >= _numberOfSamplePoints)
{
samplesToTake = _numberOfSamplePoints;
}
else
{
samplesToTake = _pointId;
}
var runningTotal = Vector2.zero;
for (int i = _pointId - samplesToTake; i < _pointId; i++)
{
runningTotal += _dictionary[_id][i].RawVelocity;
}
runningTotal += _rawVelocity;
_averageVelocity = runningTotal / samplesToTake;
var velSq = Mathf.Pow (_averageVelocity.x, 2) + Mathf.Pow(_averageVelocity.y, 2);
_speed = Mathf.Sqrt(velSq);
_active = true;
_lineDown = false;
}
_dictionary [_id].Add (this);
}
public int SamplePoints
{
set { _numberOfSamplePoints = value;}
}
public float EventTime
{
get{return _time;}
set{_time = value;}
}
public Vector2 ScreenPosition
{
get { return _screenPosition;}
set { _screenPosition = value;}
}
public Vector3 WorldPosition
{
get{return _worldPosition;}
set { _worldPosition = value;}
}
public Vector2 RawVelocity
{
get{return _rawVelocity;}
}
public Vector2 AverageVelocity
{
get { return _averageVelocity;}
set { _averageVelocity = value;}
}
public float Speed
{
get { return _speed;}
set { _speed = value;}
}
public bool Active
{
get{return _active;}
set{ _active = value;}
}
public bool LineDown
{
get{return _lineDown;}
set{ _lineDown = value;}
}
public bool Discard
{
get{return _discard;}
set{ _discard = value;}
}
}
|
using System;
using FinanceBot.Models.CommandsException;
using FinanceBot.Views.Update;
namespace FinanceBot.Models.CommandsExceptions
{
public class CategoryNotFoundException : CommandExeption
{
public CategoryNotFoundException(string categoryName)
{
base.BadCommand = string
.Format(SimpleTxtResponse.CategoryNotFound, categoryName);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FaceBookQuestions
{
public class FaceBookQuestions
{
/*
* http://www.geeksforgeeks.org/forums/topic/facebook-interview-question-for-software-engineerdeveloper-about-algorithms-3/
Given a set S, find all the maximal subsets whose sum <= k. For example, if S = {1, 2, 3, 4, 5} and k = 7
Output is: {1, 2, 3} {1, 2, 4} {1, 5} {2, 5} {3, 4}
Hint:
- Output doesn’t contain any set which is a subset of other.
- If X = {1, 2, 3} is one of the solution then all the subsets of X {1} {2} {3} {1, 2} {1, 3} {2, 3} are omitted.
- Lexicographic ordering may be used to solve it
*/
public List<List<int>> _009_FindMaxSubSet(int[] input, int k)
{
// sort input.
List<List<int>> res = new List<List<int>>();
List<int> cur = new List<int>();
TrackingTreeNode trackingTree = new TrackingTreeNode();
Tracker(input, cur, res, 0, k);
return res;
}
public bool Tracker(int[] input, List<int> current, List<List<int>> res, int index, int k)
{
if (current.Sum() > k)
{
List<int> tmp = new List<int>();
for (int i = 0; i < current.Count - 1; i++)
{
tmp.Add(current[i]);
}
res.Add(tmp);
return true;
}
if (current.Sum() == k)
{
List<int> tmp = new List<int>();
for (int i = 0; i < current.Count; i++)
{
tmp.Add(current[i]);
}
//Insert(trackingTree,tmp);
res.Add(tmp);
return true;
}
for (int i = index; i < input.Length; i++)
{
current.Add(input[i]);
bool Found = Tracker(input, current, res,i + 1, k);
current.Remove(input[i]);
if (Found) break;
}
return false;
}
private void Insert(TrackingTreeNode root, List<int> list)
{
if (list.Count == 0) return;
if (!root.dict.Keys.Contains(list[0]))
{
root.dict.Add(list[0], new TrackingTreeNode());
}
int key = list[0];
list.RemoveAt(0);
Insert(root.dict[key], list);
return;
}
public class TrackingTreeNode
{
public Dictionary<int, TrackingTreeNode> dict = new Dictionary<int, TrackingTreeNode>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiMongoDb.Models
{
public class SinhVienDatabaseSettings : ISinhVienDatabaseSettings
{
public string SinhVienCollectionName { get; set; }
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
public interface ISinhVienDatabaseSettings
{
string SinhVienCollectionName { get; set; }
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
}
|
namespace GoogleARCore.HelloAR
{
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using GoogleARCore;
using UnityEngine.UI;
public class HelloARController : MonoBehaviour
{
public Text camPoseText;
//public Text testText;
public GameObject m_firstPersonCamera;
public GameObject cameraTarget; //SpherePointer
private Vector3 m_prevARPosePosition;
private bool trackingStarted = false;
public void Start()
{
m_prevARPosePosition = Vector3.zero;
}
public void Update()
{
_QuitOnConnectionErrors();
if (Session.Status != SessionStatus.Tracking)
{
trackingStarted = false; // if tracking lost or not initialized
if (camPoseText != null)
camPoseText.text = "Lost tracking, wait ...";
const int LOST_TRACKING_SLEEP_TIMEOUT = 15;
Screen.sleepTimeout = LOST_TRACKING_SLEEP_TIMEOUT;
return;
}
else
{
// Clear camPoseText if no error
//if(camPoseText != null)
//camPoseText.text = "CamPose: " + cameraTarget.transform.position;
camPoseText.text = "" + cameraTarget.transform.position;
}
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Vector3 currentARPosition = Frame.Pose.position;
if (!trackingStarted)
{
trackingStarted = true;
m_prevARPosePosition = Frame.Pose.position;
}
//Remember the previous position so we can apply deltas
Vector3 deltaPosition = currentARPosition - m_prevARPosePosition;
m_prevARPosePosition = currentARPosition;
if (cameraTarget != null)
{
// The initial forward vector of the sphere must be aligned with the initial camera direction in the XZ plane.
// We apply translation only in the XZ plane.
cameraTarget.transform.Translate(deltaPosition.x, 0.0f, deltaPosition.z);
// Set the pose rotation to be used in the CameraFollow script
//
//m_firstPersonCamera.GetComponent<FollowTarget>().targetRot = Frame.Pose.rotation;
}
}
private void _QuitOnConnectionErrors()
{
/*
// Do not update if ARCore is not tracking.
if (Session.ConnectionState == SessionConnectionState.DeviceNotSupported)
{
camPoseText.text = "This device does not support ARCore.";
Application.Quit();
}
else if (Session.ConnectionState == SessionConnectionState.UserRejectedNeededPermission)
{
camPoseText.text = "Camera permission is needed to run this application.";
Application.Quit();
}
else if (Session.ConnectionState == SessionConnectionState.ConnectToServiceFailed)
{
camPoseText.text = "ARCore encountered a problem connecting. Please start the app again.";
Application.Quit();
}*/
}
}
} |
using System;
using System.Collections.Generic;
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.Shapes;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace Project_Pharmacy
{
/// <summary>
/// Логика взаимодействия для Win_2_1_1_ShoppingCartList.xaml
/// </summary>
public partial class Win_2_1_1_ShoppingCartList : Window
{
string connectionString;
SqlDataAdapter adapter;
SqlConnection connection = null;
DataTable supplTable;
string sql = "SELECT * from Basket";
public string stuffid = Login.StuffId;
public Win_2_1_1_ShoppingCartList()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
private void ButtonClickBack(object sender, RoutedEventArgs e)
{
Win_2_1_1_ShoppingCartList winShopCartList = this; // Вызов открытого окна
Win_2_1_New_Order winNewOrd = new Win_2_1_New_Order(); // Создание нового окна
winNewOrd.Show(); // Проявление созданного окна
winShopCartList.Close(); // Закрытие основного окна
}
private void ButtonClickGood(object sender, RoutedEventArgs e)
{
Win_1_1_Inf_Of_Item winItemInf = new Win_1_1_Inf_Of_Item();
winItemInf.Owner = this;
winItemInf.Show();
}
private void ButtonClickAdd(object sender, RoutedEventArgs e)
{
connection.Open();
string tov = IdTovar.Text ;
string kolv = Kolvo.Text ;
var selectCommand = connection.CreateCommand(); // создаем команду для запроса
selectCommand.CommandText = $"INSERT INTO Basket (IdItem, IdOrder, Amount) values('{tov}', '{Win_2_1_New_Order.order}', '{kolv}')";//прописываем запрос
var reader = selectCommand.ExecuteReader();
reader.Close();
connection.Close();
}
private void UpdateDB()
{
try
{
supplTable.Clear();
connection.Close();
SqlCommand command = new SqlCommand(sql, connection);
adapter = new SqlDataAdapter(command);
connection.Open();
adapter.Fill(supplTable);
Suppl.ItemsSource = supplTable.DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (connection != null)
connection.Close();
}
}
private void ButtonClickUpdate(object sender, RoutedEventArgs e)
{
UpdateDB();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
supplTable = new DataTable();
try
{
connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(sql, connection);
adapter = new SqlDataAdapter(command);
connection.Open();
adapter.Fill(supplTable);
Suppl.ItemsSource = supplTable.DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (connection != null)
connection.Close();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class Enemy : MonoBehaviour
{
[SerializeField] private float _speed;
[SerializeField] private Transform _platformDetection;
private Animator _enemyAnimator;
private bool _platformEnds = true;
private float _distance = 2.0f;
private bool _gameOver = false;
private void Start()
{
_enemyAnimator = GetComponent<Animator>();
_enemyAnimator.SetBool("isRunnig", true);
}
private void Update()
{
RaycastHit2D platformInfo = Physics2D.Raycast(_platformDetection.position, Vector2.down, _distance);
if (!_gameOver)
{
transform.Translate(Vector2.right * _speed * Time.deltaTime);
}
else
{
_enemyAnimator.SetBool("isRunnig", false);
}
if (!platformInfo.collider)
{
if (_platformEnds)
{
transform.Rotate(0, -180, 0);
_platformEnds = false;
}
else
{
transform.Rotate(0, 0, 0);
_platformEnds = true;
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
Player player = collision.collider.GetComponent<Player>();
if (player)
{
_gameOver = true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Classes
{
public class A
{
public A()
{
Id = Guid.NewGuid();
}
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual D D { get; set; }
}
}
|
using System.Configuration;
using System.Data;
using DapperExtensions.Sql;
using KRF.Common;
using KRF.Core;
using MySql.Data.MySqlClient;
namespace KRF.Persistence
{
public class DataAccessFactory : IDataAccessFactory
{
private readonly SecretsReader sReader_;
public DataAccessFactory()
{
sReader_ = new SecretsReader(ConfigurationManager.AppSettings["ThirdPartySecretsFile"]);
}
public string ConnectionString
{
get
{
var connectionString = ConfigurationManager.ConnectionStrings["MySqlStore"].ConnectionString;
return string.Format(connectionString, sReader_["RdsPassword"]);
}
}
public IDbConnection CreateConnection()
{
DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect();
return new MySqlConnection(ConnectionString);
}
}
} |
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.BusinessLogic.Products.Specs;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Categories;
namespace NopSolutions.NopCommerce.Web.Modules
{
public partial class ProductSpecificationFilterControl : BaseNopUserControl
{
private String[] excludeParamsForFilter = new[] { "sortBy", "pageSize", "visoutDesign", "wrapping", "bunch",
"composition", "flowers", "bunchForm", "light",
"minHeight", "maxHeight", "minWidth", "maxWidth"};
private String[] excludeFilteredOptions = new[] { "оформление без оформления", "оформление упаковка",
"оформление букет", "оформление композиция",
"по основным цветам", "форма букета", "требование к освещению",
"цвет", "диаметр", "высота"};
#region Utilities
protected void BindData()
{
SpecificationAttributeOptionFilterCollection alreadyFilteredOptions = getAlreadyFilteredSpecs();
SpecificationAttributeOptionFilterCollection notFilteredOptions = getNotFilteredSpecs();
if (alreadyFilteredOptions.Count > 0 || notFilteredOptions.Count > 0)
{
if (alreadyFilteredOptions.Count > 0)
{
rptAlreadyFilteredPSO.DataSource = alreadyFilteredOptions;
rptAlreadyFilteredPSO.DataBind();
String navigateUrl = CommonHelper.GetThisPageURL(false);
bool first = true;
foreach (var key in Request.QueryString.Keys)
{
if (key == null)
continue;
string skey = key.ToString();
if (excludeParamsForFilter.Contains(skey))
{
if (first)
{
navigateUrl += "?";
first = false;
}
else
{
navigateUrl += "&";
}
navigateUrl += key + "=" + CommonHelper.QueryStringInt(key.ToString());
}
}
hlRemoveFilter.NavigateUrl = navigateUrl;
}
else
{
pnlAlreadyFilteredPSO.Visible = false;
pnlRemoveFilter.Visible = false;
}
if (notFilteredOptions.Count > 0)
{
rptFilterByPSO.DataSource = notFilteredOptions;
rptFilterByPSO.DataBind();
}
else
{
pnlPSOSelector.Visible = false;
}
}
else
{
Visible = false;
}
}
protected SpecificationAttributeOptionFilterCollection getAlreadyFilteredSpecs()
{
SpecificationAttributeOptionFilterCollection result = new SpecificationAttributeOptionFilterCollection();
string[] queryStringParams = getAlreadyFilteredSpecsQueryStringParams();
foreach (string qsp in queryStringParams)
{
int id = 0;
int.TryParse(Request.QueryString[qsp], out id);
SpecificationAttributeOption sao = SpecificationAttributeManager.GetSpecificationAttributeOptionByID(id);
if (sao != null)
{
SpecificationAttribute sa = sao.SpecificationAttribute;
if (sa != null)
{
result.Add(new SpecificationAttributeOptionFilter
{
SpecificationAttributeID = sa.SpecificationAttributeID,
SpecificationAttributeName = sa.Name,
DisplayOrder = sa.DisplayOrder,
SpecificationAttributeOptionID = sao.SpecificationAttributeOptionID,
SpecificationAttributeOptionName = sao.Name
});
}
}
}
return result;
}
public class SpecificationAttributeOptionFilterComparer : IComparer<SpecificationAttributeOptionFilter>
{
public int Compare(SpecificationAttributeOptionFilter first, SpecificationAttributeOptionFilter second)
{
return first.SpecificationAttributeID.CompareTo(second.SpecificationAttributeID);
}
}
protected SpecificationAttributeOptionFilterCollection getNotFilteredSpecs()
{
//get all
SpecificationAttributeOptionFilterCollection result = SpecificationAttributeManager.GetSpecificationAttributeOptionFilter(this.CategoryID);
//remove already filtered
SpecificationAttributeOptionFilterCollection alreadyFilteredOptions = getAlreadyFilteredSpecs();
foreach (SpecificationAttributeOptionFilter saof1 in alreadyFilteredOptions)
{
var query = from s
in result
where s.SpecificationAttributeID == saof1.SpecificationAttributeID
select s;
List<SpecificationAttributeOptionFilter> toRemove = query.ToList();
foreach (SpecificationAttributeOptionFilter saof2 in toRemove)
{
result.Remove(saof2);
}
}
result.RemoveAll(x => excludeFilteredOptions.Contains(x.SpecificationAttributeName.ToLower()));
result.Sort(new SpecificationAttributeOptionFilterComparer());
return result;
}
protected string[] getAlreadyFilteredSpecsQueryStringParams()
{
List<String> result = new List<string>();
List<string> reservedQueryStringParamsSplitted = new List<string>();
if (!String.IsNullOrEmpty(this.ReservedQueryStringParams))
{
reservedQueryStringParamsSplitted = this.ReservedQueryStringParams.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
for (int i=0; i<Request.QueryString.Keys.Count; i++)
{
if (Request.QueryString.Keys[i] == "CategoryID" || excludeParamsForFilter.Contains(Request.QueryString.Keys[i]))
continue;
string qsp = Request.QueryString.Keys[i];
if (!String.IsNullOrEmpty(qsp))
{
if (!reservedQueryStringParamsSplitted.Contains(qsp))
{
if (!result.Contains(qsp))
result.Add(qsp);
}
}
}
return result.ToArray();
}
protected string excludeQueryStringParams(string url)
{
if (!String.IsNullOrEmpty(this.ExcludedQueryStringParams))
{
string[] excludedQueryStringParamsSplitted = this.ExcludedQueryStringParams.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string exclude in excludedQueryStringParamsSplitted)
{
url = CommonHelper.RemoveQueryString(url, exclude);
}
}
return url;
}
//private string lastSA = string.Empty;
readonly List<string> usedSA = new List<string>();
private int cnt;
protected string addSpecificationAttribute()
{
string retVal = string.Empty;
//Get the data field value of interest for this row
string currentSA = Eval("SpecificationAttributeName").ToString();
//See if there's been a change in value
if (!usedSA.Contains(currentSA))
{
//string tmp = hfLastSA.Value + " - " + currentSA;
cnt++;
//hfLastSA.Value = currentSA;
usedSA.Add(currentSA);
if (cnt == 1)
retVal = String.Format("<table width=\"100%\"><tr><td valign=\"top\" width=\"50%\" style=\"vertical-align:top;\"><p class=\"headers\">» {0}</p><div class=\"var\">", Server.HtmlEncode(currentSA));
else if (CountSpecificationAttributes() == cnt)
retVal = String.Format("</div></td>{0}<p class=\"headers\">» {1}</p><div class=\"var\">", cnt % 2 == 1 ? "</tr><tr><td valign=\"top\" style=\"vertical-align:top;\" colspan='2'>" : "<td valign=\"top\" width=\"50%\" style=\"vertical-align:top;\">", Server.HtmlEncode(currentSA));
else
retVal = String.Format("</div></td>{0}<td valign=\"top\" width=\"50%\" style=\"vertical-align:top;\"><p class=\"headers\">» {1}</p><div class=\"var\">", cnt % 2 == 1 ? "</tr><tr>" : "", Server.HtmlEncode(currentSA));
//retVal = tmp + " " + retVal;
}
return retVal;
}
private int countSpecificationAttributes = -1;
private int CountSpecificationAttributes()
{
if (countSpecificationAttributes != -1)
return countSpecificationAttributes;
List<int> counted = new List<int>();
return getNotFilteredSpecs().Count(c =>
{
if (!counted.Contains(c.SpecificationAttributeID))
{
counted.Add(c.SpecificationAttributeID);
return true;
}
return false;
});
}
#endregion
#region Handlers
protected override void OnPreRender(EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
base.OnPreRender(e);
}
protected void rptFilterByPSO_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
SpecificationAttributeOptionFilter row = e.Item.DataItem as SpecificationAttributeOptionFilter;
HyperLink lnkFilter = e.Item.FindControl("lnkFilter") as HyperLink;
if (lnkFilter != null)
{
string name = row.SpecificationAttributeName.Replace(" ", "");
string url = CommonHelper.ModifyQueryString(CommonHelper.GetThisPageURL(true), name + "=" + row.SpecificationAttributeOptionID, null);
url = excludeQueryStringParams(url);
lnkFilter.NavigateUrl = url;
}
}
}
protected void rptAlreadyFilteredPSO_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
SpecificationAttributeOptionFilter row = e.Item.DataItem as SpecificationAttributeOptionFilter;
}
}
#endregion
#region Methods
public List<int> GetAlreadyFilteredSpecOptionIDs()
{
List<int> result = new List<int>();
SpecificationAttributeOptionFilterCollection filterOptions = getAlreadyFilteredSpecs();
foreach (SpecificationAttributeOptionFilter saof in filterOptions)
{
if (!result.Contains(saof.SpecificationAttributeOptionID))
result.Add(saof.SpecificationAttributeOptionID);
}
return result;
}
#endregion
#region Properties
public string ExcludedQueryStringParams
{
get
{
if (ViewState["ExcludedQueryStringParams"] == null)
return string.Empty;
else
return (string)ViewState["ExcludedQueryStringParams"];
}
set
{
ViewState["ExcludedQueryStringParams"] = value;
}
}
public string ReservedQueryStringParams
{
get
{
if (ViewState["ReservedQueryStringParams"] == null)
return string.Empty;
else
return (string)ViewState["ReservedQueryStringParams"];
}
set
{
ViewState["ReservedQueryStringParams"] = value;
}
}
/// <summary>
/// Category identifier
/// </summary>
public int CategoryID
{
get
{
int categoryId;
if (ViewState["CategoryID"] == null)
{
categoryId = CommonHelper.QueryStringInt("CategoryID");
if (categoryId == 0)
{
Product product = ProductManager.GetProductByID(ProductID);
if (product != null)
{
ProductCategory prodCategory = product.ProductCategories.Find(p => p.Category.ParentCategory != null);
if (prodCategory != null)
{
categoryId = prodCategory.CategoryID;
}
}
}
}
else
categoryId = (int)ViewState["CategoryID"];
return categoryId;
}
set
{
ViewState["CategoryID"] = value;
}
}
public int ProductID
{
get
{
return CommonHelper.QueryStringInt("ProductID");
}
}
#endregion
}
} |
using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;
public enum GameState
{
Menu, Loading, NewPlay, ResumePlay, Lose, Win
}
public class GameManager : MonoBehaviour
{
public static GameState gameState;
public Maze mazePrefab;
public Player playerPrefab;
public End endPrefab;
public Traps trapPrefab;
public Bombs bombPrefab;
public Cup cupPrefab;
public Cheese cheesePrefab;
public Canvas menuCanvasPrefab;
public Canvas inGameCanvasPrefab;
public Canvas loadingCanvasPrefab;
private Maze mazeInstance;
public Maze MazeInstance { get { return mazeInstance; } set { mazeInstance = value; } }
private Player playerInstance;
public Player PlayerInstance { get { return playerInstance; } set { playerInstance = value; } }
private End endInstance;
public End EndInstance { get { return endInstance; } set { endInstance = value; } }
private Traps trapInstance;
public Traps TrapsInstance { get { return trapInstance; } set { trapInstance = value; } }
private Bombs[] bombInstance = new Bombs[4];
public Bombs[] BombInstance { get { return bombInstance; } set { bombInstance = value; } }
private Cup cupInstance;
public Cup CupInstance { get { return cupInstance; } set { cupInstance = value; } }
private Cheese[] cheeseInstance = new Cheese[5];
public Cheese[] CheeseInstance { get { return cheeseInstance; } set { cheeseInstance = value; } }
private Canvas inGameCanvasInstance;
public Canvas InGameCanvasInstance { get { return inGameCanvasInstance; } set { inGameCanvasInstance = value; } }
private Canvas menuCanvasInstance;
public Canvas MenuCanvasInstance { get { return menuCanvasInstance; } set { menuCanvasInstance = value; } }
public bool saved;
private Canvas loadingCanvasInstance;
private bool resumeActive;
private bool loading;
private bool loadedTimer;
private Text timer;
private int seconds, minutes;
private float counter;
private void Start()
{
gameState = GameState.Menu;
menuCanvasInstance = GameObject.Find("Menu Canvas").GetComponent<Canvas>();
//OnPlayClick();
loading = false;
loadedTimer = false;
seconds = minutes = 0;
}
private void Update()
{
switch (gameState)
{
case GameState.Menu:
if (System.IO.File.Exists("Assets/Game Data/SaveData.xml"))
{
GameObject.Find("Menu Canvas/Resume Button").GetComponent<Button>().interactable = true;
resumeActive = true;
}
loading = false;
loadedTimer = false;
seconds = minutes = 0;
break;
case GameState.Loading:
if (!loading)
{
loadingCanvasInstance = Instantiate(loadingCanvasPrefab) as Canvas;
StartCoroutine(BeginGame());
loading = true;
}
break;
case GameState.NewPlay:
if (!loadedTimer)
{
Destroy(loadingCanvasInstance.gameObject);
timer = GameObject.Find("In-game Canvas(Clone)/Timer").GetComponent<Text>();
loadedTimer = true;
}
counter += Time.deltaTime;
if (counter >= 1.0f)
{
seconds++;
if (seconds >= 60)
{
seconds = 0;
minutes++;
}
counter = 0;
}
if (seconds >= 0 && seconds <= 9)
{
timer.text = "Time: " + minutes + ":0" + seconds;
}
else
{
timer.text = "Time: " + minutes + ":" + seconds;
}
break;
case GameState.ResumePlay:
if (!loadedTimer)
{
timer = GameObject.Find("In-game Canvas(Clone)/Timer").GetComponent<Text>();
loadedTimer = true;
}
counter += Time.deltaTime;
if (counter >= 1.0f)
{
seconds++;
if (seconds >= 60)
{
seconds = 0;
minutes++;
}
counter = 0;
}
if (seconds >= 0 && seconds <= 9)
{
timer.text = "Time: " + minutes + ":0" + seconds;
}
else
{
timer.text = "Time: " + minutes + ":" + seconds;
}
break;
case GameState.Lose:
Application.LoadLevel(1);
break;
case GameState.Win:
Application.LoadLevel(2);
break;
default:
break;
}
}
private IEnumerator BeginGame()
{
mazeInstance = Instantiate(mazePrefab) as Maze;
yield return StartCoroutine(mazeInstance.Generate());
inGameCanvasInstance = Instantiate(inGameCanvasPrefab) as Canvas;
Destroy(GameObject.Find("Camera"));
playerInstance = Instantiate(playerPrefab) as Player;
playerInstance.SetLocation(mazeInstance.GetCell(mazeInstance.startCoords));
yield return 0;
endInstance = Instantiate(endPrefab) as End;
endInstance.SetLocation(mazeInstance.GetCell(mazeInstance.endCoords));
yield return 0;
trapInstance = Instantiate(trapPrefab) as Traps;
trapInstance.SetLocation(mazeInstance.GetCell(mazeInstance.RandomCoordinates));
yield return 0;
cupInstance = Instantiate(cupPrefab) as Cup;
cupInstance.SetLocation(mazeInstance.GetCell(mazeInstance.RandomCoordinates));
yield return 0;
for (int i = 0; i < cheeseInstance.Length; i++)
{
cheeseInstance[i] = Instantiate(cheesePrefab) as Cheese;
cheeseInstance[i].SetLocation(mazeInstance.GetCell(mazeInstance.RandomCoordinates));
}
yield return 0;
for (int i = 0; i < bombInstance.Length; i++)
{
bombInstance[i] = Instantiate(bombPrefab) as Bombs;
}
bombInstance[0].SetLocation(mazeInstance.GetCell(new IntVector2(0, 0)));
bombInstance[1].SetLocation(mazeInstance.GetCell(new IntVector2(0, mazeInstance.size.z - 1)));
bombInstance[2].SetLocation(mazeInstance.GetCell(new IntVector2(mazeInstance.size.x - 1, 0)));
bombInstance[3].SetLocation(mazeInstance.GetCell(new IntVector2(mazeInstance.size.x - 1, mazeInstance.size.z - 1)));
yield return 0;
gameState = GameState.NewPlay;
}
public void OnPlayClick()
{
Destroy(GameObject.Find("Menu Canvas"));
gameState = GameState.Loading;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SlipRoad : Road
{
public Road RoadA, RoadB1, RoadB2;
public bool ToggleRotate;
public GameObject ToggleSprite, RoadSprite;
public Sprite[] RoadSprites;
private void Start()
{
Type = RoadType.Slip;
if (ToggleRotate)
{
RoadSprite.GetComponent<Image>().sprite = RoadSprites[0];
Node.transform.Rotate(Vector3.forward, (ToggleRotate) ? 90.0f * transform.localScale.x : -90.0f * transform.localScale.x);
}
}
public void OnClick()
{
ToggleRotate = !ToggleRotate;
RoadSprite.GetComponent<Image>().sprite = RoadSprites[(ToggleRotate) ? 1 : 0];
RoadSprite.transform.Rotate(Vector3.forward, (ToggleRotate) ? 90.0f : -90.0f);
Node.transform.Rotate(Vector3.forward, (ToggleRotate) ? 90.0f * transform.localScale.x : -90.0f * transform.localScale.x);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OPC.Common;
using OPC.Data.Interface;
using OPC.Data;
using System.Runtime.InteropServices;
namespace AndonSCADA
{
class PC_Access
{
public String ServerProgID = "OPC.SimaticNet";//OPC服务器ID
public String ItemConfig = "2:192.168.2.1:0202:0201";//监控PLC IP地址
public String[] ArryAdress;//监控PLC地址数组
public String dataType = "BYTE";//数据类型
public String ReadWriteType = "R";//R只读,W只写,RW读写
private OpcServer theSrv;
private OpcGroup TheGrp;
public OPCItemDef[] ItemDefs;
public int[] HandlesSrv;
public OPCItemResult[] rItm;
public PC_Access()
{
}
public bool connectServer()
{
try
{
theSrv = new OpcServer();
theSrv.Connect(ServerProgID);
TheGrp = theSrv.AddGroup("S7_200_01",false,900);
TheGrp.SetEnable(true);
TheGrp.Active = true;
return true;
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show("连接服务器出错:"+e.ToString());
return false;
}
}
public void disconnectServer()
{
try
{
if (theSrv != null)
{
theSrv.Disconnect();
}
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show("断开服务器连接出错:"+e.ToString());
}
}
public void addItemToGrp()
{
try
{
if (TheGrp != null)
{
//String[] Items = new String[30];
for(int i=0;i<ArryAdress.Length;i++)
{
if (ArryAdress[i] != "")
{
String stritem = ItemConfig + "," + ArryAdress[i] + "," + dataType + "," + ReadWriteType;
ItemDefs[i] = new OPCItemDef(stritem,true,i+1,System.Runtime.InteropServices.VarEnum.VT_EMPTY);
}
}
TheGrp.AddItems(ItemDefs,out rItm);
}
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
public int[] writeSyn(int[] arryHandleServer,Object[] arryVal)
{
int[] erro=new int[1];
try
{
TheGrp.SyncWrite(arryHandleServer, arryVal,out erro);
}
catch(Exception e){
System.Windows.Forms.MessageBox.Show(e.ToString());
}
if (erro == null)
erro[0] = 0;
return erro;
}
public void readSyn(int[] arryHandleServer,int length, out String[] arryResult)
{
OPCItemState[] arrystate = new OPCItemState[length];
arryResult = new String[length];
try
{
if (arryHandleServer != null)
{
TheGrp.SyncRead(OPCDATASOURCE.OPC_DS_DEVICE, arryHandleServer, out arrystate);
}
if (arrystate != null)
{
for (int i = 0; i < arrystate.Length; i++)
{
if (arrystate[i].Quality == 192)
arryResult[i] = arrystate[i].DataValue.ToString();
else
arryResult[i] = arrystate[i].Quality.ToString();
}
}
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
public int[] writeAsyn(int[] arryHandleServer, Object[] arryVal)
{
int[] erro = new int[1];
int CancelID;
try
{
TheGrp.AsyncWrite(arryHandleServer, arryVal, 55667788, out CancelID, out erro);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
}
if (erro == null)
erro[0] = 0;
return erro;
}
public void readAsyn(int[] arryHandleServer, out String[] arryResult)
{
int[] ae;
arryResult = new String[30];
int CancelID;
try
{
if (arryHandleServer != null)
{
TheGrp.AsyncRead(arryHandleServer, 5567788,out CancelID, out ae);
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
}
}
|
using Common.ViewModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace DesktopApp.Services
{
class AuthService : IAuthService
{
private string _signUpEndpoint = "https://localhost:43744/api/users/signup";
private string _signInEndpoint = "https://localhost:43744/api/users/signin";
private string _currentAccessToken = "";
private static HttpClient _httpClient = new HttpClient();
public async Task<string> SignIn(UserSignInVM user)
{
return await AuthAction(_signInEndpoint, user);
}
public async Task<string> SignUp(UserSignUpVM user)
{
return await AuthAction(_signUpEndpoint, user);
}
public string GetAccessToken()
{
return _currentAccessToken;
}
public async Task<string> AuthAction<T>(string endpoint, T content)
{
var body = JsonConvert.SerializeObject(content);
HttpResponseMessage response = await _httpClient.PostAsync(endpoint, new StringContent(body, Encoding.UTF8, "application/json"));
if (!response.IsSuccessStatusCode)
{
return null;
}
else
{
string accessToken = await response.Content.ReadAsStringAsync();
if (accessToken.Length == 0)
{
_currentAccessToken = null;
}
else
{
_currentAccessToken = accessToken;
}
return _currentAccessToken;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using HelperLibrary.Models;
using Microsoft.AspNetCore.Mvc;
using ConnectLibrary.Service;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace WebLectionAPI.Controllers
{
[Route("api/[controller]")]
public class SubjectController : Controller
{
readonly SubjectsService _subjects = new SubjectsService();
// GET: api/<controller>
[HttpGet]
public ActionResult<IEnumerable<SubjectModel>> Get()
{
JsonResult json = new JsonResult(_subjects.FindAllSubjects());
return json;
}
// GET api/<controller>/5
[HttpGet("{id}")]
public ActionResult<SubjectModel> Get(int id)
{
JsonResult json = new JsonResult(_subjects.FindSubjectById(id));
return json;
}
// POST api/<controller>
[HttpPost]
public void Post([FromBody]SubjectModel value)
{
_subjects.AddSubject(value);
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]SubjectModel value)
{
_subjects.UpdateSubject(value);
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
_subjects.DeleteSubjectById(id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Web.Http;
namespace sfAPIService.Controllers
{
public class CDSApiController : ApiController
{
protected class CDSTokenProperties
{
public int CompanyId { get; }
public CDSTokenProperties()
{
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var companyId = identity.Claims
.Where(c => c.Type == "CompanyId")
.Select(c => c.Value).SingleOrDefault();
CompanyId = Convert.ToInt32(companyId);
}
}
protected CDSTokenProperties UserToken { get; }
public CDSApiController()
{
UserToken = new CDSTokenProperties();
}
}
}
|
using MediatR;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Generation;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.DebugAdapter.Protocol
{
namespace Events
{
[Parallel]
[Method(EventNames.Initialized, Direction.ServerToClient)]
[GenerateHandler(Name = "DebugAdapterInitialized")]
[GenerateHandlerMethods]
[GenerateRequestMethods]
public record InitializedEvent : IRequest;
}
}
|
namespace GabberPCL
{
public static class Config
{
public static string WEB_URL = "https://gabber.audio";
public static string API_ENDPOINT = "https://api.gabber.audio";
public static string DATABASE_NAME = "gabber.db3";
}
} |
using UnityEngine;
using System.Collections;
public class TutorialMainMenu : MonoBehaviour {
private float gopherIntroductionWaitTime = 5f; // in seconds
private float gopherObjectListExplainationWaitTime = 5f; // in seconds
private float gopherCameraButtonExplainationWaitTime = 4f; // in seconds
//private float splashScreenWaitTime = 5f; // in seconds
//private float gopherIntroductionWaitTime = 1f; // in seconds
public AudioClip sound;
private AudioSource source;
public AudioClip sound2;
private AudioSource source2;
public AudioClip sound3;
public void Play1 (){
Debug.Log ("PLAYING");
source.PlayOneShot(sound,1.0f);
}
public void Play2 (){
Debug.Log ("PLAYING");
source.PlayOneShot(sound2,1.0f);
}
public void Play3(){
Debug.Log ("PLAYING");
source.PlayOneShot(sound3,1.0f);
}
// IEnumerator SwitchToMainMenu(){
// Debug.Log ("splash screen \"loading\"");
// Play ();
//
// yield return new WaitForSeconds (splashScreenWaitTime);
// Debug.Log ("splash screen \"loaded\"");
// SwitchPanels.changePanelStatic ("pSplash:deactivate,pMain:activate");
// }
//
void Start(){
Debug.Log ("Initializing sound object for call");
source = GetComponent<AudioSource>();
StartCoroutine (StartTutorialTimer ());
}
private IEnumerator StartTutorialTimer(){
if (PlayerData.getInstance ().getCurrentNarrativeChunk () == 0) {
Debug.Log ("before play1");
Play1 ();
Debug.Log ("after play1");
yield return new WaitForSeconds (gopherIntroductionWaitTime);
SwitchPanels.changePanelStatic ("pMainTutorial:activate");
Debug.Log ("before play2");
Play2 ();
Debug.Log ("after play2");
yield return new WaitForSeconds (gopherObjectListExplainationWaitTime);
SwitchPanels.changePanelStatic ("pObjectListTutorial:deactivate,pCameraButtonTutorial:activate");
Debug.Log ("before play3");
Play3 ();
Debug.Log ("after play3");
yield return new WaitForSeconds (gopherCameraButtonExplainationWaitTime);
SwitchPanels.changePanelStatic ("pMainTutorial:deactivate");
}
}
}
|
namespace _15.MelrahShake
{
using System;
public class Startup
{
public static void Main(string[] args)
{
var text = Console.ReadLine();
var pattern = Console.ReadLine();
while (true)
{
var firstIndex = text.IndexOf(pattern);
var secondIndex = text.LastIndexOf(pattern);
if (firstIndex == -1 || firstIndex == secondIndex)
{
break;;
}
text = text.Remove(secondIndex, pattern.Length);
text = text.Remove(firstIndex, pattern.Length);
Console.WriteLine("Shaked it.");
if (pattern.Length <= 1)
{
break;
}
pattern = pattern.Remove(pattern.Length / 2, 1);
}
Console.WriteLine("No shake." + Environment.NewLine + text);
}
}
}
|
using QuestomAssets.BeatSaber;
using QuestomAssets.Models;
using System;
using System.Collections.Generic;
using System.Text;
using QuestomAssets.AssetsChanger;
using static QuestomAssets.MusicConfigCache;
using System.Linq;
namespace QuestomAssets.AssetOps
{
public class AddNewSongToPlaylistOp : AssetOp
{
public override bool IsWriteOp => true;
public AddNewSongToPlaylistOp(BeatSaberSong song, string playlistID, bool overwriteIfExists)
{
Song = song;
PlaylistID = playlistID;
OverwriteIfExists = overwriteIfExists;
}
public string PlaylistID { get; private set; }
public BeatSaberSong Song { get; private set; }
public bool OverwriteIfExists { get; private set; }
internal override void PerformOp(OpContext context)
{
if (string.IsNullOrEmpty(Song.SongID))
throw new InvalidOperationException("SongID must be set on the song!");
if (string.IsNullOrEmpty(Song.CustomSongPath))
throw new InvalidOperationException("CustomSongPath must be set on the song!");
if (!context.Cache.PlaylistCache.ContainsKey(PlaylistID))
throw new KeyNotFoundException($"PlaylistID {PlaylistID} not found in the cache!");
bool exists = context.Cache.SongCache.ContainsKey(Song.SongID);
if (exists && !OverwriteIfExists)
throw new AddSongException( AddSongFailType.SongExists, $"SongID {Song.SongID} already exists!");
if (exists && OverwriteIfExists)
{
OpCommon.DeleteSong(context, Song.SongID);
}
if (context.Cache.SongCache.ContainsKey(Song.SongID))
throw new AddSongException(AddSongFailType.SongExists, $"SongID {Song.SongID} already exists, even though it should have been deleted to be replaced!");
BeatmapLevelDataObject level = null;
try
{
var songsAssetFile = context.Engine.GetSongsAssetsFile();
CustomLevelLoader loader = new CustomLevelLoader(songsAssetFile, context.Config);
var deser = loader.DeserializeFromJson(Song.CustomSongPath, Song.SongID);
level = loader.LoadSongToAsset(deser, Song.CustomSongPath, true);
}
catch (Exception ex)
{
throw new Exception($"Exception loading custom song folder '{Song.CustomSongPath}' for SongID {Song.SongID}", ex);
}
if (level == null)
{
throw new AddSongException(AddSongFailType.InvalidFormat, $"Song at folder '{Song.CustomSongPath}' for SongID {Song.SongID} failed to load");
}
Song.LevelData = level;
Song.LevelAuthorName = level.LevelAuthorName;
Song.SongAuthorName = level.SongAuthorName;
Song.SongName = level.SongName;
Song.SongSubName = level.SongSubName;
var playlist = context.Cache.PlaylistCache[PlaylistID];
playlist.Playlist.BeatmapLevelCollection.Object.BeatmapLevels.Add(Song.LevelData.PtrFrom(playlist.Playlist.BeatmapLevelCollection.Object));
playlist.Songs.Add(Song.SongID, new OrderedSong() { Song = Song.LevelData, Order = playlist.Songs.Count });
context.Cache.SongCache.Add(Song.SongID, new SongAndPlaylist() { Playlist = playlist.Playlist, Song = Song.LevelData });
var qfos = context.Engine.QueuedFileOperations.Where(x => x.Tag == Song.SongID && x.Type == QueuedFileOperationType.DeleteFolder || x.Type == QueuedFileOperationType.DeleteFile).ToList();
foreach (var q in qfos)
{
context.Engine.QueuedFileOperations.Remove(q);
}
}
}
}
|
namespace KRF.Core.Entities.ValueList
{
public class Country : ValueList
{
/// <summary>
/// Holds the Country ID information.
/// </summary>
public int ID { get; set; }
/// <summary>
/// Holds the Country Name information.
/// </summary>
public string Description { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyList
{
class Program
{
static void Main(string[] args)
{
var numbers = new List<int>() {1,2,3,4,5}; ///using System.Collections.Generic; lisada ülesse, kui Listi ei saa kasutada
numbers.Add(1); //lisab massiivi muutuja juurde lõppu.
numbers.AddRange(new int[3] { 6, 7,8 }); ////saab mitu muutujat massiivi lisada
foreach (int element in numbers)
{
Console.WriteLine(element);
}
int index = numbers.IndexOf(1);
Console.WriteLine($"Value of IndexOf: {index}");
int lastIndex = numbers.LastIndexOf(1);
Console.WriteLine($"Value of IndexOf: {lastIndex}");
/*numbers.RemoveAt(lastIndex);
foreach (int element in numbers)
{
Console.WriteLine(element);
}*/
int sizeOfList = numbers.Count;
Console.WriteLine($"Your list is: {sizeOfList} long");
int sumOfList = numbers.Sum();
Console.WriteLine($"Sum of list is: {sumOfList}");
for (int i=0; i< numbers.Count;i++)
{
if (numbers[i]==1)
{
numbers.Remove(numbers[i]);
}
}
numbers.Clear();
foreach (int element in numbers)
{
Console.WriteLine($"List after clear() :{element}");
}
Console.ReadLine();
///Whiliga küsida tooted, Console.Clear puhastada list, kuvada tooted kasutajale ning küsida, kas soovib veel midagi veel lisada. äkki soovib midagi eemaldada.
///lõpuks küsida kas nüüd on lõplik. Kasutada funktsioone.
}
}
}
|
using MonkeyCache.FileStore;
using Newtonsoft.Json;
using Plugin.Connectivity;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Tindero.Api
{
public abstract class BaseCachedApiService
{
public const string BaseApiUrl = "https://reqres.in/api/";
private readonly Lazy<HttpClient> _httpClientLazy;
protected HttpClient HttpClient => _httpClientLazy.Value;
public BaseCachedApiService()
{
_httpClientLazy = new Lazy<HttpClient>(() =>
new HttpClient
{
BaseAddress = new Uri(BaseApiUrl)
});
}
public async Task<T> GetAsync<T>(string url, int days = 7, bool forceRefresh = false)
{
var json = string.Empty;
if (!CrossConnectivity.Current.IsConnected)
json = Barrel.Current.Get<string>(url);
if (!forceRefresh && !Barrel.Current.IsExpired(url))
json = Barrel.Current.Get<string>(url);
try
{
if (string.IsNullOrWhiteSpace(json))
{
json = await HttpClient.GetStringAsync(url);
Barrel.Current.Add(url, json, TimeSpan.FromDays(days));
}
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
Console.WriteLine($"Unable to get information from server {ex}");
}
return default;
}
}
}
|
using System.IO.Ports;
using System.Threading;
namespace VirtualSwitch
{
public class SwitchMcu:ISwitch
{
private bool[,] _switchArrays;
private string _visaAddress;
private int _responseTime;
private SerialPort _serialPort;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="switchArrays">开关矩阵</param>
/// <param name="visaAddress">开关visa地址</param>
/// <param name="responseTime">响应时间,单位ms</param>
public SwitchMcu(bool[,] switchArrays,string visaAddress,int responseTime=500 )
{
if (responseTime == 0)
responseTime = 500;
this._switchArrays = switchArrays;
this._visaAddress = visaAddress;
this._responseTime = responseTime;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="visaAddress">开关visa地址</param>
/// <param name="responseTime">响应时间,单位ms</param>
public SwitchMcu(string visaAddress, int responseTime=500)
{
if (responseTime == 0)
responseTime = 500;
this._visaAddress = visaAddress;
this._responseTime = responseTime;
}
public SwitchMcu(SerialPort sp, int responseTime = 500)
{
if (responseTime == 0)
responseTime = 500;
this._serialPort = sp;
this._responseTime = responseTime;
}
public bool CloseAll(ref string errMsg)
{
byte[] closeAllBytes =
{
0xEE,
0x9,
0x2,
0x80,
0x8B,
0xFF,
0xFC,
0xFF,
0xFF
};
ErrMsg retErrMsg = VisaSerial.WriteData(closeAllBytes, _visaAddress);
errMsg = retErrMsg.Msg;
return retErrMsg.Result;
}
public bool Open(int switchIndex, ref string errMsg)
{
// CloseAll(ref errMsg);
byte[] writeBytes = SwitchUtil.GetMcuFormatBytes(this._switchArrays, switchIndex);
ErrMsg retErrMsg = VisaSerial.WriteData(writeBytes, _visaAddress);
errMsg = retErrMsg.Msg+retErrMsg.ErrorCode;
if (retErrMsg.Result)
{
Thread.Sleep(_responseTime);
}
return retErrMsg.Result;
}
public bool OpenS(int switchIndex, ref string errMsg)
{
// CloseAll(ref errMsg);
byte[] writeBytes = SwitchUtil.GetMcuFormatBytes(this._switchArrays, switchIndex);
SPConnect();
_serialPort.Write(writeBytes, 0, writeBytes.Length);
return true;
}
private void SPConnect()
{
if (_serialPort != null&&!_serialPort.IsOpen)
{
_serialPort.BaudRate = 115200;
_serialPort.WriteTimeout = 1000;
_serialPort.BaudRate = 115200;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.ReadBufferSize = 1024;
_serialPort.WriteBufferSize = 4096;
_serialPort.Parity = Parity.None;
_serialPort.Open();
}
}
public bool Open(byte[] switchNum, ref string errMsg)
{
byte[] writeBytes = SwitchUtil.GetMcuFormatBytes(switchNum);
ErrMsg retErrMsg = VisaSerial.WriteData(writeBytes, _visaAddress);
errMsg = retErrMsg.Msg + retErrMsg.ErrorCode;
if (retErrMsg.Result)
{
Thread.Sleep(_responseTime);
}
return retErrMsg.Result;
}
public bool OpenS(byte[] switchNum, ref string errMsg)
{
byte[] writeBytes = SwitchUtil.GetMcuFormatBytes(switchNum);
SPConnect();
_serialPort.Write(writeBytes, 0, writeBytes.Length);
return true;
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Linq;
using System.Text;
using NuGet.Frameworks;
using Xunit;
namespace NuGet.Packaging.Test
{
public class NuspecReaderTests
{
private const string DuplicateGroups = @"<?xml version=""1.0""?>
<package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
<metadata>
<id>packageA</id>
<version>1.0.1-alpha</version>
<title>Package A</title>
<authors>ownera, ownerb</authors>
<owners>ownera, ownerb</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>package A description.</description>
<language>en-US</language>
<dependencies>
<group targetFramework="".NETPortable0.0-net403+sl5+netcore45+wp8+MonoAndroid1+MonoTouch1"">
<dependency id=""Microsoft.Bcl.Async"" />
<dependency id=""Microsoft.Net.Http"" />
<dependency id=""Microsoft.Bcl.Build"" />
</group>
<group targetFramework="".NETPortable0.0-net403+sl5+netcore45+wp8"">
<dependency id=""Microsoft.Bcl.Async"" />
<dependency id=""Microsoft.Net.Http"" />
<dependency id=""Microsoft.Bcl.Build"" />
</group>
</dependencies>
</metadata>
</package>";
private const string BasicNuspec = @"<?xml version=""1.0""?>
<package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
<metadata>
<id>packageA</id>
<version>1.0.1-alpha</version>
<title>Package A</title>
<authors>ownera, ownerb</authors>
<owners>ownera, ownerb</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>package A description.</description>
<language>en-US</language>
<references>
<reference file=""a.dll"" />
</references>
<dependencies>
<group targetFramework=""net40"">
<dependency id=""jQuery"" />
<dependency id=""WebActivator"" version=""1.1.0"" />
<dependency id=""PackageC"" version=""[1.1.0, 2.0.1)"" />
</group>
<group targetFramework=""wp8"">
<dependency id=""jQuery"" />
</group>
</dependencies>
</metadata>
</package>";
private const string EmptyGroups = @"<?xml version=""1.0""?>
<package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
<metadata>
<id>packageA</id>
<version>1.0.1-alpha</version>
<title>Package A</title>
<authors>ownera, ownerb</authors>
<owners>ownera, ownerb</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>package A description.</description>
<language>en-US</language>
<references>
<group>
<reference file=""a.dll"" />
</group>
<group targetFramework=""net45"" />
</references>
<dependencies>
<group targetFramework=""net40"">
<dependency id=""jQuery"" />
<dependency id=""WebActivator"" version=""1.1.0"" />
<dependency id=""PackageC"" version=""[1.1.0, 2.0.1)"" />
</group>
<group targetFramework=""net45"" />
</dependencies>
</metadata>
</package>";
// from: https://nuget.codeplex.com/wikipage?title=.nuspec%20v1.2%20Format
private const string CommaDelimitedFrameworksNuspec = @"<?xml version=""1.0""?>
<package>
<metadata>
<id>PackageWithGacReferences</id>
<version>1.0</version>
<authors>Author here</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A package that has framework assemblyReferences depending on the target framework.</description>
<frameworkAssemblies>
<frameworkAssembly assemblyName=""System.Web"" targetFramework=""net40"" />
<frameworkAssembly assemblyName=""System.Net"" targetFramework=""net40-client, net40"" />
<frameworkAssembly assemblyName=""Microsoft.Devices.Sensors"" targetFramework=""sl4-wp"" />
<frameworkAssembly assemblyName=""System.Json"" targetFramework=""sl3"" />
<frameworkAssembly assemblyName=""System.Windows.Controls.DomainServices"" targetFramework=""sl4"" />
</frameworkAssemblies>
</metadata>
</package>";
private const string NamespaceOnMetadataNuspec = @"<?xml version=""1.0""?>
<package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<metadata xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
<id>packageB</id>
<version>1.0</version>
<authors>nuget</authors>
<owners>nuget</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>test</description>
</metadata>
</package>";
private const string UnknownDependencyGroupsNuspec = @"<?xml version=""1.0""?>
<package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
<metadata>
<id>packageA</id>
<version>1.0.1-alpha</version>
<title>Package A</title>
<authors>ownera, ownerb</authors>
<owners>ownera, ownerb</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>package A description.</description>
<language>en-US</language>
<references>
<reference file=""a.dll"" />
</references>
<dependencies>
<group targetFramework=""net45"">
<dependency id=""jQuery"" />
</group>
<group targetFramework=""future51"">
<dependency id=""jQuery"" />
</group>
<group targetFramework=""future50"">
<dependency id=""jQuery"" />
</group>
<group targetFramework=""futurevnext10.0"">
<dependency id=""jQuery"" />
</group>
<group targetFramework=""some4~new5^conventions10"">
<dependency id=""jQuery"" />
</group>
</dependencies>
</metadata>
</package>";
[Fact]
public void NuspecReaderTests_NamespaceOnMetadata()
{
NuspecReader reader = GetReader(NamespaceOnMetadataNuspec);
string id = reader.GetId();
Assert.Equal("packageB", id);
}
[Fact]
public void NuspecReaderTests_Id()
{
NuspecReader reader = GetReader(BasicNuspec);
string id = reader.GetId();
Assert.Equal("packageA", id);
}
[Fact]
public void NuspecReaderTests_EmptyGroups()
{
NuspecReader reader = GetReader(EmptyGroups);
var dependencies = reader.GetDependencyGroups().ToList();
var references = reader.GetReferenceGroups().ToList();
Assert.Equal(2, dependencies.Count);
Assert.Equal(2, references.Count);
}
[Fact]
public void NuspecReaderTests_DependencyGroups()
{
NuspecReader reader = GetReader(BasicNuspec);
var dependencies = reader.GetDependencyGroups().ToList();
Assert.Equal(2, dependencies.Count);
}
[Fact]
public void NuspecReaderTests_DuplicateDependencyGroups()
{
NuspecReader reader = GetReader(DuplicateGroups);
var dependencies = reader.GetDependencyGroups().ToList();
Assert.Equal(2, dependencies.Count);
}
[Fact]
public void NuspecReaderTests_FrameworkGroups()
{
NuspecReader reader = GetReader(CommaDelimitedFrameworksNuspec);
var dependencies = reader.GetFrameworkReferenceGroups().ToList();
Assert.Equal(5, dependencies.Count);
}
[Fact]
public void NuspecReaderTests_FrameworkSplitGroup()
{
NuspecReader reader = GetReader(CommaDelimitedFrameworksNuspec);
var groups = reader.GetFrameworkReferenceGroups();
var group = groups.Where(e => e.TargetFramework.Equals(NuGetFramework.Parse("net40"))).Single();
Assert.Equal(2, group.Items.Count());
Assert.Equal("System.Net", group.Items.ToArray()[0]);
Assert.Equal("System.Web", group.Items.ToArray()[1]);
}
[Fact]
public void NuspecReaderTests_Language()
{
NuspecReader reader = GetReader(BasicNuspec);
var language = reader.GetLanguage();
Assert.Equal("en-US", language);
}
[Fact]
public void NuspecReaderTests_UnsupportedDependencyGroups()
{
NuspecReader reader = GetReader(UnknownDependencyGroupsNuspec);
// verify we can handle multiple unsupported dependency groups gracefully
var dependencies = reader.GetDependencyGroups().ToList();
// unsupported frameworks remain ungrouped
Assert.Equal(5, dependencies.Count);
Assert.Equal(4, dependencies.Where(g => g.TargetFramework == NuGetFramework.UnsupportedFramework).Count());
}
private static NuspecReader GetReader(string nuspec)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(nuspec)))
{
return new NuspecReader(stream);
}
}
}
}
|
using ECommerce.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ECommerce.Tools
{
public class LoginService : ILoginService
{
private bool isConnected;
public bool IsConnected => isConnected;
private DataDbContext data;
private IHttpContextAccessor accessor;
public LoginService(DataDbContext _data, IHttpContextAccessor _accessor)
{
data = _data;
accessor = _accessor;
isConnected = TestConnection();
}
public bool LoginConnection(string email, string password)
{
UserModel u = data.Users.FirstOrDefault((x) => x.Email == email && x.Password == password);
if(isConnected = u != null)
{
//Acceder au cookies en utilisant un service de type IHttpContextAccessor
accessor.HttpContext.Response.Cookies.Append("userEmail", email, new CookieOptions { Expires = DateTime.Now.AddDays(1) });
accessor.HttpContext.Response.Cookies.Append("userPassword", password, new CookieOptions { Expires = DateTime.Now.AddDays(1) });
}
return isConnected;
}
public bool TestConnection()
{
string email = accessor.HttpContext.Request.Cookies["userEmail"];
string password = accessor.HttpContext.Request.Cookies["userPassword"];
UserModel u = data.Users.FirstOrDefault((x) => x.Email == email && x.Password == password);
return u != null;
}
public void LogOut()
{
accessor.HttpContext.Response.Cookies.Append("userEmail", "", new CookieOptions { Expires = DateTime.Now.AddDays(-1) });
accessor.HttpContext.Response.Cookies.Append("userPassword", "", new CookieOptions { Expires = DateTime.Now.AddDays(-1) });
isConnected = false;
}
public int GetUserProfil()
{
string email = accessor.HttpContext.Request.Cookies["userEmail"];
string password = accessor.HttpContext.Request.Cookies["userPassword"];
UserModel u = data.Users.FirstOrDefault((x) => x.Email == email && x.Password == password);
if(u != null)
{
return u.TypeProfil;
}
else
{
return 0;
}
}
}
}
|
/*
* 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
*
* What is the sum of the digits of the number 2^1000?
*/
#r "System.Numerics"
using System.Numerics;
var sum = BigInteger.Pow(new BigInteger(2), 1000).ToString().Select(x => char.GetNumericValue(x)).Sum();
Console.WriteLine(sum);
|
using LogicBuilder.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Contoso.Forms.Parameters.Common
{
public class ValidatorDescriptionParameters
{
public ValidatorDescriptionParameters()
{
}
public ValidatorDescriptionParameters
(
[Comments("Class name")]
[NameValue(AttributeNames.DEFAULTVALUE, "Validators")]
string className,
[Comments("Function")]
[NameValue(AttributeNames.DEFAULTVALUE, "required")]
string functionName,
[Comments("Where applicable, add arguments for the validator function.")]
List<ValidatorArgumentParameters> arguments = null
)
{
ClassName = className;
FunctionName = functionName;
Arguments = arguments?.ToDictionary(kvp => kvp.Name, kvp => kvp.Value);
}
public string ClassName { get; set; }
public string FunctionName { get; set; }
public Dictionary<string, object> Arguments { get; set; }
}
}
|
using System;
namespace elevators
{
public class Building
{
public string name {get; set;}
public int noOfFloors {get; set;}
public int noOfElevators {get; set;}
public Building() {
name = "Trump Tower One";
noOfFloors = 11;
noOfElevators = 2;
}
public void chooseElevator() {
Console.WriteLine("Choose your elevator: A or B");
}
public void invalidOption () {
Console.WriteLine("This elevator does not exist !!!");
Environment.Exit(0);
}
}
}
|
using FatCat.Nes.OpCodes.Branching;
using JetBrains.Annotations;
namespace FatCat.Nes.Tests.OpCodes.Branching
{
[UsedImplicitly]
public class BranchIfPositiveTests : BranchTests
{
protected override string ExpectedName => "BPL";
protected override CpuFlag Flag => CpuFlag.Negative;
protected override bool FlagState => false;
public BranchIfPositiveTests() => opCode = new BranchIfPositive(cpu, addressMode);
}
} |
namespace EfCore.Shaman
{
/// <summary>
/// Makes modification on ShamanOptions. Can be used for batch changes on ShamanOptions
/// </summary>
public interface IShamanOptionModificationService : IShamanService
{
#region Instance Methods
void ModifyShamanOptions(ShamanOptions options);
#endregion
}
} |
using System.Collections.Generic;
namespace FileSearch
{
public interface ISearchMethod : IBaseSearchMethod
{
IList<IExtendedFileInfo> LoadAndFilter(IFilterStack filterStack);
IList<IExtendedFileInfo> LoadAndFilter(IFilterStack filterStack, SearchArgs searchArgs);
}
} |
using System;
using LubyClocker.CrossCuting.Shared.Common;
using MediatR;
namespace LubyClocker.Application.BoundedContexts.Projects.Commands.Delete
{
public class DeleteProjectCommand : BasicCommand<bool>
{
}
} |
using ComputerBuilderClasses.Contracts;
namespace ComputerBuilderClasses.SystemComponents
{
public class Cpu32Bit : BaseCpu, ICentralProcessingUnit
{
private const int Bit32Size = 500;
public Cpu32Bit(byte numberOfCores)
: base(numberOfCores, Bit32Size)
{
}
}
} |
namespace Count_Occurrences_of_Larger_Numbers_in_Array
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class CountOccurrencesOfLargerNumbersInArray
{
public static void Main(string[] args)
{
//read the input, split and convert to double array;
var input = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
//var for largest number;
var largestNumber = double.Parse(Console.ReadLine());
//var for count of occurrences of larger number;
var countOfOccurrences = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] >= largestNumber)
{
countOfOccurrences++;
}
}
Console.WriteLine(countOfOccurrences);
}
}
}
|
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.Xna.Framework.Graphics;
namespace AtarashiiMono.Framework.XNA
{
public abstract class AmTilesheet
{
public readonly Texture2D texture;
protected AmTilesheet(Texture2D texture)
{
this.texture = texture;
}
public abstract AmImage2D GetImage(int index);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ServiceDesk.Api.Services.BackgroundTasks
{
public interface ILicenseCheckerService
{
public void LicenseCheck();
}
}
|
using ScribblersPad.Objects;
using ScribblersSharp;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnitySaveGame;
/// <summary>
/// Scribble.rs Pad data namespace
/// </summary>
namespace ScribblersPad.Data
{
/// <summary>
/// A class that describes save game data
/// </summary>
[Serializable]
public class SaveGameData : ASaveGameData, ISaveGameData
{
/// <summary>
/// Scribble.rs host
/// </summary>
[SerializeField]
private string scribblersHost;
/// <summary>
/// User session IDs
/// </summary>
[SerializeField]
private string[] userSessionIDs;
/// <summary>
/// Is using secure protocols
/// </summary>
[SerializeField]
private bool isUsingSecureProtocols = true;
/// <summary>
/// Is allowed to use insecure protocols
/// </summary>
[SerializeField]
private bool isAllowedToUseInsecureProtocols = false;
/// <summary>
/// Lobby ID
/// </summary>
[SerializeField]
private string lobbyID;
/// <summary>
/// Username
/// </summary>
[SerializeField]
private string username;
/// <summary>
/// Lobby language
/// </summary>
[SerializeField]
private ELanguage lobbyLanguage;
/// <summary>
/// Drawing time in seconds
/// </summary>
[SerializeField]
private uint drawingTime = 120U;
/// <summary>
/// Round count
/// </summary>
[SerializeField]
private uint roundCount = 4U;
/// <summary>
/// Maximal player count
/// </summary>
[SerializeField]
private uint maximalPlayerCount = 12U;
/// <summary>
/// Is lobby public
/// </summary>
[SerializeField]
private bool isLobbyPublic = true;
/// <summary>
/// Custom words
/// </summary>
[SerializeField]
private string customWords = string.Empty;
/// <summary>
/// Custom words chance
/// </summary>
[SerializeField]
private uint customWordsChance = 50U;
/// <summary>
/// Players per IP limit
/// </summary>
[SerializeField]
private uint playersPerIPLimit = 8U;
/// <summary>
/// Is votekicking enabled
/// </summary>
[SerializeField]
private bool isVotekickingEnabled = true;
private Dictionary<string, string> userSessionIDLookup;
/// <summary>
/// Save game defaults
/// </summary>
private ScribblersDefaultsObjectScript defaults;
/// <summary>
/// Save game defaults
/// </summary>
private ScribblersDefaultsObjectScript Defaults => defaults ??= Resources.Load<ScribblersDefaultsObjectScript>("Defaults/ScribblersDefaults");
/// <summary>
/// Scribble.rs host
/// </summary>
public string ScribblersHost
{
get
{
if (string.IsNullOrWhiteSpace(scribblersHost))
{
scribblersHost = Defaults ? Defaults.Host : ScribblersDefaultsObjectScript.defaultHost;
}
return scribblersHost;
}
set => scribblersHost = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Is using secure protocols
/// </summary>
public bool IsUsingSecureProtocols
{
get => isUsingSecureProtocols;
set => isUsingSecureProtocols = value;
}
/// <summary>
/// Is allowed to use insecure protocols
/// </summary>
public bool IsAllowedToUseInsecureProtocols
{
get => isAllowedToUseInsecureProtocols;
set => isAllowedToUseInsecureProtocols = value;
}
/// <summary>
/// Lobby ID
/// </summary>
public string LobbyID
{
get => lobbyID ?? string.Empty;
set => lobbyID = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Username
/// </summary>
public string Username
{
get => username ?? string.Empty;
set => username = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Lobby language
/// </summary>
public ELanguage LobbyLanguage
{
get => (lobbyLanguage == ELanguage.Invalid) ? Defaults.LobbyLanguage : lobbyLanguage;
set
{
if (value == ELanguage.Invalid)
{
throw new ArgumentException("Lobby language can't be invalid.", nameof(value));
}
lobbyLanguage = value;
}
}
/// <summary>
/// Drawing time in seconds
/// </summary>
public uint DrawingTime
{
get => drawingTime;
set => drawingTime = value;
}
/// <summary>
/// Round count
/// </summary>
public uint RoundCount
{
get => roundCount;
set => roundCount = value;
}
/// <summary>
/// Maximal player count
/// </summary>
public uint MaximalPlayerCount
{
get => maximalPlayerCount;
set => maximalPlayerCount = value;
}
/// <summary>
/// Is lobby public
/// </summary>
public bool IsLobbyPublic
{
get => isLobbyPublic;
set => isLobbyPublic = value;
}
/// <summary>
/// Custom words
/// </summary>
public string CustomWords
{
get => customWords ?? string.Empty;
set => customWords = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Custom words chance
/// </summary>
public uint CustomWordsChance
{
get => customWordsChance;
set => customWordsChance = value;
}
/// <summary>
/// Players per IP limit
/// </summary>
public uint PlayersPerIPLimit
{
get => playersPerIPLimit;
set => playersPerIPLimit = value;
}
/// <summary>
/// Is votekicking enabled
/// </summary>
public bool IsVotekickingEnabled
{
get => isVotekickingEnabled;
set => isVotekickingEnabled = value;
}
/// <summary>
/// Constructs save game data
/// </summary>
public SaveGameData() : base(null)
{
// ...
}
/// <summary>
/// Constructs save game data
/// </summary>
/// <param name="saveGameData">Save game data</param>
public SaveGameData(ASaveGameData saveGameData) : base(saveGameData)
{
if (saveGameData is SaveGameData save_game_data)
{
scribblersHost = save_game_data.scribblersHost;
userSessionIDs = (save_game_data.userSessionIDs == null) ? null : save_game_data.userSessionIDs.Clone() as string[];
isUsingSecureProtocols = save_game_data.isUsingSecureProtocols;
isAllowedToUseInsecureProtocols = save_game_data.isAllowedToUseInsecureProtocols;
lobbyID = save_game_data.lobbyID;
username = save_game_data.username;
lobbyLanguage = save_game_data.lobbyLanguage;
drawingTime = save_game_data.drawingTime;
roundCount = save_game_data.roundCount;
maximalPlayerCount = save_game_data.maximalPlayerCount;
isLobbyPublic = save_game_data.isLobbyPublic;
customWords = save_game_data.customWords;
customWordsChance = save_game_data.customWordsChance;
playersPerIPLimit = save_game_data.playersPerIPLimit;
isVotekickingEnabled = save_game_data.isVotekickingEnabled;
}
}
private void InitializeUserSessionIDLookup()
{
if (userSessionIDLookup == null)
{
userSessionIDLookup = new Dictionary<string, string>();
if (userSessionIDs != null)
{
foreach (string user_session_id in userSessionIDs)
{
if (string.IsNullOrWhiteSpace(user_session_id))
{
Debug.LogError($"Session ID entry is null.");
}
else
{
string[] user_session_id_strings = user_session_id.Split('=');
if (user_session_id_strings.Length > 1)
{
string host = user_session_id_strings[0];
if (userSessionIDLookup.ContainsKey(host))
{
Debug.LogError($"Found duplicate user session ID for \"{ host }\" in save game.");
}
else
{
userSessionIDLookup.Add(host, string.Join("=", user_session_id_strings, 1, user_session_id_strings.Length - 1));
}
}
else
{
Debug.LogError($"\"{ user_session_id }\" is not a valid session ID entry.");
}
}
}
}
}
}
/// <summary>
/// Updates user session IDs
/// </summary>
private void UpdateUserSessionIDs()
{
if (userSessionIDs.Length != userSessionIDLookup.Count)
{
userSessionIDs = new string[userSessionIDLookup.Count];
}
int index = 0;
foreach (KeyValuePair<string, string> user_session_id_lookup_pair in userSessionIDLookup)
{
userSessionIDs[index] = $"{ user_session_id_lookup_pair.Key }={ user_session_id_lookup_pair.Value }";
++index;
}
}
/// <summary>
/// Gets user session ID
/// </summary>
/// <param name="host">Host</param>
/// <returns>User session ID</returns>
public string GetUserSessionID(string host) => TryGetUserSessionID(host, out string ret) ? ret : string.Empty;
/// <summary>
/// TRies to get user session ID
/// </summary>
/// <param name="host">Host</param>
/// <param name="userSessionID">User session ID</param>
/// <returns>"true" if user session ID is available, otherwise "false"</returns>
public bool TryGetUserSessionID(string host, out string userSessionID)
{
if (string.IsNullOrWhiteSpace(host))
{
throw new ArgumentNullException(nameof(host));
}
InitializeUserSessionIDLookup();
bool ret = userSessionIDLookup.TryGetValue(host, out string result);
userSessionID = ret ? result : string.Empty;
return ret;
}
/// <summary>
/// Sets an user session ID
/// </summary>
/// <param name="host">Host</param>
/// <param name="userSessionID">User session ID</param>
public void SetUserSessionID(string host, string userSessionID)
{
if (string.IsNullOrWhiteSpace(host))
{
throw new ArgumentNullException(nameof(host));
}
if (userSessionID == null)
{
throw new ArgumentNullException(nameof(userSessionID));
}
InitializeUserSessionIDLookup();
if (userSessionIDLookup.ContainsKey(host))
{
userSessionIDLookup[host] = userSessionID;
}
else
{
userSessionIDLookup.Add(host, userSessionID);
}
UpdateUserSessionIDs();
}
/// <summary>
/// Removes an user session ID
/// </summary>
/// <param name="host">Host</param>
/// <returns>"true" if successful, otherwise "false"</returns>
public bool RemoveUserSessionID(string host)
{
if (string.IsNullOrWhiteSpace(host))
{
throw new ArgumentNullException(nameof(host));
}
InitializeUserSessionIDLookup();
bool ret = userSessionIDLookup.Remove(host);
if (ret)
{
UpdateUserSessionIDs();
}
return ret;
}
/// <summary>
/// Clears user session IDs
/// </summary>
public void ClearUserSessionIDs()
{
InitializeUserSessionIDLookup();
userSessionIDLookup?.Clear();
userSessionIDs = Array.Empty<string>();
}
}
}
|
using System;
using Estaticos.Classes;
namespace Estaticos
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Conversão");
Console.WriteLine("Você quer converter de real para dolar ou de dolar para real? DIgite 1 para a primeira e 2 para a segunda opção");
int opcao = int.Parse(Console.ReadLine());
switch (opcao)
{
case 1:
Console.WriteLine("Quantos reais vc tem?");
float valorRS = float.Parse(Console.ReadLine());
Console.WriteLine(Conversor.RealparaDolar(valorRS));
break;
case 2:
Console.WriteLine("Quantos Dolares vc tem?");
float valorUS = float.Parse(Console.ReadLine());
Console.WriteLine(Conversor.DolarparaReal(valorUS));
break;
default:
Console.WriteLine("Essa opção não é válida");
break;
}
}
}
}
|
namespace GeometricCalculators
{
public abstract class ShapeCalculator
{
public abstract string Name { get; }
public abstract double Area();
}
}
|
using System.Collections.Generic;
using System.Linq;
using ApiPomar.Models;
namespace ApiPomar.Repositorio
{
public class ArvoreRepository : IArvoreRepository
{
private readonly ArvoresDbContext _contexto;
public ArvoreRepository(ArvoresDbContext ctx)
{
_contexto = ctx;
}
public void add(Arvores Arvore)
{
_contexto.Arvores.Add(Arvore);
_contexto.SaveChanges();
}
public Arvores Find(long id)
{
return _contexto.Arvores.FirstOrDefault(u => u.ArvoreId == id);
}
public IEnumerable<Arvores> GetAll()
{
return _contexto.Arvores.ToList();
}
public IEnumerable<Arvores> GettAll()
{
return _contexto.Arvores.ToList();
}
public void Remove(long id)
{
var entity = _contexto.Arvores.First(u=> u.ArvoreId == id);
_contexto.Arvores.Remove(entity);
_contexto.SaveChanges();
}
public void Update(Arvores Arvore)
{
_contexto.Arvores.Update(Arvore);
_contexto.SaveChanges();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace oopsconcepts
{
// Attribute
//Attributes allow you to add declareative information to your program.
//this information can be queried at runtime using reflection.
//there are several Pre-Defined attributes provided by .NET.It is also Possible to create, your own Custom attributes.
//A few pre-defined attributes with in the .NET framework:
//Obsolute -Marks types and type members outdated
//WebMethod -To expose a method as an XML web service method
//Serializable- Indiccates that a class can be serialized.
//It is possible to customize the attribute using parameters.An attribute is a class that inherits from System.Attribute base class.
class Attribute
{
public static void Main()
{
//you can not be used this method
Calculater.add(10, 20);
int i = Calculater.add(new List<int>() { 10, 20, 30, 40, 50 });
Console.WriteLine("adding tion of two numbers are: " + i);
}
}
public class Calculater
{
[Obsolete("Use Add(List<int> li) Method")]
public static int add(int i, int j)
{
return i + j;
}
public static int add(List<int> li)
{
int sum = 0;
foreach (int value in li)
{
sum = sum + value;
}
return sum;
}
}
}
|
namespace E04_BinarySearch
{
using System;
public class BinarySearch
{
public static void Main(string[] args)
{
// Write a program, that reads from the console an
// array of N integers and an integer K, sorts the
// array and using the method Array.BinSearch()
// finds the largest number in the array which is ≤ K.
Random randomGenerator = new Random();
int n = 0;
do
{
n = GetNumber("size of array, N");
}
while (n < 3);
int k = GetNumber("an integer K");
int[] array = new int[n];
for (int index = 0; index < n; index++)
{
// array[index] = GetNumber("array[" + index + "]");
array[index] = randomGenerator.Next(1, 21);
}
Console.WriteLine();
PrintArray(array);
Console.WriteLine();
Array.Sort(array);
int result = Array.BinarySearch(array, k);
if (result < 0)
{
result = (result * (-1)) + (-2);
}
Console.Write("The largest number in the array which is <= {0} is: ", k);
if (result == -1)
{
Console.WriteLine("There is no such element.");
}
else
{
Console.WriteLine(array[result]);
}
Console.WriteLine();
}
private static void PrintArray(int[] array)
{
Console.Write("|");
for (int index = 0; index < array.Length; index++)
{
Console.Write(" {0} |", (array[index]));
}
Console.WriteLine();
}
private static int GetNumber(string name)
{
int number;
bool isNumber = false;
do
{
Console.Write("Please, enter {0}: ", name);
isNumber = int.TryParse(Console.ReadLine(), out number);
}
while (isNumber == false);
return number;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Project_CelineGardier_2NMCT2.model
{
class Band
{
public Band() { }
public Band(Band b)
{
bandID = b.bandID;
Name = b.Name;
Description = b.Description;
Picture = b.Picture;
Twitter = b.Twitter;
Facebook = b.Facebook;
}
public Band(int id, string name, string description, string twitter, string facebook, string picture)
{
bandID = id;
Name = name;
Description = description;
Picture = picture;
Twitter = twitter;
Facebook = facebook;
}
private int _bandID;
public int bandID {
get { return _bandID; }
set { _bandID = value; }
}
private string _Name;
public string Name {
get { return _Name; }
set { _Name = value; }
}
private string _Picture;
public string Picture
{
get { return _Picture; }
set { _Picture = value; }
}
private string _Description;
public string Description
{
get { return _Description; }
set { _Description = value; }
}
private string _Twitter;
public string Twitter
{
get { return _Twitter; }
set { _Twitter = value; }
}
private string _Facebook;
public string Facebook
{
get { return _Facebook; }
set { _Facebook = value; }
}/*
private ObservableCollection<Genre> _Genres;
public ObservableCollection<Genre> Genres
{
get { return _Genres; }
set { _Genres = value; }
}*/
private ObservableCollection<Genre> _Genres;
public ObservableCollection<Genre> Genres
{
get { return _Genres; }
set { _Genres = value; }
}
private static ObservableCollection<Band> _Bands = null;
public static ObservableCollection<Band> Bands
{
get { return _Bands; }
set { _Bands = value; }
}
public static ObservableCollection<Band> GetBands()
{
Bands = new ObservableCollection<Band>();
try
{
// Get data
DbDataReader reader = Database.GetData("Select B.bandID, B.name, B.picture, B.description, B.twitter, B.facebook, Substring((Select '|'+STR(G.genreID) From BandGenres BG, Genre G Where BG.bggenreID = G.genreID AND B.bandID = BG.bgbandID For XML Path('')),2,8000) As genres From Band B ");
foreach (DbDataRecord record in reader)
{
// Create new ContactTypes
Band type = new Band();
// Get ID
if (DBNull.Value.Equals(record["bandID"])) type.bandID = -1;
else type.bandID = Convert.ToInt32(record["bandID"]);
// Get Name
if (DBNull.Value.Equals(record["name"])) type.Name = "";
else type.Name = record["name"].ToString().Trim();
// Get Company
if (DBNull.Value.Equals(record["picture"])) type.Picture = "";
else type.Picture = record["picture"].ToString();
// Get JobRole
if (DBNull.Value.Equals(record["description"])) type.Description = "";
else type.Description = record["description"].ToString().Trim();
// Get City
if (DBNull.Value.Equals(record["twitter"])) type.Twitter = "";
else type.Twitter = record["twitter"].ToString().Trim();
// Get Email
if (DBNull.Value.Equals(record["facebook"])) type.Facebook = "";
else type.Facebook = record["facebook"].ToString().Trim();
//type.Genres = Genre.GetBandGenre(type.ID);
// Get genres
string genres;
if (DBNull.Value.Equals(record["genres"])) genres = "";
else genres = record["genres"].ToString();
string[] genreIDs = genres.Split('|');
ObservableCollection<Genre> genresList = Genre.GetGenres();
foreach (string id in genreIDs)
{
try
{
foreach (Genre g in genresList)
{
if (g.genreID == Convert.ToInt32(id))
{
g.isChecked = true;
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Getting bandgenres error:\n" + ex.Message);
}
}
type.Genres = genresList;
Bands.Add(type);
}
}
// Fail
catch (Exception ex)
{
Console.WriteLine("Getting bands error:\n" + ex.Message);
}
return Bands;
}
public static Band GetBand(int id)
{
foreach (Band s in GetBands())
{
if (s.bandID == id) return s;
}
return new Band();
}
public static bool Add(Band b)
{
return Add(b.Name, b.Description, b.Twitter, b.Facebook, b.Picture);
}
public static bool Add(string name, string description, string twitter, string facebook, string picture)
{
if (name == "") return false;
try
{
// Add to db
DbParameter param1 = Database.AddParameter("@name", name);
DbParameter param2 = Database.AddParameter("@description", description);
DbParameter param3 = Database.AddParameter("@twitter", twitter);
DbParameter param4 = Database.AddParameter("@facebook", facebook);
DbParameter param5 = Database.AddParameter("@picture", picture);
int id = Database.ModifyData(true, "INSERT INTO Band(name, description, twitter, facebook, picture) OUTPUT INSERTED.contactID VALUES(@name,@description,@twitter,@facebook,@picture)", param1, param2, param3, param4, param5);
GetBands().Add(new Band(id, name, description, twitter, facebook, picture));
return true;
}
// Fail
catch (Exception ex)
{
Console.WriteLine("Add band db error: " + ex.Message);
return false;
}
}
public static bool Edit(Band b)
{
return Edit(b.bandID, b.Name, b.Description, b.Twitter, b.Facebook, b.Picture);
}
public static bool Edit(int index, string name, string description, string twitter, string facebook, string picture)
{
try
{
// Update db
DbParameter param0 = Database.AddParameter("@id", index);
DbParameter param1 = Database.AddParameter("@name", name);
DbParameter param2 = Database.AddParameter("@description", description);
DbParameter param3 = Database.AddParameter("@twitter", twitter);
DbParameter param4 = Database.AddParameter("@facebook", facebook);
DbParameter param5 = Database.AddParameter("@picture", picture);
/*int affectedRows = Database.ModifyData(false, "UPDATE band SET name = @name, description = @description, twitter = @twitter, facebook = @facebook, picture = @picture WHERE bandID = @id", param0, param1, param2, param3, param4, param5);*/
int affectedRows = Database.ModifyData(false, "UPDATE band SET name = @name WHERE bandID = @id", param0, param1);
if (affectedRows == 0) return false;
return true;
}
// Fail
catch (Exception ex)
{
Console.WriteLine("Update band db error: " + ex.Message);
return false;
}
}
public static bool Delete(int index)
{
try
{
// delete from db
DbParameter param = Database.AddParameter("@id", index);
int affectedRows = Database.ModifyData(false, "DELETE FROM Band WHERE bandID = @id", param);
if (affectedRows == 0) return false;
return true;
// Update _ContactTypes
//GetContactTypes().RemoveAt(index);
}
// Fail
catch (Exception ex)
{
Console.WriteLine("Delete band db error: " + ex.Message);
return false;
}
}
public static bool DeleteGenres(int bandID)
{
try
{
// delete from db
DbParameter param = Database.AddParameter("@id", bandID);
int affectedRows = Database.ModifyData(false, "DELETE FROM BandGenres WHERE bgbandID = @id", param);
if (affectedRows == 0) return false;
return true;
}
// Fail
catch (Exception ex)
{
Console.WriteLine("Delete band genre db error: " + ex.Message);
return false;
}
}
public static bool AddGenre(int bandID, int genreID)
{
try
{
// Add to db
DbParameter param1 = Database.AddParameter("@bandID", bandID);
DbParameter param2 = Database.AddParameter("@genreID", genreID);
int id = Database.ModifyData(false, "INSERT INTO BandGenres(bgbandID, bggenreID) VALUES(@bandID,@genreID)", param1, param2);
GetBand(bandID).Genres.Add(Genre.GetGenre(genreID));
return true;
}
// Fail
catch (Exception ex)
{
Console.WriteLine("Add band genre db error: " + ex.Message);
return false;
}
}
}
} |
using LuaInterface;
using SLua;
using System;
using UnityEngine;
using UnityEngine.Rendering;
public class Lua_UnityEngine_Rendering_CommandBuffer : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
CommandBuffer o = new CommandBuffer();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Dispose(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
commandBuffer.Dispose();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Release(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
commandBuffer.Release();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Clear(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
commandBuffer.Clear();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DrawMesh(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 4)
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
Mesh mesh;
LuaObject.checkType<Mesh>(l, 2, out mesh);
Matrix4x4 matrix4x;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x);
Material material;
LuaObject.checkType<Material>(l, 4, out material);
commandBuffer.DrawMesh(mesh, matrix4x, material);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 5)
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
Mesh mesh2;
LuaObject.checkType<Mesh>(l, 2, out mesh2);
Matrix4x4 matrix4x2;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x2);
Material material2;
LuaObject.checkType<Material>(l, 4, out material2);
int num2;
LuaObject.checkType(l, 5, out num2);
commandBuffer2.DrawMesh(mesh2, matrix4x2, material2, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 6)
{
CommandBuffer commandBuffer3 = (CommandBuffer)LuaObject.checkSelf(l);
Mesh mesh3;
LuaObject.checkType<Mesh>(l, 2, out mesh3);
Matrix4x4 matrix4x3;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x3);
Material material3;
LuaObject.checkType<Material>(l, 4, out material3);
int num3;
LuaObject.checkType(l, 5, out num3);
int num4;
LuaObject.checkType(l, 6, out num4);
commandBuffer3.DrawMesh(mesh3, matrix4x3, material3, num3, num4);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 7)
{
CommandBuffer commandBuffer4 = (CommandBuffer)LuaObject.checkSelf(l);
Mesh mesh4;
LuaObject.checkType<Mesh>(l, 2, out mesh4);
Matrix4x4 matrix4x4;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x4);
Material material4;
LuaObject.checkType<Material>(l, 4, out material4);
int num5;
LuaObject.checkType(l, 5, out num5);
int num6;
LuaObject.checkType(l, 6, out num6);
MaterialPropertyBlock materialPropertyBlock;
LuaObject.checkType<MaterialPropertyBlock>(l, 7, out materialPropertyBlock);
commandBuffer4.DrawMesh(mesh4, matrix4x4, material4, num5, num6, materialPropertyBlock);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DrawRenderer(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 3)
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
Renderer renderer;
LuaObject.checkType<Renderer>(l, 2, out renderer);
Material material;
LuaObject.checkType<Material>(l, 3, out material);
commandBuffer.DrawRenderer(renderer, material);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 4)
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
Renderer renderer2;
LuaObject.checkType<Renderer>(l, 2, out renderer2);
Material material2;
LuaObject.checkType<Material>(l, 3, out material2);
int num2;
LuaObject.checkType(l, 4, out num2);
commandBuffer2.DrawRenderer(renderer2, material2, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 5)
{
CommandBuffer commandBuffer3 = (CommandBuffer)LuaObject.checkSelf(l);
Renderer renderer3;
LuaObject.checkType<Renderer>(l, 2, out renderer3);
Material material3;
LuaObject.checkType<Material>(l, 3, out material3);
int num3;
LuaObject.checkType(l, 4, out num3);
int num4;
LuaObject.checkType(l, 5, out num4);
commandBuffer3.DrawRenderer(renderer3, material3, num3, num4);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DrawProcedural(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 6)
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
Matrix4x4 matrix4x;
LuaObject.checkValueType<Matrix4x4>(l, 2, out matrix4x);
Material material;
LuaObject.checkType<Material>(l, 3, out material);
int num2;
LuaObject.checkType(l, 4, out num2);
MeshTopology meshTopology;
LuaObject.checkEnum<MeshTopology>(l, 5, out meshTopology);
int num3;
LuaObject.checkType(l, 6, out num3);
commandBuffer.DrawProcedural(matrix4x, material, num2, meshTopology, num3);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 7)
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
Matrix4x4 matrix4x2;
LuaObject.checkValueType<Matrix4x4>(l, 2, out matrix4x2);
Material material2;
LuaObject.checkType<Material>(l, 3, out material2);
int num4;
LuaObject.checkType(l, 4, out num4);
MeshTopology meshTopology2;
LuaObject.checkEnum<MeshTopology>(l, 5, out meshTopology2);
int num5;
LuaObject.checkType(l, 6, out num5);
int num6;
LuaObject.checkType(l, 7, out num6);
commandBuffer2.DrawProcedural(matrix4x2, material2, num4, meshTopology2, num5, num6);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 8)
{
CommandBuffer commandBuffer3 = (CommandBuffer)LuaObject.checkSelf(l);
Matrix4x4 matrix4x3;
LuaObject.checkValueType<Matrix4x4>(l, 2, out matrix4x3);
Material material3;
LuaObject.checkType<Material>(l, 3, out material3);
int num7;
LuaObject.checkType(l, 4, out num7);
MeshTopology meshTopology3;
LuaObject.checkEnum<MeshTopology>(l, 5, out meshTopology3);
int num8;
LuaObject.checkType(l, 6, out num8);
int num9;
LuaObject.checkType(l, 7, out num9);
MaterialPropertyBlock materialPropertyBlock;
LuaObject.checkType<MaterialPropertyBlock>(l, 8, out materialPropertyBlock);
commandBuffer3.DrawProcedural(matrix4x3, material3, num7, meshTopology3, num8, num9, materialPropertyBlock);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DrawProceduralIndirect(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 6)
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
Matrix4x4 matrix4x;
LuaObject.checkValueType<Matrix4x4>(l, 2, out matrix4x);
Material material;
LuaObject.checkType<Material>(l, 3, out material);
int num2;
LuaObject.checkType(l, 4, out num2);
MeshTopology meshTopology;
LuaObject.checkEnum<MeshTopology>(l, 5, out meshTopology);
ComputeBuffer computeBuffer;
LuaObject.checkType<ComputeBuffer>(l, 6, out computeBuffer);
commandBuffer.DrawProceduralIndirect(matrix4x, material, num2, meshTopology, computeBuffer);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 7)
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
Matrix4x4 matrix4x2;
LuaObject.checkValueType<Matrix4x4>(l, 2, out matrix4x2);
Material material2;
LuaObject.checkType<Material>(l, 3, out material2);
int num3;
LuaObject.checkType(l, 4, out num3);
MeshTopology meshTopology2;
LuaObject.checkEnum<MeshTopology>(l, 5, out meshTopology2);
ComputeBuffer computeBuffer2;
LuaObject.checkType<ComputeBuffer>(l, 6, out computeBuffer2);
int num4;
LuaObject.checkType(l, 7, out num4);
commandBuffer2.DrawProceduralIndirect(matrix4x2, material2, num3, meshTopology2, computeBuffer2, num4);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 8)
{
CommandBuffer commandBuffer3 = (CommandBuffer)LuaObject.checkSelf(l);
Matrix4x4 matrix4x3;
LuaObject.checkValueType<Matrix4x4>(l, 2, out matrix4x3);
Material material3;
LuaObject.checkType<Material>(l, 3, out material3);
int num5;
LuaObject.checkType(l, 4, out num5);
MeshTopology meshTopology3;
LuaObject.checkEnum<MeshTopology>(l, 5, out meshTopology3);
ComputeBuffer computeBuffer3;
LuaObject.checkType<ComputeBuffer>(l, 6, out computeBuffer3);
int num6;
LuaObject.checkType(l, 7, out num6);
MaterialPropertyBlock materialPropertyBlock;
LuaObject.checkType<MaterialPropertyBlock>(l, 8, out materialPropertyBlock);
commandBuffer3.DrawProceduralIndirect(matrix4x3, material3, num5, meshTopology3, computeBuffer3, num6, materialPropertyBlock);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetRenderTarget(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 2)
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTarget;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTarget);
commandBuffer.SetRenderTarget(renderTarget);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, num, 2, typeof(RenderTargetIdentifier), typeof(RenderTargetIdentifier)))
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier);
RenderTargetIdentifier renderTargetIdentifier2;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier2);
commandBuffer2.SetRenderTarget(renderTargetIdentifier, renderTargetIdentifier2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, num, 2, typeof(RenderTargetIdentifier[]), typeof(RenderTargetIdentifier)))
{
CommandBuffer commandBuffer3 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier[] array;
LuaObject.checkArray<RenderTargetIdentifier>(l, 2, out array);
RenderTargetIdentifier renderTargetIdentifier3;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier3);
commandBuffer3.SetRenderTarget(array, renderTargetIdentifier3);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, num, 2, typeof(RenderTargetIdentifier), typeof(int)))
{
CommandBuffer commandBuffer4 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier4;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier4);
int num2;
LuaObject.checkType(l, 3, out num2);
commandBuffer4.SetRenderTarget(renderTargetIdentifier4, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, num, 2, typeof(RenderTargetIdentifier), typeof(RenderTargetIdentifier), typeof(int)))
{
CommandBuffer commandBuffer5 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier5;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier5);
RenderTargetIdentifier renderTargetIdentifier6;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier6);
int num3;
LuaObject.checkType(l, 4, out num3);
commandBuffer5.SetRenderTarget(renderTargetIdentifier5, renderTargetIdentifier6, num3);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, num, 2, typeof(RenderTargetIdentifier), typeof(int), typeof(CubemapFace)))
{
CommandBuffer commandBuffer6 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier7;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier7);
int num4;
LuaObject.checkType(l, 3, out num4);
CubemapFace cubemapFace;
LuaObject.checkEnum<CubemapFace>(l, 4, out cubemapFace);
commandBuffer6.SetRenderTarget(renderTargetIdentifier7, num4, cubemapFace);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 5)
{
CommandBuffer commandBuffer7 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier8;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier8);
RenderTargetIdentifier renderTargetIdentifier9;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier9);
int num5;
LuaObject.checkType(l, 4, out num5);
CubemapFace cubemapFace2;
LuaObject.checkEnum<CubemapFace>(l, 5, out cubemapFace2);
commandBuffer7.SetRenderTarget(renderTargetIdentifier8, renderTargetIdentifier9, num5, cubemapFace2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Blit(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(RenderTargetIdentifier), typeof(RenderTargetIdentifier)))
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier);
RenderTargetIdentifier renderTargetIdentifier2;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier2);
commandBuffer.Blit(renderTargetIdentifier, renderTargetIdentifier2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(Texture), typeof(RenderTargetIdentifier)))
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
Texture texture;
LuaObject.checkType<Texture>(l, 2, out texture);
RenderTargetIdentifier renderTargetIdentifier3;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier3);
commandBuffer2.Blit(texture, renderTargetIdentifier3);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(RenderTargetIdentifier), typeof(RenderTargetIdentifier), typeof(Material)))
{
CommandBuffer commandBuffer3 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier4;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier4);
RenderTargetIdentifier renderTargetIdentifier5;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier5);
Material material;
LuaObject.checkType<Material>(l, 4, out material);
commandBuffer3.Blit(renderTargetIdentifier4, renderTargetIdentifier5, material);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(Texture), typeof(RenderTargetIdentifier), typeof(Material)))
{
CommandBuffer commandBuffer4 = (CommandBuffer)LuaObject.checkSelf(l);
Texture texture2;
LuaObject.checkType<Texture>(l, 2, out texture2);
RenderTargetIdentifier renderTargetIdentifier6;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier6);
Material material2;
LuaObject.checkType<Material>(l, 4, out material2);
commandBuffer4.Blit(texture2, renderTargetIdentifier6, material2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(RenderTargetIdentifier), typeof(RenderTargetIdentifier), typeof(Material), typeof(int)))
{
CommandBuffer commandBuffer5 = (CommandBuffer)LuaObject.checkSelf(l);
RenderTargetIdentifier renderTargetIdentifier7;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 2, out renderTargetIdentifier7);
RenderTargetIdentifier renderTargetIdentifier8;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier8);
Material material3;
LuaObject.checkType<Material>(l, 4, out material3);
int num;
LuaObject.checkType(l, 5, out num);
commandBuffer5.Blit(renderTargetIdentifier7, renderTargetIdentifier8, material3, num);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(Texture), typeof(RenderTargetIdentifier), typeof(Material), typeof(int)))
{
CommandBuffer commandBuffer6 = (CommandBuffer)LuaObject.checkSelf(l);
Texture texture3;
LuaObject.checkType<Texture>(l, 2, out texture3);
RenderTargetIdentifier renderTargetIdentifier9;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier9);
Material material4;
LuaObject.checkType<Material>(l, 4, out material4);
int num2;
LuaObject.checkType(l, 5, out num2);
commandBuffer6.Blit(texture3, renderTargetIdentifier9, material4, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetTemporaryRT(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 4)
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
int num2;
LuaObject.checkType(l, 2, out num2);
int num3;
LuaObject.checkType(l, 3, out num3);
int num4;
LuaObject.checkType(l, 4, out num4);
commandBuffer.GetTemporaryRT(num2, num3, num4);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 5)
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
int num5;
LuaObject.checkType(l, 2, out num5);
int num6;
LuaObject.checkType(l, 3, out num6);
int num7;
LuaObject.checkType(l, 4, out num7);
int num8;
LuaObject.checkType(l, 5, out num8);
commandBuffer2.GetTemporaryRT(num5, num6, num7, num8);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 6)
{
CommandBuffer commandBuffer3 = (CommandBuffer)LuaObject.checkSelf(l);
int num9;
LuaObject.checkType(l, 2, out num9);
int num10;
LuaObject.checkType(l, 3, out num10);
int num11;
LuaObject.checkType(l, 4, out num11);
int num12;
LuaObject.checkType(l, 5, out num12);
FilterMode filterMode;
LuaObject.checkEnum<FilterMode>(l, 6, out filterMode);
commandBuffer3.GetTemporaryRT(num9, num10, num11, num12, filterMode);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 7)
{
CommandBuffer commandBuffer4 = (CommandBuffer)LuaObject.checkSelf(l);
int num13;
LuaObject.checkType(l, 2, out num13);
int num14;
LuaObject.checkType(l, 3, out num14);
int num15;
LuaObject.checkType(l, 4, out num15);
int num16;
LuaObject.checkType(l, 5, out num16);
FilterMode filterMode2;
LuaObject.checkEnum<FilterMode>(l, 6, out filterMode2);
RenderTextureFormat renderTextureFormat;
LuaObject.checkEnum<RenderTextureFormat>(l, 7, out renderTextureFormat);
commandBuffer4.GetTemporaryRT(num13, num14, num15, num16, filterMode2, renderTextureFormat);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 8)
{
CommandBuffer commandBuffer5 = (CommandBuffer)LuaObject.checkSelf(l);
int num17;
LuaObject.checkType(l, 2, out num17);
int num18;
LuaObject.checkType(l, 3, out num18);
int num19;
LuaObject.checkType(l, 4, out num19);
int num20;
LuaObject.checkType(l, 5, out num20);
FilterMode filterMode3;
LuaObject.checkEnum<FilterMode>(l, 6, out filterMode3);
RenderTextureFormat renderTextureFormat2;
LuaObject.checkEnum<RenderTextureFormat>(l, 7, out renderTextureFormat2);
RenderTextureReadWrite renderTextureReadWrite;
LuaObject.checkEnum<RenderTextureReadWrite>(l, 8, out renderTextureReadWrite);
commandBuffer5.GetTemporaryRT(num17, num18, num19, num20, filterMode3, renderTextureFormat2, renderTextureReadWrite);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 9)
{
CommandBuffer commandBuffer6 = (CommandBuffer)LuaObject.checkSelf(l);
int num21;
LuaObject.checkType(l, 2, out num21);
int num22;
LuaObject.checkType(l, 3, out num22);
int num23;
LuaObject.checkType(l, 4, out num23);
int num24;
LuaObject.checkType(l, 5, out num24);
FilterMode filterMode4;
LuaObject.checkEnum<FilterMode>(l, 6, out filterMode4);
RenderTextureFormat renderTextureFormat3;
LuaObject.checkEnum<RenderTextureFormat>(l, 7, out renderTextureFormat3);
RenderTextureReadWrite renderTextureReadWrite2;
LuaObject.checkEnum<RenderTextureReadWrite>(l, 8, out renderTextureReadWrite2);
int num25;
LuaObject.checkType(l, 9, out num25);
commandBuffer6.GetTemporaryRT(num21, num22, num23, num24, filterMode4, renderTextureFormat3, renderTextureReadWrite2, num25);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ReleaseTemporaryRT(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
commandBuffer.ReleaseTemporaryRT(num);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ClearRenderTarget(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 4)
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
bool flag;
LuaObject.checkType(l, 2, out flag);
bool flag2;
LuaObject.checkType(l, 3, out flag2);
Color color;
LuaObject.checkType(l, 4, out color);
commandBuffer.ClearRenderTarget(flag, flag2, color);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 5)
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
bool flag3;
LuaObject.checkType(l, 2, out flag3);
bool flag4;
LuaObject.checkType(l, 3, out flag4);
Color color2;
LuaObject.checkType(l, 4, out color2);
float num2;
LuaObject.checkType(l, 5, out num2);
commandBuffer2.ClearRenderTarget(flag3, flag4, color2, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetGlobalFloat(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(float)))
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
float num2;
LuaObject.checkType(l, 3, out num2);
commandBuffer.SetGlobalFloat(num, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(float)))
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
float num3;
LuaObject.checkType(l, 3, out num3);
commandBuffer2.SetGlobalFloat(text, num3);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetGlobalVector(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Vector4)))
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Vector4 vector;
LuaObject.checkType(l, 3, out vector);
commandBuffer.SetGlobalVector(num, vector);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Vector4)))
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Vector4 vector2;
LuaObject.checkType(l, 3, out vector2);
commandBuffer2.SetGlobalVector(text, vector2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetGlobalColor(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Color)))
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Color color;
LuaObject.checkType(l, 3, out color);
commandBuffer.SetGlobalColor(num, color);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Color)))
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Color color2;
LuaObject.checkType(l, 3, out color2);
commandBuffer2.SetGlobalColor(text, color2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetGlobalMatrix(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Matrix4x4)))
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Matrix4x4 matrix4x;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x);
commandBuffer.SetGlobalMatrix(num, matrix4x);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Matrix4x4)))
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Matrix4x4 matrix4x2;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x2);
commandBuffer2.SetGlobalMatrix(text, matrix4x2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetGlobalTexture(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(RenderTargetIdentifier)))
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
RenderTargetIdentifier renderTargetIdentifier;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier);
commandBuffer.SetGlobalTexture(num, renderTargetIdentifier);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(RenderTargetIdentifier)))
{
CommandBuffer commandBuffer2 = (CommandBuffer)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
RenderTargetIdentifier renderTargetIdentifier2;
LuaObject.checkValueType<RenderTargetIdentifier>(l, 3, out renderTargetIdentifier2);
commandBuffer2.SetGlobalTexture(text, renderTargetIdentifier2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int IssuePluginEvent(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
IntPtr intPtr;
LuaObject.checkType(l, 2, out intPtr);
int num;
LuaObject.checkType(l, 3, out num);
commandBuffer.IssuePluginEvent(intPtr, num);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_name(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, commandBuffer.get_name());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_name(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
string name;
LuaObject.checkType(l, 2, out name);
commandBuffer.set_name(name);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_sizeInBytes(IntPtr l)
{
int result;
try
{
CommandBuffer commandBuffer = (CommandBuffer)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, commandBuffer.get_sizeInBytes());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.Rendering.CommandBuffer");
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.Dispose));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.Release));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.Clear));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.DrawMesh));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.DrawRenderer));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.DrawProcedural));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.DrawProceduralIndirect));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.SetRenderTarget));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.Blit));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.GetTemporaryRT));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.ReleaseTemporaryRT));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.ClearRenderTarget));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.SetGlobalFloat));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.SetGlobalVector));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.SetGlobalColor));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.SetGlobalMatrix));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.SetGlobalTexture));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.IssuePluginEvent));
LuaObject.addMember(l, "name", new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.get_name), new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.set_name), true);
LuaObject.addMember(l, "sizeInBytes", new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.get_sizeInBytes), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Rendering_CommandBuffer.constructor), typeof(CommandBuffer));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace br.com.weblayer.logistica.core.Model
{
public class CenarioEntrega
{
public virtual int nr_dias
{ get; set; }
public virtual int nr_notas
{ get; set; }
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity_Dialogue
{
[CreateAssetMenu(fileName = "DialogueTree", menuName =
"ScriptableObjects/Dialogue Tree")]
public class DialogueTreeObject : ScriptableObject
{
public string npcName;
public string defaultState;
public DialogueOption defaultOption;
public string[] scriptableCallbackNames;
public DialogueUnit[] dialogueUnits;
// Non-editor class members
public DialogueState dialogueState;
public Action continueCallback;
public Action endDialogueCallback;
public Dictionary<string, DialogueUnit> dialogueUnitsDict;
public Dictionary<string, Action> scriptableCallbacks =
new Dictionary<string, Action>();
public void AddToState(string stateToAdd)
{
dialogueState.stateDict[npcName] += stateToAdd;
}
public void RemoveState(int length = 1)
{
if (dialogueState.stateDict[npcName].Length < length)
{
return;
}
dialogueState.stateDict[npcName] = dialogueState.stateDict[npcName].
Remove(dialogueState.stateDict[npcName].Length - length);
}
public void ResetState(string newState)
{
dialogueState.stateDict[npcName] = newState;
}
public void CallScriptableAction(string actionName)
{
scriptableCallbacks[actionName]();
}
public void Continue()
{
continueCallback();
}
public void EndDialogue()
{
endDialogueCallback();
}
public void RegisterScriptableCallback(string callbackName,
Action action)
{
scriptableCallbacks[callbackName] = action;
}
public void SetUpDialogueUnitsDict()
{
dialogueUnitsDict = new Dictionary<string, DialogueUnit>();
foreach (var dialogueUnit in dialogueUnits)
{
dialogueUnitsDict[dialogueUnit.requiredStateKey] = dialogueUnit;
}
}
public void SetUpDialogueState(DialogueState state)
{
dialogueState = state;
if (!dialogueState.stateDict.ContainsKey(npcName))
{
dialogueState.stateDict[npcName] = defaultState;
}
}
public void ResetCallbacks()
{
continueCallback = () => { };
endDialogueCallback = () => { };
scriptableCallbacks.Clear();
}
public DialogueUnit GetNextDialogueUnit()
{
return dialogueUnitsDict.TryGetValue(dialogueState.stateDict
[npcName], out var value DialogueUnit) ? value : null;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ResultsController : MonoBehaviour {
Randomizer x;
public Text score, wins, verdict, examScore, classGrade;
private int wins2;
// Use this for initialization
void Start () {
x = GameObject.FindGameObjectWithTag ("Randomizer").GetComponent<Randomizer> ();
wins2 = x.getWins ();
int exScore = x.examScore;
wins.text = "Games won: " + wins2;
string judge = "";
switch (wins2) {
case 0:
judge = "AHAHAHAHA YOU SUCK, LOSER";
break;
case 1:
judge = "If only there was nux mode...";
break;
case 2:
judge = "Git gud, son";
break;
case 3:
judge = "50%...just like your grade in algorithms/compilers!";
break;
case 4:
judge = "Ehhhh, not bad.";
break;
case 5:
judge = "Almost there! Stay determined!";
break;
case 6:
judge = "AHAHAHA YOU BEAT THEM ALL?! What a no life loser!";
break;
default:
judge = "CHEATER";
break;
}
verdict.text = judge;
int scored = Random.Range (-9000, 9000);
score.text = "GAME SCORE: " + scored;
examScore.text = "EXAM SCORE: " + exScore;
string grade = "GRADE: F";
classGrade.color = Color.red;
if (exScore >= 60) {
grade = "GRADE: D";
}
if (exScore >= 70) {
grade = "GRADE: C";
}
if (exScore >= 80) {
grade = "GRADE: B";
classGrade.color = Color.yellow;
}
if (exScore >= 90) {
grade = "GRADE: A";
classGrade.color = Color.green;
}
if (exScore >= 100) {
grade = "GRADE: STEPHEN ROBINSON";
}
classGrade.text = grade;
}
// Update is called once per frame
void Update () {
}
}
|
using Newtonsoft.Json;
using NUnit.Framework;
using Set.Api.Models;
using SetApi.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Set.ApiTests
{
class PostValidSetTests
{
[Test]
public async Task TestPostingValidSet()
{
var seed = new NewGameDTO { IsDaily = true, UserLocalTime = new DateTime(2022, 5, 29).ToShortTimeString() };
StringContent postContent = TestUtilities.ObjToStringContent(seed);
HttpClient client = TestUtilities.GetHttpClient();
HttpResponseMessage response = await client.PostAsync("newgame", postContent);
string content = await response.Content.ReadAsStringAsync();
BoardDTO gameObj = JsonConvert.DeserializeObject<BoardDTO>(content);
List<Card> cards = TestUtilities.FindSet(gameObj.Cards);
GuessDTO guess = new GuessDTO { GameID = gameObj.GameID, Card1 = cards[0], Card2 = cards[1], Card3 = cards[2] };
StringContent guessContent = TestUtilities.ObjToStringContent(guess);
HttpResponseMessage postResponse = await client.PostAsync("submitguess", guessContent);
string responseContent = await postResponse.Content.ReadAsStringAsync();
GameDTO gameDTO = JsonConvert.DeserializeObject<GameDTO>(responseContent);
Assert.AreEqual(true, gameDTO.ValidSet, "Posted cards should have registered as valid but are invalid");
Assert.AreEqual(78, gameDTO.CardsRemaining, "Cards remaining should have been 78 but are not");
Assert.IsFalse(gameDTO.WinState, "Win state after a single POST should be false but is true");
Assert.IsFalse(TestUtilities.BoardContainsCards(gameDTO.Board, guess.Card1, guess.Card2, guess.Card3), "Posted cards should be removed from the board but are still present");
}
}
}
|
using System.Text.Json.Serialization;
namespace ZenHub.Models
{
public class IssueDetails
{
[JsonPropertyName("issue_number")]
public int IssueNumber { get; set; }
[JsonPropertyName("is_epic")]
public bool IsEpic { get; set; }
[JsonPropertyName("repo_id")]
public long RepositoryId { get; set; }
[JsonPropertyName("position")]
public int Position { get; set; }
[JsonPropertyName("estimate")]
public EstimateValue Estimate { get; set; }
[JsonPropertyName("pipelines")]
public ZenHubPipeline[] Pipelines { get; set; }
[JsonPropertyName("pipeline")]
public ZenHubPipeline Pipeline { get; set; }
[JsonPropertyName("plus_ones")]
public CreatedDate[] PlusOnes { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using BankAccounts.Models;
using System.Linq;
using System;
namespace BankAccounts.Models
{
public class BankAccountsContext : DbContext
{
public BankAccountsContext(DbContextOptions options) : base(options) { }
public DbSet<Account> AccountUsers {get;set;}
public DbSet<Transaction> Transactions {get;set;}
public int Create(Account accountuser)
{
PasswordHasher<Account> Hasher = new PasswordHasher<Account>();
accountuser.Password = Hasher.HashPassword(accountuser, accountuser.Password);
Add(accountuser);
SaveChanges();
return accountuser.AccountId;
}
public void Create(Transaction accountTransaction)
{
Add(accountTransaction);
SaveChanges();
}
}
} |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PowerShell.EditorServices.Utility;
namespace Microsoft.PowerShell.EditorServices.Services.PowerShellContext
{
internal class WindowsConsoleOperations : IConsoleOperations
{
private ConsoleKeyInfo? _bufferedKey;
private SemaphoreSlim _readKeyHandle = AsyncUtils.CreateSimpleLockingSemaphore();
public int GetCursorLeft() => System.Console.CursorLeft;
public int GetCursorLeft(CancellationToken cancellationToken) => System.Console.CursorLeft;
public Task<int> GetCursorLeftAsync() => Task.FromResult(System.Console.CursorLeft);
public Task<int> GetCursorLeftAsync(CancellationToken cancellationToken) => Task.FromResult(System.Console.CursorLeft);
public int GetCursorTop() => System.Console.CursorTop;
public int GetCursorTop(CancellationToken cancellationToken) => System.Console.CursorTop;
public Task<int> GetCursorTopAsync() => Task.FromResult(System.Console.CursorTop);
public Task<int> GetCursorTopAsync(CancellationToken cancellationToken) => Task.FromResult(System.Console.CursorTop);
public async Task<ConsoleKeyInfo> ReadKeyAsync(bool intercept, CancellationToken cancellationToken)
{
await _readKeyHandle.WaitAsync(cancellationToken);
try
{
return
_bufferedKey.HasValue
? _bufferedKey.Value
: await Task.Factory.StartNew(
() => (_bufferedKey = System.Console.ReadKey(intercept)).Value);
}
finally
{
_readKeyHandle.Release();
// Throw if we're cancelled so the buffered key isn't cleared.
cancellationToken.ThrowIfCancellationRequested();
_bufferedKey = null;
}
}
public ConsoleKeyInfo ReadKey(bool intercept, CancellationToken cancellationToken)
{
_readKeyHandle.Wait(cancellationToken);
try
{
return
_bufferedKey.HasValue
? _bufferedKey.Value
: (_bufferedKey = System.Console.ReadKey(intercept)).Value;
}
finally
{
_readKeyHandle.Release();
// Throw if we're cancelled so the buffered key isn't cleared.
cancellationToken.ThrowIfCancellationRequested();
_bufferedKey = null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace APIEcommerce.Responses
{
public class ProdutoResponse
{
public string IdProduto { get; set; }
public string Nome { get; set; }
public string Descricao { get; set; }
public string ValorUnitario { get; set; }
}
}
|
using Alarmy.Common;
using Alarmy.Core;
using Alarmy.Tests.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Alarmy.Tests.Core
{
[TestClass]
public class CSVImporterTests
{
private FakeAlarmService service;
private CSVImporter importer;
private ImportContext importContext;
[TestInitialize]
public void Setup()
{
this.service = Substitute.For<FakeAlarmService>();
this.importer = new CSVImporter(this.service);
this.importContext = new ImportContext {
CaptionFormat = "{0}",
CaptionPatterns = new [] { "\\W+" },
DateFormat = "dd.MM.yyyy HH:mm"
};
}
private void Import(string content)
{
var stream = new MemoryStream();
var streamWriter = new StreamWriter(stream);
streamWriter.Write(content);
streamWriter.Flush();
stream.Position = 0;
var streamReader = new StreamReader(stream);
importer.Import(importContext, streamReader);
}
[TestMethod]
public void CSVImporter_Import_WhenNoAlarmsInFile_DoesNotAddAnyAlarms()
{
IList<IAlarm> alarms = null;
service.WhenForAnyArgs(x => x.Import(null, false)).Do(x => alarms = ((IEnumerable<IAlarm>)x.Args()[0]).ToList());
this.Import("Caption\tDate\r\nFooter");
Assert.AreEqual(0, alarms.Count);
}
[TestMethod]
public void CSVImporter_Import_WhenOneAlarmInFile_AddsAlarm()
{
IList<IAlarm> alarms = null;
service.WhenForAnyArgs(x => x.Import(null, false)).Do(x => alarms = ((IEnumerable<IAlarm>)x.Args()[0]).ToList());
this.Import("Caption\tDate\r\nTest Caption\t10.10.1987 10:00\r\nFooter");
Assert.AreEqual(1, alarms.Count);
Assert.AreEqual("Test Caption", alarms[0].Title);
Assert.AreEqual(new DateTime(1987, 10, 10, 10, 0, 0), alarms[0].Time);
}
[TestMethod]
public void CSVImporter_Import_WhenDateTimeSeperated_MergesDateAndTime()
{
IList<IAlarm> alarms = null;
service.WhenForAnyArgs(x => x.Import(null, false)).Do(x => alarms = ((IEnumerable<IAlarm>)x.Args()[0]).ToList());
this.Import("Caption\tDate\tTime\r\nTest Caption\t10.10.1987\t10:00\r\nFooter");
Assert.AreEqual(1, alarms.Count);
Assert.AreEqual("Test Caption", alarms[0].Title);
Assert.AreEqual(new DateTime(1987, 10, 10, 10, 0, 0), alarms[0].Time);
}
[TestMethod]
public void CSVImporter_Import_WhenTimeIsBeforeDate_MergesDateAndTime()
{
IList<IAlarm> alarms = null;
service.WhenForAnyArgs(x => x.Import(null, false)).Do(x => alarms = ((IEnumerable<IAlarm>)x.Args()[0]).ToList());
this.Import("Caption\tTime\tDate\r\nTest Caption\t10:00\t10.10.1987\r\nFooter");
Assert.AreEqual(1, alarms.Count);
Assert.AreEqual("Test Caption", alarms[0].Title);
Assert.AreEqual(new DateTime(1987, 10, 10, 10, 0, 0), alarms[0].Time);
}
[TestMethod]
public void CSVImporter_Import_WhenMultipleAlarms_AddsAll()
{
IList<IAlarm> alarms = null;
service.WhenForAnyArgs(x => x.Import(null, false)).Do(x => alarms = ((IEnumerable<IAlarm>)x.Args()[0]).ToList());
this.Import("Caption\tTime\tDate\r\nTest Caption\t10:00\t10.10.1987\r\nTest Caption 2\t11:00\t11.10.1987\r\nFooter");
Assert.AreEqual(2, alarms.Count);
Assert.AreEqual("Test Caption", alarms[0].Title);
Assert.AreEqual(new DateTime(1987, 10, 10, 10, 0, 0), alarms[0].Time);
Assert.AreEqual("Test Caption 2", alarms[1].Title);
Assert.AreEqual(new DateTime(1987, 10, 11, 11, 0, 0), alarms[1].Time);
}
[TestMethod]
public void CSVImporter_Import_WhenMultipleCaptionFields_MergesAll()
{
importContext.CaptionFormat = "{0} - {1}";
importContext.CaptionPatterns = new[] { "\\w+", "^\\w{4}$" };
IList<IAlarm> alarms = null;
service.WhenForAnyArgs(x => x.Import(null, false)).Do(x => alarms = ((IEnumerable<IAlarm>)x.Args()[0]).ToList());
this.Import("Caption\tCaption2\tTime\tDate\r\nTest Caption\tTest\t10:00\t10.10.1987\r\nFooter");
Assert.AreEqual(1, alarms.Count);
Assert.AreEqual("Test Caption - Test", alarms[0].Title);
Assert.AreEqual(new DateTime(1987, 10, 10, 10, 0, 0), alarms[0].Time);
}
}
}
|
using AutoMapper;
using Amazon.Suporte.ViewModel;
using Amazon.Suporte.Model;
namespace Amazon.Suporte.Profiles
{
public class ProblemProfile : Profile
{
public ProblemProfile()
{
CreateMap<ProblemRequest,Problem>();
CreateMap<Problem, ProblemResponse>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BrakeBarController : MonoBehaviour {
float maxRotation = 129;
float currentRotation = 0;
private Player player;
// Update is called once per frame
void Update() {
float offset = 0;
// if player alive and spawned
if (player != null) {
offset = CalculateOffset();
}
else {
offset = -currentRotation;
}
currentRotation += offset;
gameObject.transform.Rotate(Vector3.forward, -offset);
}
private float CalculateOffset() {
return (maxRotation * (player.GetComponent<PlayerMovement>().GetBrakeTime() / player.GetComponent<PlayerMovement>().maxBrakeTime)) - currentRotation;
}
public void SetPlayer(Player ply) {
player = ply;
maxRotation = 129;
currentRotation = 0;
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MaxMinCelciusScript : MonoBehaviour {
public bool knowsWeather;
private WeatherAPI weather;
Text tempText;
// Use this for initialization
// Use this for initialization
void Start () {
knowsWeather = false;
tempText = GameObject.Find("MinMaxCelcius").GetComponent<Text>();
weather = WeatherAPI.FindObjectOfType<WeatherAPI>();
}
// Update is called once per frame
void Update () {
if (!knowsWeather && weather.temp != 0)
{
double temp_min = weather.temp_min - 273.15f;
int celcius_min = Mathf.RoundToInt((float)temp_min);
double temp_max = weather.temp_max - 273.15f;
int celcius_max = Mathf.RoundToInt((float)temp_max);
tempText.text = celcius_min.ToString() + "° " + celcius_max.ToString() + "°";
knowsWeather = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace FlexLabs.Glimpse.Linq2Sql
{
public class PluginTextWriter : TextWriter
{
private static PluginTextWriter _instance;
private static readonly object _instanceLock = new object();
public static PluginTextWriter Instance
{
get
{
if (_instance == null)
lock (_instanceLock)
if (_instance == null)
_instance = new PluginTextWriter();
return _instance;
}
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
public override void Write(char value)
{
LogItemHandler.WriteLine(value.ToString());
}
public override void Write(string value)
{
if (value != null)
{
LogItemHandler.WriteLine(value);
}
}
public override void Write(char[] buffer, int index, int count)
{
if (buffer == null || index < 0 || count < 0 || buffer.Length - index < count)
{
base.Write(buffer, index, count); // delegate throw exception to base class
}
var value = new string(buffer, index, count);
LogItemHandler.WriteLine(value);
}
}
}
|
using UnityEngine;
using System.Collections;
using Infated.Tools;
using System.Collections.Generic;
namespace Infated.CoreEngine
{
public class SplashCheck : MonoBehaviour
{
public bool splashEnabled = false;
public List<Collider2D> splashList = new List<Collider2D>();
public int SplashDamage = 5;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void DealDamage(){
foreach(Collider2D col in splashList){
if((col.tag == "Enemy")) {
Health hp = col.transform.GetComponent<Health>();
if(hp != null){
hp.Damage(SplashDamage, this.gameObject, 5, 0.5f);
}
}
}
}
//called when something enters the trigger
void OnTriggerEnter2D(Collider2D Collider)
{
//if the object is not already in the list
if(!splashList.Contains(Collider))
{
//add the object to the list
splashList.Add(Collider);
}
}
//called when something exits the trigger
void OnTriggerExit2D(Collider2D Collider)
{
//if the object is in the list
if(splashList.Contains(Collider))
{
//remove it from the list
splashList.Remove(Collider);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Chess.Pieces
{
public class Pawn : Piece
{
public Pawn(Color color, int x, int y) : base(color, x, y)
{
}
protected override IEnumerable<(int X, int Y)> GetPossibleMovements(Board board)
{
int yMovement = Color switch
{
Color.White => +1,
Color.Black => -1,
_ => throw new NotImplementedException(),
};
IEnumerable<(int X, int Y)> getCaptureMoves()
{
yield return (X - 1, Y + yMovement);
yield return (X + 1, Y + yMovement);
}
IEnumerable<(int X, int Y)> getRegularMoves()
{
yield return (X, Y + yMovement);
if (!HasMoved && board[X, Y + yMovement] == default)
yield return (X, Y + yMovement * 2);
}
Piece tempPiece;
foreach (var movement in getCaptureMoves())
if (IsInBounds(movement.X, movement.Y)
&& ((tempPiece = board[movement.X, movement.Y]) != default && tempPiece.Color == Color.Invert()
|| board.PossibleEnPassantTarget == movement))
yield return movement;
foreach (var movement in getRegularMoves())
if (IsInBounds(movement.X, movement.Y) && board[movement.X, movement.Y] == default)
yield return movement;
}
}
}
|
using System.Collections.Generic;
namespace Converter.UI.Settings
{
/// <summary>
/// A preference category is a set of IPreference objects that is related.
/// Each PreferenceCategory matches a <category> tag in Configuration.xml, and gets turned into a tab in the converter UI.
/// </summary>
public class PreferenceCategory
{
private IList<IPreference> preferences;
/// <summary>
/// Gets the list of preferences in this category.
/// </summary>
/// <value>
/// The preferences.
/// </value>
public IList<IPreference> Preferences
{
get
{
return this.preferences ?? (this.preferences = new List<IPreference>());
}
}
/// <summary>
/// Gets or sets the friendly name for this category.
/// </summary>
/// <value>
/// The name of the friendly.
/// </value>
public string FriendlyName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Core.Interfaces
{
public interface IBaseRepository<T>
{
/// <summary>
/// Lấy toàn bộ dữ liệu của bảng trong database
/// </summary>
/// <returns>Danh sách đối tượng</returns>
/// CreatedBy: DTHieu(13/4/2021)
IEnumerable<T> GetEntities();
/// <summary>
/// Lấy thông tin của thực thể theo khóa chính
/// </summary>
/// <param name="entityId">Id của đối tượng</param>
/// <returns>1 thực thể duy nhất có Id tương ứng</returns>
/// CreatedBy: DTHieu(13/4/2021)
T GetById(Guid entityId);
/// <summary>
/// Thêm mới
/// </summary>
/// <param name="entity">Thực thể</param>
/// <returns>số bản ghi thêm mới được vào Db</returns>
/// CreatedBy: DTHieu(13/4/2021)
int Insert(T entity);
/// <summary>
/// Sửa thông tin của đối tượng
/// </summary>
/// <param name="entity">Thực thể đã được chỉnh sửa</param>
/// <param name="entityId">ID của thực thể</param>
/// <returns>Số bản ghi đã update được trong Db</returns>
/// CreatedBy: DTHieu(13/4/2021)
int Update(T entity, Guid entityId);
/// <summary>
/// Xóa đối tượng theo Id
/// </summary>
/// <param name="entityId">Khóa chính của thực thể</param>
/// <returns>Số bản ghi đã xóa được trong Db</returns>
/// CreatedBy: DTHieu(13/4/2021)
int Delete(Guid entityId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CareerCup150.Chapter9_SortingSearch
{
public class _09_06_FindIn2DArray
{
public int FindIn2DArray(int[,] input, int value)
{
return 0;
}
}
}
|
namespace ClassInheritExercise
{
public interface IProfesor
{
int NumProfesor { get; set; }
Asignatura ProfeDe { get; set; }
string titulo { get; set; }
bool AprobarCosas();
void DarClasesDeCosas();
bool SuspenderCosas(IAlumno jc, bool yaMeReireYo);
}
} |
using System;
using System.Linq;
namespace _13._TriFunction
{
class TriFunction
{
static void Main(string[] args)
{
int targetASCII = int.Parse(Console.ReadLine());
string[] inputNames = Console.ReadLine().Split();
Action<string> Print = name => Console.WriteLine(name);
Func<string, int, bool> IsSumEqual =
(name, ascii) => name.Sum(c => c) >= ascii;
Func<string[], Func<string, int, bool>, string> FindFirstName =
(names, IsSumEqualASCII) => names.FirstOrDefault(n => IsSumEqual(n, targetASCII));
string result = FindFirstName(inputNames, IsSumEqual);
Print(result);
}
}
}
|
using HCL.Academy.Model;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using HCLAcademy.Util;
using Microsoft.ApplicationInsights;
using System.Diagnostics;
namespace HCLAcademy.Controllers
{
public class SearchController : Controller
{
private static List<Result> lstResult;
/// <summary>
/// Fetches results for a particular Keyword
/// </summary>
/// <param name="keyword"></param>
/// <returns></returns>
[HttpPost]
[Authorize]
[SessionExpire]
public ActionResult Search(string keyword)
{
try
{
//IDAL dal = (new DALFactory()).GetInstance();
SPAuthUtility spUtil = new SPAuthUtility();
lstResult = spUtil.Search(keyword);
return RedirectToAction("Search", "Search");
}
catch (Exception ex)
{
//UserManager user = (UserManager)Session["CurrentUser"];
//LogHelper.AddLog("SearchController", ex.Message, ex.StackTrace, "HCL.Academy.Web", user.EmailID);
TelemetryClient telemetry = new TelemetryClient();
telemetry.TrackException(ex);
return View();
}
}
/// <summary>
/// Search for a particular keyword
/// </summary>
/// <returns></returns>
[Authorize]
[SessionExpire]
public ActionResult Search()
{
if (lstResult != null && lstResult.Count > 0)
{
ViewBag.lstResults = lstResult;
}
else
{
ViewBag.lstResults = null;
}
return View();
}
}
} |
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 FlappyBird
{
public partial class Form1 : Form
{
string username; // giu username cua nguoi choi
SqlConnection sqlCon;// giu database ket noi voi tro choi
Random size = new Random(); //random kich thuoc pipe
int speed = new int();
int gravity = 2;
int score = 0;
public Form1(LoginForm form)
{
InitializeComponent();
loginForm = form;
}
LoginForm loginForm;// chua form login
public void GetValue(string name, SqlConnection sql)
{
username = name;
sqlCon = sql;
}
void SaveScore() //luu highscore vao database
{
int highscore = new int();
string getscore = "select score from [Table] where username = '" + username + "'";
try
{
SqlCommand command = new SqlCommand(getscore, sqlCon);
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
highscore = Int32.Parse(dr["score"].ToString());
}
dr.Close();
if (score > highscore)
{
string query = "Update [Table] set score = " + score + " where username = '" + username + "'";
SqlCommand cmd = new SqlCommand(query, sqlCon);
cmd.ExecuteNonQuery();
}
}catch(Exception)
{
if(MessageBox.Show("Kiểm tra kết nối internet")==DialogResult.OK)
this.Close();
loginForm.Show();
}
}
int[] InitSpeed()//tao mang gia tri toc do
{
int[] Speed = { 5, 6, 7, 8, 9, 10, 11, 12 };
return Speed;
}
private void Form1_Load(object sender, EventArgs e)
{
LoginForm frm = new LoginForm();
frm.mydata = new LoginForm.GetData(GetValue);
LoadGame();
try
{
sqlCon.Open();
}catch(SqlException k)
{
MessageBox.Show(k.Message);
loginForm.ShowDialog();
this.Close();
}
}
void EndGame()
{
gameTimer.Stop();
SaveScore();
btn_Exit.Enabled = true;
btn_start.Enabled = true;
btn_highscore.Enabled = true;
}
void CheckEnd()
{
if (Bird.Bounds.IntersectsWith(pipeBotom1.Bounds))
EndGame();
else if (Bird.Bounds.IntersectsWith(pipeBotom2.Bounds))
EndGame();
else if (Bird.Bounds.IntersectsWith(pipeTop1.Bounds))
EndGame();
else if (Bird.Bounds.IntersectsWith(pipeTop2.Bounds))
EndGame();
else if (Bird.Bounds.IntersectsWith(ground.Bounds))
EndGame();
}
void GetScore()
{
Scoretxt.Text = score.ToString();
}
void ControlSpeed()//dieu khien toc do
{
int[] Speed = InitSpeed();
int i = score / 10;
speed = Speed[i];
}
private void GameTimer_Tick(object sender, EventArgs e)
{
GetScore();
ControlSpeed();
Bird.Top += gravity;
pipeBotom1.Left -= speed;
pipeBotom2.Left -= speed;
pipeTop1.Left -= speed;
pipeTop2.Left -= speed;
if(pipeBotom1.Left<=-30)
{
score++;
int h = size.Next(120, 130);
pipeBotom1.Height = h;
int t = 306 - h;
pipeBotom1.Location = new Point(490, t);
}
if(pipeBotom2.Left <= -30)
{
score++;
int h = size.Next(120, 130);
pipeBotom2.Height = h;
int t = 306 - h;
pipeBotom2.Location = new Point(490, t);
}
if(pipeTop1.Left <= -30)
{
score++;
int h = size.Next(103, 135);
pipeTop1.Height = h;
pipeTop1.Location = new Point(505, 0);
}
if (pipeTop2.Left <= -30)
{
score++;
int h = size.Next(103, 135);
pipeTop2.Height = h;
pipeTop2.Location = new Point(505, 0);
}
CheckEnd();
}
void LoadGame()
{
//speed
score = 0;
Scoretxt.Text = "0";
pipeBotom1.Left = 228;
pipeBotom2.Left = 368;
pipeTop1.Left = 257;
pipeTop2.Left = 438;
Bird.Location = new Point(12, 189);
}
private void Btn_start_Click(object sender, EventArgs e)
{
if (btn_start.Text == "Bắt đầu")
{
gameTimer.Start();
btn_start.Enabled = false;
btn_Exit.Enabled = false;
btn_highscore.Enabled = false;
btn_start.Text = "Chơi lại";
}
else
{
LoadGame();
btn_start.Text = "Bắt đầu";
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode==Keys.Space)
{
e.SuppressKeyPress = true;
gravity = -2;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
gravity = 2;
}
}
private void Btn_Exit_Click(object sender, EventArgs e)
{
sqlCon.Close();
Application.Exit();
}
private void Btn_highscore_Click(object sender, EventArgs e)
{
HighScore highScore = new HighScore(sqlCon);
highScore.ShowDialog();
}
}
}
|
using System;
using System.Threading.Tasks;
using LannisterAPI.Models;
using Microsoft.AspNetCore.Mvc;
namespace LannisterAPI.Controllers
{
[Produces("application/json")]
public class TrackingController : Controller
{
[HttpGet]
[Route("trackings")]
[ProducesResponseType(typeof(TrackingList), 200)]
[ProducesResponseType(typeof(Error), 400)]
public async Task<IActionResult> GetUserTrackings()
{
return Ok(
new TrackingList(
Guid.NewGuid().ToString(),
new[]
{
new TrackingPreview(
Guid.NewGuid().ToString(),
"Tracking Name",
-342.23F,
6,
"USD",
true),
new TrackingPreview(
Guid.NewGuid().ToString(),
"Another tracking name",
960F,
2,
"RUR",
false)
}));
}
[HttpGet]
[Route("trackings/{id}")]
[ProducesResponseType(typeof(Tracking), 200)]
[ProducesResponseType(typeof(Error), 400)]
public async Task<IActionResult> GetTracking(string id)
{
var participants = new[]
{
new TrackingParticipant(Guid.NewGuid().ToString(), "Jessica Jones", "Jjones",
new Uri("https://typeset-beta.imgix.net/2017%2F2%2F15%2Fa7a7b3ca-2255-4625-9fb9-fefdb19a5a96.jpg"), true),
new TrackingParticipant(Guid.NewGuid().ToString(), "Sergey Piterskiy", "pitor",
new Uri("https://image.freepik.com/free-icon/male-user-shadow_318-34042.jpg"), true),
new TrackingParticipant(Guid.NewGuid().ToString(), "Herman Gold", "X-Man",
new Uri("https://image.freepik.com/free-icon/male-user-shadow_318-34042.jpg"), false)
};
return Ok(new Tracking(
id,
"Tracking name",
"RUB",
participants,
participants[0].Id,
DateTimeOffset.UtcNow.AddDays(-23),
null));
}
[HttpPost]
[Route("trackings")]
[ProducesResponseType(typeof(CreateTrackingResponse), 200)]
[ProducesResponseType(typeof(Error), 400)]
public async Task<IActionResult> CreateTracking([FromBody] CreateTrackingRequest createTrackingRequest)
{
return Ok();
}
[HttpPost]
[Route("trackings/{trackingId}/users/{userId}")]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(Error), 400)]
public async Task<IActionResult> InviteUser(string trackingId, string userId)
{
return Ok();
}
[HttpDelete]
[Route("trackings/{trackingId}/users/{userId}")]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(Error), 400)]
public async Task<IActionResult> DeleteUser(string trackingId, string userId)
{
return Ok();
}
[HttpDelete]
[Route("trackings/{trackingId}")]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(Error), 400)]
public async Task<IActionResult> CloseTracking(string trackingId)
{
return Ok();
}
}
} |
using HedgeHog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace IBApi {
public static class Mixin {
}
public partial class Contract {
private string HashKey => Instrument +
(IsCombo ? ":" + ComboLegs.OrderBy(l => l.Ratio).Select(l => $"{l.ConId}-{l.Ratio}").Flatter(":") : "");
public double IntrinsicValue(double undePrice) =>
!IsOption
? 0
: IsCall
? (undePrice - Strike).Max(0)
: IsPut
? (Strike - undePrice).Max(0)
: 0;
public double ExtrinsicValue(double optionPrice, double undePrice) =>
!IsOption
? 0
: IsCall
? optionPrice - (undePrice - Strike).Max(0)
: IsPut
? optionPrice - (Strike - undePrice).Max(0)
: 0;
DateTime? _lastTradeDateOrContractMonth;
public DateTime Expiration =>
(_lastTradeDateOrContractMonth ??
(_lastTradeDateOrContractMonth = LastTradeDateOrContractMonth.FromTWSDateString(DateTime.Now.Date))
).Value;
public string Key => Instrument;
public string Instrument => ComboLegsToString().IfEmpty((LocalSymbol.IfEmpty(Symbol)?.Replace(".", "") + "").ToUpper());
static readonly ConcurrentDictionary<string, Contract> _contracts = new ConcurrentDictionary<string, Contract>(StringComparer.OrdinalIgnoreCase);
public static IDictionary<string, Contract> Contracts => _contracts;
public Contract AddToCache() {
if(!_contracts.TryAdd(Key, this) && _contracts[Key].HashKey != HashKey)
_contracts.AddOrUpdate(Key, this, (k, c) => this);
return this;
}
public IEnumerable<ContractDetails> FromDetailsCache() => ContractDetails.FromCache(this);
public IEnumerable<Contract> FromCache() => FromCache(Key);
public IEnumerable<T> FromCache<T>(Func<Contract, T> map) => FromCache(Key, map);
public static IEnumerable<Contract> Cache() => Contracts.Values;
public static IEnumerable<Contract> FromCache(string instrument) => Contracts.TryGetValue(instrument);
public static IEnumerable<T> FromCache<T>(string instrument, Func<Contract, T> map) => Contracts.TryGetValue(instrument).Select(map);
public double PipCost() => MinTick() * ComboMultiplier;
public double MinTick() {
return ContractDetails.FromCache(this)
.Select(cd => cd.MinTick)
.Where(mt => mt > 0)
.IfEmpty(() => Legs().SelectMany(c => ContractDetails.FromCache(c.c)).MaxByOrEmpty(cd => cd.MinTick).Select(cd => cd.MinTick).Take(1))
.Count(1, _ => Debugger.Break(), _ => Debugger.Break())
.DefaultIfEmpty(0.01)
.Single();
}
public int ComboMultiplier => new[] { Multiplier }.Concat(Legs().Select(l => l.c.Multiplier)).Where(s => !s.IsNullOrWhiteSpace()).DefaultIfEmpty("1").Select(int.Parse).First();
public bool IsCombo => ComboLegs?.Any() == true;
public bool IsCall => IsOption && Right == "C";
public bool IsPut => IsOption && Right == "P";
public bool IsOption => SecType == "OPT" || SecType == "FOP";
public bool IsFutureOption => SecType == "FOP";
public bool HasFutureOption => IsFutureOption || Legs().Any(l => l.c.IsFutureOption);
public bool IsFuture => SecType == "FUT";
public bool IsButterFly => ComboLegs?.Any() == true && String.Join("", comboLegs.Select(l => l.Ratio)) == "121";
public double ComboStrike() => Strike > 0 ? Strike : LegsEx().Sum(c => c.contract.strike * c.leg.Ratio) / LegsEx().Sum(c => c.leg.Ratio);
public int ReqId { get; set; }
string SecTypeToString() => SecType == "OPT" ? "" : " " + SecType;
string ExpirationToString() => IsOption && LocalSymbol.IsNullOrWhiteSpace() || IsFutureOption ? " " + LastTradeDateOrContractMonth : "";
public override string ToString() =>
ComboLegsToString().IfEmpty($"{LocalSymbol ?? Symbol}{SecTypeToString()}{ExpirationToString()}");// {Exchange} {Currency}";
internal string ComboLegsToString() =>
Legs()
.ToArray()
.With(legs => (legs, r: legs.Select(l => l.r).DefaultIfEmpty().Max())
.With(t =>
t.legs
.Select(l => l.c.Instrument + (t.r > 1 ? ":" + l.r : ""))
.OrderBy(s => s)
.ToArray()
.MashDiffs()));
public IEnumerable<(Contract c, int r)> Legs() =>
(from l in ComboLegs ?? new List<ComboLeg>()
join c in Contracts.Select(cd => cd.Value) on l.ConId equals c.ConId
select (c, l.Ratio)
);
public IEnumerable<(Contract contract, ComboLeg leg)> LegsEx() =>
(from l in ComboLegs ?? new List<ComboLeg>()
join c in Contracts.Select(cd => cd.Value) on l.ConId equals c.ConId
select (c, l)
);
}
public static class ContractMixins {
public static bool IsIndex(this Contract c) => c.SecType == "IND";
}
}
|
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
using System;
using System.Diagnostics;
namespace EnhancedEditor
{
/// <summary>
/// Base class to derive all custom method attributes from.
/// <para/>
/// A custom attribute can be hooked up with a custom drawer
/// to get callbacks when the target editor script is being drawn in the inspector.
/// </summary>
[Conditional("UNITY_EDITOR")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public abstract class EnhancedMethodAttribute : Attribute
{
#region Global Members
/// <summary>
/// Optional field to specify the order that multiple <see cref="EnhancedMethodAttribute"/> should be drawn in.
/// </summary>
public int Order { get; set; } = 0;
/// <summary>
/// Determines if the associated drawer should be called before or after
/// drawing the target editor script inspector.
/// <para/>
/// True by default.
/// </summary>
public bool IsDrawnOnTop { get; set; } = true;
/// <summary>
/// Tooltip displayed on mouse hover.
/// </summary>
public string Tooltip { get; set; } = string.Empty;
#endregion
}
}
|
using UnityEngine;
public class StopPlay : MonoBehaviour {
public Manager manager;
// Use this for initialization
void Start () {
manager.StopPlayerControlls(true);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
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 GeorgePairs
{
public partial class GameOver : Window
{
public GameOver()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
InitializeComponent();
}
private void btnExit_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void btnConfirm_Click(object sender, RoutedEventArgs e)
{
foreach (Window window in Application.Current.Windows.OfType<LevelOne>())
{
LevelOne openAgainLevelOne = new LevelOne();
App.Current.MainWindow = openAgainLevelOne;
this.Close();
openAgainLevelOne.Show();
if (window != openAgainLevelOne)
window.Close();
}
foreach (Window window in Application.Current.Windows.OfType<LevelTwo>())
{
LevelTwo openAgainLevelTwo = new LevelTwo();
App.Current.MainWindow = openAgainLevelTwo;
this.Close();
openAgainLevelTwo.Show();
if (window != openAgainLevelTwo)
window.Close();
}
foreach (Window window in Application.Current.Windows.OfType<LevelThree>())
{
LevelThree openAgainLevelThree = new LevelThree();
App.Current.MainWindow = openAgainLevelThree;
this.Close();
openAgainLevelThree.Show();
if (window != openAgainLevelThree)
window.Close();
}
}
private void btnInfirm_Click(object sender, RoutedEventArgs e)
{
App.Current.Shutdown();
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using System.Text.RegularExpressions;
using Whale.Shared.Models;
using System.Linq;
using Whale.Shared.Services;
using Whale.Shared.Exceptions;
using Whale.Shared.Models.User;
using System.Security.Claims;
namespace Whale.API.Controllers
{
[Route("[controller]")]
[ApiController]
[Authorize]
public class UserController : ControllerBase
{
private readonly UserService _userService;
public UserController(UserService userService)
{
_userService = userService;
}
[HttpGet]
public async Task<ActionResult<UserDTO>> GetCurrentUser()
{
var email = HttpContext?.User.Claims
.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var contact = await _userService.GetUserByEmailAsync(email);
if (contact == null)
return NotFound();
return Ok(contact);
}
[HttpGet("{id}")]
public async Task<ActionResult<UserDTO>> Get(Guid id)
{
if (id == Guid.Empty)
throw new BaseCustomException("Invalid id");
var user = await _userService.GetUserAsync(id);
return Ok(user);
}
[HttpGet("email/{email}")]
public async Task<ActionResult<UserDTO>> GetUserByEmail(string email)
{
if (!Regex.IsMatch(email,
@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)))
{
throw new BaseCustomException("Invaid email format");
}
var result = await _userService.GetUserByEmailAsync(email);
return Ok(result);
}
[HttpPost]
public async Task<ActionResult<UserDTO>> AddUser([FromBody] UserModel user)
{
var email = HttpContext?.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var name = HttpContext?.User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
if (!ModelState.IsValid || user.Email != email || user.DisplayName != name)
throw new BaseCustomException("Invalid data");
var result = await _userService.CreateUser(user);
return Ok(result);
}
[HttpPut]
public async Task<ActionResult<UserDTO>> Update([FromBody] UserDTO userDTO)
{
var email = HttpContext?.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
if (!ModelState.IsValid || userDTO.Email != email)
throw new BaseCustomException("Invalid data");
return Ok( await _userService.UpdateUserAsync(userDTO));
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(Guid id)
{
var email = HttpContext?.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
await _userService.DeleteUserAsync(id, email);
return NoContent();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using AorBaseUtility;
public class ErlByteKit
{
public static ErlType simpleAnalyse(ByteBuffer data)
{
int position = data.position;
int tag = data.readByte();
data.position = position;
if (tag == ErlByte.TAG)
{
ErlByte erlByte = new ErlByte(0);
erlByte.bytesRead(data);
return erlByte;
}
else if (tag == ErlByteArray.TAG)
{
ErlByteArray erlByteArray = new ErlByteArray(null);
erlByteArray.bytesRead(data);
return erlByteArray;
}
else if (tag == ErlInt.TAG)
{
ErlInt erlInt = new ErlInt(0);
erlInt.bytesRead(data);
return erlInt;
}
else if (tag == ErlString.TAG)
{
ErlString erlString = new ErlString("");
erlString.bytesRead(data);
return erlString;
}
else if (tag == ErlLong.TAG)
{
ErlLong erlLong = new ErlLong();
erlLong.bytesRead(data);
return erlLong;
}
else
{
return null;
}
}
public static ErlType complexAnalyse(ByteBuffer data)
{
int position = data.position;
int tag = data.readByte();
data.position = position;
// MonoBehaviour.print("----------complexAnalyse--------------"+tag);
if (tag == ErlArray.TAG[0] || tag == ErlArray.TAG[1])
{
ErlArray erlArray = new ErlArray(null);
erlArray.bytesRead(data);
return erlArray;
}
else if (tag == ErlNullList.TAG)
{
ErlNullList erlNullList = new ErlNullList();
erlNullList.bytesRead(data);
return erlNullList;
}
else if (tag == ErlList.TAG)
{
ErlList erlList = new ErlList(null);
erlList.bytesRead(data);
return erlList;
}
else if (tag == ErlAtom.TAG)
{
ErlAtom erlAtom = new ErlAtom(null);
erlAtom.bytesRead(data);
return erlAtom;
}
else if (tag == ErlString.TAG)
{
ErlString erlString = new ErlString(null);
erlString.sampleBytesRead(data);
return erlString;
}
else if (tag == ErlLong.TAG)
{
ErlLong erlLong = new ErlLong();
erlLong.bytesRead(data);
return erlLong;
}
else if (tag == ErlByteArray.TAG)
{
ErlByteArray erlByteArray = new ErlByteArray(null);
erlByteArray.bytesRead(data);
return erlByteArray;
}
else
{
return null;
}
}
public static ErlType natureAnalyse(ByteBuffer data)
{
uint p = (uint)data.position;
uint tag = (uint)data.readUnsignedByte();
// MonoBehaviour.print("=======natureAnalyse======= tag="+tag);
if (tag == ErlKVMessage.VER)//ErlKVMessage.VER)
{
return complexAnalyse(data);
}
else
{
data.position = (int)p;
if (tag == ErlArray.TAG[0] || tag == ErlArray.TAG[1] || tag == ErlNullList.TAG || tag == ErlList.TAG || tag == ErlAtom.TAG || tag == ErlByteArray.TAG)
{
return complexAnalyse(data);
}
else
{
return natureSampleAnalyse(data);
}
}
}
public static ErlType natureSampleAnalyse(ByteBuffer data)
{
int position = data.position;
int tag = data.readUnsignedByte();
data.position = position;
if (tag == ErlByte.TAG)
{
ErlByte erlByte = new ErlByte(0);
erlByte.bytesRead(data);
return erlByte;
}
else if (tag == ErlByteArray.TAG)
{
ErlByteArray erlByteArray = new ErlByteArray(null);
erlByteArray.bytesRead(data);
return erlByteArray;
}
else if (tag == ErlInt.TAG)
{
ErlInt erlInt = new ErlInt(0);
erlInt.bytesRead(data);
return erlInt;
}
else if (tag == ErlString.TAG)
{
ErlString erlString = new ErlString("");
erlString.sampleBytesRead(data);
return erlString;
}
else if (tag == ErlLong.TAG)
{
ErlLong erlLong = new ErlLong();
erlLong.bytesRead(data);
return erlLong;
}
else return null;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using Microsoft.Research.Kinect.Nui;
using System.Collections;
//using System.Timers;
using System.Diagnostics;
using System.Windows.Forms;
using System.Windows.Threading;
//using System.Windows.Threading.DispatcherTimer;
namespace KinectGesture_ArmsPosition
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Runtime nui;
int totalFrames = 0;
int lastFrames = 0;
DateTime lastTime = DateTime.MaxValue;
// We want to control how depth data gets converted into false-color data
// for more intuitive visualization, so we keep 32-bit color frame buffer versions of
// these, to be updated whenever we receive and process a 16-bit frame.
const int RED_IDX = 2;
const int GREEN_IDX = 1;
const int BLUE_IDX = 0;
byte[] depthFrame32 = new byte[320 * 240 * 4];
ArrayList sequence= new ArrayList();
private DateTime _captureCountdown = DateTime.Now;
ArrayList input = new ArrayList();
bool liveCapturing = false;
bool capture = false;
bool processing = false;
int[] previousJoint = new int[20];
ArrayList[][] recordedAngle = new ArrayList[20][]; //Saves the Angles of the gesture you record
ArrayList[][] recordedVectorAngle = new ArrayList[20][]; //Saves the vectors' directions of the gesture you record
ArrayList[][] boundaryRecordedAngle = new ArrayList[20][]; //Saves the Angles of the gesture with highest/lowest boundary you record
ArrayList[][] boundaryRecordedVectorAngle = new ArrayList[20][]; //Saves the vectors' directions of the gesture with highest/lowest boundary you record
ArrayList[] currentAngle = new ArrayList[20]; // Saves the angle of the real-time data
ArrayList[] currentVectorAngle = new ArrayList[20]; // Saves the vector direction of the real-time data
int[] alreadyInQueue = new int[200];// 200 is define as the highest number of gestures in database
ArrayList[] importantPoints = new ArrayList[20]; // This variable hold the important points of each gesture
bool captureProcessingDone = false;
double[][] range=new double[20][];
bool lowerBoundaryDone = false;
double[][] score = new double[5000][];
double penalty = 5;
double[] userCode_Direction = new double[5000];// includes the recorded directions in the current real time segmentation
double[] gestureCodePureAngle = new double[5000];// includes the saved directions for the gesture in database
double[] userCodePureAngle = new double[5000]; // includes the recorded angles in the current real time segmentation
double[] gestureCode_Direction = new double[5000];// includes the saved angles for the gesture in database
double[][] path = new double[5000][]; // This is a debugging variable for the alignment method,using this variable you can find the best match's path. Just ignore it for now
String gestureInfo = ""; // We use this variable in Saving data to file
Timer _captureCountdownTimer;
int dataBaseCounter = 0;
Dictionary<JointID, Brush> jointColors = new Dictionary<JointID, Brush>() {
{JointID.HipCenter, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
{JointID.Spine, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
{JointID.ShoulderCenter, new SolidColorBrush(Color.FromRgb(168, 230, 29))},
{JointID.Head, new SolidColorBrush(Color.FromRgb(200, 0, 0))},
{JointID.ShoulderLeft, new SolidColorBrush(Color.FromRgb(79, 84, 33))},
{JointID.ElbowLeft, new SolidColorBrush(Color.FromRgb(84, 33, 42))},
{JointID.WristLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
{JointID.HandLeft, new SolidColorBrush(Color.FromRgb(215, 86, 0))},
{JointID.ShoulderRight, new SolidColorBrush(Color.FromRgb(33, 79, 84))},
{JointID.ElbowRight, new SolidColorBrush(Color.FromRgb(33, 33, 84))},
{JointID.WristRight, new SolidColorBrush(Color.FromRgb(77, 109, 243))},
{JointID.HandRight, new SolidColorBrush(Color.FromRgb(37, 69, 243))},
{JointID.HipLeft, new SolidColorBrush(Color.FromRgb(77, 109, 243))},
{JointID.KneeLeft, new SolidColorBrush(Color.FromRgb(69, 33, 84))},
{JointID.AnkleLeft, new SolidColorBrush(Color.FromRgb(229, 170, 122))},
{JointID.FootLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
{JointID.HipRight, new SolidColorBrush(Color.FromRgb(181, 165, 213))},
{JointID.KneeRight, new SolidColorBrush(Color.FromRgb(71, 222, 76))},
{JointID.AnkleRight, new SolidColorBrush(Color.FromRgb(245, 228, 156))},
{JointID.FootRight, new SolidColorBrush(Color.FromRgb(77, 109, 243))}
};
private void Window_Loaded(object sender, EventArgs e)
{
nui = new Runtime();
#region previousJoints Assigning the start and end points that define bones
// Later on we want to calculate the angle that each "Bone" is making with the x-axis. Each bone consists of two joints
// for example the Elbow bone is the line between Elbow joint and Should Joint. So we need to have the Previous Joint for
// each of the joint so that we can define a bone for that. previousJoin[2]=3 means that previous Joint point of the point 2 (which is the left elbow) is point 3 which is left shoulder
previousJoint[0] = 1;
previousJoint[1] = 2;
previousJoint[2] = 3;
previousJoint[3] = 8;
previousJoint[4] = 5;
previousJoint[5] = 6;
previousJoint[6] = 7;
previousJoint[7] = 8;
previousJoint[8] = 19;
previousJoint[9] = 8;
previousJoint[10] = 11;
previousJoint[11] = 12;
previousJoint[12] = 13;
previousJoint[13] = 14;
previousJoint[14] = 19; // Hipcenter -> Spine
previousJoint[15] = 16;
previousJoint[16] = 17;
previousJoint[17] = 18;
previousJoint[18] = 14;
previousJoint[19] = 14; // Spine -> Hipcenter
#endregion
// Initialization
for (int i = 0; i != 20; i++)
importantPoints[i] = new ArrayList();
for (int i = 0; i != 5000; i++)
score[i] = new double[5000];
for (int i = 0; i != 5000; i++)
path[i] = new double[5000];
for (int point = 0; point != 20; point++)
{
recordedAngle[point] = new ArrayList[400]; // 0 is the database capture number
recordedAngle[point][dataBaseCounter] = new ArrayList();
recordedVectorAngle[point] = new ArrayList[400];
recordedVectorAngle[point][dataBaseCounter] = new ArrayList();
boundaryRecordedAngle[point] = new ArrayList[400]; // 0 is the database capture number
boundaryRecordedAngle[point][dataBaseCounter] = new ArrayList();
boundaryRecordedVectorAngle[point] = new ArrayList[400];
boundaryRecordedVectorAngle[point][dataBaseCounter] = new ArrayList();
currentAngle[point] = new ArrayList();
currentVectorAngle[point] = new ArrayList();
range[point] = new double[400];
range[point][dataBaseCounter] = 0;
}
try
{
nui.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
}
catch (InvalidOperationException)
{
System.Windows.MessageBox.Show("Runtime initialization failed. Please make sure Kinect device is plugged in.");
return;
}
try
{
nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
nui.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);
}
catch (InvalidOperationException)
{
System.Windows.MessageBox.Show("Failed to open stream. Please make sure to specify a supported image type and resolution.");
return;
}
lastTime = DateTime.Now;
nui.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_DepthFrameReady);
nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);
nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_ColorFrameReady);
}
void nui_ColorFrameReady(object sender, ImageFrameReadyEventArgs e)
{
// 32-bit per pixel, RGBA image
PlanarImage Image = e.ImageFrame.Image;
video.Source = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
}
void nui_DepthFrameReady(object sender, ImageFrameReadyEventArgs e)
{
PlanarImage Image = e.ImageFrame.Image;
byte[] convertedDepthFrame = convertDepthFrame(Image.Bits);
depth.Source = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, convertedDepthFrame, Image.Width * 4);
++totalFrames;
DateTime cur = DateTime.Now;
if (cur.Subtract(lastTime) > TimeSpan.FromSeconds(1))
{
int frameDiff = totalFrames - lastFrames;
lastFrames = totalFrames;
lastTime = cur;
frameRate.Text = frameDiff.ToString() + " fps";
}
}
void nui_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
SkeletonFrame skeletonFrame = e.SkeletonFrame;
int iSkeleton = 0;
Brush[] brushes = new Brush[6];
brushes[0] = new SolidColorBrush(Color.FromRgb(255, 0, 0));
brushes[1] = new SolidColorBrush(Color.FromRgb(0, 255, 0));
brushes[2] = new SolidColorBrush(Color.FromRgb(64, 255, 255));
brushes[3] = new SolidColorBrush(Color.FromRgb(255, 255, 64));
brushes[4] = new SolidColorBrush(Color.FromRgb(255, 64, 255));
brushes[5] = new SolidColorBrush(Color.FromRgb(128, 128, 255));
skeleton.Children.Clear();
foreach (SkeletonData data in skeletonFrame.Skeletons)
{
if (SkeletonTrackingState.Tracked == data.TrackingState)
{
// Draw bones
Brush brush = brushes[iSkeleton % brushes.Length];
skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.Spine, JointID.ShoulderCenter, JointID.Head));
skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderLeft, JointID.ElbowLeft, JointID.WristLeft, JointID.HandLeft));
skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.ShoulderCenter, JointID.ShoulderRight, JointID.ElbowRight, JointID.WristRight, JointID.HandRight));
skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.HipLeft, JointID.KneeLeft, JointID.AnkleLeft, JointID.FootLeft));
skeleton.Children.Add(getBodySegment(data.Joints, brush, JointID.HipCenter, JointID.HipRight, JointID.KneeRight, JointID.AnkleRight, JointID.FootRight));
var p = new Point[20];
// Draw joints
foreach (Joint joint in data.Joints)
{
Point jointPos = getDisplayPosition(joint);
Line jointLine = new Line();
jointLine.X1 = jointPos.X - 3;
jointLine.X2 = jointLine.X1 + 6;
jointLine.Y1 = jointLine.Y2 = jointPos.Y;
jointLine.Stroke = jointColors[joint.ID];
jointLine.StrokeThickness = 6;
skeleton.Children.Add(jointLine);
switch (joint.ID)
{
case JointID.HandLeft:
p[0] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.WristLeft:
p[1] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.ElbowLeft:
p[2] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.ShoulderLeft:
p[3] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.HandRight:
p[4] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.WristRight:
p[5] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.ElbowRight:
p[6] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.ShoulderRight:
p[7] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.ShoulderCenter:
p[8] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.Head:
p[9] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.FootLeft:
p[10] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.AnkleLeft:
p[11] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.KneeLeft:
p[12] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.HipLeft:
p[13] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.HipCenter:
p[14] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.FootRight:
p[15] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.AnkleRight:
p[16] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.KneeRight:
p[17] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.HipRight:
p[18] = new Point(joint.Position.X, joint.Position.Y);
break;
case JointID.Spine:
p[19] = new Point(joint.Position.X, joint.Position.Y);
break;
}
}
if (capture) // If we are in the Recording phase,add the joints data to the sequence variable
{
sequence.Add(p);
}
if (sequence.Count > 80 && !processing) // PROCESSING THE CAPTURED SEQUENCE
{
status.Text = "Captured!";
capture = false;
processing = true;
#region Calculate The Angle that each bone is making with the x-axis
for (int pointNum = 0; pointNum != 7; pointNum++)
{
for (int i = 0; i != sequence.Count; i++)
{
double yDif = ((Point[])sequence[i])[pointNum].Y - ((Point[])sequence[i])[previousJoint[pointNum]].Y;
double xDif = ((Point[])sequence[i])[pointNum].X - ((Point[])sequence[i])[previousJoint[pointNum]].X;
double d1 = new double();
if (xDif != 0) d1 = (Math.Atan(yDif / xDif) * 180 / Math.PI);
else if (yDif > 0) d1 = 90;
else if (yDif < 0) d1 = -90;
else d1 = 0;
recordedAngle[pointNum][dataBaseCounter].Add((double)(int)d1);
}
#endregion
#region Calculate the Direction of the Vectors between frames
int zeroCounter = 0;
int zeroStartIndex = 0;
//Each Joint is compared to ITSELF in 15 frames later and a vector is drawn from the joint in frame x1 to the same joint in frame x1+1
for (int i = 0; i != sequence.Count - 15; i++)
{
//vector direction is calculated using the formula : (y2-y2/x2-x1) y2 and x2 are the positions of the same joints in 15 frames later than x1 and y1
double xFrameDif = ((Point[])sequence[i])[pointNum].X - ((Point[])sequence[i + 15])[pointNum].X;
double yFrameDif = ((Point[])sequence[i])[pointNum].Y - ((Point[])sequence[i + 15])[pointNum].Y;
double angle = new double();
if (xFrameDif != 0) angle = Math.Atan(yFrameDif / xFrameDif) * (180 / Math.PI);
else if (yFrameDif > 0) angle = 90;
else if (yFrameDif < 0) angle = -90;
if (yFrameDif == 0 && xFrameDif >= 0) angle = 0;
if (yFrameDif == 0 && xFrameDif < 0) angle = 180;
angle = Math.Round(angle, 2);
//We calculate the vector size
double vectorSize = Math.Sqrt(Math.Pow(xFrameDif, 2) + Math.Pow(yFrameDif, 2));
vectorSize = (int)(vectorSize * 100);
// I want to trim the data that I record,because many times the users stays still
// at the first frames or last frames and it's not part of the gesture
// So I need to find the constant points in the movements
if (vectorSize <= 5)
{
//If the vector size was less than 5 it means that the joints hasn't moved within 15 frames but
// we still cannot say it's a constant point because it might be caused by noises, so we wait for
// 4 more Zeros to receive to say that the point has been constant
if (zeroCounter == 0) zeroStartIndex = recordedVectorAngle[pointNum][dataBaseCounter].Count-1; // I save the frame number that the Zeros has started in, so that if the zeros were
//more than 4 I can just trim the data from the starting frame
if (zeroStartIndex < 0) zeroStartIndex = 0;
recordedVectorAngle[pointNum][dataBaseCounter].Add(400.0); // 400 is the number I assign instead of Zero
zeroCounter++;
}
else
{
// If the Zeros were disturbed in the middle, I say zeroCounter-=2 but I do not say Zero Counter=0
// because the Non-Zero number could be a noise. for example I have Zeros in 000100 and they have been disturbed by a 1
// I want to be able to trim that as well.
zeroCounter -= 2;
if (zeroCounter < 0) zeroCounter = 0; // Sentinel
recordedVectorAngle[pointNum][dataBaseCounter].Add(angle);
// If the point has not been a constant point I consider it as an important point in the gesture
// Writing this comment I just realized that I need to enhance this part a little because some noises might
//be added here as well
if (!importantPoints[dataBaseCounter].Contains(pointNum))
{
importantPoints[dataBaseCounter].Add(pointNum);
}
}
if (zeroCounter >= 4)
{
// Here we are ! We just recognized some non-moving event happening ! We don't need it
// Lets just Trim !
recordedVectorAngle[pointNum][dataBaseCounter].RemoveRange(zeroStartIndex, 4);
recordedAngle[pointNum][dataBaseCounter].RemoveRange(zeroStartIndex, 4);
zeroCounter = 0;
zeroStartIndex = 0;
}
}
}
#endregion
// Processing The Captured data is finished here so we prepare for receiving the boundaries
wait(40000000);
status.Text = "Upper Boundary";
sequence.Clear();
captureProcessingDone = true;
capture = true;
txtSavedVectorAngles.Clear();
txtSavedAngles.Clear();
dataBaseCounter++;
}
if (captureProcessingDone && sequence.Count > 80)
{
status.Text = "Captured!";
capture = false;
processing = true;
captureProcessingDone = false;
#region Calculate The Angle that each bone is making with the x-axis
for (int pointNum = 0; pointNum != 7; pointNum++)
{
for (int i = 0; i != sequence.Count; i++)
{
double yDif = ((Point[])sequence[i])[pointNum].Y - ((Point[])sequence[i])[previousJoint[pointNum]].Y;
double xDif = ((Point[])sequence[i])[pointNum].X - ((Point[])sequence[i])[previousJoint[pointNum]].X;
double d1 = new double();
if (xDif != 0) d1 = (Math.Atan(yDif / xDif) * 180 / Math.PI);
else if (yDif > 0) d1 = 90;
else if (yDif < 0) d1 = -90;
else d1 = 0;
boundaryRecordedAngle[pointNum][dataBaseCounter-1].Add((double)(int)d1); // TO DO: fix
}
#endregion
#region Calculate the Direction of the Vectors between frames
for (int i = 0; i != sequence.Count - 15; i++)
{
double xFrameDif = ((Point[])sequence[i])[pointNum].X - ((Point[])sequence[i + 15])[pointNum].X;
double yFrameDif = ((Point[])sequence[i])[pointNum].Y - ((Point[])sequence[i + 15])[pointNum].Y;
double angle = new double();
if (xFrameDif != 0) angle = Math.Atan(yFrameDif / xFrameDif) * (180 / Math.PI);
else if (yFrameDif > 0) angle = 90;
else if (yFrameDif < 0) angle = -90;
if (yFrameDif == 0 && xFrameDif >= 0) angle = 0;
if (yFrameDif == 0 && xFrameDif < 0) angle = 180;
double tool = Math.Sqrt(Math.Pow(xFrameDif, 2) + Math.Pow(yFrameDif, 2));
tool = (int)(tool * 100);
angle = Math.Round(angle, 2);
if (tool <= 5)
{
boundaryRecordedVectorAngle[pointNum][dataBaseCounter - 1].Add(400.0);
}
else
{
boundaryRecordedVectorAngle[pointNum][dataBaseCounter - 1].Add(angle);
}
}
}
#endregion
// Processing The Second Captured data is finished here, we prepare for lower boundary
align2(dataBaseCounter - 1, 80, 0);
if (!lowerBoundaryDone)
{
wait(40000000);
txtSavedVectorSizes.Clear();
status.Text = "Lower Boundary";
lowerBoundaryDone = true;
sequence.Clear();
captureProcessingDone = true;
capture = true; // NEXT level
}
// We have all the boundaries information lets just start recognizing realtime gestures
else
{
wait(40000000);
liveCapturing = true;
status.Text = "LIVE!";
}
}
#region Almost the same calculations that we did when recording the data,the different is that in that time we had all the data saved but here it just updates and we calculate everything live time
else if (liveCapturing)
{
input.Add(p);
double d1 = new double();
double angle = new double();
double tool = new double();
for (int pointNum = 0; pointNum != 7; pointNum++)
{
double xDif4Angle = ((Point[])input[input.Count - 1])[pointNum].X - ((Point[])input[input.Count - 1])[previousJoint[pointNum]].X;
double yDif4Angle = ((Point[])input[input.Count - 1])[pointNum].Y - ((Point[])input[input.Count - 1])[previousJoint[pointNum]].Y;
if (xDif4Angle != 0) d1 = (Math.Atan(yDif4Angle / xDif4Angle) * 180 / Math.PI);
else if (yDif4Angle > 0) d1 = 90;
else if (yDif4Angle < 0) d1 = -90;
else d1 = 0;
currentAngle[pointNum].Add((double)(int)d1); // for example currentAngle[2][0] is the angle of point 2 (left wrist) in the 0(first) frame
if (input.Count > 15)
{
double xFrameDif = ((Point[])input[input.Count - 16])[pointNum].X - ((Point[])input[input.Count - 1])[pointNum].X;
double yFrameDif = ((Point[])input[input.Count - 16])[pointNum].Y - ((Point[])input[input.Count - 1])[pointNum].Y;
if (xFrameDif != 0) angle = Math.Atan(yFrameDif / xFrameDif) * (180 / Math.PI);
else if (yFrameDif > 0) angle = 90;
else if (yFrameDif < 0) angle = -90;
if (yFrameDif == 0 && xFrameDif >= 0) angle = 0;
if (yFrameDif == 0 && xFrameDif < 0) angle = 180;
tool = Math.Sqrt(Math.Pow(xFrameDif, 2) + Math.Pow(yFrameDif, 2));
tool = (int)(tool * 100);
angle = Math.Round(angle, 2);
if (tool <= 5)
{
currentVectorAngle[pointNum].Add(400.0);
}
else
{
currentVectorAngle[pointNum].Add(angle);
}
}
}
#endregion
#region After each frame we check whether we a gesture has been performed
double _Thr = 15; // TODO: CALCULATE CORRECT Threshhold
int correctCounter = 0;
// Clearing data each 400 frames
if (input.Count > 400)
{
input.RemoveRange(0, 400 - 70);
for (int i = 0; i != dataBaseCounter; i++)
{
alreadyInQueue[0] = 0;
alreadyInQueue[1] = 0;
}
for (int k = 0; k != 7; k++)
{
currentAngle[k].RemoveRange(0,400-70);
currentVectorAngle[k].RemoveRange(0,400-70);
}
textBox5.Clear();
gestureL.Clear();
textBox3.Clear();
for (int t = 0; t != 300; t++)
for (int j = 0; j != 300; j++)
score[t][j] = 0;
}
// Segmentation
// Segmentation part is not complete,it has to be enhanced a lot more. Currently we check the first angle of the current movement with the first of the one in the database and
// if they were almost equal we sent the data frame that frame to 70 frames later to the alignment method
// The thing that needs to be considered is that we are not just having one joint, so the first frame's angles should be checked
// for all the joints involved in the gesture (which are already recognized as "importantPoint"). if more than 80% of the
// points satisfied the condition we segment the data.
// NOTE on "alreadyInQueue" variable:
// As we are having a threshold for the equality of angles, an angle may be considered equal whenever it is within a range
// so for example frames x1,x1+1,x1+2 till x1+10 will satisfy the condition and starting from each of them to 70 frames later
// the data wil be segmented and sent to the alignment method.We just need one in every ten frames, so if another segmentation was going to
// be sent within 10 frames from the current frame we just ignore it.
for (int dataBaseRec = 0; dataBaseRec != dataBaseCounter && (input.Count - 1 > 70); dataBaseRec++) // for each Record in database check
{
correctCounter = 0;
if ((input.Count - alreadyInQueue[dataBaseRec] < 10 && (alreadyInQueue[dataBaseRec]) != 0)) continue;
for (int po = 0; po != importantPoints[dataBaseRec].Count; po++)
{
if (Math.Abs((double)(currentAngle[(int)(importantPoints[dataBaseRec][po])])[currentAngle[(int)(importantPoints[dataBaseRec][po])].Count - 1] - (double)(recordedAngle[(int)(importantPoints[dataBaseRec][po])][dataBaseRec][(recordedAngle[(int)(importantPoints[dataBaseRec][po])][dataBaseRec].Count) - 1])) < _Thr)
{ // if currentAngle[in noghte] dar [in lahze] az recordedAngle [hamoon noghte] dar [folan record] dar [lahzeyeh avval] ekhtelafe kami dasht:
correctCounter++;
}
}
if (correctCounter >= (int)(importantPoints[dataBaseRec].Count * 0.8)) // 80% of number of points
{
//We need to check the boundaries here
// IF True go on
double finalScore = align(dataBaseRec, input.Count - 1, input.Count - 1 -70);
if (finalScore == 1) textBox3.Text += dataBaseRec.ToString()+" ";
textBox5.Text += score.ToString();
gestureL.Text += input.Count;//"aligned with "+dataBaseIndex.ToString();
alreadyInQueue[dataBaseRec] = input.Count;
}
correctCounter = 0;
}
#endregion
}
}
iSkeleton++;
} // for each skeleton
}
byte[] convertDepthFrame(byte[] depthFrame16)
{
for (int i16 = 0, i32 = 0; i16 < depthFrame16.Length && i32 < depthFrame32.Length; i16 += 2, i32 += 4)
{
int player = depthFrame16[i16] & 0x07;
int realDepth = (depthFrame16[i16 + 1] << 5) | (depthFrame16[i16] >> 3);
// transform 13-bit depth information into an 8-bit intensity appropriate
// for display (we disregard information in most significant bit)
byte intensity = (byte)(255 - (255 * realDepth / 0x0fff));
depthFrame32[i32 + RED_IDX] = 0;
depthFrame32[i32 + GREEN_IDX] = 0;
depthFrame32[i32 + BLUE_IDX] = 0;
// choose different display colors based on player
switch (player)
{
case 0:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 2);
break;
case 1:
depthFrame32[i32 + RED_IDX] = intensity;
break;
case 2:
depthFrame32[i32 + GREEN_IDX] = intensity;
break;
case 3:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 4);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 4:
depthFrame32[i32 + RED_IDX] = (byte)(intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 4);
break;
case 5:
depthFrame32[i32 + RED_IDX] = (byte)(intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 4);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 6:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 7:
depthFrame32[i32 + RED_IDX] = (byte)(255 - intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(255 - intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(255 - intensity);
break;
}
}
return depthFrame32;
}
private Point getDisplayPosition(Joint joint)
{
float depthX, depthY;
nui.SkeletonEngine.SkeletonToDepthImage(joint.Position, out depthX, out depthY);
depthX = Math.Max(0, Math.Min(depthX * 320, 320)); //convert to 320, 240 space
depthY = Math.Max(0, Math.Min(depthY * 240, 240)); //convert to 320, 240 space
int colorX, colorY;
ImageViewArea iv = new ImageViewArea();
// only ImageResolution.Resolution640x480 is supported at this point
nui.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, iv, (int)depthX, (int)depthY, (short)0, out colorX, out colorY);
// map back to skeleton.Width & skeleton.Height
return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
}
Polyline getBodySegment(Microsoft.Research.Kinect.Nui.JointsCollection joints, Brush brush, params JointID[] ids)
{
PointCollection points = new PointCollection(ids.Length);
for (int i = 0; i < ids.Length; ++i)
{
points.Add(getDisplayPosition(joints[ids[i]]));
}
Polyline polyline = new Polyline();
polyline.Points = points;
polyline.Stroke = brush;
polyline.StrokeThickness = 5;
return polyline;
}
private void Window_Closed(object sender, EventArgs e)
{
nui.Uninitialize();
Environment.Exit(0);
}
private void btnRecord_Click(object sender, RoutedEventArgs e)
{
//status.Text = "Waiting Three Seconds";
wait(40000000);
// System.Windows.Forms.MessageBox.Show("Test");
status.Text = "Recording";
gestureL.Clear();
gestureR.Clear();
textBox1.Clear();
textBox2.Clear();
textBox3.Text += ">";
textBox4.Text += ">";
sequence.Clear();
txtCurrentVectorAngles.Text += ">";
txtCurrentAngles.Text += ">";
txtCurrentVectorSizes.Text += ">";
txtSavedAngles.Text += ">";
txtSavedVectorAngles.Text += ">";
txtSavedVectorSizes.Text += ">";
textBox5.Clear();
liveCapturing = false;
for (int k = 0; k != 200; k++)
alreadyInQueue[k] = 0;//200 is the most number of gestures in database
for (int point = 0; point != 20; point++)
{
recordedAngle[point][dataBaseCounter] = new ArrayList();
recordedVectorAngle[point][dataBaseCounter] = new ArrayList();
boundaryRecordedAngle[point][dataBaseCounter] = new ArrayList();
boundaryRecordedVectorAngle[point][dataBaseCounter] = new ArrayList();
range[point][dataBaseCounter] = 0;
}
processing = false;
capture = true;
}
private void wait(long ticks)
{
long dtEnd = DateTime.Now.AddTicks(ticks).Ticks;
int count = 0;
while (DateTime.Now.Ticks < dtEnd)
{
status.Text = ((count / 10000) + 1).ToString();
count++;
this.Dispatcher.Invoke(DispatcherPriority.Background, (DispatcherOperationCallback)delegate(object unused) { return null; }, null);
}
}
double align(int dataBaseIndex,int endFrame,int startFrame)
{
// Dynamic Alignment Method
// Whenever we segmented a real-time data it will be sent to this method and we will align it with the basic saved gesture
// The alignment has a score and if the score was within a range that we have already defined, it will be considered as a valid gesture.
int maxCounter = 0;
int numberOfPoints = importantPoints[dataBaseIndex].Count;
for (int pointNum = 0; pointNum != numberOfPoints; pointNum++)
{
// score[][] is the Dynamic Matrix that we fill
// for more information on Dynamic Programming refer to "Introduction to Algorithms" By Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein - MIT Press
// for more information on DTW and other dynamic alignment methods refer to Wikipedia or other papers
// I have define a linear gap penalty and free end gaps(no penalty for gaps at start and end of the alignment)
score[0][0] = 0;
for (int i = 1; i != recordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count+1; i++)
{
gestureCode_Direction[i] = (double)(recordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex])[i - 1];
}
int gestureSize = recordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count;
for (int i = startFrame+1; i != (endFrame - 15) + 1+1; i++)
{
userCode_Direction[(i - startFrame)] = (double)(currentVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]])[i-1]; //indexing starts from 1 (0 is sentinel)
}
int userSize = (endFrame - 15+1) - (startFrame + 1)+1;
for (int i = 1; i != recordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count+1; i++)
{
gestureCodePureAngle[i] = (double)(recordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex])[i - 1];
}
int gestureAngleSize = recordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count;
for (int i = startFrame+1; i != endFrame + 1+1; i++)
{
userCodePureAngle[(i - startFrame)] = (double)(currentAngle[(int)importantPoints[dataBaseIndex][pointNum]])[i-1];
}
for (int j = 0; j != gestureCode_Direction.Length; j++) score[0][j] = 0;
for (int j = 0; j != userCode_Direction.Length; j++) score[j][0] = 0;
int previousGap1 = 1;
int previousGap2 = 1;
for (int i = 0; i != 5000; i++)
{
path[0][i] = 2;
path[i][0] = 1;
}
for (int j = 1; j != gestureSize + 1; j++)
for (int i = 1; i != userSize + 1; i++)
{
double max = -50000;
if (j == gestureSize)
{
if (score[i - 1][j] > score[i][j - 1] - (penalty * previousGap2))
{
max = score[i - 1][j];
score[i][j] = score[i - 1][j];
path[i][j] = 1;
}
else
{
max = score[i][j - 1] - (penalty * previousGap2);
score[i][j] = score[i][j - 1] - (penalty * previousGap2);
path[i][j] = 2;
previousGap2++;
previousGap1 = 1;
}
if (score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10) > max)
{
max = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
score[i][j] = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
path[i][j] = 3;
previousGap1 = 1;
previousGap2 = 1;
}
}
else
{
if (score[i - 1][j] - (penalty * previousGap1) > score[i][j - 1] - (penalty * previousGap2))
{
max = score[i - 1][j] - (penalty * previousGap1);
score[i][j] = score[i - 1][j] - (penalty * previousGap1);
path[i][j] = 1;
previousGap1++;
previousGap2 = 1;
}
else
{
max = score[i][j - 1] - (penalty * previousGap2);
score[i][j] = score[i][j - 1] - (penalty * previousGap2);
path[i][j] = 2;
previousGap2++;
previousGap1 = 1;
}
if (score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10) > max)
{
max = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
score[i][j] = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
path[i][j] = 3;
previousGap1 = 1;
previousGap2 = 1;
}
}
}
int maxScore =(gestureSize - 1) * 35;
textBox5.Text += "Point[" + ((int)importantPoints[dataBaseIndex][pointNum]).ToString() + "] = " + (maxScore - score[userSize][gestureSize]).ToString() + " ";
if (maxScore - score[userSize][gestureSize] <= range[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex]+200)
maxCounter++;
}
if (maxCounter >= numberOfPoints * 0.8)
return 1; // To EDIT
else return 0;
}
// SORRY guys I know I'm doing this so dirty but I really don't have time!
// This function aligns the Upper Boundary with the Basic Gesture and also the Lower Boundary with the Basic Gesture
// The returning value is a Range of Alignment Scores(for each point) that a gesture should gain to be valid
double align2(int dataBaseIndex, int endFrame, int startFrame)
{
int numberOfPoints = importantPoints[dataBaseIndex].Count;
for (int pointNum = 0; pointNum != importantPoints[dataBaseIndex].Count; pointNum++)
{
score[0][0] = 0;
for (int i = 1; i != recordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count+1; i++)
{
gestureCode_Direction[i] = (double)(recordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex])[i - 1];
}
int gestureSize = recordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count;
for (int i = startFrame + 1; i != (endFrame - 15) + 1+1; i++)
{
userCode_Direction[(i - startFrame)] = (double)(boundaryRecordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex])[i - 1]; //indexing starts from 1 (0 is sentinel)
}
int userSize = (endFrame - 15+1) - (startFrame + 1)+1;
for (int i = 1; i != recordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count+1; i++)
{
gestureCodePureAngle[i] = (double)(recordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex])[i - 1];
}
int gestureAngleSize = recordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Count;
for (int i = startFrame + 1; i != endFrame + 1+1; i++)
{
userCodePureAngle[(i - startFrame)] = (double)(boundaryRecordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex])[i - 1];
}
for (int j = 0; j != gestureCode_Direction.Length; j++) score[0][j] = 0;
for (int j = 0; j != userCode_Direction.Length; j++) score[j][0] = 0;
int previousGap1 = 1;
int previousGap2 = 1;
for (int i = 0; i != 5000; i++)
{
path[0][i] = 2;
path[i][0] = 1;
}
for (int j = 1; j != gestureSize + 1; j++)
for (int i = 1; i != userSize + 1; i++)
{
double max = -50000;
if (j == gestureSize)
{
if (score[i - 1][j] > score[i][j - 1] - (penalty * previousGap2))
{
max = score[i - 1][j];
score[i][j] = score[i - 1][j];
path[i][j] = 1;
}
else
{
max = score[i][j - 1] - (penalty * previousGap2);
score[i][j] = score[i][j - 1] - (penalty * previousGap2);
path[i][j] = 2;
previousGap2++;
previousGap1 = 1;
}
if (score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10) > max)
{
max = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
score[i][j] = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
path[i][j] = 3;
previousGap1 = 1;
previousGap2 = 1;
}
}
else
{
if (score[i - 1][j] - (penalty * previousGap1) > score[i][j - 1] - (penalty * previousGap2))
{
max = score[i - 1][j] - (penalty * previousGap1);
score[i][j] = score[i - 1][j] - (penalty * previousGap1);
path[i][j] = 1;
previousGap1++;
previousGap2 = 1;
}
else
{
max = score[i][j - 1] - (penalty * previousGap2);
score[i][j] = score[i][j - 1] - (penalty * previousGap2);
path[i][j] = 2;
previousGap2++;
previousGap1 = 1;
}
if (score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10) > max)
{
max = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
score[i][j] = score[i - 1][j - 1] + distance(userCode_Direction[i] - gestureCode_Direction[j], 25) + distance(userCodePureAngle[i] - gestureCodePureAngle[j], 10);
path[i][j] = 3;
previousGap1 = 1;
previousGap2 = 1;
}
}
}
int maxScore = (gestureSize-1)*35;
double difference = maxScore - score[userSize][gestureSize];
if (difference > range[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex])
range[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex] = difference;
boundaryRecordedVectorAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Clear();
boundaryRecordedAngle[(int)importantPoints[dataBaseIndex][pointNum]][dataBaseIndex].Clear();
}
return 0;
}
double distance(double x1, double x2)
{
// Instead of just calculating the difference between two vectors or two angles
// we calculate a distance which is a function of the difference.
// So if the difference was less than 10 the distance is 25(you can change)for vectors and 10 for angles and so on
double x = Math.Abs(x1);
double score = 0;
if (x <= 10) score = x2;
else if (x <= 30) score = x2 + 10 - 0.4 * x;
else score = x2 + 10 - x;
return score;
}
private void depth_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
}
private void button1_Click(object sender, RoutedEventArgs e)
{
// Record Number
gestureInfo += "N "+(dataBaseCounter-1).ToString() ; // Showing start of Important Points
// Save Important Points
gestureInfo += "\r\nP"; // Showing start of Important Points
for (int i = 0; i!=importantPoints[dataBaseCounter - 1].Count; i++)
{
gestureInfo += importantPoints[dataBaseCounter - 1][i].ToString()+ " ";
}
// Save Range for each of Important Points
gestureInfo += "\r\nR"; // Showing start of Range
for (int i = 0; i != importantPoints[dataBaseCounter - 1].Count; i++)
{
gestureInfo += range[(int)importantPoints[dataBaseCounter - 1][i]][dataBaseCounter-1].ToString()+ " ";
}
//Save Angles
gestureInfo += "\r\n@"; // Showing start of Angles
for (int P = 0; P != importantPoints[dataBaseCounter - 1].Count; P++)
{
for (int i = 0; i != recordedAngle[(int)importantPoints[dataBaseCounter - 1][P]][dataBaseCounter - 1].Count; i++)
gestureInfo += recordedAngle[(int)importantPoints[dataBaseCounter - 1][P]][dataBaseCounter - 1][i].ToString() + " ";
gestureInfo += "End ";
}
//Save Vector Angles
gestureInfo += "\r\nV";// Showing start of Vectors
for (int P = 0; P != importantPoints[dataBaseCounter - 1].Count; P++)
{
for (int i = 0; i != recordedVectorAngle[(int)importantPoints[dataBaseCounter - 1][P]][dataBaseCounter - 1].Count; i++)
gestureInfo += recordedVectorAngle[(int)importantPoints[dataBaseCounter - 1][P]][dataBaseCounter - 1][i].ToString() + " ";
gestureInfo += "End ";
}
string fileName = "Gesture" + (dataBaseCounter-1).ToString()+ participantNum.Text + ".txt";
System.IO.File.WriteAllText(@"C:\HCI Lab\" + fileName,gestureInfo);
status.Text = "Saved to " + fileName;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
dlg.InitialDirectory = @"C:\HCI Lab\";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
LoadGesturesFromFile(dlg.FileName);
//dtwTextOutput.Text = _dtw.RetrieveText();
status.Text = "Gestures loaded!";
}
}
public void LoadGesturesFromFile(string fileLocation)
{
int itemCount = 0;
string[] line=new string[20];
string block;
string gestureName = String.Empty;
ArrayList frames = new ArrayList();
double[] items = new double[12];
int recordNumber=0;
int[] loadedImportantPoints=new int[20];
int numberOfImportantPoints = 0;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(fileLocation);
block = file.ReadToEnd();
line[0] = block.Split('P')[0]; //N block
block = block.Split('P')[1];
line[1] = block.Split('R')[0]; // P block
int[] lineSize=new int[20];
block = block.Split('R')[1];
line[2] = block.Split('@')[0]; // R block
block = block.Split('@')[1];
line[3] = block.Split('V')[0]; // @ block
block = block.Split('V')[1];
line[4] = block;// V block
recordNumber = Convert.ToInt32(line[0].Split(' ')[1]);
//initialization
for (int point = 0; point != 20; point++)
{
recordedAngle[point][recordNumber] = new ArrayList();
recordedVectorAngle[point][recordNumber] = new ArrayList();
boundaryRecordedAngle[point][recordNumber] = new ArrayList();
boundaryRecordedVectorAngle[point][recordNumber] = new ArrayList();
range[point][recordNumber] = 0;
}
dataBaseCounter++;
char[] space = new char[1];
// space[0]=' ';
// line[1] = line[1].Remove(lineSize[1]-2,2);
// line[1] = line[1].Remove(0, 2); // Remove "P "
lineSize[1] = line[1].Split(' ').Count() - 2;
for (int i = 0; i != lineSize[1]+1; i++)
{
loadedImportantPoints[i] = Convert.ToInt32(line[1].Split(' ')[i]);
importantPoints[recordNumber].Add(loadedImportantPoints[i]);
numberOfImportantPoints++;
}
//line[3] = line[3].Remove(0, 2); // Remove "@ "
string[] angles = line[3].Split(' ');
int nextIndex = 0;
for (int i = 0;i!=numberOfImportantPoints; i++)
{
for (int j = nextIndex; angles[j] != "End"; j++) //2 for spaces
{
recordedAngle[loadedImportantPoints[i]][recordNumber].Add(Convert.ToDouble(angles[j]));
nextIndex = j + 2;
}
}
//line[2] = line[2].Remove(0, 2);
for (int i = 0; i != numberOfImportantPoints; i++)
{
range[loadedImportantPoints[i]][recordNumber] = Convert.ToDouble(line[2].Split(' ')[i]);
}
itemCount++;
// line[4] = line[4].Remove(0, 2); // Remove "@ "
string[] vectorAngles = line[4].Split(' ');
nextIndex = 0;
for (int i = 0; i != numberOfImportantPoints; i++)
{
for (int j = nextIndex; vectorAngles[j] != "End"; j++) //2 for spaces
{
recordedVectorAngle[loadedImportantPoints[i]][recordNumber].Add(Convert.ToDouble(vectorAngles[j]));
nextIndex = j + 2; //if we are already at the end,next step is "j+1" so next number is "j+2"
}
}
file.Close();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
wait(40000000);
liveCapturing = true;
status.Text = "LIVE!";
}
}
}
|
using RGB.NET.Core;
using System;
namespace RGB.NET.Devices.CorsairLink
{
/// <inheritdoc />
/// <summary>
/// Represents a generic information for a Corsair Link-<see cref="T:RGB.NET.Core.IRGBDevice" />.
/// </summary>
public class CorsairLinkRGBDeviceInfo : IRGBDeviceInfo
{
// we could add parameters for stuff like the url here
#region Properties & Fields
public RGBDeviceType DeviceType => RGBDeviceType.LedStripe;
public string Manufacturer => "Corsair";
public string Model => "Link";
public RGBDeviceLighting Lighting => RGBDeviceLighting.Device;
public Uri Image { get; set; }
public bool SupportsSyncBack => false;
#endregion
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.