text stringlengths 13 6.01M |
|---|
using Microsoft.Owin;
using Owin;
using Swashbuckle;
using System.Web.Http;
[assembly: OwinStartupAttribute(typeof(Cognology.FlightBookingApp.Startup))]
namespace Cognology.FlightBookingApp
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
HttpConfiguration configuration = new HttpConfiguration();
Bootstrapper.Init(configuration);
}
}
}
|
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 TubesAI
{
public partial class MessageForm : Form
{
public MessageForm(string SQLScript, string error)
{
InitializeComponent();
ScriptBox.Text = SQLScript;
MessageError.Text = error;
}
private void MessageForm_FormClosed(object sender, FormClosedEventArgs e)
{
DatabaseScript.ErrorForm = new MessageForm("","");
}
}
}
|
// Copyright (c) Simple Injector Contributors. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for license information.
namespace SimpleInjector.Advanced
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Threading;
using SimpleInjector.Internals;
#if NET40 || NET45
internal sealed partial class PropertyInjectionHelper
{
private static long injectorClassCounter;
partial void TryCompileLambdaInDynamicAssembly(LambdaExpression expression, ref Delegate? compiledDelegate)
{
compiledDelegate = null;
if (this.container.Options.EnableDynamicAssemblyCompilation &&
!CompilationHelpers.ExpressionNeedsAccessToInternals(expression))
{
compiledDelegate = CompileLambdaInDynamicAssemblyWithFallback(expression);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Not all delegates can be JITted. We fall back to the slower expression.Compile " +
"in that case.")]
private static Delegate? CompileLambdaInDynamicAssemblyWithFallback(LambdaExpression expression)
{
try
{
var @delegate = CompilationHelpers.CompileLambdaInDynamicAssembly(expression,
"DynamicPropertyInjector" + GetNextInjectorClassId(),
"InjectProperties");
// Test the creation. Since we're using a dynamically created assembly, we can't create every
// delegate we can create using expression.Compile(), so we need to test this.
CompilationHelpers.JitCompileDelegate(@delegate);
return @delegate;
}
catch
{
return null;
}
}
private static long GetNextInjectorClassId() => Interlocked.Increment(ref injectorClassCounter);
}
#endif
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System.IO; //System.IO.FileInfo, System.IO.StreamReader, System.IO.StreamWriter
using System; //Exception
using System.Text;
using MiniJSON;
//using CityCreater;
public class CameraMove : MonoBehaviour {
const float SPEED = 0.1f;
public Canvas canvas;
public Text file_name;
private string src_txt = "";
public CityCreater cc;
public string ta;
private bool view_src;
// Use this for initialization
void Start () {
view_src = true;
cc = GameObject.Find ("CityCreater").GetComponent<CityCreater> ();
foreach( Transform child in canvas.transform){
file_name = child.gameObject.GetComponent<Text>();
// file_name = GameObject.Find("Text");
file_name.text = "";
}
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.UpArrow)){
GetComponent<Rigidbody>().velocity = transform.forward * 100.0f;
}
if(Input.GetKey(KeyCode.LeftArrow)){
//GetComponent<Rigidbody>().velocity = transform.right * -100.0f;
transform.Rotate(new Vector3(0,-0.8f,0));
}
if(Input.GetKey(KeyCode.DownArrow)){
GetComponent<Rigidbody>().velocity = transform.forward * -100.0f;
}
if(Input.GetKey(KeyCode.RightArrow)){
//GetComponent<Rigidbody>().velocity = transform.right * 100.0f;
transform.Rotate(new Vector3(0,0.8f,0));
}
if (Input.GetKey (KeyCode.Space)) {
GetComponent<Rigidbody>().velocity = transform.up * 100.0f;
}
if (Input.GetKey (KeyCode.V)) {
view_src = true;
}
if (Input.GetKey (KeyCode.H)) {
view_src = false;
}
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast (transform.position, fwd, out hit, 10000)) {
if (hit.transform.name != file_name.text){
var prev = GameObject.Find (file_name.text);
var next = GameObject.Find (hit.transform.name);
var path = SearchPathFromFileName(hit.transform.name);
src_txt = ReadFile(path);
file_name.text = hit.transform.name;
if (prev)
prev.GetComponent<Renderer>().material.color = Color.white;
next.GetComponent<Renderer>().material.color = Color.red;
}
} else {
var prev = GameObject.Find (file_name.text);
if (prev)
prev.GetComponent<Renderer>().material.color = Color.white;
file_name.text = "";
}
// this.transform.Translate ( 0, 0,( Input.GetAxis ( "Vertical" ) * 1 ) );
// this.transform.Rotate (0,( Input.GetAxis ("Horizontal" ) * 1 ),0);
}
void OnGUI()
{
if(view_src)
src_txt = GUI.TextArea (new Rect (5, 5, Screen.width-10, Screen.height-100), src_txt);
}
/*
void OnGUI () {
// ラベルを表示する
GUI.Label(new Rect(10,10,100,100), “MenuWindow”);
}
*/
void OnCollisionEnter(Collision collision){
//file_name.text = collision.transform.name;
}
void OnCollisionExit(Collision collision){
//file_name.text = "";
}
string ReadFile(string path){
// FileReadTest.txtファイルを読み込む
Debug.Log (path);
FileInfo fi = new FileInfo(path);
string st = "";
try {
// 一行毎読み込み
using (StreamReader sr = new StreamReader(fi.OpenRead(), Encoding.UTF8)){
st = sr.ReadToEnd();
}
} catch (Exception e){
// 改行コード
st += SetDefaultText();
}
return st;
}
string SearchPathFromFileName(string file_name){
string path = "";
IList buildings = cc.GetCity()["buildings"] as IList;
foreach (Dictionary<string,object> building in buildings) {
if(building["name"].ToString() == file_name){
path = building["path"].ToString();
}
}
return path;
}
// 改行コード処理
string SetDefaultText(){
return "cant read\n";
}
}
|
using System.Collections.Generic;
namespace TryHardForum.ViewModels.Topic
{
public class TopicIndexModel
{
// TODO заполнить!
public int NumberOfTopics { get; set; }
public IEnumerable<TopicInformationModel> TopicList { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Nac.Common.Control {
[DataContract, Serializable]
public class NacBlockIf : NacBlockSeq {
[DataMember]
private HashSet<string> _nextTrue;
public HashSet<string> NextTrue { get { if (_nextTrue == null) _nextTrue = new HashSet<string>(); return _nextTrue; } set { _nextTrue = value; } }
public HashSet<string> NextFalse { get { return Next; } set { Next = value; } }
public override IEnumerable<string> OutputConnections { get { return NextTrue.Union(NextFalse); } }
public override void ConnectNext(string path, string connector) {
if (connector == "True") NextTrue.Add(path);
if (connector == "False") NextFalse.Add(path);
}
public override void DisconnectNext(string path, string connector) {
if (connector == "True") NextTrue.Remove(path);
if (connector == "False") NextFalse.Remove(path);
}
//public override void Dispose(bool disposing) {
// if (disposing) {
// foreach (var path in NextTrue) (Engine[path] as NacBlockSeq)?.Prev.Remove(Path);
// }
// base.Dispose(disposing);
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;// библиотека для работы с текстовыми файлами
namespace TextFiles
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\TestFolder\file.txt";//символ @ чтобы воспринимать как путь, а не escape-последовательности
StreamReader sr = new StreamReader(path);//считывание текста из файла
string line0;
//while (!sr.EndOfStream)//выводим, пока не окажемся в конце файла
//{
// line0 = sr.ReadLine();
// Console.WriteLine(line0);
//}
//while ((line0 = sr.ReadLine()) != null)//ещё один вариант вывода
//{
// Console.WriteLine(line0);
//}
int[] arr = new int[0];
int index = 0;
while ((line0 = sr.ReadLine()) != null)
{
//Console.WriteLine(line0);
Array.Resize(ref arr, arr.Length + 1);
arr[index++] = Convert.ToInt32(line0);
}
sr.Close();//закрываем ридер после того, как прочли файл, чтобы не отнимать ресурсы у системы.
int max = arr[0];
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] > max) max = arr[i];
}
StreamWriter sw = new StreamWriter(@"D:\TestFolder\maxFile.txt",true);//Запись данных в файл(флажок true мы поставили,
//чтобы файл не перезаписывался, а данные добавлялись в уже созданный файл с сохранённой информацией. По-умолчанию будет false)
sw.WriteLine("Максимальное значение");//запись данных в буфер, для того, чтобы они оказались в файле, его надо закрыть
sw.WriteLine(max);
sw.Close();//закрываем файл
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;
using CAPCO.Infrastructure.Domain;
namespace CAPCO.Infrastructure.Data
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity
{
protected readonly CAPCOContext _CapcoContext;
public Repository(CAPCOContext context)
{
_CapcoContext = context;
}
public void Detach(object entity)
{
((IObjectContextAdapter)_CapcoContext).ObjectContext.Detach(entity);
}
public IQueryable<TEntity> All
{
get { return _CapcoContext.Set<TEntity>(); }
}
public IQueryable<TEntity> AllIncluding(params Expression<Func<TEntity, object>>[] includeProperties)
{
var query = All;
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public TEntity Find(int id)
{
return _CapcoContext.Set<TEntity>().Find(id);
}
public bool InsertOrUpdate(TEntity entity)
{
try
{
_CapcoContext.Set<TEntity>().AddOrUpdate<TEntity>(entity);
}
catch
{
//TODO: Log exception
return false;
}
return true;
}
public void Delete(int id)
{
TEntity entity = Find(id);
_CapcoContext.Set<TEntity>().Remove(entity);
}
public void Save()
{
_CapcoContext.SaveChanges();
}
public IQueryable<TEntity> FindBySpecification(Specification<TEntity> specification)
{
if (specification == null)
throw new ArgumentNullException("specification", "specification is null");
var specs = new List<Specification<TEntity>> {specification};
return FindBySpecification(null, specs.ToArray());
}
public IQueryable<TEntity> FindBySpecification(params Specification<TEntity>[] specifications)
{
return FindBySpecification(null, specifications);
}
public IQueryable<TEntity> FindBySpecification(Expression<Func<TEntity, object>>[] includeProperties, params Specification<TEntity>[] specifications)
{
if (specifications == null || specifications.Any(x => x == null))
throw new ArgumentNullException("specifications", "specifications is null or collection contains a null specification");
var query = includeProperties != null ? AllIncluding(includeProperties) : All;
return specifications.Aggregate(query, (current, specification) => specification.SatisfyingElementsFrom(current));
}
}
} |
using Lab2.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Lab2_api.Models
{
public enum Genre
{
action,
comedy,
horror,
thriller
}
public enum Watched
{
yes,
no
}
public class Movie
{
//[Key()]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[EnumDataType(typeof(Genre))]
public string Genre { get; set; }
public int Duration { get; set; }
public int Year { get; set; }
public string Director { get; set; }
public DateTime Date { get; set; }
[Range(1, 10)]
public int Rating { get; set; }
[EnumDataType(typeof(Watched))]
public bool Watched { get; set; }
public List<Comment> Comments { get; set; }
}
} |
using MongoDB.Bson.Serialization;
using Ninject.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using System.IO;
using Ninject;
using MongoDB.Driver;
using Nailhang.Mongodb.ModulesStorage.Processing;
using Nailhang.Mongodb.Base;
namespace Nailhang.Mongodb
{
[Module]
[ModuleDescription("Модуль хранения данных Nailhang в БД Mongo")]
public class Module : NinjectModule
{
public override void Load()
{
Kernel.Bind<IMongoDatabase>()
.ToMethod(q =>
{
var mongoConnection = q.Kernel.Get<MongoConnection>();
var client = new MongoClient(mongoConnection.ConnectionString);
return client.GetDatabase(mongoConnection.DbName);
});
BsonSerializer.UseZeroIdChecker = true;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Task1;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// Создание обычного треугольника
Triangle casual = new Triangle(3, 4, 6);
Task1.Triangle.Type type = Triangle.checkRight(casual);
Assert.AreEqual((float)casual.calcArea(), (float)5.33268225192539);
Assert.AreEqual(Triangle.checkRight(casual), Task1.Triangle.Type.NonRight);
}
[TestMethod]
public void TestMethod2()
{
// Создание прямоугольного треугольника
Triangle right = new Triangle(3, 4, 5);
Assert.AreEqual(Triangle.checkRight(right), Task1.Triangle.Type.Right);
Assert.AreEqual((float)right.calcArea(), (float)6);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"Сумма длин двух сторон должна быть больше длины третьей")]
public void TestMethod3()
{
// Создание неверного треугольника
Triangle third = new Triangle(3, 4, 200);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"Это не прямоугольный треугольник!")]
public void TestMethod4()
{
// Создание неверного прямоугольного треугольника
RightTriangle fourth = new RightTriangle (3, 4, 8);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"Это неверный треугольник!")]
public void TestMethod5()
{
// Создание неверного треугольника
Triangle fifth = new Triangle(3, -4, 4);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"Это неверный треугольник!")]
public void TestMethod6()
{
// Создание неверного треугольника
Triangle fifth = new Triangle(3, 0, 4);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Crystal.Plot2D.Common
{
[DebuggerDisplay("Count = {Count}")]
internal sealed class ResourcePool<T>
{
private readonly List<T> pool = new();
public T Get()
{
T item;
if (pool.Count < 1)
{
item = default(T);
}
else
{
int index = pool.Count - 1;
item = pool[index];
pool.RemoveAt(index);
}
return item;
}
public void Put(T item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
#if DEBUG
if (pool.IndexOf(item) != -1)
{
Debugger.Break();
}
#endif
pool.Add(item);
}
public int Count => pool.Count;
public void Clear() => pool.Clear();
}
}
|
using AppLogic.Dto;
using AppLogic.DtoCreate;
using AppLogic.DtoUpdate;
using AppLogic.Management;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace BeerShop.Controllers
{
public class BeerKindController : ApiController
{
BeerKindManager manager = new BeerKindManager();
// GET: api/BeerKind
public List<ReadBeerKind> Get()
{
return manager.GetAll();
}
// GET: api/BeerKind/5
public ReadBeerKind Get(int id)
{
return manager.Get(id);
}
// POST: api/BeerKind
public void Post([FromBody]CreateBeerKind create)
{
manager.Add(create);
}
// PUT: api/BeerKind/5
public void Put(int id, [FromBody]UpdateBeerKind update)
{
if (id == update.ID)
{
manager.Update(update);
}
}
// DELETE: api/BeerKind/5
public void Delete(int id)
{
manager.Remove(id);
}
}
}
|
using Andr3as07.Logging.Formater;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Andr3as07.Logging.Sink {
public class DebugSink : ISink {
public readonly ITextFormater Formater;
public DebugSink(ITextFormater formater) {
this.Formater = formater;
}
public void Dispatch(LogLevel level, DateTime time, string message, Dictionary<string, object> context, params object[] data) {
string str = Formater.FormatText(level, time, message, context);
Debug.WriteLine(str);
}
}
}
|
using EQS.AccessControl.Domain.Specification.Role;
using EQS.AccessControl.Domain.Validation.Base;
namespace EQS.AccessControl.Domain.Validation.Role
{
public class RoleConsistentValidation
{
public BaseValidation BaseValidation { get; set; }
public RoleConsistentValidation(Entities.Role person)
{
BaseValidation = new BaseValidation();
var nameSpecification = new NameIsNotNullSpecification();
BaseValidation.AddSpecification("Name-Specification",
nameSpecification.IsSatisfyedBy(person),
"Name is null.");
}
}
}
|
using System.Data.Entity;
namespace DataAccess.Tests
{
public class TestInitializer : DropCreateDatabaseAlways<TestBlogContext>
{
}
}
|
using System.Collections.Generic;
using System.Linq;
using ODL.ApplicationServices.DTOModel.Query;
using ODL.DataAccess;
using ODL.DomainModel.Avtal;
using ODL.DomainModel.Organisation;
using ODL.DomainModel.Person;
namespace ODL.ApplicationServices.Queries
{
internal class PersonerPerResultatenhetQuery
{
public IContext DbContext { get; set; }
public PersonerPerResultatenhetQuery(IContext dbContext)
{
DbContext = dbContext;
}
public IEnumerable<PersonPerResultatenhetDTO> Execute(string kstNr)
{
var allaAvtal = DbContext.DbSet<Avtal>();
var personer = DbContext.DbSet<Person>();
var organisationer = DbContext.DbSet<Organisation>();
var allaOrganisationsAvtal = DbContext.DbSet<OrganisationAvtal>();
// Vi delar upp frågan i två separata delar för enkelhets skull:
var projektionAnstallda = from person in personer
join avtal in allaAvtal on person.Id equals avtal.AnstalldAvtal.PersonId
join organisationsAvtal in allaOrganisationsAvtal on avtal.Id equals organisationsAvtal.AvtalId
join organisation in organisationer on organisationsAvtal.OrganisationId equals organisation.Id
where organisation.Resultatenhet.KstNr == kstNr
select new {person.Id, KostnadsstalleNr = kstNr, person.Personnummer, person.Fornamn, person.Efternamn,
Resultatenhetansvarig = avtal.Ansvarig, avtal.Anstallningsdatum, avtal.Avgangsdatum };
var projektionKonsulter = from person in personer
join avtal in allaAvtal on person.Id equals avtal.KonsultAvtal.PersonId
join organisationsAvtal in allaOrganisationsAvtal on avtal.Id equals organisationsAvtal.AvtalId
join organisation in organisationer on organisationsAvtal.OrganisationId equals organisation.Id
where organisation.Resultatenhet.KstNr == kstNr
select new {person.Id, KostnadsstalleNr = kstNr, person.Personnummer, person.Fornamn, person.Efternamn,
Resultatenhetansvarig = avtal.Ansvarig, avtal.Anstallningsdatum, avtal.Avgangsdatum};
var anstallda = projektionAnstallda.ToList();
var konsulter = projektionKonsulter.ToList();
anstallda.AddRange(konsulter);
var groups = anstallda.GroupBy(a => new { a.Id, a.Personnummer, a.Fornamn, a.Efternamn });
var personPerResultatenhet = groups.Select(group =>
new PersonPerResultatenhetDTO {
Id = group.Key.Id,
Personnummer = group.Key.Personnummer,
KostnadsstalleNr = kstNr,
Fornamn = group.Key.Fornamn,
Efternamn = group.Key.Efternamn,
Resultatenhetansvarig = group.Any(item => item.Resultatenhetansvarig), // true om personen är ansvaig på minst ett av avtalen!
Anstallningsdatum = group.Min(item => item.Anstallningsdatum).FormatteraSomDatum(), // tidigaste anställningsdatumet används
Avgangsdatum = group.Any(item => item.Avgangsdatum == null) ? null : group.Max(item => item.Avgangsdatum).FormatteraSomDatum() }); // Om något av avgångsdatumen är null, returnera då detta, annars det senaste!
return personPerResultatenhet;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IWorkFlow.DataBase;
namespace IWorkFlow.ORM
{
[Serializable]
[DataTableInfo("B_OA_Supervision_Complete", "id")]
public class B_OA_Supervision_Complete : QueryInfo
{
#region Model
private int _id;
[DataField("id", "B_OA_Supervision_Complete", false)]
public int id
{
set { _id = value; }
get { return _id; }
}
[DataField("completeDate", "B_OA_Supervision_Complete")]
public DateTime completeDate
{
set { _completeDate = value; }
get { return _completeDate; }
}
private DateTime _completeDate;
[DataField("completeStatus", "B_OA_Supervision_Complete")]
public string completeStatus
{
set { _completeStatus = value; }
get { return _completeStatus; }
}
private string _completeStatus;
[DataField("relationcaseid", "B_OA_Supervision_Complete")]
public string relationcaseid
{
set { _relationcaseid = value; }
get { return _relationcaseid; }
}
private string _relationcaseid;
#endregion Model
}
}
|
using System;
using System.Collections.Generic;
using TDC_Union.Model;
using TDC_Union.ViewModels;
namespace TDC_Union.Models
{
public class UnionPeeEvenModel : EventArgs
{
public List<ClassUnionFee> lClassUnionFee { get; set; }
public UnionPeeEvenModel() { }
public UnionPeeEvenModel(ClassViewModel ev)
{
}
public UnionPeeEvenModel(List<ClassUnionFee> classUnionFee)
{
this.lClassUnionFee = classUnionFee;
}
}
}
|
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
GameObject triangle;
public int life;
public int score;
public int record;
public float rotspeed;
public bool pause;
public void Catch(int typeOfSide, int typeOfObject)
{
if (typeOfSide != 0)
{
if (typeOfSide == typeOfObject)
{
score++;
if (PlayerPrefs.GetInt("record") < score)
PlayerPrefs.SetInt("record", score);
}
else
{
life--;
if (life == 0)
pause = true;
}
}
}
public void Start ()
{
//PlayerPrefs.SetInt("BestScore", 0);
triangle = transform.GetChild(0).gameObject;
record = PlayerPrefs.GetInt("record");
score = 0;
life = 3;
}
void Update()
{
if (score > record)
{
record = score;
PlayerPrefs.SetInt("record", record);
}
if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(KeyCode.Return))
{
if (life > 0)
pause = !pause;
}
if (!pause)
{
if (Input.GetAxis("Rotation") != 0)
triangle.transform.eulerAngles += new Vector3(0, 0, -1 * rotspeed * Input.GetAxis("Rotation"));
else if (Input.GetMouseButton(0) && Input.mousePosition.y < Screen.height / 2 && Input.mousePosition.x < Screen.width / 2)
triangle.transform.eulerAngles += new Vector3(0, 0, rotspeed);
else if (Input.GetMouseButton(0) && Input.mousePosition.y < Screen.height / 2 && Input.mousePosition.x > Screen.width / 2)
triangle.transform.eulerAngles -= new Vector3(0, 0, rotspeed);
}
}
}
|
//*************************************************************************
//@header EventCategory
//@abstract Set type of event with enum
//@version v1.0.0
//@author Felix Zhang
//@copyright Copyright 2015-2016 FFTAI Co.,Ltd.All rights reserved.
//**************************************************************************
namespace FZ.HiddenObjectGame
{
public enum EventCategory
{
CommonEvent,
UIEvent,
GameEvent,
OtherEvent,
}
} |
using System.ComponentModel;
namespace ModelViewViewModel_Voorbeeld.Stap5
{
class PersoonViewModel : INotifyPropertyChanged
{
private readonly Persoon Model;
private string _txtNaam;
private string _txtLeeftijd;
private bool _isMannelijk;
public string TxtNaam
{
get { return _txtNaam; }
set
{
_txtNaam = value;
RaisePropertyChanged("TxtNaam");
}
}
public string TxtLeeftijd
{
get { return _txtLeeftijd; }
set
{
_txtLeeftijd = value;
RaisePropertyChanged("TxtLeeftijd");
}
}
public bool IsMannelijk
{
get
{
return _isMannelijk;
}
set
{
_isMannelijk = value;
RaisePropertyChanged("IsMannelijk");
}
}
public PersoonViewModel(Persoon model)
{
this.Model = model;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
// take a copy to prevent thread issues
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO;
namespace GSVM.Components.Processors.CPU_1.Assembler
{
public class Preprocessor
{
List<string> code;
Dictionary<string, string> definitions;
Dictionary<string, string> pragmas;
public Dictionary<string, string> Pragmas { get { return pragmas; } }
public Preprocessor()
{
code = new List<string>();
definitions = new Dictionary<string, string>();
pragmas = new Dictionary<string, string>();
}
public void AddCode(string[] lines)
{
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
try
{
if (line.StartsWith("%include "))
{
Include(line);
}
else
{
code.Add(line);
}
}
catch
{
throw;
}
}
}
public string[] ProcessCode()
{
List<string> phase1 = new List<string>();
List<string> result = new List<string>();
for (int i = 0; i < code.Count; i++)
{
string line = code[i];
if (line.StartsWith("%define "))
{
Define(line);
}
else if (line.StartsWith("%undef "))
{
Undefine(line);
}
else if (line.StartsWith("%pragma "))
{
Pragma(line);
}
else if (line.StartsWith("#") | line.StartsWith(";") | (line == ""))
{
// DO NOTHING
}
else if (line.EndsWith(":"))
{
phase1.Add("");
phase1.Add(line);
}
else
{
phase1.Add(line);
}
}
for (int i = 0; i < phase1.Count; i++)
{
string line = phase1[i];
line = Substitute(line);
result.Add(line);
}
return result.ToArray();
}
void Include(string line)
{
int inc = "%include ".Length;
string path = line.Substring(inc, line.Length - inc);
if (definitions.ContainsKey(path))
path = definitions[path];
try
{
string[] lines = File.ReadAllLines(path);
AddCode(lines);
}
catch
{
throw;
}
}
void Define(string line)
{
Match match = Regex.Match(line, "%define (.*?) (.*)");
if (match.Success)
{
string key = match.Groups[1].Value;
string value = match.Groups[2].Value;
if (definitions.ContainsKey(key))
definitions[key] = value;
else
definitions.Add(key, value);
}
else
{
match = Regex.Match(line, "%define (.*)");
if (!match.Success)
return;
string key = match.Groups[1].Value;
if (!definitions.ContainsKey(key))
definitions.Add(key, "");
}
}
void Undefine(string line)
{
int inc = "%undef ".Length;
string key = line.Substring(inc, line.Length - inc);
if (definitions.ContainsKey(key))
definitions.Remove(key);
}
void Pragma(string line)
{
Match match = Regex.Match(line, "%pragma (.*?) (.*)");
if (match.Success)
{
string key = match.Groups[1].Value;
string value = match.Groups[2].Value;
if (pragmas.ContainsKey(key))
pragmas[key] = value;
else
pragmas.Add(key, value);
}
}
string Substitute(string line)
{
string result = line;
string[] keys = definitions.Keys.ToArray();
for (int i = 0; i < keys.Length; i++)
{
if (result.Contains(keys[i]))
result = result.Replace(keys[i], definitions[keys[i]]);
}
return result;
}
}
}
|
using System.Threading.Tasks;
namespace Szogun1987.EventsAndTasks
{
public interface ITaskAdapter
{
Task<int> GetNextInt();
Task<int> GetNextIntWithArg(string arg);
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Jypeli.Physics;
using Jypeli.Profiling;
namespace Jypeli
{
/// <summary>
/// Kantaluokka fysiikkapeleille.
/// </summary>
public abstract partial class PhysicsGameBase : Game
{
protected struct CollisionRecord
{
public IPhysicsObject obj;
public IPhysicsObject target;
public object targetTag;
public Delegate handler;
public CollisionRecord(IPhysicsObject obj, IPhysicsObject target, object targetTag, Delegate handler)
{
this.obj = obj;
this.target = target;
this.targetTag = targetTag;
this.handler = handler;
}
}
public IPhysicsEngine Engine { get; private set; }
public SynchronousList<IAxleJoint> Joints = new SynchronousList<IAxleJoint>();
protected Dictionary<CollisionRecord, CollisionHandler<IPhysicsObject, IPhysicsObject>> collisionHandlers =
new Dictionary<CollisionRecord, CollisionHandler<IPhysicsObject, IPhysicsObject>>();
protected Dictionary<CollisionRecord, CollisionHandler<IPhysicsObject, IPhysicsObject>> protectedCollisionHandlers =
new Dictionary<CollisionRecord, CollisionHandler<IPhysicsObject, IPhysicsObject>>();
private Vector gravity = Vector.Zero;
/// <summary>
/// Painovoima. Voimavektori, joka vaikuttaa kaikkiin ei-staattisiin kappaleisiin.
/// </summary>
public Vector Gravity
{
get
{
return gravity;
}
set
{
gravity = value;
Engine.Gravity = value;
}
}
/// <summary>
/// Käynnissä olevan fysiikkapelin pääolio.
/// </summary>
public static new PhysicsGameBase Instance
{
get
{
if (Game.Instance == null)
throw new InvalidOperationException("Game class is not initialized");
if (!(Game.Instance is PhysicsGameBase))
throw new InvalidOperationException("Game class is not PhysicsGame");
return (PhysicsGameBase)(Game.Instance);
}
}
/// <summary>
/// Onko fysiikan laskenta käytössä vai ei.
/// </summary>
public bool PhysicsEnabled { get; set; }
/// <summary>
/// Alustaa uuden fysiikkapelin.
/// </summary>
public PhysicsGameBase(IPhysicsEngine engine)
: base()
{
this.Engine = engine;
PhysicsEnabled = true;
Joints.ItemAdded += OnJointAdded;
Joints.ItemRemoved += OnJointRemoved;
}
void OnJointAdded(IAxleJoint j)
{
if (!j.Object1.IsAddedToGame)
{
j.SetEngine(Engine);
j.Object1.AddedToGame += j.AddToEngine;
}
else if (j.Object2 != null && !j.Object2.IsAddedToGame)
{
j.SetEngine(Engine);
j.Object2.AddedToGame += j.AddToEngine;
}
else
{
Engine.AddJoint(j);
}
}
void OnJointRemoved(IAxleJoint j)
{
Engine.RemoveJoint(j);
}
/// <summary>
/// Kun olio lisätään peliin
/// </summary>
/// <param name="obj"></param>
protected override void OnObjectAdded(IGameObject obj)
{
if (obj is PhysicsObject && obj.Parent == null)
{
PhysicsObject po = (PhysicsObject)obj;
Engine.AddBody(po.Body);
}
base.OnObjectAdded(obj);
}
/// <summary>
/// Kun olio poistetaan pelistä
/// </summary>
/// <param name="obj"></param>
protected override void OnObjectRemoved(IGameObject obj)
{
if (obj is PhysicsObject && obj.Parent is null)
{
PhysicsObject po = (PhysicsObject)obj;
Engine.RemoveBody(po.Body);
}
base.OnObjectRemoved(obj);
}
/// <summary>
/// Pysäyttää kaiken liikkeen.
/// </summary>
public void StopAll()
{
foreach (var layer in Layers)
{
foreach (var obj in layer.Objects)
{
if (obj is PhysicsObject)
((PhysicsObject)obj).Stop();
}
}
}
/// <summary>
/// Tuhoaa kaikki pelioliot, ajastimet, törmäyksenkuuntelijat ja näppäinkuuntelijat, sekä resetoi kameran.
/// </summary>
public override void ClearAll()
{
if (!FarseerGame)
ClearPhysics(); // Farseerilla tämä poistaa jo kappaleet moottorilta ja ne poistettaisiin uudestaan myöhemmin Layerien tyhjennyksen yhteydessä, joka taas aiheuttaa nullpointerin.
RemoveCollisionHandlers();
base.ClearAll();
}
/// <summary>
/// Nollaa fysiikkamoottorin.
/// </summary>
private void ClearPhysics()
{
Engine.Clear();
}
/// <summary>
/// Ajetaan kun pelin tilannetta päivitetään. Päivittämisen voi toteuttaa perityssä luokassa
/// toteuttamalla tämän metodin. Perityn luokan metodissa tulee kutsua kantaluokan metodia.
/// </summary>
/// <param name="time"></param>
protected override void Update(Time time)
{
double dt = time.SinceLastUpdate.TotalSeconds;
if (PhysicsEnabled)
{
Profiler.BeginStep("PhysicsEngine");
Engine.Update(dt);
Profiler.EndStep();
}
base.Update(time);
// Updating joints must be after base.Update so that the bodies
// are added to the engine before the joints
Profiler.BeginStep("Joints");
Joints.Update(time);
Profiler.EndStep();
}
/// <summary>
/// Lisää liitoksen peliin.
/// </summary>
public void Add(IAxleJoint j)
{
Joints.Add(j);
}
/// <summary>
/// Poistaa liitoksen pelistä.
/// </summary>
/// <param name="j"></param>
internal void Remove(IAxleJoint j)
{
Joints.Remove(j);
}
#region Collision handlers
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun olio <code>obj</code> törmää johonkin toiseen olioon.
/// </summary>
/// <typeparam name="O">Törmäävän olion tyyppi.</typeparam>
/// <typeparam name="T">Kohdeolion tyyppi.</typeparam>
/// <param name="obj">Törmäävä olio</param>
/// <param name="handler">Törmäyksen käsittelevä aliohjelma.</param>
public void AddCollisionHandler<O, T>(O obj, CollisionHandler<O, T> handler)
where O : IPhysicsObject
where T : IPhysicsObject
{
if (obj == null)
throw new NullReferenceException("Colliding object must not be null");
if (handler == null)
throw new NullReferenceException("Handler must not be null");
CollisionHandler<IPhysicsObject, IPhysicsObject> targetHandler =
delegate (IPhysicsObject collider, IPhysicsObject collidee)
{
if (collidee is T)
handler((O)collider, (T)collidee);
};
obj.Collided += targetHandler;
collisionHandlers.Add(new CollisionRecord(obj, null, null, handler), targetHandler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun olio <code>obj</code> törmää johonkin toiseen olioon.
/// Jypelin sisäiseen käyttöön!
/// </summary>
/// <typeparam name="O">Törmäävän olion tyyppi.</typeparam>
/// <typeparam name="T">Kohdeolion tyyppi.</typeparam>
/// <param name="obj">Törmäävä olio</param>
/// <param name="handler">Törmäyksen käsittelevä aliohjelma.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public void AddProtectedCollisionHandler<O, T>(O obj, CollisionHandler<O, T> handler)
where O : IPhysicsObject
where T : IPhysicsObject
{
if (obj == null)
throw new NullReferenceException("Colliding object must not be null");
if (handler == null)
throw new NullReferenceException("Handler must not be null");
CollisionHandler<IPhysicsObject, IPhysicsObject> targetHandler =
delegate (IPhysicsObject collider, IPhysicsObject collidee)
{
if (collidee is T)
handler((O)collider, (T)collidee);
};
obj.Collided += targetHandler;
protectedCollisionHandlers.Add(new CollisionRecord(obj, null, null, handler), targetHandler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun yleinen fysiikkaolio <code>obj</code>
/// törmää johonkin toiseen yleiseen fysiikkaolioon.
/// </summary>
/// <param name="obj">Törmäävä olio</param>
/// <param name="handler">Törmäyksen käsittelevä aliohjelma.</param>
public void AddCollisionHandler(IPhysicsObject obj, CollisionHandler<IPhysicsObject, IPhysicsObject> handler)
{
AddCollisionHandler<IPhysicsObject, IPhysicsObject>(obj, handler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun fysiikkaolio <code>obj</code> törmää johonkin toiseen fysiikkaolioon.
/// </summary>
/// <param name="obj">Törmäävä olio</param>
/// <param name="handler">Törmäyksen käsittelevä aliohjelma.</param>
public void AddCollisionHandler(PhysicsObject obj, CollisionHandler<PhysicsObject, PhysicsObject> handler)
{
AddCollisionHandler<PhysicsObject, PhysicsObject>(obj, handler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun fysiikkaolio <code>obj</code> törmää johonkin fysiikkarakenteeseen.
/// </summary>
/// <param name="obj">Törmäävä olio</param>
/// <param name="handler">Törmäyksen käsittelevä aliohjelma.</param>
public void AddCollisionHandler(PhysicsObject obj, CollisionHandler<PhysicsObject, PhysicsStructure> handler)
{
AddCollisionHandler<PhysicsObject, PhysicsStructure>(obj, handler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun fysiikkarakenne <code>o</code> törmää johonkin fysiikkaolioon.
/// </summary>
/// <param name="obj">Törmäävä fysiikkarakenne</param>
/// <param name="handler">Törmäyksen käsittelevä aliohjelma.</param>
public void AddCollisionHandler(PhysicsStructure obj, CollisionHandler<PhysicsStructure, PhysicsObject> handler)
{
AddCollisionHandler<PhysicsStructure, PhysicsObject>(obj, handler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun fysiikkarakenne <code>o</code> törmää toiseen fysiikkarakenteeseen.
/// </summary>
/// <param name="obj">Törmäävä fysiikkarakenne</param>
/// <param name="handler">Törmäyksen käsittelevä aliohjelma.</param>
public void AddCollisionHandler(PhysicsStructure obj, CollisionHandler<PhysicsStructure, PhysicsStructure> handler)
{
AddCollisionHandler<PhysicsStructure, PhysicsStructure>(obj, handler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun
/// olio <code>obj</code> törmää tiettyyn toiseen olioon <code>target</code>.
/// </summary>
/// <param name="obj">Törmäävä olio.</param>
/// <param name="target">Olio johon törmätään.</param>
/// <param name="handler">Metodi, joka käsittelee törmäyksen (ei parametreja).</param>
public void AddCollisionHandlerByRef<O, T>(O obj, T target, CollisionHandler<O, T> handler)
where O : IPhysicsObject
where T : IPhysicsObject
{
if (obj == null)
throw new NullReferenceException("Colliding object must not be null");
if (target == null)
throw new NullReferenceException("Collision target must not be null");
if (handler == null)
throw new NullReferenceException("Handler must not be null");
CollisionHandler<IPhysicsObject, IPhysicsObject> targetHandler =
delegate (IPhysicsObject collider, IPhysicsObject collidee)
{
if (object.ReferenceEquals(collidee, target))
handler((O)collider, (T)collidee);
};
obj.Collided += targetHandler;
collisionHandlers.Add(new CollisionRecord(obj, target, null, handler), targetHandler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun
/// olio <code>obj</code> törmää toiseen olioon, jolla on tietty tagi <code>tag</code>.
/// </summary>
/// <param name="obj">Törmäävä olio.</param>
/// <param name="tag">Törmättävän olion tagi.</param>
/// <param name="handler">Metodi, joka käsittelee törmäyksen (ei parametreja).</param>
public void AddCollisionHandlerByTag<O, T>(O obj, object tag, CollisionHandler<O, T> handler)
where O : IPhysicsObject
where T : IPhysicsObject
{
if (obj == null)
throw new NullReferenceException("Colliding object must not be null");
if (tag == null)
throw new NullReferenceException("Tag must not be null");
if (handler == null)
throw new NullReferenceException("Handler must not be null");
CollisionHandler<IPhysicsObject, IPhysicsObject> targetHandler =
delegate (IPhysicsObject collider, IPhysicsObject collidee)
{
if (collidee is T && StringHelpers.StringEquals(collidee.Tag, tag))
handler((O)collider, (T)collidee);
};
obj.Collided += targetHandler;
collisionHandlers.Add(new CollisionRecord(obj, null, tag, handler), targetHandler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun
/// olio <code>obj</code> törmää toiseen olioon.
/// </summary>
/// <param name="obj">Törmäävä olio.</param>
/// <param name="target">Törmättävän olion viite tai tagi.</param>
/// <param name="handler">Metodi, joka käsittelee törmäyksen (ei parametreja).</param>
public void AddCollisionHandler<O, T>(O obj, object target, CollisionHandler<O, T> handler)
where O : IPhysicsObject
where T : IPhysicsObject
{
if (target is T)
AddCollisionHandlerByRef(obj, (T)target, handler);
else
AddCollisionHandlerByTag(obj, target, handler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun
/// yleinen fysiikkaolio <code>obj</code> törmää toiseen yleiseen fysiikkaolioon, jolla on tietty tagi <code>tag</code>.
/// </summary>
/// <param name="obj">Törmäävä olio.</param>
/// <param name="tag">Törmättävän olion tagi.</param>
/// <param name="handler">Metodi, joka käsittelee törmäyksen (ei parametreja).</param>
public void AddCollisionHandler(IPhysicsObject obj, object tag, CollisionHandler<IPhysicsObject, IPhysicsObject> handler)
{
AddCollisionHandler<IPhysicsObject, IPhysicsObject>(obj, tag, handler);
}
/// <summary>
/// Määrää, mihin aliohjelmaan siirrytään kun
/// fysiikkaolio <code>obj</code> törmää toiseen fysiikkaolioon, jolla on tietty tagi <code>tag</code>.
/// </summary>
/// <param name="obj">Törmäävä olio.</param>
/// <param name="tag">Törmättävän olion tagi.</param>
/// <param name="handler">Metodi, joka käsittelee törmäyksen (ei parametreja).</param>
public void AddCollisionHandler(PhysicsObject obj, object tag, CollisionHandler<PhysicsObject, PhysicsObject> handler)
{
AddCollisionHandler<PhysicsObject, PhysicsObject>(obj, tag, handler);
}
/// <summary>
/// Poistaa kaikki ehdot täyttävät törmäyksenkäsittelijät.
/// </summary>
/// <param name="obj">Törmäävä olio. null jos ei väliä.</param>
/// <param name="target">Törmäyksen kohde. null jos ei väliä.</param>
/// <param name="tag">Törmäyksen kohteen tagi. null jos ei väliä.</param>
/// <param name="handler">Törmäyksenkäsittelijä. null jos ei väliä.</param>
public void RemoveCollisionHandlers(PhysicsObject obj = null, PhysicsObject target = null, object tag = null, Delegate handler = null)
{
Predicate<CollisionRecord> pred = rec =>
(obj == null || object.ReferenceEquals(obj, rec.obj)) &&
(target == null || target == rec.target) &&
(tag == null || StringHelpers.StringEquals(tag, rec.targetTag)) &&
(handler == null || object.ReferenceEquals(handler, rec.handler));
List<CollisionRecord> remove = new List<CollisionRecord>();
foreach (var key in collisionHandlers.Keys)
{
if (pred(key))
remove.Add(key);
}
foreach (var key in remove)
{
key.obj.Collided -= collisionHandlers[key];
collisionHandlers.Remove(key);
}
}
/// <summary>
/// Poistaa kaikki ehdot täyttävät törmäyksenkäsittelijät.
/// Jypelin sisäiseen käyttöön!
/// </summary>
/// <param name="obj">Törmäävä olio. null jos ei väliä.</param>
/// <param name="target">Törmäyksen kohde. null jos ei väliä.</param>
/// <param name="tag">Törmäyksen kohteen tagi. null jos ei väliä.</param>
/// <param name="handler">Törmäyksenkäsittelijä. null jos ei väliä.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public void RemoveProtectedCollisionHandlers(PhysicsObject obj = null, PhysicsObject target = null, object tag = null, Delegate handler = null)
{
Predicate<CollisionRecord> pred = rec =>
(obj == null || object.ReferenceEquals(obj, rec.obj)) &&
(target == null || target == rec.target) &&
(tag == null || tag.Equals(rec.targetTag)) &&
(handler == null || object.ReferenceEquals(handler, rec.handler));
List<CollisionRecord> remove = new List<CollisionRecord>();
foreach (var key in collisionHandlers.Keys)
{
if (pred(key))
remove.Add(key);
}
foreach (var key in remove)
{
key.obj.Collided -= protectedCollisionHandlers[key];
protectedCollisionHandlers.Remove(key);
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DateBlockControl : MonoBehaviour
{
Component halo;
public GameObject player;
public float speed = 3;
private Vector3 screenPoint;
private Vector3 offset;
private Component placementCollider;
private Transform placementTransform;
public bool isSnap = false; //whether the block is snapped into place
public bool isHeld = false; //whether the block is currently being grabbed
private float rotateX;
private float rotateY;
private float rotateZ;
private Vector3 initialRotation;
Rigidbody rigidbody;
void Start()
{
halo = GetComponent("Halo");
halo.GetType().GetProperty("enabled").SetValue(halo, false, null);
rigidbody = GetComponent<Rigidbody>();
placementTransform = transform.parent;
placementCollider = placementTransform.GetComponent<BoxCollider>();
placementTransform.gameObject.GetComponent<Renderer>().enabled = false;
rotateX = Random.Range(-1f, 1f);
rotateY = Random.Range(-1f, 1f);
rotateZ = Random.Range(-1f, 1f);
initialRotation = placementTransform.forward;
}
void Update()
{
if (isSnap)
{
transform.position = Vector3.MoveTowards(transform.position, placementTransform.position, speed * Time.deltaTime);
}
if (!isSnap && !isHeld)
{
RotateBlock();
}
else
{
transform.forward = initialRotation;
}
}
void OnMouseOver()
{
if (!isSnap)
{
halo.GetType().GetProperty("enabled").SetValue(halo, true, null);
PlacementControl(true);
}
}
void OnMouseExit()
{
halo.GetType().GetProperty("enabled").SetValue(halo, false, null);
PlacementControl(false);
}
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag() //block dragging mechanism. Magic lasso should go here.
{ //Find the distance between the player and the block. Decide on maximum distance to drag.
//Scroll with mouse wheel maybe?
if (!isSnap)
{
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
transform.position = Vector3.MoveTowards(transform.position, cursorPosition, speed * Time.deltaTime);
rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
isHeld = true;
}
}
private void OnMouseUp()
{
rigidbody.constraints = RigidbodyConstraints.FreezeAll;
isHeld = false;
}
void OnTriggerEnter(Collider other) //detects if the block is within it's placement
{
if (other == placementCollider)
{
isSnap = true;
}
}
private void PlacementControl(bool state) //Whether the green placement blocks are visible
{
Component placementHalo = placementTransform.gameObject.GetComponent("Halo");
placementHalo.GetType().GetProperty("enabled").SetValue(placementHalo, state, null);
placementTransform.gameObject.GetComponent<Renderer>().enabled = state;
}
private void RotateBlock()
{
transform.Rotate(rotateX, rotateY, rotateZ);
}
}
|
using BootcampTwitterKata.Helpers;
namespace BootcampTwitterKata.Tests
{
using NFluent;
using NUnit.Framework;
public class Part_2_EventStore
{
private IEventStore eventStore;
public class FakeEvent
{
private readonly int val;
public FakeEvent(int val)
{
this.val = val;
}
public override bool Equals(object obj)
{
var fakeEvent = obj as FakeEvent;
return this.val == fakeEvent.val;
}
public override int GetHashCode()
{
return 0;
}
}
[SetUp]
public void Setup()
{
var injecter = new Injecter();
injecter.Bind<IFile, FileIO>().Bind<IEventStore, EventStore>();
eventStore = injecter.Get<IEventStore>();
}
[Test]
public void Shoudl_have_an_event_in_collection_When_insert_event()
{
eventStore.Insert("Event 1");
Check.That(eventStore.Events).ContainsExactly("Event 1");
}
[Test]
public void Shoudl_have_twoo_events_in_collection_When_insert_a_second_event()
{
eventStore.Insert("Event 1");
eventStore.Insert("Event 2");
Check.That(eventStore.Events).ContainsExactly("Event 1", "Event 2");
}
[Test]
public void Shoudl_have_an_object_event_in_collection_When_insert_an_object()
{
eventStore.Insert(new FakeEvent(1));
Check.That(eventStore.Events).ContainsExactly(new FakeEvent(1));
}
[Test]
public void Shoudl_have_two_object_event_in_collection_When_object_are_equal()
{
eventStore.Insert(new FakeEvent(1));
eventStore.Insert(new FakeEvent(1));
Check.That(eventStore.Events).ContainsExactly(new FakeEvent(1), new FakeEvent(1));
}
}
} |
using MyShop.Core.Model;
using System.Collections.Generic;
namespace MyShop.Core.Contracts
{
public interface IRepository<T> where T : BaseEntity
{
void Commit();
void Delete(string id);
T Find(string id);
IEnumerable<T> GetAll();
void Insert(T t);
void Update(T t);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BethanyShop.Models
{
public static class DBIntializer
{
public static void seed(AppDbContext context)
{
if(!context.Pies.Any())
{
context.AddRange(
new Pie { Name = "Apple Pie", Price = 12.95M, ShortDescription = "Our famous apple pies!",
LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.", ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/applepie.jpg", IsPieOfTheWeek = true,
ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/applepiesmall.jpg"},
new Pie { Name = "Blueberry Cheese Cake", Price = 18.95M, ShortDescription = "You'll love it!",
LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.",
ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/blueberrycheesecake.jpg",
IsPieOfTheWeek = false, ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/blueberrycheesecakesmall.jpg" },
new Pie { Name = "Cheese Cake", Price = 18.95M, ShortDescription = "Plain cheese cake. Plain pleasure.", LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.",
ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/cheesecake.jpg",
IsPieOfTheWeek = false, ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/cheesecakesmall.jpg"},
new Pie { Name = "Cherry Pie", Price = 15.95M, ShortDescription = "A summer classic!",
LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.",
ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/cherrypie.jpg",
IsPieOfTheWeek = false, ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/cherrypiesmall.jpg"},
new Pie { Name = "Christmas Apple Pie", Price = 13.95M, ShortDescription = "Happy holidays with this pie!",
LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.",
ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/christmasapplepie.jpg",
IsPieOfTheWeek = false, ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/christmasapplepiesmall.jpg"},
new Pie { Name = "Cranberry Pie", Price = 17.95M, ShortDescription = "A Christmas favorite",
LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.",
ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/cranberrypie.jpg",IsPieOfTheWeek = false,
ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/cranberrypiesmall.jpg"},
new Pie { Name = "Peach Pie", Price = 15.95M, ShortDescription = "Sweet as peach",
LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.",
ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/peachpie.jpg", IsPieOfTheWeek = false,
ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/peachpiesmall.jpg"},
new Pie { Name = "Pumpkin Pie", Price = 12.95M, ShortDescription = "Our Halloween favorite",
LongDescription = "Icing carrot cake jelly-o cheesecake. Sweet roll marzipan marshmallow toffee brownie brownie candy tootsie roll.",
ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/pumpkinpie.jpg",
IsPieOfTheWeek = true, ImageThumbnailUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/pumpkinpiesmall.jpg"}
);
context.SaveChanges();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicBullet : BulletInterface
{
protected override void instantEffect()
{
}
protected override void persistantEffect()
{
}
protected override void OnCollisionEnter(Collision collision)
{
base.OnCollisionEnter(collision);
}
}
|
using ISE.Framework.Server.Core.DataAccessBase;
using ISE.SM.Common.DTO;
using ISE.SM.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISE.SM.DataAccess
{
public class PermissionToUserTDataAccess : TDataAccess<PermissionToUser, PermissionToUserDto, PermissionToUserRepository>
{
public PermissionToUserTDataAccess()
: base(new PermissionToUserRepository())
{
}
}
}
|
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.Prf;
using Profiling2.Web.Mvc.Areas.System.Controllers.ViewModels;
using SharpArch.NHibernate.Web.Mvc;
using SharpArch.Web.Mvc.JsonNet;
using System.Web.Mvc;
namespace Profiling2.Web.Mvc.Areas.System.Controllers
{
public class RolesController : SystemBaseController
{
protected readonly IUserTasks userTasks;
public RolesController(IUserTasks userTasks)
{
this.userTasks = userTasks;
}
public JsonNetResult Name(int id)
{
AdminRole r = this.userTasks.GetAdminRole(id);
if (r != null)
{
return JsonNet(new
{
Id = id,
Name = r.Name
});
}
else
return JsonNet(string.Empty);
}
public JsonNetResult All()
{
if (!string.IsNullOrEmpty(Request.QueryString["term"]))
return JsonNet(this.userTasks.GetAdminRolesJson(Request.QueryString["term"]));
else
return JsonNet(this.userTasks.GetAdminRolesJson());
}
public ActionResult Index()
{
return View(this.userTasks.GetAllAdminRoles());
}
public ActionResult Create()
{
return View(new RoleViewModel());
}
[HttpPost]
[Transaction]
public ActionResult Create(RoleViewModel vm)
{
if (ModelState.IsValid)
{
AdminRole role = this.userTasks.GetAdminRole(vm.Name);
if (role != null)
{
ModelState.AddModelError("Name", "Role name already exists.");
return View();
}
role = new AdminRole();
role.Name = vm.Name;
if (!string.IsNullOrEmpty(vm.AdminPermissionIds))
{
string[] ids = vm.AdminPermissionIds.Split(',');
foreach (string id in ids)
{
int result;
if (int.TryParse(id, out result))
{
AdminPermission p = this.userTasks.GetAdminPermission(result);
if (p != null)
role.AdminPermissions.Add(p);
}
}
}
role = this.userTasks.SaveOrUpdateAdminRole(role);
return RedirectToAction("Index");
}
return Create();
}
public ActionResult Edit(int id)
{
AdminRole role = this.userTasks.GetAdminRole(id);
if (role != null)
{
RoleViewModel vm = new RoleViewModel(role);
return View(vm);
}
return new HttpNotFoundResult();
}
[HttpPost]
[Transaction]
public ActionResult Edit(RoleViewModel vm)
{
if (ModelState.IsValid)
{
AdminRole role = this.userTasks.GetAdminRole(vm.Id);
if (role != null)
{
role.Name = vm.Name;
role.AdminPermissions.Clear();
if (!string.IsNullOrEmpty(vm.AdminPermissionIds))
{
string[] ids = vm.AdminPermissionIds.Split(',');
foreach (string id in ids)
{
int result;
if (int.TryParse(id, out result))
{
AdminPermission p = this.userTasks.GetAdminPermission(result);
if (p != null)
role.AdminPermissions.Add(p);
}
}
}
return RedirectToAction("Index");
}
return new HttpNotFoundResult();
}
return Edit(vm.Id);
}
}
} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Nailhang.Display.MD5Cache
{
public class MD5NonBlockingCache : IMD5Cache
{
readonly ConcurrentDictionary<string, Guid> md5Dict = new ConcurrentDictionary<string, Guid>();
static Guid MakeGuidFromString(string content)
{
using (var md5 = MD5.Create())
return new Guid(md5.ComputeHash(Encoding.UTF8.GetBytes(content)));
}
public Guid ToMD5(string parameter)
{
Guid res;
if (md5Dict.TryGetValue(parameter, out res))
return res;
res = MakeGuidFromString(parameter);
md5Dict.TryAdd(parameter, res);
return res;
}
}
}
|
/*
Designer for the OptionGroup Control
*/
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.Windows.Forms.Design;
namespace Com.Colin.Win.Customized
{
/// <summary>
/// OptionGroupDesigner extends the design mode behavior of an OptionGroup control
/// </summary>
public class OptionGroupDesigner : ParentControlDesigner
{
private DesignerVerbCollection dVerbs;
private const int padding = 3;
private OptionGroup myControl;
public OptionGroupDesigner()
{
this.dVerbs = new DesignerVerbCollection();
}
/// <summary>
/// Prevents any control from been moved on the OptionGroupís surface
/// </summary>
public override bool CanParent(Control control)
{
return false;
}
/// <summary>
/// Prevents any control from been moved on the OptionGroupís surface
/// </summary>
public override bool CanParent(ControlDesigner controlDesigner)
{
return false;
}
/// <summary>
/// Initializes the designer
/// Obtain the reference to an OptionGroup control this designer is associated with
/// </summary>
public override void Initialize(IComponent component)
{
base.Initialize(component);
this.myControl = (OptionGroup) component;
}
/// <summary>
/// Creates a new SelOption and adds it to the control collection
/// </summary>
private void OnAddOption(object sender, EventArgs e)
{
int m_x, m_y, m_ymax=0;
SelOption selopt;
int maxvalue = 0;
bool firstoption = true;
int toppadding = myControl.GetFontHeight() + padding ;
// Define the very lower-down child control
foreach (Control cnt in this.myControl.Controls)
{
if (cnt is SelOption)
{
m_ymax = Math.Max(m_ymax, cnt.Top + cnt.Height);
selopt = (SelOption)cnt;
maxvalue = Math.Max(selopt.Value, maxvalue);
firstoption = false;
}
}
if (m_ymax == 0)
m_ymax = toppadding;
// Check if there is enough room below for a new control
if (this.myControl.ClientRectangle.Contains(padding, m_ymax + 4 * padding))
{
m_x = padding;
m_y = m_ymax + padding;
}
else
{
// As no free space available at the bottom just place a new control in the up-left
m_y = 3 * padding + toppadding;
m_x = 3 * padding;
}
SelOption seloption;
// Get IDesignerHost service and wrap creation of a SelOption in transaction
IDesignerHost h = (IDesignerHost) this.GetService(typeof(IDesignerHost));
IComponentChangeService c = (IComponentChangeService) this.GetService(typeof(IComponentChangeService));
DesignerTransaction dt;
dt = h.CreateTransaction("Add Option");
seloption = (SelOption) h.CreateComponent(typeof(SelOption));
int i3=this.myControl.ButtonCount + 1;
seloption.Text = "Option" + i3.ToString();
seloption.Top = m_y;
seloption.Left = m_x;
// If this is the first SelOption added to an OptionGroup
// set its TabStop property to true.
// It causes the selection of this option when the user
// presses TAB key and none SelOption is checked.
if (firstoption)
seloption.TabStop = true;
seloption.Value = maxvalue + 1;
c.OnComponentChanging(this.myControl, null);
// If this is not the first option in an OptionGroup
// rearrange the controls collection, so that the new SelOption
// will be the first item of the controls collection.
// This imitates the Bring to Front method
if (this.myControl.Controls.Count > 0)
{
int count = this.myControl.Controls.Count;
Control[] controls = new Control[count + 1];
controls[0] = seloption;
this.myControl.Controls.CopyTo(controls, 1);
this.myControl.Controls.Clear();
this.myControl.Controls.AddRange(controls);
int i1;
count = this.myControl.Controls.Count - 1;
for (i1 = 0; i1<=this.myControl.Controls.Count - 1; i1++)
{
this.myControl.Controls[i1].TabIndex = count - i1;
}
}
else
{
this.myControl.Controls.Add(seloption);
}
c.OnComponentChanged(this.myControl, null, null, null);
dt.Commit();
}
/// <summary>
/// Removes a SelOption from the OptionGroup
/// </summary>
private void OnRemoveOption(SelOption seloption)
{
IDesignerHost h = (IDesignerHost) this.GetService(typeof(IDesignerHost));
IComponentChangeService c = (IComponentChangeService) this.GetService(typeof(IComponentChangeService));
DesignerTransaction dt = h.CreateTransaction("Remove Option");
c.OnComponentChanging(this.myControl, null);
h.DestroyComponent(seloption);
this.myControl.Controls.Remove(seloption);
c.OnComponentChanged(this.myControl, null, null, null);
dt.Commit();
}
/// <summary>
/// Sets the default properties for on OptionGroup
/// and adds two SelOptions to a new OptionGroup
/// after it being instanced in the Win Form designer
/// </summary>
public override void OnSetComponentDefaults()
{
this.OnAddOption(this, new EventArgs());
this.OnAddOption(this, new EventArgs());
}
/// <summary>
/// Hides the ButtonCount property of an OptionGroup and activates
/// the design-time only property defined in the designer
/// </summary>
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
Attribute[] attributeArray1 = new Attribute[] { CategoryAttribute.Appearance };
properties["ButtonCount"] = TypeDescriptor.CreateProperty(typeof(OptionGroupDesigner), "ButtonCount", typeof(int), attributeArray1);
}
/// <summary>
/// Gets/sets a number of options this control hosts
/// </summary>
[DesignOnly(true)]
public int ButtonCount
{
get
{
// Call the original OptionGroup property
if (this.myControl != null)
return this.myControl.ButtonCount;
return 0;
}
set
{
// Add new options to an OptionGroup or delete existing
IDesignerHost h = (IDesignerHost) this.GetService(typeof(IDesignerHost));
if (h != null && !h.Loading)
{
if (value < 0)
throw new ArgumentException("Illigal value for this property");
if (this.myControl.ButtonCount != value)
{
int i1;
// The new value is grater then the number of options,
// so create new options and add them to an OptionGroup
if (value > this.myControl.ButtonCount)
{
for (i1 = this.myControl.ButtonCount + 1; i1 <= value; i1++)
this.OnAddOption(this, new EventArgs());
}
else
{
// The new value is less then the number of options,
// so delete options from a Option Group
// The deletion starts with the first item in the Controls collection - the last added
int count = this.myControl.ButtonCount - value;
SelOption seloption;
do
{
seloption = null;
for (i1 = 0; i1 <= this.myControl.Controls.Count - 1; i1++)
{
if (this.myControl.Controls[i1] is SelOption)
{
seloption = (SelOption) this.myControl.Controls[i1];
break;
}
}
if (seloption != null)
{
this.OnRemoveOption(seloption);
count--;
}
else
break;
}
while (count > 0);
}
}
}
}
}
/// <summary>
/// Adds a new item to the context menu of an OptionGroup
/// </summary>
public override DesignerVerbCollection Verbs
{
get
{
DesignerVerbCollection v = new DesignerVerbCollection();
v.Add(new DesignerVerb("&Add Option", new EventHandler(this.OnAddOption)));
return v;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01.LeapYear
{
class FindLeap
{
static int year;
static void Main()
{
Console.WriteLine("Enter a year to check if it is leap: ");
year = int.Parse(Console.ReadLine());
CheckLeapYear();
}
static void CheckLeapYear()
{
bool result = DateTime.IsLeapYear(year);
if (result == true)
{
Console.WriteLine("The year {0} is a leap year!", year);
}
else
{
Console.WriteLine("The year {0} is not a leap year!", year);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entities.MDM
{
public class AvailableSite
{
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 产品叶标识
/// </summary>
public int T102LeafID { get; set; }
/// <summary>
/// 产品代码
/// </summary>
public string T102Code { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string T102Name { get; set; }
/// <summary>
/// 客户叶标识
/// </summary>
public int T105LeafID { get; set; }
/// <summary>
/// 客户代码
/// </summary>
public string T105Code { get; set; }
/// <summary>
/// 客户名称
/// </summary>
public string T105Name { get; set; }
/// <summary>
/// 地点叶标识
/// </summary>
public int T172LeafID { get; set; }
/// <summary>
/// 地点名称
/// </summary>
public string T172Code { get; set; }
/// <summary>
/// 地点名称
/// </summary>
public string T172Name { get; set; }
/// <summary>
/// 标签关联信息
/// </summary>
public long CorrelationID { get; set; }
/// <summary>
/// 地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 邮政编码
/// </summary>
public string PostCode { get; set; }
/// <summary>
/// 联系人姓名
/// </summary>
public string ToContact { get; set; }
/// <summary>
/// 办公电话
/// </summary>
public string OPhoneNo { get; set; }
/// <summary>
/// 邮件地址
/// </summary>
public string EmailAddr { get; set; }
/// <summary>
/// 移动电话
/// </summary>
public string MPhoneNo { get; set; }
/// <summary>
/// 经度坐标(±ddd°ff′mm″)
/// </summary>
public string Longitude { get; set; }
/// <summary>
/// 纬度坐标(±dd°ff′mm″)
/// </summary>
public string Latitude { get; set; }
/// <summary>
/// 标签模板叶标识
/// </summary>
public int T117LeafID { get; set; }
/// <summary>
/// 标签模板代码
/// </summary>
public string T117Code { get; set; }
/// <summary>
/// 标签模板名称
/// </summary>
public string T117Name { get; set; }
public AvailableSite Clone()
{
return MemberwiseClone() as AvailableSite;
}
public override string ToString()
{
return string.Format(
"[{0}]{1}",
T172Code,
Address.Trim());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NotSoSmartSaverAPI.DTO.GoalDTO;
using NotSoSmartSaverAPI.Interfaces;
namespace NotSoSmartSaverAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GoalController : ControllerBase
{
IGoalProcessor _goalProcessor;
public GoalController(IGoalProcessor goalProcessor)
{
_goalProcessor = goalProcessor;
}
[HttpGet]
public async Task<IActionResult> GetGoals(string ownerId)
{
GetGoalsDTO data = new GetGoalsDTO { ownerId = ownerId };
return Ok(await Task.Run(() => _goalProcessor.getGoals(data)));
}
[HttpDelete("{goalID}")]
public async Task<IActionResult> RemoveGoal(string goalID)
{
await Task.Run(() => _goalProcessor.removeGoal(goalID));
return Ok("Goal removed");
}
[HttpPut]
public async Task<IActionResult> ModifyGoal([FromBody]ModifyGoalDTO data)
{
await Task.Run(() => _goalProcessor.modifyGoal(data));
return Ok("Goal modified");
}
[HttpPost]
public async Task<IActionResult> AddNewGoal([FromBody] NewGoalDTO data)
{
await Task.Run(() => _goalProcessor.addNewGoal(data));
return Ok("Goal added");
}
[HttpDelete("CompleteGoal/{goalID}")]
public async Task<IActionResult> CompleteGoal(string goalID)
{
if (await Task.Run(() => _goalProcessor.CompleteGoal(goalID)))
{
return Ok("Goal complete");
}
else return BadRequest("Goal not complete");
}
[HttpPut("AddMoneyToGoal")]
public async Task<IActionResult> AddMoneyToGoal([FromBody]AddMoneyDTO data)
{
await Task.Run(() => _goalProcessor.addMoneyToGoal(data));
return Ok("Money added");
}
}
}
|
namespace Sentry;
/// <summary>
/// A type of application crash.
/// Used exclusively by <see cref="SentrySdk.CauseCrash"/>.
/// </summary>
[Obsolete("WARNING: This method deliberately causes a crash, and should not be used in a real application.")]
public enum CrashType
{
/// <summary>
/// A managed <see cref="ApplicationException"/> will be thrown from .NET.
/// </summary>
Managed,
/// <summary>
/// A managed <see cref="ApplicationException"/> will be thrown from .NET on a background thread.
/// </summary>
ManagedBackgroundThread,
#if ANDROID
/// <summary>
/// A <see cref="global::Java.Lang.RuntimeException"/> will be thrown from Java.
/// </summary>
Java,
/// <summary>
/// A <see cref="global::Java.Lang.RuntimeException"/> will be thrown from Java on a background thread.
/// </summary>
JavaBackgroundThread,
#endif
#if __MOBILE__
/// <summary>
/// A native operation that will crash the appliction will be performed by a C library.
/// </summary>
Native
#endif
}
|
public class Category {
public string Name { get; }
public int Val { get; set; }
public bool IsScored { get; set; }
public Category(string name) {
Name = name;
Val = 0;
IsScored = false;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MultiUserBlock.Common.Enums;
namespace MultiUserBlock.DB
{
public class Program
{
public static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
ConsoleKeyInfo cki;
_outputMenue();
do
{
cki = Console.ReadKey();
switch (cki.KeyChar)
{
case '1':
Console.WriteLine();
Console.WriteLine("Versuche Database zu löschen und neu zu erzeugen, einen Moment bitte...");
_create(true, true);
_outputMenue();
break;
case '2':
Console.WriteLine();
Console.WriteLine("Versuche Database zu löschen, einen Moment bitte...");
_create(true, false);
_outputMenue();
break;
case '3':
Console.WriteLine();
Console.WriteLine("Versuche Database zu erzeugen, einen Moment bitte...");
_create(false, true);
_outputMenue();
break;
}
} while (cki.Key != ConsoleKey.Escape);
Console.WriteLine("Rdy");
Console.ReadLine();
}
internal static void _outputMenue()
{
Console.WriteLine();
Console.WriteLine("1 - Delete/Create");
Console.WriteLine("2 - Delete");
Console.WriteLine("3 - Create");
Console.WriteLine("Esc - Exit");
}
internal static void _create(bool del, bool create)
{
var optionsbuilder = new DbContextOptionsBuilder<DataContext>();
optionsbuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Core-Test-V1;Trusted_Connection=True;MultipleActiveResultSets=true");
using (var context = new DataContext(optionsbuilder.Options))
{
if (del)
{
if (context.Database.EnsureDeleted())
{
Console.WriteLine("Database gelöscht...");
}
else
{
Console.WriteLine("Keine Database gefunden...");
}
}
if (create)
{
if (context.Database.EnsureCreated())
{
Console.WriteLine("Database erzeugt...");
}
else
{
Console.WriteLine("Database existiert bereits...");
//return;
}
Console.WriteLine("Erzeuge Daten...");
Createer_Roles.Create(context);
Creater_Users.Create(context,
new UserRoleType[] { UserRoleType.Admin, UserRoleType.Default },
new User
{
Name = "Riesner",
Vorname = "Rene",
Username = "rr1980",
Password = "12003"
});
Creater_Users.Create(context,
new UserRoleType[] { UserRoleType.Default },
new User
{
Name = "Riesner",
Vorname = "Sven",
Username = "Oxi",
Password = "12003"
});
}
}
}
}
}
|
using System;
namespace DevilDaggersCore.MemoryHandling.Variables
{
public class BoolVariable : AbstractVariable<bool>
{
public override bool ValuePrevious => BitConverter.ToBoolean(BytesPrevious, 0);
public override bool Value => BitConverter.ToBoolean(Bytes, 0);
public BoolVariable(int localBaseAddress, int offset)
: base(localBaseAddress, offset, 4) // Not 1 byte!
{
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using DigitalRuby.PyroParticles;
public class Cultist : MonoBehaviour
{
// All cultists
public float invisibility;
public float disappearSpeed = 0.5f;
public float disappearDelay;
public bool performingAction = false;
// Audio
public AudioSource voice;
public AudioSource combat;
// voice clips
public AudioClip[] line;
// next two for melee cultists only
public float attackDamageDelay = 0.6f;
public int assignedPlayerIndex;
// Variables for Summoner cultist only
public GameObject wallOfFire;
public Transform wallOfFireLocation;
public Transform wallOfFireSingleTargetLocation;
public bool attackSingleTarget;
// Variables for crow cultists only
private bool crowsAreDispatched;
public float summonCrowAttackDelay = 2.0f;
public float crowAttackCooldownTime;
public Creature[] crow;
public Material mat; // Link to material in project window for now!
public enum Status { attack, summon, floatSummon, appear };
public Status cultistStatus;
private Animator _animator;
// Use this for initialization
void Start()
{
// start invisible
invisibility = 1;
_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
mat.SetFloat("_DissolveIntensity", invisibility);
// manually clamp invisibility level
if (invisibility < 0)
invisibility = 0;
if (invisibility > 1)
invisibility = 1;
// Determines if cultist is physicaly present
if (invisibility < 1f)
{
this.performingAction = true;
}
else
{
this.performingAction = false;
}
}
public void DoAction()
{
StartCoroutine(AppearAndDoAnimation());
}
public void GetHurt()
{
StopAllCoroutines();
StartCoroutine(GetHurtCR());
}
IEnumerator GetHurtCR()
{
_animator.SetTrigger("getHurt"); // Really just an Idle animation!
while (invisibility < 1)
{
invisibility += disappearSpeed * Time.deltaTime;
yield return null;
}
}
IEnumerator AppearAndDoAnimation()
{
GameObject wof = new GameObject(); // Create new gameobject for wall of fire
// Play spooky voice sfx (Randomized)
int lineToPlay = Random.Range(0, 10);
if (lineToPlay < 6 && cultistStatus != Status.summon) // Summoner cultists dont say random lines
{
voice.clip = line[lineToPlay];
voice.PlayDelayed(0.5f);
}
while (invisibility > 0)
{
invisibility -= disappearSpeed * Time.deltaTime;
yield return null;
}
// Slight delay before attack
yield return new WaitForSeconds(2f);
// Switch statement determines animation based on enum
switch (cultistStatus)
{
case (Status.attack):
_animator.SetTrigger("attack");
yield return new WaitForSeconds(attackDamageDelay);
// Play SFX for attack
combat.PlayDelayed(0.0f);
GameManager.Instance.DamagePlayer(assignedPlayerIndex, "cultist");
break;
case (Status.summon):
_animator.SetTrigger("summon");
yield return new WaitForSeconds(3);
wof = Instantiate(wallOfFire);
if (attackSingleTarget)
{
wof.GetComponent<FireConstantBaseScript>().Duration = 1;
wof.transform.position = wallOfFireSingleTargetLocation.position;
GameManager.Instance.DamagePlayer(assignedPlayerIndex, "fireSingle");
attackSingleTarget = false; // reset bool
}
else
{
wof.GetComponent<FireConstantBaseScript>().Duration = 1;
wof.transform.position = wallOfFireLocation.position;
GameManager.Instance.DamagePlayer(assignedPlayerIndex, "fire");
}
break;
case (Status.floatSummon):
_animator.SetTrigger("floatSummon");
StartCoroutine(SummonsCrows(assignedPlayerIndex));
break;
default:
break;
}
yield return new WaitForSeconds(disappearDelay);
while (invisibility < 1)
{
invisibility += disappearSpeed * Time.deltaTime;
yield return null;
}
if (wallOfFire != null)
{
Destroy(wof);
}
}
IEnumerator SummonsCrows(int playerIndex)
{
crowsAreDispatched = true;
yield return new WaitForSeconds(summonCrowAttackDelay);
foreach (Creature cre in crow)
{
cre.gameObject.SetActive(true);
cre.Attack(playerIndex);
}
// We subtract summonCrowAttackDelay to make the overall cooldown time precise
yield return new WaitForSeconds(crowAttackCooldownTime - summonCrowAttackDelay);
}
}
|
using System.Collections.Generic;
using Xunit;
using ImagoCore.Models;
using ImagoCore.Enums;
using System.Collections;
namespace ImagoCore.Tests.Models
{
public class KoerperTests
{
[Fact]
public void ConstructKoerper_KoerperHasKopf()
{
var koerper = new KoerperTeileCollection();
var id = ImagoEntitaetFactory.GetNewEntitaet(ImagoKoerperTeil.Kopf);
Assert.NotNull(koerper.Kopf);
Assert.Equal(id, koerper.Kopf.Identifier);
}
[Fact]
public void ConstructKoerper_KoerperHasTorso()
{
var koerper = new KoerperTeileCollection();
var id = ImagoEntitaetFactory.GetNewEntitaet(ImagoKoerperTeil.Torso);
Assert.NotNull(koerper.Torso);
Assert.Equal(id, koerper.Torso.Identifier);
}
[Fact]
public void ConstructKoerper_KoerperHasArmRechts()
{
var koerper = new KoerperTeileCollection();
var id = ImagoEntitaetFactory.GetNewEntitaet(ImagoKoerperTeil.ArmRechts);
Assert.NotNull(koerper.ArmRechts);
Assert.Equal(id, koerper.ArmRechts.Identifier);
}
[Fact]
public void ConstructKoerper_KoerperHasArmLinks()
{
var koerper = new KoerperTeileCollection();
var id = ImagoEntitaetFactory.GetNewEntitaet(ImagoKoerperTeil.ArmLinks);
Assert.NotNull(koerper.ArmLinks);
Assert.Equal(id, koerper.ArmLinks.Identifier);
}
[Fact]
public void ConstructKoerper_KoerperHasBeinRechts()
{
var koerper = new KoerperTeileCollection();
var id = ImagoEntitaetFactory.GetNewEntitaet(ImagoKoerperTeil.BeinRechts);
Assert.NotNull(koerper.BeinRechts);
Assert.Equal(id, koerper.BeinRechts.Identifier);
}
[Fact]
public void ConstructKoerper_KoerperHasBeinLinks()
{
var koerper = new KoerperTeileCollection();
var id = ImagoEntitaetFactory.GetNewEntitaet(ImagoKoerperTeil.BeinLinks);
Assert.NotNull(koerper.BeinLinks);
Assert.Equal(id, koerper.BeinLinks.Identifier);
}
[Theory]
[ClassData(typeof(KopfTrefferpunkteBerechnenTestData))]
public void KopfTrefferpunkteBerechnenStrategy(int konstitution, int expectedTp)
{
var koerper = new KoerperTeileCollection();
koerper.Kopf.BerechneTrefferpunkte(konstitution);
Assert.Equal(expectedTp, koerper.Kopf.MaxTrefferPunkte);
}
[Theory]
[ClassData(typeof(TorsoTrefferpunkteBerechnenTestData))]
public void TorsoTrefferpunkteBerechnenStrategy(int konstitution, int expectedTp)
{
var koerper = new KoerperTeileCollection();
koerper.Torso.BerechneTrefferpunkte(konstitution);
Assert.Equal(expectedTp, koerper.Torso.MaxTrefferPunkte);
}
[Theory]
[ClassData(typeof(ArmTrefferpunkteBerechnenTestData))]
public void ArmTrefferpunkteBerechnenStrategy(int konstitution, int expectedTp)
{
var koerper = new KoerperTeileCollection();
koerper.ArmRechts.BerechneTrefferpunkte(konstitution);
koerper.ArmLinks.BerechneTrefferpunkte(konstitution);
Assert.Equal(expectedTp, koerper.ArmRechts.MaxTrefferPunkte);
Assert.Equal(expectedTp, koerper.ArmLinks.MaxTrefferPunkte);
}
[Theory]
[ClassData(typeof(BeinTrefferpunkteBerechnenTestData))]
public void BeinTrefferpunkteBerechnenStrategy(int konstitution, int expectedTp)
{
var koerper = new KoerperTeileCollection();
koerper.BeinRechts.BerechneTrefferpunkte(konstitution);
koerper.BeinLinks.BerechneTrefferpunkte(konstitution);
Assert.Equal(expectedTp, koerper.BeinRechts.MaxTrefferPunkte);
Assert.Equal(expectedTp, koerper.BeinLinks.MaxTrefferPunkte);
}
}
public class KopfTrefferpunkteBerechnenTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 115; i++)
{
if(i >= 0 && i <= 4)
yield return new object[] { i, 0 };
if (5 <= i && i <= 14)
yield return new object[] { i, 1 };
if (15 <= i && i <= 24)
yield return new object[] { i, 2 };
if (25 <= i && i <= 34)
yield return new object[] { i, 3 };
if (35 <= i && i <= 44)
yield return new object[] { i, 4 };
if (45 <= i && i <= 54)
yield return new object[] { i, 5 };
if (55 <= i && i <= 64)
yield return new object[] { i, 6 };
if (65 <= i &&i <= 74)
yield return new object[] { i, 7 };
if (75 <= i && i <= 84)
yield return new object[] { i, 8 };
if (85 <= i && i <= 94)
yield return new object[] { i, 9 };
if (95 <= i && i <= 104)
yield return new object[] { i, 10 };
if (105 <= i && i <= 114)
yield return new object[] { i, 11 };
if (115 <= i && i <= 125)
yield return new object[] { i, 12 };
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class TorsoTrefferpunkteBerechnenTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 115; i++)
{
if (i >= 0 && i <= 2 )
yield return new object[] { i, 0 };
if (3 <= i && i <= 7)
yield return new object[] { i, 1 };
if (8 <= i && i <= 12)
yield return new object[] { i, 2 };
if (13 <= i && i <= 17)
yield return new object[] { i, 3 };
if (18 <= i && i <= 22)
yield return new object[] { i, 4 };
if (23 <= i && i <= 27)
yield return new object[] { i, 5 };
if (28 <= i && i <= 32)
yield return new object[] { i, 6 };
if (33 <= i && i <= 37)
yield return new object[] { i, 7 };
if (38 <= i && i <= 42)
yield return new object[] { i, 8 };
if (43 <= i && i <= 47)
yield return new object[] { i, 9 };
if (48 <= i && i <= 52)
yield return new object[] { i, 10 };
if (53 <= i && i <= 57)
yield return new object[] { i, 11 };
if (58 <= i && i <= 62)
yield return new object[] { i, 12 };
if (63 <= i && i <= 67)
yield return new object[] { i, 13 };
if (68 <= i && i <= 72)
yield return new object[] { i, 14 };
if (73 <= i && i <= 77)
yield return new object[] { i, 15 };
if (78 <= i && i <= 82)
yield return new object[] { i, 16 };
if (83 <= i && i <= 87)
yield return new object[] { i, 17 };
if (88 <= i && i <= 92)
yield return new object[] { i, 18 };
if (93 <= i && i <= 97)
yield return new object[] { i, 19 };
if (98 <= i && i <= 102)
yield return new object[] { i, 20 };
if (103 <= i && i <= 107)
yield return new object[] { i, 21 };
if (108 <= i && i <= 112)
yield return new object[] { i, 22 };
if (113 <= i && i <= 115)
yield return new object[] { i, 23 };
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class ArmTrefferpunkteBerechnenTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 115; i++)
{
if (i>= 0 && i <= 3)
yield return new object[] { i, 0 };
if (4 <= i && i <= 10)
yield return new object[] { i, 1 };
if (11 <= i && i <= 17)
yield return new object[] { i, 2 };
if (18 <= i && i <= 24)
yield return new object[] { i, 3 };
if (25 <= i && i <= 31)
yield return new object[] { i, 4 };
if (32 <= i && i <= 38)
yield return new object[] { i, 5 };
if (39 <= i && i <= 45)
yield return new object[] { i, 6 };
if (46 <= i && i <= 52)
yield return new object[] { i, 7 };
if (53 <= i && i <= 59)
yield return new object[] { i, 8 };
if (60 <= i && i <= 66)
yield return new object[] { i, 9 };
if (67 <= i && i <= 73)
yield return new object[] { i, 10 };
if (74 <= i && i <= 80)
yield return new object[] { i, 11 };
if (81 <= i && i <= 87)
yield return new object[] { i, 12 };
if (88 <= i && i <= 94)
yield return new object[] { i, 13 };
if (95 <= i && i <= 101)
yield return new object[] { i, 14 };
if (102 <= i && i <= 108)
yield return new object[] { i, 15 };
if (109 <= i && i <= 115)
yield return new object[] { i, 16 };
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class BeinTrefferpunkteBerechnenTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
for (int i = 0; i <= 115; i++)
{
if (i >= 0 && i <= 2)
yield return new object[] { i, 0 };
if (3 <= i && i <= 8)
yield return new object[] { i, 1 };
if (9 <= i && i <= 14)
yield return new object[] { i, 2 };
if (15 <= i && i <= 20)
yield return new object[] { i, 3 };
if (21 <= i && i <= 26)
yield return new object[] { i, 4 };
if (27 <= i && i <= 32)
yield return new object[] { i, 5 };
if (33 <= i && i <= 38)
yield return new object[] { i, 6 };
if (39 <= i && i <= 44)
yield return new object[] { i, 7 };
if (45 <= i && i <= 50)
yield return new object[] { i, 8 };
if (51 <= i && i <= 56)
yield return new object[] { i, 9 };
if (57 <= i && i <= 62)
yield return new object[] { i, 10 };
if (63 <= i && i <= 68)
yield return new object[] { i, 11 };
if (69 <= i && i <= 74)
yield return new object[] { i, 12 };
if (75 <= i && i <= 80)
yield return new object[] { i, 13 };
if (81 <= i && i <= 86)
yield return new object[] { i, 14 };
if (87 <= i && i <= 92)
yield return new object[] { i, 15 };
if (93 <= i && i <= 98)
yield return new object[] { i, 16 };
if (99 <= i && i <= 104)
yield return new object[] { i, 17 };
if (105 <= i && i <= 110)
yield return new object[] { i, 18 };
if (111 <= i && i <= 115)
yield return new object[] { i, 19 };
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
namespace CryptoReaper.Simulation.Devices
{
class HellFireReceiver : GameToken, IOutputs<HellFire>
{
public HellFireReceiver() : base("Sprites/HellFireReceiver")
{
}
public IInputs<HellFire> OutputTo => throw new System.NotImplementedException();
public IODirection OutputToDirection => throw new System.NotImplementedException();
}
class SoulReceiver : GameToken, IOutputs<Soul>
{
public SoulReceiver() : base("Sprites/SoulReceiver")
{
}
public IInputs<Soul> OutputTo => throw new System.NotImplementedException();
public IODirection OutputToDirection => throw new System.NotImplementedException();
}
}
|
using ControleFinanceiro.Domain.Contracts.Repositories;
using ControleFinanceiro.Domain.Contracts.Services;
using ControleFinanceiro.Domain.Entities;
using ControleFinanceiro.Infra.Data.EF;
using System;
using System.Collections.Generic;
namespace ControleFinanceiro.Domain.Service.Services
{
public class ServicoReceita : ServicoBase<Receita>, IServicoReceita
{
private readonly IRepositorioReceita _repositorioReceita;
public ServicoReceita(IRepositorioReceita repositorioReceita, EFContext context) : base(repositorioReceita, context)
{
_repositorioReceita = repositorioReceita;
}
public List<Receita> ListarReceitaPorData(DateTime data, int idUsuario)
{
return _repositorioReceita.ListarReceitaPorData(data, idUsuario);
}
}
}
|
using AutoMapper;
using IntegrationAdapters.Apis.Grpc;
using IntegrationAdapters.Dtos;
namespace IntegrationAdapters.MapperProfiles
{
public class PharmacySystemProfile_Id1 : Profile
{
public PharmacySystemProfile_Id1()
{
CreateMap<Drug, DrugDto>().ForMember(dest => dest.PharmacyDto, opt => opt.MapFrom(src => src.Pharmacy));
CreateMap<Pharmacy, PharmacyDto>();
}
}
}
|
namespace FoodPricer.Core.Order.Meal
{
public class Sandwich : IMeal
{
public double Price => 10;
}
} |
using DataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
namespace DataStorage
{
public class BatContext : DbContext
{
public BatContext(DbContextOptions<BatContext> options)
: base(options) { }
public BatContext() { }
public DbSet<Person> Persons { get; set; }
}
}
|
using Bolster.API.Interface.Stateless;
using NUnit.Framework;
namespace Bolster.Test
{
[TestFixture]
public class TestStatus
{
[Test]
public static void TestFluentInterface() {
var didNotWork = Status.Failure.Reason("The operation did not work");
var worked = Status.Success.Result("The operation worked");
Assert.True(didNotWork.IsFailure);
Assert.True(worked.IsSuccess);
}
}
} |
using EPI.Sorting;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.Sorting
{
[TestClass]
public class MergeSortUnitTest
{
[TestMethod]
public void MergeSortTest()
{
int[] A = new[] { 23, 1, 56, 99, 0, -1, 7, 7, 8 };
MergeSort<int>.Sort(A);
A.ShouldBeEquivalentTo(new[] { -1, 0, 1, 7, 7, 8, 23, 56, 99 });
}
}
}
|
using System;
using System.IO;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
using SixLabors.Shapes;
namespace Overmapper
{
class Program
{
static void Main(string[] args)
{
var raw = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
using var img = new Image<Rgba32>(144, 144);
var font = SystemFonts.CreateFont("Consolas", 24, FontStyle.Regular);
var size = TextMeasurer.Measure("H", new RendererOptions(font));
var tgo = new TextGraphicsOptions
{
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
DpiX = 72,
DpiY = 72,
};
var go = new GraphicsOptions
{
};
var y = 0;
for (var i = 0; i < raw.Length; i++)
{
var x = (i%6)*24;
if (i % 6 == 0)
{
y = (int)(i / 6 * 24);
}
var i1 = i;
var y1 = y;
img.Mutate(ctx => ctx
.Fill(go, Color.Green, new RectangleF(x, y1, 24, 24))
.DrawText(tgo, raw[i1].ToString(), font, Color.Black, new PointF(x, y1)));
}
img.Save("temp.png");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using Quark.Conditions;
using Quark.Contexts;
using UnityEngine;
using Quark.Utilities;
namespace Quark
{
public class ConditionCollection<T> : Condition<T>, IEnumerable<ICondition>, IDeepCopiable<ConditionCollection<T>>, IDisposable where T : class, IContext
{
private List<ICondition> _conditions;
/// <summary>
/// Initialize a new condition collection
/// </summary>
public ConditionCollection()
{
_conditions = new List<ICondition>();
}
~ConditionCollection()
{
Dispose();
}
public void Dispose()
{
foreach (ICondition condition in _conditions)
condition.SetContext(null);
_conditions.Clear();
_conditions = null;
}
public ConditionCollection<T> DeepCopy()
{
ConditionCollection<T> newCollection = new ConditionCollection<T>();
newCollection._conditions = new List<ICondition>(_conditions);
return newCollection;
}
object IDeepCopiable.DeepCopy()
{
return DeepCopy();
}
/// <summary>
/// Add a new condition to this collection
/// </summary>
/// <param name="condition">The condition to be added</param>
public void Add(ICondition<T> condition)
{
_conditions.Add(condition);
}
public IEnumerator<ICondition> GetEnumerator()
{
return _conditions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _conditions.GetEnumerator();
}
public override bool Check()
{
foreach (ICondition condition in _conditions)
{
condition.SetContext(Context);
if (!condition.Check())
return false;
}
return true;
}
public override bool Check(Character character)
{
foreach (ICondition condition in _conditions)
{
condition.SetContext(Context);
if (!condition.Check(character))
return false;
}
return true;
}
public override bool Check(Targetable target)
{
foreach (ICondition condition in _conditions)
{
condition.SetContext(Context);
if (!condition.Check(target))
return false;
}
return true;
}
public override bool Check(Vector3 point)
{
foreach (ICondition condition in _conditions)
{
condition.SetContext(Context);
if (!condition.Check(point))
return false;
}
return true;
}
}
}
|
using System;
using System.Runtime.CompilerServices;
using iSukces.Code.Interfaces;
using JetBrains.Annotations;
namespace iSukces.Code
{
public class CsCodeWriter : CodeWriter, ICsCodeWriter
{
public CsCodeWriter([CallerMemberName] string memberName = null,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = 0)
: base(CsLangInfo.Instance)
{
Location = new SourceCodeLocation(lineNumber, memberName, filePath);
}
public static CsCodeWriter Create(SourceCodeLocation location)
{
var code = new CsCodeWriter
{
Location = location
};
code.WriteLine("// generator : " + location.ToString());
return code;
}
public static CsCodeWriter Create<T>([CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null
) =>
Create(new SourceCodeLocation(lineNumber, memberName, filePath)
.WithGeneratorClass(typeof(T)));
public static CsCodeWriter Create(Type generatorClass, [CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null
) =>
Create(new SourceCodeLocation(lineNumber, memberName, filePath)
.WithGeneratorClass(generatorClass));
public void AddAutocodeGeneratedAttribute(IAttributable attributable, [NotNull] ITypeNameResolver resolver)
{
attributable.WithAutocodeGeneratedAttribute(resolver, Location);
}
public SourceCodeLocation Location { get; set; }
}
} |
//Max And Min Of Array
public void MaxAndMinOfArray(List<string> readInList)
{
List<int> myList = new List<int>();
string[] temp = null;
foreach (string x in readInList)
{
temp = x.Split(' ');
}
foreach (string s in temp)
{
myList.Add(Convert.ToInt32(s));
}
int maxValue = myList[0];
int minValue = myList[0];
for (int x = 0; x < myList.Count; x++)
{
if (myList[x] > maxValue)
{
maxValue = myList[x];
}
if (myList[x] < minValue)
{
minValue = myList[x];
}
}
Console.Write(maxValue + " " + minValue);
}
|
namespace RTBid.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class new1 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Auctions",
c => new
{
AuctionId = c.Int(nullable: false, identity: true),
ProductId = c.Int(nullable: false),
AuctionTitle = c.String(),
NumberOfBidders = c.Int(),
NumberOfGuests = c.Int(),
CreatedDate = c.DateTime(nullable: false),
DeletedDate = c.DateTime(),
StartTime = c.DateTime(nullable: false),
ClosedTime = c.DateTime(),
})
.PrimaryKey(t => t.AuctionId)
.ForeignKey("dbo.Products", t => t.ProductId, cascadeDelete: true)
.Index(t => t.ProductId);
CreateTable(
"dbo.Bids",
c => new
{
BidId = c.Int(nullable: false, identity: true),
AuctionId = c.Int(nullable: false),
UserId = c.Int(nullable: false),
ProductId = c.Int(nullable: false),
CurrentAmount = c.Decimal(nullable: false, precision: 18, scale: 2),
AttachedText = c.String(),
TimeStamp = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.BidId)
.ForeignKey("dbo.Auctions", t => t.AuctionId, cascadeDelete: true)
.ForeignKey("dbo.Products", t => t.ProductId)
.ForeignKey("dbo.RTBidUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.AuctionId)
.Index(t => t.UserId)
.Index(t => t.ProductId);
CreateTable(
"dbo.Products",
c => new
{
ProductId = c.Int(nullable: false, identity: true),
CategoryId = c.Int(nullable: false),
UserId = c.Int(),
Name = c.String(),
Description = c.String(),
ImageUrl = c.String(),
ShippingCost = c.Decimal(precision: 18, scale: 2),
SellingPrice = c.Decimal(precision: 18, scale: 2),
StartBid = c.Decimal(precision: 18, scale: 2),
MinimumIncrement = c.Decimal(precision: 18, scale: 2),
})
.PrimaryKey(t => t.ProductId)
.ForeignKey("dbo.Categories", t => t.CategoryId, cascadeDelete: true)
.ForeignKey("dbo.RTBidUsers", t => t.UserId)
.Index(t => t.CategoryId)
.Index(t => t.UserId);
CreateTable(
"dbo.Categories",
c => new
{
CategoryId = c.Int(nullable: false, identity: true),
CategoryName = c.String(),
CategoryDescription = c.String(),
CreatedDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.CategoryId);
CreateTable(
"dbo.Purchases",
c => new
{
PurchaseId = c.Int(nullable: false, identity: true),
UserId = c.Int(nullable: false),
InvoiceNumber = c.String(),
ShippingCost = c.Decimal(precision: 18, scale: 2),
Price = c.Decimal(precision: 18, scale: 2),
CreatedDate = c.DateTime(nullable: false),
ProductId = c.Int(nullable: false),
})
.PrimaryKey(t => t.PurchaseId)
.ForeignKey("dbo.RTBidUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.Products", t => t.ProductId)
.Index(t => t.UserId)
.Index(t => t.ProductId);
CreateTable(
"dbo.RTBidUsers",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserName = c.String(),
PasswordHash = c.String(),
SecurityStamp = c.String(),
Address = c.String(),
Telephone = c.String(),
Email = c.String(),
Age = c.Int(nullable: false),
AccountBalance = c.Decimal(precision: 18, scale: 2),
CreatedDate = c.DateTime(nullable: false),
DeletedDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.UserAuctions",
c => new
{
UserId = c.Int(nullable: false),
AuctionId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.UserId, t.AuctionId })
.ForeignKey("dbo.RTBidUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.Auctions", t => t.AuctionId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.AuctionId);
CreateTable(
"dbo.Comments",
c => new
{
CommentId = c.Int(nullable: false, identity: true),
AuctionId = c.Int(nullable: false),
UserId = c.Int(nullable: false),
Title = c.String(),
Description = c.String(),
AttachmentUrl = c.String(),
TimeStamp = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.CommentId)
.ForeignKey("dbo.RTBidUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.Auctions", t => t.AuctionId)
.Index(t => t.AuctionId)
.Index(t => t.UserId);
CreateTable(
"dbo.UserRoles",
c => new
{
UserId = c.Int(nullable: false),
RoleId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.Roles", t => t.RoleId, cascadeDelete: true)
.ForeignKey("dbo.RTBidUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.Roles",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropForeignKey("dbo.UserAuctions", "AuctionId", "dbo.Auctions");
DropForeignKey("dbo.Comments", "AuctionId", "dbo.Auctions");
DropForeignKey("dbo.Purchases", "ProductId", "dbo.Products");
DropForeignKey("dbo.UserRoles", "UserId", "dbo.RTBidUsers");
DropForeignKey("dbo.UserRoles", "RoleId", "dbo.Roles");
DropForeignKey("dbo.Purchases", "UserId", "dbo.RTBidUsers");
DropForeignKey("dbo.Products", "UserId", "dbo.RTBidUsers");
DropForeignKey("dbo.Comments", "UserId", "dbo.RTBidUsers");
DropForeignKey("dbo.Bids", "UserId", "dbo.RTBidUsers");
DropForeignKey("dbo.UserAuctions", "UserId", "dbo.RTBidUsers");
DropForeignKey("dbo.Products", "CategoryId", "dbo.Categories");
DropForeignKey("dbo.Bids", "ProductId", "dbo.Products");
DropForeignKey("dbo.Auctions", "ProductId", "dbo.Products");
DropForeignKey("dbo.Bids", "AuctionId", "dbo.Auctions");
DropIndex("dbo.UserRoles", new[] { "RoleId" });
DropIndex("dbo.UserRoles", new[] { "UserId" });
DropIndex("dbo.Comments", new[] { "UserId" });
DropIndex("dbo.Comments", new[] { "AuctionId" });
DropIndex("dbo.UserAuctions", new[] { "AuctionId" });
DropIndex("dbo.UserAuctions", new[] { "UserId" });
DropIndex("dbo.Purchases", new[] { "ProductId" });
DropIndex("dbo.Purchases", new[] { "UserId" });
DropIndex("dbo.Products", new[] { "UserId" });
DropIndex("dbo.Products", new[] { "CategoryId" });
DropIndex("dbo.Bids", new[] { "ProductId" });
DropIndex("dbo.Bids", new[] { "UserId" });
DropIndex("dbo.Bids", new[] { "AuctionId" });
DropIndex("dbo.Auctions", new[] { "ProductId" });
DropTable("dbo.Roles");
DropTable("dbo.UserRoles");
DropTable("dbo.Comments");
DropTable("dbo.UserAuctions");
DropTable("dbo.RTBidUsers");
DropTable("dbo.Purchases");
DropTable("dbo.Categories");
DropTable("dbo.Products");
DropTable("dbo.Bids");
DropTable("dbo.Auctions");
}
}
}
|
namespace ClipModels
{
public class SupplierList
{
public int ID { get; set; }
public virtual SupplierClip SupplierClip { get; set; }
public int SupplierClipId { get; set; }
}
}
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
using LogoSystem;
using Shared;
using Xunit;
namespace Tests
{
public class LogoTests
{
[Fact]
public static async Task FetchesFavicon()
{
var result = await QueueFunction.FetchLogo(new HttpClient{Timeout = TimeSpan.FromSeconds(5)}, new LogoRequest { Uri = new Uri("https://google.com") });
Assert.False(string.IsNullOrWhiteSpace(result));
}
}
}
|
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace FamilyAccounting.AutoMapper
{
public static class MappingConfiguration
{
public static IServiceCollection AddModelMapping(this IServiceCollection services)
{
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
return services;
}
}
}
|
using Jogging.Model.JsonConverters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jogging.Model
{
public class Session
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("start")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Start { get; set; }
[JsonProperty("end")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime End { get; set; }
[JsonProperty("user")]
public User User { get; set; }
[JsonIgnore]
public double AverageTemperature { get; set; }
[JsonIgnore]
public double AverageHumidity { get; set; }
[JsonIgnore]
public double AverageActivity { get; set; }
[JsonIgnore]
public double AveragePressure { get; set; }
public TimeSpan Duration
{
get
{
return End - Start;
}
}
}
}
|
using System;
namespace DmManager.Models
{
public class Note
{
public int Id { get; set; }
public string Body { get; set; }
public DateTime When { get; set; } = DateTime.UtcNow;
public int GameId { get; set; }
public Game Game { get; set; }
}
public class NoteVM
{
public string Body { get; set; }
}
} |
using RiverPuzzle1.Models;
using System.Collections.Generic;
using Xunit;
namespace RiverPuzzle1.Tests.Models
{
public class BeanTests
{
[Fact]
public void NotCompatibleCharacters_ReturnsListOfStrings()
{
// Arrange
var character = new Bean();
// Act
var result = character.NotCompatibleCharacters;
// Assert
Assert.IsType<Dictionary<string, string>>(result);
Assert.Equal(1, result.Count);
Assert.Equal("Goose will eat the bean", result["Goose"]);
}
}
}
|
using System;
namespace accessController
{
internal class Packet
{
public static int WGPacketSize = 64; //Short Packet Length
//2015-04-29 22:22:41 const static unsigned char Type = 0x19; //Type
public static int Type = 0x17; //2015-04-29 22:22:50 //Type
public static int ControllerPort = 60000; //Access Controller' Port
public static long SpecialFlag = 0x55AAAA55; //Special logo to prevent misuse
public int functionID; //Function ID
public long iDevSn; //Deceive Serial Number(Controller) four bytes, nine dec number
public string IP; //Access Controller' IP Address
public byte[] data = new byte[56]; //56 bytes of data [including sequenceId]
public byte[] recv = new byte[WGPacketSize]; //Receive Data buffer
private static long sequenceId;
public Packet(string IpAddress, long SerialNumber)
{
iDevSn = SerialNumber;
IP = IpAddress;
Reset();
}
public void Reset() //Data reset
{
for (int i = 0; i < 56; i++)
{
data[i] = 0;
}
}
public byte[] ToByte() //Generates a 64-byte short package
{
byte[] buff = new byte[WGPacketSize];
sequenceId++;
buff[0] = (byte)Type;
buff[1] = (byte)functionID;
Array.Copy(System.BitConverter.GetBytes(iDevSn), 0, buff, 4, 4);
Array.Copy(data, 0, buff, 8, data.Length);
Array.Copy(System.BitConverter.GetBytes(sequenceId), 0, buff, 40, 4);
return buff;
}
private readonly WG3000_COMM.Core.wgMjController controller = new();
public int Run() //send command ,receive return command
{
byte[] buff = ToByte();
int tries = 3;
int errcnt = 0;
controller.IP = IP;
controller.PORT = ControllerPort;
do
{
if (controller.ShortPacketSend(buff, ref recv) < 0)
{
return -1;
}
else
{
//sequenceId
long sequenceIdReceived = 0;
for (int i = 0; i < 4; i++)
{
long lng = recv[40 + i];
sequenceIdReceived += (lng << (8 * i));
}
if ((recv[0] == Type) //Type consistent
&& (recv[1] == functionID) //Function ID is consistent
&& (sequenceIdReceived == sequenceId)) //Controller'Serial number correspondence
{
return 1;
}
else
{
errcnt++;
}
}
} while (tries-- > 0); //Retry three times
return -1;
}
public static long SequenceIdSent()//
{
return sequenceId; // The last issue of the serial number(xid)
}
public void Close()
{
controller.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COM_ports
{
public static class Extens
{
public static Size Div(this Size size, int div)
{
return new Size(size.Height / div, size.Width / div);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ShoppingCart
{
public class Jeans : Pants
{
public override double SizeValue(int ProductSize)
{
return base.SizeValue(ProductSize);
}
}
}
|
using eTicaretProjesi.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eTicaretProjesi.BL.Repository
{
public class BaseRepository<T, TId> where T : class
{
protected internal static MyContext dbContext;
public virtual List<T> Listele()
{
try
{
dbContext = new MyContext();
return dbContext.Set<T>().ToList();
}
catch (Exception ex)
{
throw ex;
}
}
public virtual IQueryable<T> GenelListele()
{
try
{
dbContext = new MyContext();
return dbContext.Set<T>().AsQueryable();
}
catch (Exception ex)
{
throw ex;
}
}
public virtual T IDyeGoreBul(TId id)
{
try
{
dbContext = new MyContext();
return dbContext.Set<T>().Find(id);
}
catch (Exception ex)
{
throw ex;
}
}
public virtual int Ekle(T entity)
{
try
{
dbContext = dbContext ?? new MyContext();
dbContext.Set<T>().Add(entity);
return dbContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
public virtual int Sil(T entity)
{
try
{
dbContext = dbContext ?? new MyContext();
dbContext.Set<T>().Remove(entity);
return dbContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
public virtual int Guncelle()
{
try
{
dbContext = dbContext ?? new MyContext();
return dbContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
using AuctionApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;
namespace SpecflowWorkshop.Steps
{
[Binding]
class RetrieveAuctionsGivenSteps
{
private readonly RetrieveAuctionContext _context;
public RetrieveAuctionsGivenSteps(RetrieveAuctionContext context)
{
_context = context;
}
[Given(@"A list of (.*) auctions stored in database")]
public void GivenAListOfAuctionsStoredInDatabase(int numberOfAuctions)
{
CreateAuctions(_context.Storage, numberOfAuctions);
}
[Given(@"An auctions with id (.*) and start time ""(.*)"" and end time ""(.*)""")]
public void GivenAnAuctionsWithIdAndStartTimeAndEndTime(int id, DateTime starTime, DateTime endTime)
{
var auction = new Auction()
{
Id = id,
StartDateTime = starTime,
EndDateTime = endTime
};
_context.Storage.Add(auction);
}
[Given(@"An stored auction")]
public void GivenAnAuctionsWithAndAnd(Table table)
{
IList<Auction> auctions = table.CreateSet<Auction>().ToList();
foreach (var item in auctions)
{
_context.Storage.Add(item);
}
}
private void CreateAuctions(IList<Auction> storage, int numberOfAuctions)
{
for (int i = 0; i < numberOfAuctions; i++)
{
var auction = new Auction()
{
Id = i,
StartDateTime = DateTime.Now,
EndDateTime = DateTime.Now.AddDays(1)
};
storage.Add(auction);
}
}
}
}
|
using SMG.Common.Transitions;
using System;
using System.Collections.Generic;
namespace SMG.Common.Conditions
{
/// <summary>
/// Static operations and extensions on the ICondition interface.
/// </summary>
public static class ConditionOperations
{
/// <summary>
/// Calls a replace handler recursively.
/// </summary>
/// <param name="c">The condition object to convert.</param>
/// <param name="replacer">The replace method.</param>
/// <returns>The converted object.</returns>
/// <remarks>
/// <para>This method leaves the original condition intact.</para>
/// </remarks>
public static ICondition Replace(this ICondition c, Func<ICondition, ICondition> replacer)
{
var r = c.Clone();
for(int j = 0; j < r.Elements.Count; ++j)
{
r.Elements[j] = replacer(r.Elements[j]);
}
return replacer(r);
}
/// <summary>
/// Creates a condition that represents the negation of the argument.
/// </summary>
/// <param name="c">The condition to invert.</param>
/// <returns>The inverted condition.</returns>
public static ICondition Invert(this ICondition c)
{
return new InvertCondition(c);
}
/// <summary>
/// Creates a condition that represents the union (sum) of two conditions.
/// </summary>
/// <param name="a">Argument condition.</param>
/// <param name="b">Argument condition.</param>
/// <returns>The union condition.</returns>
public static ICondition Union(this ICondition a, ICondition b)
{
var list = new List<ICondition>();
foreach (var e in new[] { a, b })
{
if (e is UnionCondition)
{
list.AddRange(e.Elements);
}
else
{
list.Add(e);
}
}
return new UnionCondition(list);
}
/// <summary>
/// Creates a condition that represents the intersection (product) of two conditions.
/// </summary>
/// <param name="a">Argument condition.</param>
/// <param name="b">Argument condition.</param>
/// <returns>The resulting intersection condition.</returns>
public static ICondition Intersection(this ICondition a, ICondition b)
{
var list = new List<ICondition>();
foreach (var e in new[] { a, b })
{
if (e is IntersectCondition)
{
list.AddRange(e.Elements);
}
else
{
list.Add(e);
}
}
return new IntersectCondition(list);
}
public static bool ContainsTransitions(this ICondition c)
{
var tset = new TransitionSet(c);
return !tset.IsEmpty;
}
public static IGate Decompose(this IVariableCondition vc)
{
return vc.CreateElementaryCondition(vc.StateIndex);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Linedata.Foundation.Domain.Messaging;
namespace Account.DDD.Commands
{
public class BlockAccount : Command
{
public Guid AccountId;
public BlockAccount(Guid id)
{
AccountId = id;
}
}
}
|
namespace Template
{
public class UHCPharmacyInsuranceValidator : PharmacyInsuranceValidator
{
public UHCPharmacyInsuranceValidator(PatientProfile patient) : base(patient)
{
}
protected override decimal GetCoveragePrice(Drug drug)
{
return drug.Price / 5;
}
protected override bool IsDrugCovered(Drug drug)
{
return (drug.DrugCode.StartsWith("UHC"));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameRecorder : MonoBehaviour {
[SerializeField]
private Transform players;
private Stack<GameObject> lifeRanking;
private int nbPlayers;
private int alivePlayers;
private bool checkAlive;
// Use this for initialization
void Start () {
players = GameObject.Find ("Players").transform;
DontDestroyOnLoad (gameObject);
DontDestroyOnLoad (players.gameObject);
lifeRanking = new Stack<GameObject> ();
checkAlive = true;
}
// Update is called once per frame
void Update () {
if (checkAlive && alivePlayers <= 1) {
GameObject winner = GameObject.FindGameObjectWithTag ("Player");
//winner.GetComponent<AudioSource> ().Stop ();
//winner.GetComponent<AudioSource> ().loop = false;
winner.GetComponent<Player> ().gameFinished = true;
checkAlive = false;
lifeRanking.Push (winner);
SceneManager.LoadScene (3);
}
}
public void Initialize(int players) {
nbPlayers = players;
alivePlayers = nbPlayers;
}
public void playerDies(GameObject player) {
lifeRanking.Push (player);
alivePlayers -= 1;
player.GetComponent<AudioSource> ().loop = false;
player.GetComponent<AudioSource> ().Stop ();
player.GetComponent<Player> ().gameFinished = true;
}
public void DisplayRanking() {
GameObject[] ranks = lifeRanking.ToArray ();
Transform places = GameObject.Find ("PodiumSpawn").transform;
for (int i = 0; i < ranks.Length; ++i) {
ranks [i].transform.position = places.GetChild (i).position + new Vector3 (0, 0.7f, 0);
ranks [i].transform.localScale *= 2;
ranks [i].transform.rotation = Quaternion.Euler(new Vector3(0, 180, 0));
ranks [i].SetActive (true);
}
}
}
|
using SoulHunter.Enemy;
using UnityEngine;
public class EnemyAnimation : MonoBehaviour // Mort
{
EnemyBase enemyBase;
EnemyCombat enemyCombat;
EnemyScript movement;
SpriteRenderer spriteRenderer;
Animator anim;
private void Awake()
{
enemyBase = GetComponentInParent<EnemyBase>();
enemyCombat = GetComponentInParent<EnemyCombat>();
movement = GetComponentInParent<EnemyScript>();
spriteRenderer = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
private void LateUpdate()
{
UpdateValues();
FlipTexture();
}
/// <summary>
/// Updates animator values
/// </summary>
void UpdateValues()
{
// Syncs animator booleans with static booleans
anim.SetBool("isAttacking", enemyCombat.attacking);
anim.SetBool("isDead", enemyBase.isDead);
anim.SetBool("isHurt", false);
// Syncs animator speed with enemy speed
anim.SetFloat("Speed", Mathf.Abs(movement.currentSpeed));
}
/// <summary>
/// Flips enemy sprite according to its movement direction
/// </summary>
void FlipTexture()
{
if (movement.Moving)
{
if (movement.MoveRight)
{
spriteRenderer.flipX = false;
}
else
{
spriteRenderer.flipX = true;
}
}
}
/// <summary>
/// Plays hurt animation once
/// </summary>
public void HurtAnimation()
{
anim.SetBool("isHurt", true);
}
}
|
using Airelax.Domain.Houses.Defines;
namespace Airelax.Application.ManageHouses.Request
{
public class HouseCategoryInput
{
public Category Category { get; set; }
public HouseType? HouseType { get; set; }
public RoomCategory? RoomCategory { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MVCManukauTech.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//2019-03-19 JPC
using MVCManukauTech.Models.DB;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace MVCManukauTech
{
public class Startup
{
//2018-03-12 JPC use of Session ref:
//https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?tabs=aspnetcore2x
//Add injection of hostingEnvironment
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
Configuration = configuration;
_hostingEnvironment = hostingEnvironment;
}
public IConfiguration Configuration { get; }
private readonly IHostingEnvironment _hostingEnvironment;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Pagination from X.PagedList
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//2019-03-19 JPC NOTE
//IF you do assignment Part C the official Microsoft Way you will need to comment this block out
//You may need to keep this block if you code directly to the AspNet database tables.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
//2019-03-29 JPC need ".AddRoles" to support working with User data
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
//2019-03-19 JPC This may need renaming for a differently-named database and its context class
services.AddDbContext<RareShoesContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Adds a default in-memory implementation of IDistributedCache.
// This is needed for Session support
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
// Comment-out returns to the default of 20 min
// options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
//2019-03-29 JPC updating to ASP.NET Core 2.2
//security option needed on "cookies" to maintain Session data. Ref:
//https://stackoverflow.com/questions/49770491/session-variable-value-is-getting-null-in-asp-net-core
//
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
//2018-03-12 JPC Session. Note that this needs to go in before app.UseMvc
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using E_LEARNING.Data;
using E_LEARNING.Models;
using Microsoft.AspNetCore.Identity;
namespace E_LEARNING.Controllers
{
public class formationsController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _usermanager;
public formationsController(ApplicationDbContext context, UserManager<IdentityUser> usermanage)
{
_context = context;
_usermanager = usermanage;
}
// GET: formations
public async Task<IActionResult> Index()
{
if (User.Identity.IsAuthenticated)
{
await DataByUser();
}
else
{
return NotFound();
}
return View();
}
public async Task<IActionResult> DataByUser()
{
var student = await _usermanager.GetUserAsync(HttpContext.User);
var format = await _context.formations.Include(i => i.Student).Include(c=>c.categorie).ToListAsync();
return View(format.Where(i=>i.StudentId==student.Id));
}
public IActionResult Create()
{
ViewBag.categorie = _context.categories.ToList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(formation formation)
{
if (ModelState.IsValid)
{
var student = await _usermanager.GetUserAsync(HttpContext.User);
var reser = new formation();
reser.Date = formation.Date;
reser.Name = formation.Name;
reser.Description = formation.Description;
reser.StudentId = student.Id;
reser.CategorieId = formation.CategorieId;
_context.Add(reser);
await _context.SaveChangesAsync();
return RedirectToAction("index");
}
return View(formation);
}
public async Task<IActionResult> Edit(int id)
{
var form =await _context.formations.FindAsync(id);
return View(form);
}
[HttpPost]
public async Task<IActionResult> Edit(formation formation)
{
if (ModelState.IsValid)
{
var categ = _context.categories.Where(r => r.Id == formation.CategorieId).FirstOrDefault();
var student = await _usermanager.GetUserAsync(HttpContext.User);
formation.StudentId = student.Id;
formation.CategorieId = categ.Id;
_context.Update(formation);
await _context.SaveChangesAsync();
}
return RedirectToAction("index",formation);
}
public IActionResult Details(int id)
{
var form = _context.formations.Include(s=>s.Student).FirstOrDefault(r=>r.Id==id);
return View(form);
}
public async Task<IActionResult> Delete(int id)
{
var form = await _context.formations.Include(s=>s.Student).FirstOrDefaultAsync(r=>r.Id==id);
return View(form);
}
[HttpPost]
public IActionResult Delete(int? id)
{
var form = _context.formations.Find(id);
_context.Remove(form);
_context.SaveChanges();
return RedirectToAction("index");
}
}
}
|
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace ScriptableObjectFramework.Attributes
{
/// <summary>
/// Connects a field to a property so that when it is changed in editor, the property will be triggered as well.
/// </summary>
/// <remarks>
/// This works by, on change, assigning the field to the property. Therefor checks to prevent the property from doing anything if the value is the same as the one already stored may interfere.
/// </remarks>
[AttributeUsage(AttributeTargets.Field)]
public class PairedProperty : PropertyModifier
{
public string PropertyName;
public bool PlaymodeOnly;
public PairedProperty(string propertyName, bool playmodeOnly = true)
{
PropertyName = propertyName;
PlaymodeOnly = playmodeOnly;
}
#if UNITY_EDITOR
public override void OnValueChanged(SerializedProperty property, FieldInfo fieldInfo)
{
property.serializedObject.ApplyModifiedProperties();
if (EditorApplication.isPlaying || !PlaymodeOnly)
{
object target = property.serializedObject.targetObject;
var targetType = target.GetType();
var targetProperty = targetType.GetProperty(PropertyName);
if (targetProperty != null)
{
if (targetProperty.CanWrite)
{
object val = fieldInfo.GetValue(target);
targetProperty.SetValue(target, val);
}
else
{
Debug.LogError($"{target.GetType()}.{PropertyName} does not have a setter.");
}
}
else
{
Debug.LogError($"{target.GetType()} does not have a property named {PropertyName}.");
}
}
}
#endif
}
}
|
// <copyright file="LanguageSystemRecord.cs" company="WaterTrans">
// © 2020 WaterTrans
// </copyright>
namespace WaterTrans.GlyphLoader.Internal.OpenType
{
/// <summary>
/// The OpenType language system record.
/// </summary>
internal sealed class LanguageSystemRecord
{
/// <summary>
/// Initializes a new instance of the <see cref="LanguageSystemRecord"/> class.
/// </summary>
/// <param name="reader">The <see cref="TypefaceReader"/>.</param>
internal LanguageSystemRecord(TypefaceReader reader)
{
IsDefault = false;
Tag = reader.ReadCharArray(4);
Offset = reader.ReadUInt16();
}
/// <summary>
/// Initializes a new instance of the <see cref="LanguageSystemRecord"/> class.
/// </summary>
/// <param name="isDefault">Sets IsDefault.</param>
/// <param name="offset">Sets Offset.</param>
internal LanguageSystemRecord(bool isDefault, ushort offset)
{
IsDefault = isDefault;
Tag = "DFLT";
Offset = offset;
}
/// <summary>Gets a value indicating whether default LangSysTable.</summary>
/// <remarks>Default LangSysTable.</remarks>
public bool IsDefault { get; }
/// <summary>Gets Tag.</summary>
/// <remarks>LangSysTag identifier.</remarks>
public string Tag { get; }
/// <summary>Gets Offset.</summary>
/// <remarks>Offset to LangSys table.— from beginning of Script table.</remarks>
public ushort Offset { get; }
}
}
|
using System;
using System.Linq;
using Xunit;
using ticketarena.lib.services;
using ticketarena.lib.model;
namespace ticketarena.tests
{
public class VendTests
{
private readonly IVendService _vendService;
private readonly ICoinService _coinService;
public VendTests()
{
_vendService = new VendService();
_coinService = new CoinService();
}
[Fact]
public void Vend_ListVend_ShouldReturnThreeProducts()
{
var products = _vendService.ListProducts();
Assert.True(products.Count() == 3);
}
[Fact]
public void Vend_PurchaseProduct_ShouldReturnThankYouNoChange()
{
var colaProductId = 1;
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.OneDollar));
var result = _vendService.Purchase(colaProductId);
Assert.Equal(result.ResultType, VendResultTypes.Dispensed);
Assert.Equal(result.Change, 0);
Assert.Equal(_vendService.Coins.Count(),0);
}
[Fact]
public void Vend_PurchaseProduct_DuplicateCoins_ShouldReturnThankYouNoChange()
{
var colaProductId = 1;
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiftyCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiftyCents));
var result = _vendService.Purchase(colaProductId);
Assert.Equal(result.ResultType, VendResultTypes.Dispensed);
Assert.Equal(result.Change, 0);
Assert.Equal(_vendService.Coins.Count(),0);
}
[Fact]
public void Vend_PurchaseProduct_ShouldReturnThankYouWithChange()
{
var chipsProductId = 2;
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.OneDollar));
var result = _vendService.Purchase(chipsProductId);
Assert.Equal(result.ResultType, VendResultTypes.Dispensed);
Assert.Equal(0.5m, result.Change);
Assert.Equal(0, _vendService.Coins.Count());
}
[Fact]
public void Vend_PurchaseProduct_ShouldReturnNoCoins()
{
var colaProductId = 1;
var result = _vendService.Purchase(colaProductId);
Assert.Equal(result.ResultType, VendResultTypes.No_Coins);
Assert.Equal(0, result.Change);
Assert.Equal(0, _vendService.Coins.Count());
}
[Fact]
public void Vend_PurchaseProduct_ShouldReturnInsufficientFunds()
{
var candyProductId = 3;
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
var result = _vendService.Purchase(candyProductId);
Assert.Equal(result.ResultType, VendResultTypes.Insufficient_Funds);
Assert.Equal(0, result.Change);
Assert.Equal(1, _vendService.Coins.Count());
}
[Fact]
public void Vend_AddCoin_ShouldReturnCurrentTotal()
{
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.OneDollar));
var curValue = _vendService.GetCurrentValue();
Assert.Equal(curValue, 1.05m);
Assert.Equal(_vendService.Coins.Count(), 2);
}
[Fact]
public void Vend_AddCoin_ShouldReturnUnacceptable()
{
Exception ex = Assert.Throws<ArgumentException>(() => _vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveDollars)));
Assert.Equal(ex.Message, "This coin type is not accepted.");
}
[Fact]
public void Product_ReturnCoins_ShouldReturnCoinsEquallingTotal()
{
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
var curValue = _vendService.GetCurrentValue();
var result = _vendService.Return();
Assert.Equal(result.ResultType, ReturnResultTypes.Returned);
Assert.Equal(curValue, 0.5m);
Assert.Equal(_vendService.Coins.Count(), 0);
}
[Fact]
public void Product_ReturnCoins_ShouldReturnNoCoinsNoValue()
{
var curValue = _vendService.GetCurrentValue();
var result = _vendService.Return();
Assert.Equal(result.ResultType, ReturnResultTypes.No_Coins);
Assert.Equal(curValue, 0m);
Assert.Equal(_vendService.Coins.Count(), 0);
}
[Fact]
public void Vend_GetCurrentValue_ShouldReturnOneDollarSixtyFive()
{
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.OneDollar));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiveCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.FiftyCents));
_vendService.AddCoin(_coinService.GetCoinByType(CoinTypes.TenCents));
var value = _vendService.GetCurrentValue();
Assert.True(value == 1.65m);
}
[Fact]
public void Coins_ListAcceptedCoins_ShouldReturnAllCoinTypes()
{
var coinTypes = _vendService.ListCoinsAccepted();
Assert.False(coinTypes.Contains(CoinTypes.FiveDollars));
}
}
}
|
using System;
namespace OperatorOverloading
{
public class Demo4
{
public static void Run()
{
Point p1 = new Point(100, 100);
Point p2 = new Point(40, 40);
Point p3 = p1;
Console.WriteLine("p1 == p2: {0}", p1 == p2);
Console.WriteLine("p1 != p2: {0}", p1 != p2);
Console.WriteLine("p1 == p3: {0}", p1 == p3);
Console.WriteLine("p1 != p3: {0}", p1 != p3);
}
}
} |
using UnityEngine;
using System.Collections;
public class SnowballController : MonoBehaviour {
public float movementSpeed;
public float initPush;
public bool p1;
private Rigidbody rb;
public GameObject level1;
public GameObject level2;
public GameObject level3;
public float baseVelocity;
public float baseVelocityIncrement;
// Use this for initialization
void Start () {
if (p1) { // pick a random level (only for p1 so its only spawning one level)
int levelPicker = Random.Range(0,3);
if (levelPicker == 0)
level1.SetActive (true);
else if (levelPicker == 1)
level2.SetActive (true);
else
level3.SetActive (true);
}
rb = GetComponent<Rigidbody> ();
rb.AddForce (0, 0, initPush); // start with a bit more speed than 0
}
// Update is called once per frame
void Update () {
if (rb.velocity.z < baseVelocity) // if you get stopped, start up again quicker
rb.AddForce (0, 0, baseVelocityIncrement);
if (p1) {
rb.velocity = new Vector3 (Input.GetAxis ("HorizontalPlatformer1") * movementSpeed / 5, rb.velocity.y, rb.velocity.z);
rb.AddForce(0, 0, Input.GetAxis ("FruitVertical1") * movementSpeed); // get vertical input for increase speed
}
else {
rb.velocity = new Vector3 (Input.GetAxis ("HorizontalPlatformer2") * movementSpeed / 5, rb.velocity.y, rb.velocity.z);
rb.AddForce(0, 0, Input.GetAxis ("FruitVertical2") * movementSpeed);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuffManager : MonoBehaviour
{
[SerializeField]
private List<GameObject> buffs;
[SerializeField]
private int _buffDropRate = 100;
public void GetBuff(Vector3 position)
{
int pick = Utils.GenerateNumber(0, _buffDropRate);
if (pick == 0)
{
int randomBuffIndex = Utils.GenerateNumber(0, buffs.Count);
Instantiate(buffs[randomBuffIndex], position, Quaternion.identity);
}
}
public void SetBuffDropRate(int dropRate)
{
this._buffDropRate = dropRate;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GroundControl : MonoBehaviour {
public float velocidad;
public Text letreroDebug;
private Vector3 vectorAnterior;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (-moveVertical, 0.0f,- moveHorizontal);
transform.Rotate (movement);
float movimientoXAhora = Input.acceleration.y;//valores del acelerometro
float movimientoZAhora = Input.acceleration.x;
if (movimientoZAhora > 0) {//si la rotación es positiva
if (movimientoZAhora < vectorAnterior.z) {
movimientoZAhora = -movimientoZAhora;
}
} else {//si la rotación es negativa
if (movimientoZAhora < vectorAnterior.z) {
} else {
movimientoZAhora = -movimientoZAhora ;
}
}
if (movimientoXAhora > 0) {//si la rotación es positiva
if (movimientoXAhora < vectorAnterior.x) {
movimientoXAhora = -movimientoXAhora;
}
} else {//si la rotación es negativa
if (movimientoXAhora < vectorAnterior.x) {
} else {
movimientoXAhora = -movimientoXAhora ;
}
}
Vector3 dir = Vector3.zero;
//dir.x = Input.acceleration.y;
//dir.z = -Input.acceleration.x;
dir.x= movimientoXAhora;
dir.z = movimientoZAhora;
if (dir.sqrMagnitude > 1) {
dir.Normalize ();
}
vectorAnterior = dir;
//Debug
letreroDebug.text= "";
letreroDebug.text = "x.acel: " + (dir.x).ToString() + "\n";
letreroDebug.text += "z.acel: " + (dir.z).ToString() + "\n";
letreroDebug.text += "Rot.x: " + transform.rotation.x.ToString() + "\n";
letreroDebug.text += "Rot.z: " + transform.rotation.z.ToString() + "\n";
dir *= Time.deltaTime;
transform.Rotate (dir * velocidad);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Simpler;
using WebApplication1.Models;
namespace WebApplication1.Tasks
{
public class GetCustomerIdTask : OutSimpleTask<string>
{
public override void Execute()
{
var sql = "SELECT AutoCustPrefix as Prefix, AutoCustSuffix as Suffix, AutoCustSize as Length from DBA.PosControls";
Out = SharedDb.PosimDb.Get<SuffixPrefix>(sql).StringValue;
sql =
string.Format("update PosControls set AutoCustSuffix = AutoCustSuffix + 1");
SharedDb.PosimDb.Execute(sql);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Query.DTO
{
public class AccessTokenDto
{
public int Id { get; set; }
public string StoreName { get; set; }
public int PosId { get; set; }
public string CDKey { get; set; }
}
}
|
using EasySave.Helpers.Files;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
namespace EasySave.Model.Management
{
/// <summary>
/// Load the configuration.
/// </summary>
public class Config
{
private const string FOLDER_NAME = "config";
private string configPath;
public Config()
{
this.configPath = Directory.CreateDirectory(
Path.Combine(Directory.GetCurrentDirectory(), FOLDER_NAME)
).FullName;
}
/// <summary>
/// Load ERP blacklist.
/// </summary>
public List<string> LoadErpBlackList()
{
return JsonHelper.ReadJson<List<string>>(Path.Combine(configPath, "ERP blacklist.json")) ?? new List<string>();
}
/// <summary>
/// Save ERP blacklist.
/// </summary>
/// <param name="erp">Entered list by the user</param>
public void SaveErpBlackList(List<string> erp)
{
JsonHelper.WriteJson(erp, Path.Combine(configPath, "ERP blacklist.json"));
}
/// <summary>
/// Load the crypt format of the tasks.
/// </summary>
public List<string> LoadEncryptFormat()
{
return JsonHelper.ReadJson<List<string>>(Path.Combine(configPath, "Encrypt extensions.json")) ?? new List<string>();
}
/// <summary>
/// Save the crypt format of the task
/// </summary>
/// <param name="format">Entered crypt format by the user</param>
public void SaveEncryptFormat(List<string> format)
{
JsonHelper.WriteJson(format, Path.Combine(configPath, "Encrypt extensions.json"));
}
/// <summary>
/// Load the config of the differential save.
/// </summary>
/// <param name="path">Entered path by the user</param>
public Dictionary<string, string> LoadDiffSaveConfig(string path)
{
return JsonHelper.ReadJson<Dictionary<string, string>>(Path.Combine(path, "conf.json")) ?? new Dictionary<string, string>();
}
/// <summary>
/// Save the config of the differential save.
/// </summary>
/// <param name="diffConfign">Entered the differencial save config by the user</param>
/// <param name="path">Entered path by the user</param>
public void SaveDiffSaveConfig(Dictionary<string, string> diffConfign, string path)
{
string filePath = Path.Combine(path, "conf.json");
if (!File.Exists(filePath))
JsonHelper.WriteJson(diffConfign, filePath);
}
/// <summary>
/// Load all the tasks.
/// </summary>
public List<Task.Task> LoadTasks()
{
return JsonHelper.ReadJson<List<Task.Task>>(Path.Combine(configPath, "tasks.json")) ?? new List<Task.Task>();
}
/// <summary>
/// Save a renseigned task.
/// </summary>
/// <param name="tasks">Save the new tasks in the json file</param>
public void SaveTasks(List<Task.Task> tasks)
{
JsonHelper.WriteJson(tasks, Path.Combine(configPath, "tasks.json"));
}
public LangFormat LoadLang()
{
return JsonHelper.ReadJson<LangFormat>(Path.Combine(configPath, "lang.json")) ?? new LangFormat();
}
/// <summary>
/// Load the crypt format of the tasks.
/// </summary>
public List<string> LoadPriorityExtension()
{
return JsonHelper.ReadJson<List<string>>(Path.Combine(configPath, "Priority extensions.json")) ?? new List<string>();
}
/// <summary>
/// Save the crypt format of the task
/// </summary>
/// <param name="extension">Entered crypt format by the user</param>
public void SavePriorityExtension(List<string> extension)
{
JsonHelper.WriteJson(extension, Path.Combine(configPath, "Priority extensions.json"));
}
}
}
|
using System.Collections.Generic;
using System.Data;
using Docller.Core.Models;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace Docller.Core.Repository.Mappers.StoredProcMappers
{
public class FileVersionDownloadMapper : IResultSetMapper<FileVersion>
{
private readonly IRowMapper<FileVersion> _fileVersionMapper;
private readonly IRowMapper<FileAttachmentVersion> _attachmentMapper;
public FileVersionDownloadMapper()
{
_fileVersionMapper = DefaultMappers.ForFileVersionDownload;
this._attachmentMapper = MapBuilder<FileAttachmentVersion>.MapNoProperties()
.MapByName(x => x.FileId)
.MapByName(x => x.FileName)
.MapByName(x => x.FileExtension)
.MapByName(x => x.ContentType)
.MapByName(x => x.FileSize)
.MapByName(x => x.RevisionNumber)
.MapByName(x=>x.VersionPath)
.Build();
}
public IEnumerable<FileVersion> MapSet(IDataReader reader)
{
FileVersion version = null;
while (reader.Read())
{
version = this._fileVersionMapper.MapRow(reader);
version.Attachments = new List<FileAttachmentVersion>();
}
if (reader.NextResult() && version != null)
{
while (reader.Read())
{
FileAttachmentVersion attachment = this._attachmentMapper.MapRow(reader);
attachment.Folder = version.Folder;
attachment.Project = version.Project;
attachment.ParentFile = version.FileInternalName;
version.Attachments.Add(attachment);
}
}
return new List<FileVersion>(){version};
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sparks : MonoBehaviour
{
public ParticleSystem smoke;
public ParticleSystem smallbois;
private void Awake()
{
transform.parent = LevelConfig.instance.effects;
smoke.Play();
smallbois.Play();
Invoke(nameof(Destroy), 5f);
}
private void Destroy()
{
Destroy(this.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AIMLbot.UnitTest
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class UserTests
{
private User _user;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
[TestMethod]
public void TestConstructorPopulatesUserObject()
{
_user = new User("1");
Assert.AreEqual("*", _user.Topic);
Assert.AreEqual("1", _user.UserId);
// the +1 in the following assert is the creation of the default topic predicate
var predicates = ConfigurationManager.GetSection("Predicates") as Dictionary<string, string>;
Assert.IsNotNull(predicates);
Assert.AreEqual(predicates.Count + 1, _user.Predicates.Count);
}
[TestMethod]
public void TestResultHandlers()
{
_user = new User();
Assert.AreEqual("", _user.GetResultSentence());
var mockRequest = new Request("Sentence 1. Sentence 2", _user);
var mockResult = new Result(_user, mockRequest);
mockResult.InputSentences.Add("Result 1");
mockResult.InputSentences.Add("Result 2");
mockResult.OutputSentences.Add("Result 1");
mockResult.OutputSentences.Add("Result 2");
_user.AddResult(mockResult);
var mockResult2 = new Result(_user, mockRequest);
mockResult2.InputSentences.Add("Result 3");
mockResult2.InputSentences.Add("Result 4");
mockResult2.OutputSentences.Add("Result 3");
mockResult2.OutputSentences.Add("Result 4");
_user.AddResult(mockResult2);
Assert.AreEqual("Result 3", _user.GetResultSentence());
Assert.AreEqual("Result 3", _user.GetResultSentence(0));
Assert.AreEqual("Result 1", _user.GetResultSentence(1));
Assert.AreEqual("Result 4", _user.GetResultSentence(0, 1));
Assert.AreEqual("Result 2", _user.GetResultSentence(1, 1));
Assert.AreEqual("", _user.GetResultSentence(0, 2));
Assert.AreEqual("", _user.GetResultSentence(2, 0));
Assert.AreEqual("Result 3", _user.GetThat());
Assert.AreEqual("Result 3", _user.GetThat(0));
Assert.AreEqual("Result 1", _user.GetThat(1));
Assert.AreEqual("Result 4", _user.GetThat(0, 1));
Assert.AreEqual("Result 2", _user.GetThat(1, 1));
Assert.AreEqual("", _user.GetThat(0, 2));
Assert.AreEqual("", _user.GetThat(2, 0));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Tomelt.Localization;
using Tomelt.ContentManagement;
using Tomelt.Mvc;
using Tomelt.Mvc.AntiForgery;
using Tomelt.Mvc.Extensions;
using Tomelt.Tags.Drivers;
using Tomelt.Tags.Models;
using Tomelt.Tags.ViewModels;
using Tomelt.Tags.Services;
using Tomelt.UI.Navigation;
namespace Tomelt.Tags.Controllers {
[ValidateInput(false)]
public class AdminController : Controller {
private readonly ITagService _tagService;
public AdminController(ITomeltServices services, ITagService tagService) {
Services = services;
_tagService = tagService;
T = NullLocalizer.Instance;
}
public ITomeltServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Index(PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Can't manage tags")))
return new HttpUnauthorizedResult();
IEnumerable<TagRecord> tags = _tagService.GetTags();
var pager = new Pager(Services.WorkContext.CurrentSite, pagerParameters);
var pagerShape = Services.New.Pager(pager).TotalItemCount(tags.Count());
if (pager.PageSize != 0) {
tags = tags.Skip(pager.GetStartIndex()).Take(pager.PageSize);
}
var entries = tags.Select(CreateTagEntry).ToList();
var model = new TagsAdminIndexViewModel { Pager = pagerShape, Tags = entries };
return View(model);
}
public ActionResult List()
{
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("无权限")))
return new HttpUnauthorizedResult();
return View();
}
[HttpPost]
[ValidateAntiForgeryTokenTomelt(false)]
public ActionResult GetList(TagsSearch search)
{
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("无权限")))
return new HttpUnauthorizedResult();
IEnumerable<TagRecord> tags = _tagService.GetTags();
if (!string.IsNullOrWhiteSpace(search.TagName))
{
tags = tags.Where(d => d.TagName.ToLower().Contains(search.TagName.ToLower()));
}
search.total = tags.Count();
//分页
int pageSize = search.rows ?? 10;
var maxPagedCount = Services.WorkContext.CurrentSite.MaxPagedCount;
if (maxPagedCount > 0 && pageSize > maxPagedCount)
pageSize = maxPagedCount;
int page = search.page ?? 1;
string order = string.IsNullOrWhiteSpace(search.order) ? "desc" : search.order;
tags = order == "desc" ? tags.OrderByDescending(d => d.Id).Skip((page - 1) * pageSize).Take(pageSize) : tags.OrderBy(d => d.Id).Skip((page - 1) * pageSize).Take(pageSize);
return Json(new
{
search.total,
rows = tags.Select(d => new
{
d.TagName,
d.Id
})
});
}
[HttpPost]
[FormValueRequired("submit.BulkEdit")]
public ActionResult Index(FormCollection input) {
var viewModel = new TagsAdminIndexViewModel {Tags = new List<TagEntry>(), BulkAction = new TagAdminIndexBulkAction()};
if ( !TryUpdateModel(viewModel) ) {
return View(viewModel);
}
IEnumerable<TagEntry> checkedEntries = viewModel.Tags.Where(t => t.IsChecked);
switch (viewModel.BulkAction) {
case TagAdminIndexBulkAction.None:
break;
case TagAdminIndexBulkAction.Delete:
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Couldn't delete tag")))
return new HttpUnauthorizedResult();
foreach (TagEntry entry in checkedEntries) {
_tagService.DeleteTag(entry.Tag.Id);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
return RedirectToAction("Index");
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.Create")]
public ActionResult IndexCreatePOST() {
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Couldn't create tag")))
return new HttpUnauthorizedResult();
var viewModel = new TagsAdminCreateViewModel();
if (TryUpdateModel(viewModel)) {
if (viewModel.TagName.Intersect(TagsPartDriver.DisalowedChars).Any()) {
ModelState.AddModelError("_FORM", T("The tag \"{0}\" could not be added because it contains forbidden chars: {1}", viewModel.TagName, String.Join(", ", TagsPartDriver.DisalowedChars)));
}
}
if(!ModelState.IsValid) {
ViewData["CreateTag"] = viewModel;
return RedirectToAction("Index");
}
_tagService.CreateTag(viewModel.TagName);
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryTokenTomelt(false)]
public ActionResult Create(string tagName)
{
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Couldn't create tag")))
return Json(new {State = 0, Msg = T("无权限").Text});
if (tagName.Intersect(TagsPartDriver.DisalowedChars).Any())
{
return Json(new { State = 0, Msg = T("标签 \"{0}\" 新增失败,不能包含这些特殊字符: {1}", tagName, String.Join(", ", TagsPartDriver.DisalowedChars)).Text });
}
_tagService.CreateTag(tagName);
return Json(new { State = 1, Msg = T("添加成功").Text });
}
public ActionResult Edit(int id) {
TagRecord tagRecord = _tagService.GetTag(id);
if(tagRecord == null) {
return RedirectToAction("Index");
}
var viewModel = new TagsAdminEditViewModel {
Id = tagRecord.Id,
TagName = tagRecord.TagName,
};
ViewData["ContentItems"] = _tagService.GetTaggedContentItems(id, VersionOptions.Latest).ToList();
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(FormCollection input) {
var viewModel = new TagsAdminEditViewModel();
if ( !TryUpdateModel(viewModel) ) {
return View(viewModel);
}
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Couldn't edit tag")))
return new HttpUnauthorizedResult();
if (viewModel.TagName.Intersect(TagsPartDriver.DisalowedChars).Any()) {
ModelState.AddModelError("_FORM", T("The tag \"{0}\" could not be modified because it contains forbidden chars: {1}", viewModel.TagName, String.Join(", ", TagsPartDriver.DisalowedChars)));
return View(viewModel);
}
_tagService.UpdateTag(viewModel.Id, viewModel.TagName);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult EditAJAX(FormCollection input)
{
var viewModel = new TagsAdminEditViewModel();
if (!TryUpdateModel(viewModel))
{
return Json(new { State = 0, Msg = T("数据校验失败").Text });
}
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Couldn't edit tag")))
return Json(new { State = 0, Msg = T("无权限").Text });
if (viewModel.TagName.Intersect(TagsPartDriver.DisalowedChars).Any())
{
return Json(new { State = 0, Msg = T("标签 \"{0}\" 修改失败,不能包含这些特殊字符: {1}", viewModel.TagName, String.Join(", ", TagsPartDriver.DisalowedChars)).Text });
}
_tagService.UpdateTag(viewModel.Id, viewModel.TagName);
return Json(new { State = 1, Msg = T("修改成功").Text });
}
[HttpPost]
public ActionResult Remove(int id, string returnUrl) {
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Couldn't remove tag")))
return new HttpUnauthorizedResult();
TagRecord tagRecord = _tagService.GetTag(id);
if (tagRecord == null)
return new HttpNotFoundResult();
_tagService.DeleteTag(id);
return this.RedirectLocal(returnUrl, () => RedirectToAction("Index"));
}
[HttpPost]
[ValidateAntiForgeryTokenTomelt(false)]
public ActionResult DeleteAJAX(int id)
{
if (!Services.Authorizer.Authorize(Permissions.ManageTags, T("Couldn't remove tag")))
return Json(new { State = 0, Msg = T("无权限").Text });
TagRecord tagRecord = _tagService.GetTag(id);
if (tagRecord == null)
return Json(new { State = 0, Msg = T("标签不存在").Text });
_tagService.DeleteTag(id);
return Json(new { State = 1, Msg = T("删除成功").Text });
}
public JsonResult FetchSimilarTags(string snippet) {
return Json(
_tagService.GetTagsByNameSnippet(snippet).Select(tag => tag.TagName).ToList(),
JsonRequestBehavior.AllowGet
);
}
private static TagEntry CreateTagEntry(TagRecord tagRecord) {
return new TagEntry {
Tag = tagRecord,
IsChecked = false,
};
}
}
}
|
namespace Krafteq.ElsterModel.Common
{
using Krafteq.ElsterModel.ValidationCore;
using LanguageExt;
public class AdditionalHouseNumber : NewType<AdditionalHouseNumber, string>
{
static readonly Validator<StringError, string> Validator = Validators.All(
StringValidators.MaxLength(15)
);
AdditionalHouseNumber(string value) : base(value)
{
}
public static Validation<StringError, AdditionalHouseNumber> Create(string value) =>
Validator(value).Map(x => new AdditionalHouseNumber(x));
}
} |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Alabo.Domains.Repositories.Mongo.Extension;
using MongoDB.Bson;
using Newtonsoft.Json;
namespace Alabo.Framework.Basic.PostRoles.Dtos
{
public class PlatformRoleTreeOutput
{
/// <summary>
/// id
/// </summary>
[JsonConverter(typeof(ObjectIdConverter))]
public ObjectId Id { get; set; }
/// <summary>
/// 上一级权限
/// </summary>
[Display(Name = "链接名称")]
public string Name { get; set; }
/// <summary>
/// 是否开启
/// </summary>
[Display(Name = "是否启用")]
public bool IsEnable { get; set; } = true;
/// <summary>
/// Url及权限
/// </summary>
[Display(Name = "地址")]
public string Url { get; set; }
/// <summary>
/// 下级
/// </summary>
public IList<PlatformRoleTreeOutput> AppItems { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormularioPrincipal
{
public partial class FrmInicioSistema : Form
{
//Variável _objForm é para controlar as propriedade dos forms
private Form _objForm;
//
//
public FrmInicioSistema()
{
InitializeComponent();
}
private void FrmInicioSistema_Load(object sender, EventArgs e)
{
// Get the current Real Time.
timer1.Enabled = true;
timer1.Interval = 25;
//
// Create the ToolTip and associate with the Form container.
ToolTip toolTip1 = new ToolTip();
// Set up the delays for the ToolTip.
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip1.ShowAlways = true;
// Set up the ToolTip text for the Button and Checkbox.
toolTip1.SetToolTip(this.btnInicioSistemaCategoriaAdd, "Cadastro de Categoria");
toolTip1.SetToolTip(this.btnInicioSistemaProdutoAdd, "Cadastro de Produto");
toolTip1.SetToolTip(this.btnInicioSistemaUsuarioAdd, "Cadastro de Usuário");
toolTip1.SetToolTip(this.btnInicioSistemaUpdateUsuario, "Alterar Usuário");
toolTip1.SetToolTip(this.btnInicioSistemaChangeUser, "Trocar Usuário");
toolTip1.SetToolTip(this.btnInicioSistemaUpdateCategoria, "Alterar Categoria");
toolTip1.SetToolTip(this.btnInicioSistemaUpdateProduto, "Alterar Produto");
toolTip1.SetToolTip(this.btnInicioSistemaUpdateEstoque, "Alterar Estoque");
toolTip1.SetToolTip(this.btnInicioSistemaViewEstoque, "Visualizar Estoque");
toolTip1.SetToolTip(this.btnInicioSistemaViewCategoria, "Visualizar Categoria");
toolTip1.SetToolTip(this.btnInicioSistemaViewProduto, "Visualizar Produto");
toolTip1.SetToolTip(this.btnInicioSistemaViewUsuario, "Visualizar Usuário");
//
//
}
private void timer1_Tick(object sender, EventArgs e)
{
// Get the current date.
DateTime thisDay = DateTime.Today;
lbInicioSistemaGetDate.Text = thisDay.ToString("D") +" | " +DateTime.Now.ToLongTimeString();
}
private void btnInicioSistemaProdutoAdd_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaCadProduto
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
//
//pnInicioSistemaRecebeDecisoes.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
//
}
private void btnInicioSistemaPedidoAdd_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaCadCategoria
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
//
//pnInicioSistemaRecebeDecisoes.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
//
}
private void btnInicioSistemaUsuarioAdd_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaCadUsuario
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
//
//pnInicioSistemaRecebeDecisoes.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
//
}
private void btnInicioSistemaChangeUser_Click(object sender, EventArgs e)
{
FrmLogin efetuarLogoff = new FrmLogin();
efetuarLogoff.Show();
this.Close();
}
private void pnInicioSistemaTop_Paint(object sender, PaintEventArgs e)
{
}
private void btnInicioSistemaVendaAdd_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaAlteraUsuario
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
//
//pnInicioSistemaRecebeDecisoes.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
//
}
private void btnInicioSistemaUpdateCategoria_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaAlteraCategoria
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
}
private void btnInicioSistemaUpdateProduto_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaAlteraProduto
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void btnInicioSistemaViewUsuario_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaVisualizaUsuario
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
}
private void btnInicioSistemaViewCliente_Click(object sender, EventArgs e)
{
}
private void btnInicioSistemaViewProduto_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaVisualizaProduto
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void btnInicioSistemaUpdateEstoque_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaAlteraEstoque
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
}
private void btnInicioSistemaViewCategoria_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaVisualizaCategoria
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
}
private void btnInicioSistemaViewEstoque_Click(object sender, EventArgs e)
{
_objForm?.Close();//Se a variável _objForm estiver ocupada(com algum form aberto), será fechado.
//Se não.
_objForm = new FrmTelaVisualizaEstoque
{
TopLevel = false, //TopLevel = false, para que respeite o tamanho do Panel
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill
};
//
pnInicioSistemaRecebeTelas.Controls.Add(_objForm);
_objForm.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
public class TinhThanh
{
private int maTinhThanh;
public int MaTinhThanh
{
get { return maTinhThanh; }
set { maTinhThanh = value; }
}
private String tenTinhThanh;
public String TenTinhThanh
{
get { return tenTinhThanh; }
set { tenTinhThanh = value; }
}
}
}
|
using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Numerics;
using System.Windows.Forms;
namespace Projet2Cpi
{
public class Sec
{
public const int ALPHA = 1;
public const int ALPHANUM = 2;
public const int PRINTABLE = 3;
private const String ned_constant = "nekess_ya_Nedjima!";
private static String pepper = decrypt("tKtPrTTDZXiOEr0ftJQyIv1MJIW4gU5MS5m4CMgROzo=$kJAimQgOqbM87df+4KfWVw==$bXiwfqMgyvB0kMdleHUKH94UmME=", ned_constant);
private static BigInteger P = new BigInteger(new byte[] { 0xb, 0x3d, 0xc, 0xce, 0x89, 0x94, 0xa3, 0x7a, 0xbe, 0x7f, 0x25, 0xf3, 0xdc, 0x1d, 0x5d, 0xac, 0xc0, 0x17, 0x24, 0x8c
, 0x4b, 0xd8, 0x6f, 0xbc, 0x38, 0xb9, 0x46, 0x41, 0xb1, 0x3, 0xfa, 0x9, 0x40, 0x43, 0x33, 0x4a, 0xe7, 0xcf, 0x8c, 0x75,
0x6, 0xb5, 0xfc, 0xc0, 0xff, 0x30, 0xe4, 0x9d, 0x2f, 0x66, 0x1b, 0xe3, 0x56, 0x7a, 0x6e, 0x2b, 0xc3, 0xca, 0xa5, 0xf7,
0x88, 0x7e, 0xe8, 0x1d, 0xb5, 0xbf, 0xce, 0x4, 0xdd, 0x27, 0xc5, 0xe6, 0xc5, 0xe4, 0xa0, 0xd5, 0x77, 0x6d, 0x91, 0xfb,
0x63, 0x46, 0xef, 0x33, 0xb5, 0x7e, 0x38, 0x19, 0xe7, 0xa9, 0x55, 0xc9, 0xc3, 0x97, 0x6, 0xae, 0x6e, 0x2c, 0xb8, 0xc5,
0x2a, 0x98, 0xf7, 0xa2, 0x2c, 0xc6, 0x6c, 0xef, 0xdb, 0x3c, 0x64, 0x54, 0x90, 0x4e, 0xbd, 0xbf, 0xad, 0x3c, 0x95, 0xb7,
0x28, 0xfe, 0x0, 0xc8, 0x26, 0x94, 0x1a, 0xfc, 00 });
private static BigInteger G = new BigInteger(2);
public static byte[] dh_secret;
public static String checksum(String data)
{
// BASE64(SHA1(MD5("<red>"+input+"</red>")))
SHA1Managed sha = new SHA1Managed();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] input = Encoding.ASCII.GetBytes("<nekess_nedjima>" + data + "</nekess_nedjima>");
return base64_encode(sha.ComputeHash(md5.ComputeHash(input)));
}
public static String checksum(byte[] data)
{
// BASE64(SHA1(MD5("<red>"+input+"</red>")))
SHA1Managed sha = new SHA1Managed();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] input = Encoding.ASCII.GetBytes("<nekess_nedjima>" + data + "</nekess_nedjima>");
return base64_encode(sha.ComputeHash(md5.ComputeHash(input)));
}
public static String encrypt(String data, String key)
{
try
{
if (key.Length > 32)
{
throw new System.Security.Cryptography.CryptographicException("Key can't be longer than 32 characters");
}
key = key.PadRight(32);
AesManaged aes = new AesManaged();
//aes.BlockSize = 256;
aes.Key = Encoding.ASCII.GetBytes(key);
aes.Mode = CipherMode.CBC;
aes.GenerateIV();
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] encrypted;
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(data);
}
encrypted = msEncrypt.ToArray();
}
}
String main_enc_data = base64_encode(encrypted);
String enc_iv = base64_encode(aes.IV);
return main_enc_data + "$" + enc_iv + "$" + checksum(main_enc_data + enc_iv);
}
catch (System.Security.Cryptography.CryptographicException e)
{
return "a Cryptographic exception has occured : " + e.Message;
}
catch (System.Exception e)
{
return "an exception has occured : " + e.Message;
}
}
public static String encrypt(String data, byte[] key)
{
try
{
byte[] padded_key = new byte[32];
if (key.Length > 32)
throw new System.Security.Cryptography.CryptographicException("Key can't be longer than 32 characters");
else if (key.Length < 32)
Array.Copy(key, padded_key, key.Length);
else
padded_key = key;
AesManaged aes = new AesManaged();
aes.Key = padded_key;
aes.Mode = CipherMode.CBC;
aes.GenerateIV();
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] encrypted;
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(data);
}
encrypted = msEncrypt.ToArray();
}
}
String main_enc_data = base64_encode(encrypted);
String enc_iv = base64_encode(aes.IV);
//MessageBox.Show("iv = " + hexify(aes.IV) + "\nkey = " + hexify(aes.Key) + "\ndata = " + hexify(Encoding.ASCII.GetBytes(data)));
return main_enc_data + "$" + enc_iv + "$" + checksum(main_enc_data + enc_iv);
}
catch (System.Security.Cryptography.CryptographicException e)
{
return "a Cryptographic exception has occured : " + e.Message;
}
catch (System.Exception e)
{
return "an exception has occured : " + e.Message;
}
}
public static String base64_encode(byte[] e)
{
return remove(System.Convert.ToBase64String(e), '\n');
}
public static String hexify(byte[] s)
{
StringBuilder hex = new StringBuilder(s.Length);
foreach (byte b in s)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
public static String decrypt(String raw_data, String key)
{
try
{
if (key.Length > 32)
{
throw new System.Security.Cryptography.CryptographicException("Key can't be longer than 32 characters");
}
key = key.PadRight(32);
String[] results = raw_data.Split('$');
String chksum = results[2];
if (checksum(results[0] + results[1]) != chksum)
{
throw new System.Security.Cryptography.CryptographicException("File integrity check failed!");
}
byte[] data = System.Convert.FromBase64String(results[0]);
byte[] iv = System.Convert.FromBase64String(results[1]);
RijndaelManaged aes = new RijndaelManaged();
aes.Key = Encoding.ASCII.GetBytes(key);
aes.Mode = CipherMode.CBC;
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
String plain;
using (MemoryStream msDecrypt = new MemoryStream(data))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plain = srDecrypt.ReadToEnd();
}
}
}
return plain;
}
catch (System.Security.Cryptography.CryptographicException e)
{
return "A Cryptographic exception has occured in decrypt : " + e.Message;
}
catch (System.Exception e)
{
return "an exception has occured : " + e.Message;
}
}
public static String decrypt(String raw_data, byte[] key)
{
try
{
byte[] padded_key = new byte[32];
if (key.Length > 32)
throw new System.Security.Cryptography.CryptographicException("Key can't be longer than 32 characters");
else if (key.Length < 32)
Array.Copy(key, padded_key, key.Length);
else
padded_key = key;
String[] results = raw_data.Split('$');
String chksum = results[2];
if (checksum(results[0] + results[1]) != chksum)
{
throw new System.Security.Cryptography.CryptographicException("File integrity check failed!");
}
byte[] data = System.Convert.FromBase64String(results[0]);
byte[] iv = System.Convert.FromBase64String(results[1]);
AesManaged aes = new AesManaged();
aes.Key = padded_key;
aes.Mode = CipherMode.CBC;
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
String plain;
using (MemoryStream msDecrypt = new MemoryStream(data))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plain = srDecrypt.ReadToEnd();
}
}
}
return plain;
}
catch (System.Security.Cryptography.CryptographicException e)
{
return "A Cryptographic exception has occured in decrypt : " + e.Message;
}
catch (System.Exception e)
{
return "an exception has occured : " + e.Message;
}
}
private static String getSalt(int len = 32)
{
byte[] salt = new byte[len];
using (RNGCryptoServiceProvider random = new RNGCryptoServiceProvider())
{
random.GetNonZeroBytes(salt);
}
return base64_encode(salt);
}
public static String hash(String data)
{
String salt = getSalt();
return hash(data, salt);
}
public static String hash(String data, String salt)
{
String mysalt = Encoding.ASCII.GetString(System.Convert.FromBase64String(salt));
SHA256Managed sha = new SHA256Managed();
byte[] input = Encoding.ASCII.GetBytes(data + salt + Sec.pepper);
return base64_encode(sha.ComputeHash(input)) + '$' + salt;
}
public static bool hash_and_compare(String pass_plain, String resulting_hash)
{
// resulting_hash is the previously computed hash
String[] res = resulting_hash.Split('$');
return hash(pass_plain, res[1]) == resulting_hash;
}
public static byte[] positive(byte[] x)
{
byte[] positive = new byte[x.Length + 1];
Array.Copy(x, positive, x.Length);
return positive;
}
public static void dh(NetworkStream s, StreamReader r, StreamWriter w)
{
try
{
// Diffie hellman key exchange on GF(P)
// genererate
byte[] rand = positive(Convert.FromBase64String(getSalt(128)));
BigInteger a = new BigInteger(rand);
// send g**secret to the server
BigInteger g_a = BigInteger.ModPow(G, a, P);
byte[] g_a_byte = g_a.ToByteArray().Reverse().ToArray();
w.WriteLine(base64_encode(g_a_byte));
w.Flush();
BigInteger g_b = new BigInteger(positive(Convert.FromBase64String(r.ReadLine()).Reverse().ToArray()));
// read g_b and compute g_b_a
// compute g_b_a
byte[] secret = BigInteger.ModPow(g_b, a, P).ToByteArray().Reverse().ToArray();
if (secret.Length != 128)
{
byte[] temp = new byte[128];
Array.Copy(secret, 1, temp, 0, 128);
Array.Copy(temp, secret, 128);
}
SHA256Managed sha = new SHA256Managed();
dh_secret = sha.ComputeHash(secret, 0, 128);
}
catch (Exception)
{
// DH error
OtherThread.disconnect();
}
// DONE DIFFIE HELLMAN
}
public static String remove(String data, char c)
{
try
{
StringBuilder builder = new StringBuilder();
foreach (byte ch in data)
if (ch != c) builder.Append((char)ch);
return builder.ToString();
}
catch (Exception e)
{
return e.Message;
}
}
public static String inspect(String data)
{
StringBuilder t = new StringBuilder();
foreach (byte c in data)
{
if ((c >= 32) && (c < 127)) t.Append((char)c);
else t.Append("\\x" + c.ToString());
}
return t.ToString();
}
}
}
|
using System.Text;
using Sind.Model;
namespace Sind.BLL.Excel
{
public class ImportaPlanilha
{
public int IdIndicador { get; set; }
public Filial Filial { get; set; }
public string MesAno { get; set; }
public string TipoBase { get; set; }
public int Valor { get; set; }
public StringBuilder Mensagem { get; set; }
public string MensagemErro { get; set; }
}
}
|
using Alabo.Domains.Entities;
namespace Alabo.Domains.Services.View {
/// <summary>
/// 获取视图
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
public interface IViewBase<TEntity, in TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> {
/// <summary>
/// 获取视图
/// </summary>
/// <param name="id">Id</param>
TEntity GetViewById(object id);
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DogBar : MonoBehaviour
{
public Camera cameraDogBar;
public Sprite ImgDogLeftBar, ImgDogRightBar;
public GameObject ojosDogBar;
void start()
{
this.GetComponent<SpriteRenderer>().enabled = true;
}
void Update()
{
Vector3 mouse = Input.mousePosition;
if (BotonBar.rightBar)
{
this.GetComponent<SpriteRenderer>().sprite = ImgDogRightBar;
ojosDogBar.GetComponent<Transform>().localRotation = new Quaternion(0, 0f, 0, 0);
ojosDogBar.GetComponent<Transform>().localPosition = new Vector3(0.52564f, 0.5755f, 0f);
}
if (BotonBar.leftBar)
{
this.GetComponent<SpriteRenderer>().sprite = ImgDogLeftBar;
ojosDogBar.GetComponent<Transform>().localRotation = new Quaternion(0, 180f, 0, 0);
ojosDogBar.GetComponent<Transform>().localPosition = new Vector3(-0.537f, 0.569f, 0f);
}
}
void FixedUpdate()
{
if (!PiesBar.pies_pisoBar)
{
this.GetComponent<SpriteRenderer>().enabled = false;
}
else this.GetComponent<SpriteRenderer>().enabled = true;
}
} |
namespace GraphicalEditorServer.DTO
{
public class PatientBasicDTO
{
public string Name { get; set; }
public string Surname { get; set; }
public string Jmbg { get; set; }
public int PatientCardId { get; set; }
public PatientBasicDTO() { }
public PatientBasicDTO(string name, string surname, string jmbg, int patientCardId)
{
Name = name;
Surname = surname;
Jmbg = jmbg;
PatientCardId = patientCardId;
}
}
}
|
using FootballTAL.Data;
using FootballTAL.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FootballTAL.BusinessLogic;
namespace FootballTAL.BusinessLogic
{
public class FootballClubArray
{
private IList<FootballClubExtenions> FootballClubList { get; set; }
public IList<FootballClubExtenions> GetFootballClubList(IFileReading FileRead)
{
FootballClubList = new List<FootballClubExtenions>();
//fileRead.readFile will return each line from the raw file
FileRead.ReadFile().ToList().ForEach(i => FootballClubList.Add(new CreateFootballClub().CreateClub(i)));
return FootballClubList;
}
public bool GetContainsError()
{
if (FootballClubList != null)
return FootballClubList.Any(i => i.ErrorFound) ;
else
return false;
}
}
}
|
using FluentValidation.Attributes;
namespace VnStyle.Web.Models.Auth
{
[Validator(typeof(LoginRequestValidator))]
public class LoginRequest
{
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class DinamicConditioner : MonoBehaviour
{
[SerializeField]
private bool[] conditions;
public UnityEvent OnTrue;
public bool[] Conditions
{
get
{
return conditions;
}
set
{
conditions = value;
}
}
public void TrueCondition(int index)
{
if (index >= conditions.Length)
{
return;
}
Conditions[index] = true;
CheckConditions();
}
public void FalseCondition(int index)
{
if (index >= conditions.Length)
{
return;
}
Conditions[index] = false;
CheckConditions();
}
private void CheckConditions()
{
foreach (bool condition in conditions)
{
if (!condition)
{
return;
}
}
OnTrue.Invoke();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.