text stringlengths 13 6.01M |
|---|
using Alabo.Cloud.School.SmallTargets.Domain.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Cloud.School.SmallTargets.Domain.Repositories
{
public interface ISmallTargetRepository : IRepository<SmallTarget, ObjectId>
{
}
} |
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Uintra.Features.Notification.Configuration;
using Uintra.Persistence;
using Uintra.Persistence.Sql;
namespace Uintra.Features.Notification.Sql
{
[UintraTable("Notification")]
public class Notification : SqlEntity<Guid>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public override Guid Id { get; set; }
public Guid ReceiverId { get; set; }
public DateTime Date { get; set; }
public bool IsNotified { get; set; }
public bool IsViewed { get; set; }
public int Type { get; set; }
[DefaultValue((int)NotifierTypeEnum.UiNotifier)]
public int NotifierType { get; set; }
public string Value { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicios_LibroCSharp.Cap._9.Entidades
{
public struct ProductosT
{
public string Nombre {get; set;}
public string Codigo { get; set; }
public string Precio { get; set; }
public string Cantidad { get; set;}
}
}
|
/* The MIT License (MIT)
*
* Copyright (c) 2018 Marc Clifton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* Code Project Open License (CPOL) 1.02
* https://www.codeproject.com/info/cpol10.aspx
*/
using System;
namespace Clifton.Meaning
{
public class NullEntity : IEntity
{
protected static NullEntity instance;
public static NullEntity Instance => instance;
static NullEntity()
{
instance = new NullEntity();
}
}
public class NullRelationship : IRelationship
{
protected static NullRelationship instance;
public static NullRelationship Instance => instance;
static NullRelationship()
{
instance = new NullRelationship();
}
}
public class ContextEntity
{
//public enum RelationshipSide
//{
// ConcreteEntity,
// RelatedTo,
//}
public static IEntity NullRelatedEntity = new NullEntity();
public IEntity ConcreteEntity { get; protected set; }
public IEntity RelatedTo { get; protected set; }
public Type RelationshipType { get; protected set; }
/// <summary>
/// Create a root entity container that has no relationship to another entity.
/// This method is used exclusively for unit tests.
/// </summary>
public static ContextEntity Create(IEntity concreteEntity)
{
return new ContextEntity(concreteEntity, NullRelatedEntity, typeof(NullRelationship));
}
/// <summary>
/// Create an entity container that is in the specified relationship with another entity.
/// </summary>
public static ContextEntity Create<T>(IEntity concreteEntity, IEntity relatedTo) where T : IRelationship
{
return new ContextEntity(concreteEntity, relatedTo, typeof(T));
}
/// <summary>
/// Constructor not accessible to the rest of the world.
/// </summary>
protected ContextEntity(IEntity concreteEntity, IEntity relatedTo, Type relationshipType)
{
ConcreteEntity = concreteEntity;
RelatedTo = relatedTo;
RelationshipType = relationshipType;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace WizSE.RPC
{
public class Client
{
private Dictionary<string, Conncetion> connections = new Dictionary<string, Conncetion>();
public class Call
{
private Guid id;
private Packet mRequest;
private Packet mResponse;
private bool isDone;
public Call(Packet request)
{
mRequest = request;
}
private void CallComplete()
{
isDone = true;
}
private void SetResponse()
{
}
}
public class Conncetion:ITask
{
public string RemoteID { get; set; }
private Dictionary<Guid, Call> calls = new Dictionary<Guid, Call>();
private void SendRequest()
{
return;
}
private void ReceiveReponse()
{
return;
}
private void Touch()
{
return;
}
private void AddCall()
{
return;
}
public override void Run()
{
try
{
while (true)
{
ReceiveReponse();
}
}
catch (Exception ex)
{
Stop();
}
}
}
}
}
|
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace BinaryFog.NameParser {
public static class RegexNameComponents {
private static string SplitAndJoin(string res) {
var stringBuilder = new StringBuilder();
using (var reader = new StringReader(res)) {
stringBuilder.Append(reader.ReadLine());
for(;;) {
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line)) break;
stringBuilder.Append('|').Append(Regex.Escape(line));
}
}
return stringBuilder.ToString();
}
//public static readonly string FemaleFirstNames = SplitAndJoin(Resources.FemaleFirstNames);
//public static readonly string MaleFirstNames = SplitAndJoin(Resources.MaleFirstNames);
//public static readonly string USCensusLastNames = SplitAndJoin(Resources.USCensusLastNames);
public static readonly string LastNamePrefixes = SplitAndJoin(Resources.LastNamePrefixes);
public static readonly string PostNominals = SplitAndJoin(Resources.PostNominals);
public static readonly string JobTitles = SplitAndJoin(Resources.JobTitles);
public static readonly string Suffixes = SplitAndJoin(Resources.Suffixes);
public static readonly string Titles = SplitAndJoin(Resources.Titles);
public static readonly string CompanySuffixes = SplitAndJoin(Resources.CompanySuffixes);
public static readonly string JobTitle = @"(?<jobTitle>" + JobTitles + @")";
public static readonly string Title = @"(?<title>(" + Titles + @")((?!\s)\W)?)";
//public static readonly string Suffix = @"(?<suffix>((" + Suffixes + @")((?!\s)\W)?)([\s]*(?<=[\s\W]+)(" + PostNominals + @")((?!\s)\W)?)*?|([\s]*(?<=[\s\W]+)(" + PostNominals + @")((?!\s)\W)?))";
public static readonly string Suffix = @"(?<suffix>(" + Suffixes + @")((?!\s)\W)?)";
public static readonly string Prefix = @"(?<prefix>" + LastNamePrefixes + @")";
public const string Space = @"((?<=\W)\s*|\s*(?=\W)|(?<!\W)\s+)";
//public const string OptionalCommaSpace = @"(\s*,)?\s*";
public const string OptionalCommaSpace = @"\s*,?\s+";
public const string OptionalSpace = @"\s?";
public const string CommaSpace = @"\s*,\s*";
public const string Initial = @"(?<initial>[a-z]\.?)";
public const string First = @"(?<first>\w+|\w+'\w*)";
public const string Last = @"(?<last>\w+|\w+'\w*|'\w+)";
public const string Middle = @"(?<middle>\w+)";
public const string LastHyphenated = @"(?<last>(?<lastPart1>\w+)-(?<lastPart2>\w+))";
public const string Nick = @"(?=\(\w+\)|'\w+'|""\w+"")[\('""](?<nick>\w+)[\)'""]";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlackJack.model.rules
{
interface IDealCardStrategy
{
void DealCard(Deck a_deck, Dealer a_dealer, Player a_player, bool a_show = true);
}
}
|
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf.Suggestions
{
public class AdminSuggestionFeaturePersonResponsibility : Entity
{
public const string IS_SUPERIOR_TO = "IS_SUPERIOR_TO";
public const string FOUGHT_WITH = "FOUGHT_WITH";
public const string IS_A_SUBORDINATE = "IS_A_SUBORDINATE";
public const string ACTED_WITH = "ACTED_WITH";
public const string IS_DEPUTY_OF = "IS_DEPUTY_OF";
public const string IS_BODYGUARD_OF = "IS_BODYGUARD_OF";
public const string FOUGHT_IN_SAME_GROUP_AS = "FOUGHT_IN_SAME_GROUP_AS";
public const string BELONGED_TO_SAME_GROUP_AS = "BELONGED_TO_SAME_GROUP_AS";
public const string PROVIDED_WEAPONS_AND_AMMUNITION_TO = "PROVIDED_WEAPONS_AND_AMMUNITION_TO";
public const string RESPONSIBLE_FOR_RELATED_EVENT = "RESPONSIBLE_FOR_RELATED_EVENT";
public const string LAST_NAME_APPEARS = "LAST_NAME_APPEARS";
public const string FIRST_NAME_APPEARS = "FIRST_NAME_APPEARS";
public const string COMMON_SOURCE = "COMMON_SOURCE";
public const string ALIAS_APPEARS = "ALIAS_APPEARS";
public const string CAREER_IN_LOCATION = "CAREER_IN_LOCATION";
public const string CAREER_IN_ORG_RESPONSIBLE = "CAREER_IN_ORG_RESPONSIBLE";
public const string CAREER_IN_UNIT_RESPONSIBLE = "CAREER_IN_UNIT_RESPONSIBLE";
public const string RESPONSIBILITY_IN_LOCATION = "RESPONSIBILITY_IN_LOCATION";
public virtual string Feature { get; set; }
public virtual float CurrentWeight { get; set; }
public virtual bool Archive { get; set; }
public virtual string Notes { get; set; }
public virtual string Code { get; set; }
}
}
|
namespace AquaShop.Core
{
using AquaShop.Core.Contracts;
using AquaShop.Models.Aquariums;
using AquaShop.Models.Aquariums.Contracts;
using AquaShop.Models.Decorations;
using AquaShop.Models.Fish;
using AquaShop.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Controller : IController
{
private DecorationRepository decorations;
private ICollection<IAquarium> aquariums;
public Controller()
{
this.decorations = new DecorationRepository();
this.aquariums = new List<IAquarium>();
}
public string AddAquarium(string aquariumType, string aquariumName)
{
if (aquariumType != "FreshwaterAquarium" && aquariumType != "SaltwaterAquarium")
{
throw new InvalidOperationException("Invalid aquarium type.");
}
if (aquariumType == "FreshwaterAquarium")
{
this.aquariums.Add(new FreshwaterAquarium(aquariumName));
}
if (aquariumType == "SaltwaterAquarium")
{
this.aquariums.Add(new SaltwaterAquarium(aquariumName));
}
return $"Successfully added {aquariumType}.";
}
public string AddDecoration(string decorationType)
{
if (decorationType != "Ornament" && decorationType != "Plant")
{
throw new InvalidOperationException("Invalid decoration type.");
}
if (decorationType == "Ornament")
{
this.decorations.Add(new Ornament());
}
if (decorationType == "Plant")
{
this.decorations.Add(new Plant());
}
return $"Successfully added {decorationType}.";
}
public string AddFish(string aquariumName, string fishType, string fishName, string fishSpecies, decimal price)
{
if (fishType != "FreshwaterFish" && fishType != "SaltwaterFish")
{
throw new InvalidOperationException("Invalid fish type.");
}
var aquarium = this.aquariums.Single(a => a.Name == aquariumName);
if (aquarium.GetType().Name == "FreshwaterAquarium" &&
fishType == "SaltwaterFish" ||
aquarium.GetType().Name == "SaltwaterAquarium" &&
fishType == "FreshwaterFish")
{
return "Water not suitable.";
}
else
{
if (fishType == "SaltwaterFish")
{
aquarium.AddFish(new SaltwaterFish(fishName, fishSpecies, price));
}
if (fishType == "FreshwaterFish")
{
aquarium.AddFish(new FreshwaterFish(fishName, fishSpecies, price));
}
return $"Successfully added {fishType} to {aquariumName}.";
}
}
public string CalculateValue(string aquariumName)
{
var aquarium = this.aquariums.Single(a => a.Name == aquariumName);
var fishPrice = aquarium.Fish.Sum(f => f.Price);
var decorationsPrice = aquarium.Decorations.Sum(d => d.Price);
var combinedPrice = fishPrice + decorationsPrice;
return $"The value of Aquarium {aquariumName} is {combinedPrice:f2}.";
}
public string FeedFish(string aquariumName)
{
var aquarium = this.aquariums.Single(a => a.Name == aquariumName);
aquarium.Feed();
return $"Fish fed: {aquarium.Fish.Count}";
}
public string InsertDecoration(string aquariumName, string decorationType)
{
if (!this.decorations.Models.Any(d => d.GetType().Name == decorationType))
{
throw new InvalidOperationException($"There isn't a decoration of type {decorationType}.");
}
var decoration = this.decorations.Models.First(d => d.GetType().Name == decorationType);
var aquarium = this.aquariums.Single(a => a.Name == aquariumName);
aquarium.AddDecoration(decoration);
this.decorations.Remove(decoration);
return $"Successfully added {decorationType} to {aquariumName}.";
}
public string Report()
{
var sb = new StringBuilder();
foreach (var aquarium in aquariums)
{
sb.AppendLine(aquarium.GetInfo());
}
return sb.ToString().TrimEnd();
}
}
}
|
/*
Description Script:
Name:
Date:
Upgrade:
*/
using UnityEngine;
public class InputController : MonoBehaviour
{
public delegate void inputEventController();
public KeyCode rightControl_left, // equal to button Squad
rightControl_up, // equal to button Triangle
rightControl_right, // equal to button Circle
rightControl_down, // equal to button X
rightControlUp_Up, // equal to button R2
rightControlUp_Down, // equal to button R1
leftControlUp_Up, // equal to button L2
leftControlUp_Down, // equal to button L1
leftControl_left, // equal to button left arrow
leftControl_up, // equal to button up arrow
leftControl_right, // equal to button right arrow
leftControl_down, // equal to button down arrow
control_start, // equal to button start
control_select; // equal to button select
/// <summary>
/// Evento Stay
/// </summary>
public inputEventController ev_rightControl_left, // event to button Squad
ev_rightControl_up, // event to button Triangle
ev_rightControl_right, // event to button Circle
ev_rightControl_down, // event to button X
ev_rightControlUp_Up, // event to button R2
ev_rightControlUp_Down, // event to button R1
ev_leftControlUp_Up, // event to button L2
ev_leftControlUp_Down, // event to button L1
ev_leftControl_left, // event to button left arrow
ev_leftControl_up, // event to button up arrow
ev_leftControl_right, // event to button right arrow
ev_leftControl_down, // event to button down arrow
ev_control_start, // event to button start
ev_control_select, // event to button select
ev_last_frame;
/// <summary>
/// Evento Up
/// </summary>
public inputEventController ev_rightControl_left_UP, // event to button Squad
ev_rightControl_up__UP, // event to button Triangle
ev_rightControl_right__UP, // event to button Circle
ev_rightControl_down__UP, // event to button X
ev_rightControlUp_Up__UP, // event to button R2
ev_rightControlUp_Down__UP, // event to button R1
ev_leftControlUp_Up__UP, // event to button L2
ev_leftControlUp_Down__UP, // event to button L1
ev_leftControl_left_UP, // event to button left arrow
ev_leftControl_up_UP, // event to button up arrow
ev_leftControl_right_UP, // event to button right arrow
ev_leftControl_down_UP, // event to button down arrow
ev_control_start_UP, // event to button start
ev_control_select_UP; // event to button select
/// <summary>
/// Evento Down
/// </summary>
public inputEventController ev_rightControl_left_DOWN, // event to button Squad
ev_rightControl_up_DOWN, // event to button Triangle
ev_rightControl_right_DOWN, // event to button Circle
ev_rightControl_down_DOWN, // event to button X
ev_rightControlUp_Up_DOWN, // event to button R2
ev_rightControlUp_Down_DOWN, // event to button R1
ev_leftControlUp_Up_DOWN, // event to button L2
ev_leftControlUp_Down_DOWN, // event to button L1
ev_leftControl_left_DOWN, // event to button left arrow
ev_leftControl_up_DOWN, // event to button up arrow
ev_leftControl_right_DOWN, // event to button right arrow
ev_leftControl_down_DOWN, // event to button down arrow
ev_control_start_DOWN, // event to button start
ev_control_select_DOWN; // event to button select
private bool buttonPress = false;
void Update()
{
if (Input.anyKey)
buttonPress = true;
//#region GET KEY DOWN
if (Input.GetKeyDown(this.rightControl_left))
{
if (this.ev_rightControl_left_DOWN != null) this.ev_rightControl_left_DOWN();
}
if (Input.GetKeyDown(this.rightControl_up))
{
if (this.ev_rightControl_up_DOWN != null) this.ev_rightControl_up_DOWN();
}
if (Input.GetKeyDown(this.rightControl_right))
{
if (this.ev_rightControl_right_DOWN != null) this.ev_rightControl_right_DOWN();
}
if (Input.GetKeyDown(this.rightControl_down))
{
if (this.ev_rightControl_down_DOWN != null) this.ev_rightControl_down_DOWN();
}
if (Input.GetKeyDown(this.rightControlUp_Up))
{
if (this.ev_rightControlUp_Up_DOWN != null) this.ev_rightControlUp_Up_DOWN();
}
if (Input.GetKeyDown(this.rightControlUp_Down))
{
if (this.ev_rightControlUp_Down_DOWN != null) this.ev_rightControlUp_Down_DOWN();
}
if (Input.GetKeyDown(this.leftControl_left))
{
if (this.ev_leftControl_left_DOWN != null) this.ev_leftControl_left_DOWN();
}
if (Input.GetKeyDown(this.leftControl_up))
{
if (this.ev_leftControl_up_DOWN != null) this.ev_leftControl_up_DOWN();
}
if (Input.GetKeyDown(this.leftControl_right))
{
if (this.ev_leftControl_right_DOWN != null) this.ev_leftControl_right_DOWN();
}
if (Input.GetKeyDown(this.leftControl_down))
{
if (this.ev_leftControl_down_DOWN != null) this.ev_leftControl_down_DOWN();
}
if (Input.GetKeyDown(this.control_start))
{
if (this.ev_control_start_DOWN != null) this.ev_control_start_DOWN();
}
if (Input.GetKeyDown(this.control_select))
{
if (this.ev_control_start_DOWN != null) this.ev_control_start_DOWN();
}
//#endregion
//#region GET KEY UP
//if (Input.GetKeyUp(this.rightControl_left))
//{
// if (this.ev_rightControl_left != null) this.ev_rightControl_left();
//}
//if (Input.GetKeyUp(this.rightControl_up))
//{
// if (this.ev_rightControl_up != null) this.ev_rightControl_up();
//}
//if (Input.GetKeyUp(this.rightControl_right))
//{
// if (this.ev_rightControl_right != null) this.ev_rightControl_right();
//}
//if (Input.GetKeyUp(this.rightControl_down))
//{
// if (this.ev_rightControl_down != null) this.ev_rightControl_down();
//}
//if (Input.GetKeyUp(this.rightControlUp_Up))
//{
// if (this.ev_rightControlUp_Up != null) this.ev_rightControlUp_Up();
//}
//if (Input.GetKeyUp(this.rightControlUp_Down))
//{
// if (this.ev_rightControlUp_Down != null) this.ev_rightControlUp_Down();
//}
//if (Input.GetKeyUp(this.leftControl_left))
//{
// if (this.ev_leftControl_left != null) this.ev_leftControl_left();
//}
//if (Input.GetKeyUp(this.leftControl_up))
//{
// if (this.ev_leftControl_up != null) this.ev_leftControl_up();
//}
//if (Input.GetKeyUp(this.leftControl_right))
//{
// if (this.ev_leftControl_right != null) this.ev_leftControl_right();
//}
//if (Input.GetKeyUp(this.leftControl_down))
//{
// if (this.ev_leftControl_down != null) this.ev_leftControl_down();
//}
//if (Input.GetKeyUp(this.control_start))
//{
// if (this.ev_control_start != null) this.ev_control_start();
//}
//if (Input.GetKeyUp(this.control_select))
//{
// if (this.ev_control_start != null) this.ev_control_start();
//}
//#endregion
#region GET KEY
if (Input.GetKey(this.rightControl_left))
{
if (this.ev_rightControl_left != null) this.ev_rightControl_left();
}
if (Input.GetKey(this.rightControl_up))
{
if (this.ev_rightControl_up != null) this.ev_rightControl_up();
}
if (Input.GetKey(this.rightControl_right))
{
if (this.ev_rightControl_right != null) this.ev_rightControl_right();
}
if (Input.GetKey(this.rightControl_down))
{
if (this.ev_rightControl_down != null) this.ev_rightControl_down();
}
if (Input.GetKey(this.rightControlUp_Up))
{
if (this.ev_rightControlUp_Up != null) this.ev_rightControlUp_Up();
}
if (Input.GetKey(this.rightControlUp_Down))
{
if (this.ev_rightControlUp_Down != null) this.ev_rightControlUp_Down();
}
if (Input.GetKey(this.leftControl_left))
{
if (this.ev_leftControl_left != null) this.ev_leftControl_left();
}
if (Input.GetKey(this.leftControl_up))
{
if (this.ev_leftControl_up != null) this.ev_leftControl_up();
}
if (Input.GetKey(this.leftControl_right))
{
if (this.ev_leftControl_right != null) this.ev_leftControl_right();
}
if (Input.GetKey(this.leftControl_down))
{
if (this.ev_leftControl_down != null) this.ev_leftControl_down();
}
if (Input.GetKey(this.control_start))
{
if (this.ev_control_start != null) this.ev_control_start();
}
if (Input.GetKey(this.control_select))
{
if (this.ev_control_start != null) this.ev_control_start();
}
#endregion
if (Input.GetKeyUp(leftControl_down) || Input.GetKeyUp(leftControl_left) || Input.GetKeyUp(leftControl_up) ||
Input.GetKeyUp(leftControl_right))
{
this.eventLastFrame();
}
this.notEnyPressButton();
}
/// <summary>
///
/// </summary>
void notEnyPressButton()
{
if (this.buttonPress && !Input.anyKey)
{
this.eventLastFrame();
}
}
/// <summary>
///
/// </summary>
void eventLastFrame()
{
if (this.ev_last_frame != null)
{
this.buttonPress = !this.buttonPress;
ev_last_frame();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
namespace Mario__.Components
{
class Trump : Drawable
{
static Texture2D texture;
Physics physics;
Vector2 position, dimensions;
RectangleF collision;
public Trump(Vector2 position, Vector2 dimensions, Physics physics)
{
this.position = position;
this.dimensions = dimensions;
this.physics = physics;
this.collision = physics.boundingBox(position, (int)dimensions.X, (int)dimensions.Y);
}
public override void destroy()
{
physics.colliders.Remove(this.collision);
}
public override void draw(SpriteBatch spriteBatch)
{
Draw(spriteBatch, texture, collision, Microsoft.Xna.Framework.Color.White);
}
public override void load()
{
physics.colliders.Add(this.collision);
}
public static void loadResource(ContentManager Content)
{
texture = Content.Load<Texture2D>("trumpWall");
}
public override void update(GameTime gameTime, InputListener input)
{
Vector2 move = new Vector2((float)Math.Sin(gameTime.TotalGameTime.TotalMilliseconds / 200.0f)*40.0f, (float)Math.Cos(gameTime.TotalGameTime.TotalMilliseconds / 200.0f) *40.0f);
physics.transform(move, ref this.position, ref this.collision);
}
}
}
|
using Emanate.Core.Input;
using Emanate.Core.Output;
using Emanate.Service;
using Moq;
using NUnit.Framework;
namespace Emanate.UnitTests.Service
{
[TestFixture]
public class monitoring_service
{
[Test]
public void should_populate_string_properties()
{
var monitor = new Mock<IBuildMonitor>();
var output = new Mock<IOutput>();
var service = new EmanateService(monitor.Object, output.Object);
}
}
}
|
using System;
using System.Windows.Forms;
using Phenix.Core;
using Phenix.Core.Rule;
using Phenix.Core.Security;
using Phenix.Core.Windows;
namespace Phenix.Windows
{
internal partial class CriteriaExpressionNewDialog : Phenix.Core.Windows.DialogForm
{
private CriteriaExpressionNewDialog()
{
InitializeComponent();
this.readLevelEnumKeyCaptionBindingSource.DataSource = EnumKeyCaptionCollection.Fetch<ReadLevel>();
}
#region 工厂
public static CriteriaExpressionKeyCaption Execute(CriteriaExpressionKeyCaptionCollection criteriaExpressionKeyCaptionCollection, ReadLevel readLevel)
{
CriteriaExpressionPropertyKeyCaptionCollection criteriaExpressionProperties = CriteriaExpressionPropertySelectDialog.Execute(criteriaExpressionKeyCaptionCollection);
if (criteriaExpressionProperties != null)
using (CriteriaExpressionNewDialog dialog = new CriteriaExpressionNewDialog())
{
dialog.CriteriaExpressionKeyCaptionCollection = criteriaExpressionKeyCaptionCollection;
dialog.CriteriaExpressionKeyCaption = CriteriaExpressionKeyCaption.New(criteriaExpressionProperties, readLevel, UserIdentity.CurrentIdentity);
return dialog.ShowDialog() == DialogResult.OK ? dialog.CriteriaExpressionKeyCaption : null;
}
return null;
}
#endregion
#region 属性
private CriteriaExpressionKeyCaptionCollection CriteriaExpressionKeyCaptionCollection { get; set; }
private CriteriaExpressionKeyCaption CriteriaExpressionKeyCaption
{
get { return BindingSourceHelper.GetDataSourceCurrent(this.criteriaExpressionKeyCaptionBindingSource) as CriteriaExpressionKeyCaption; }
set { this.criteriaExpressionKeyCaptionBindingSource.DataSource = value; }
}
#endregion
#region 方法
private void ApplyRules()
{
this.okButton.Enabled =
UserIdentity.CurrentIdentity != null && UserIdentity.CurrentIdentity.AllowSet(CriteriaExpressionKeyCaption) &&
!String.IsNullOrEmpty(this.CaptionTextEdit.Text);
}
#endregion
private void CriteriaExpressionNewDialog_Shown(object sender, System.EventArgs e)
{
ApplyRules();
}
private void CaptionTextEdit_EditValueChanged(object sender, EventArgs e)
{
ApplyRules();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void okButton_Click(object sender, System.EventArgs e)
{
try
{
CriteriaExpressionKeyCaptionCollection.Save(CriteriaExpressionKeyCaption);
this.DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
string hint = String.Format(Phenix.Windows.Properties.Resources.DataSaveAborted, CriteriaExpressionKeyCaptionCollection.Caption, CriteriaExpressionKeyCaption.Caption, AppUtilities.GetErrorHint(ex));
MessageBox.Show(hint, Phenix.Windows.Properties.Resources.DataSave, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
namespace gView.GraphicsEngine.Abstraction
{
public interface IDrawTextFormat
{
StringAlignment Alignment { get; set; }
StringAlignment LineAlignment { get; set; }
object EngineElement { get; }
}
}
|
using ClassLibraryAandelen.basis;
using ClassLibraryAandelen.classes;
using System;
using System.Collections.ObjectModel;
namespace WpfAandelenBeheer.viewmodels
{
public class AandelenWindowViewModel : BaseUserControl
{
#region fields
private Portefeuille _CurrentPortefeuille;
private Aandeel _selecteerdeAandeel;
private ObservableCollection<Aandeel> _aandelen;
private Double _ActueleWaarde = 0;
private Double _BeginWaarde = 0;
private String _BedrijfsNaam;
AandelenRepo repo;
#endregion
#region events
public event Action AddAandeelEvent, RemoveAandeelEvent, UpdateAandeelEvent;
#endregion
#region constructor
/// <summary>
/// taken van de constructor:
/// 1. haalt de repo(context) en id van de gebruiker binnen en stelt ze gelijk aan de velden in de klasse, om later gebruikt te worden.
/// 2. Titel wordt verandert
/// 3. Aandelen worden binnengehaald
/// 4. Commando's voor het toevoegen, wijzigen en verwijderen worden aangemaakt
/// </summary>
/// <param name="repo">context waaruit alle data zal uit komen</param>
/// <param name="idGebruiker">id van de gebruiker</param>
/// <param name="portefeuille">Portefeuille waar uit de aandelen zullen uit komen.</param>
public AandelenWindowViewModel(AandelenRepo repo, int idGebruiker, Portefeuille portefeuille)
{
this.repo = repo;
IdGebruiker = idGebruiker;
CurrentPortefeuille = portefeuille;
Titel = $"Aandelen uit portefeuille {CurrentPortefeuille.Naam}";
AandelenCollectie = repo.GetAandelen(idGebruiker, portefeuille);
CmdAddAandeel = new CmdHelper(VoegAandeelToe, KanAandeelToevoegen);
CmdRemoveAandeel = new CmdHelper(VerwijderAandeel, KanAandeelVerwijderenUpdate);
CmdUpdateAandeel = new CmdHelper(UpdateAandeel, KanAandeelVerwijderenUpdate);
}
#endregion
#region properties
public int IdGebruiker { get; set; }
public CmdHelper CmdAddAandeel { get; private set; }
public CmdHelper CmdRemoveAandeel { get; private set; }
public CmdHelper CmdUpdateAandeel { get; private set; }
public String BedrijfsNaam
{
get { return _BedrijfsNaam; }
set
{
if (_BedrijfsNaam != value) _BedrijfsNaam = value;
OnPropertyChanged();
}
}
public Double BeginWaarde
{
get { return _BeginWaarde; }
set
{
if (_BeginWaarde != value) _BeginWaarde = value.toEuro();
OnPropertyChanged();
}
}
public Double ActueleWaarde
{
get { return _ActueleWaarde; }
set
{
if (_ActueleWaarde != value) _ActueleWaarde = value.toEuro();
OnPropertyChanged();
}
}
public Aandeel SelecteerdeAandeel
{
get { return _selecteerdeAandeel; }
set
{
if (_selecteerdeAandeel != value)
{
_selecteerdeAandeel = value;
}
if (_selecteerdeAandeel != null)
{
BedrijfsNaam = SelecteerdeAandeel.Bedrijfsnaam;
BeginWaarde = SelecteerdeAandeel.BeginWaarde;
ActueleWaarde = SelecteerdeAandeel.ActueleWaarde;
}
NotifyProperties("AandelenCollectie");
}
}
public Portefeuille CurrentPortefeuille
{
get { return _CurrentPortefeuille; }
set
{
if (_CurrentPortefeuille != value) _CurrentPortefeuille = value;
OnPropertyChanged();
RefreshViewModel();
}
}
public ObservableCollection<Aandeel> AandelenCollectie
{
get { return _aandelen; }
set
{
if (_aandelen != value) _aandelen = value;
OnPropertyChanged();
}
}
#endregion
#region methods
/// <summary>
/// Als de portefeuille niet leeg is wordt, de titel en aandelen uit de portefeuille aangepast op de nieuwe portefeuille en
/// worden de aandelen form geleegd
/// </summary>
public void RefreshViewModel()
{
if (CurrentPortefeuille != null)
{
Titel = $"Aandelen uit portefeuille {CurrentPortefeuille.Naam}";
AandelenCollectie = repo.GetAandelen(IdGebruiker, CurrentPortefeuille);
MaakVeldenLeeg();
}
}
/// <summary>
/// Voegt een aandeel toe op de portefeuille van dit moment en leegt de aandelen form.
/// </summary>
private void VoegAandeelToe()
{
repo.AddAandeel(IdGebruiker, CurrentPortefeuille, new Aandeel(BedrijfsNaam, BeginWaarde, ActueleWaarde));
MaakVeldenLeeg();
AddAandeelEvent?.Invoke();
}
/// <summary>
/// Verwijdert een aandeel uit de portefeuille van dit moment en leegt de aandelen form.
/// </summary>
private void VerwijderAandeel()
{
repo.RemoveAandeel(IdGebruiker, CurrentPortefeuille, SelecteerdeAandeel);
MaakVeldenLeeg();
RemoveAandeelEvent?.Invoke();
}
/// <summary>
/// Wijzigt de geselecteerde aandeel uit het portefeuille.
/// </summary>
private void UpdateAandeel()
{
repo.UpdateAandeel(IdGebruiker, CurrentPortefeuille, SelecteerdeAandeel, BedrijfsNaam, BeginWaarde, ActueleWaarde);
OnPropertyChanged("CurrentPortefeuille");
UpdateAandeelEvent?.Invoke();
}
/// <summary>
/// Leegt de aandelen form
/// </summary>
private void MaakVeldenLeeg()
{
BedrijfsNaam = "";
ActueleWaarde = BeginWaarde = 0;
}
//Methode om te bepalen of er een aandeel toegevoegd kan worden.
private bool KanAandeelToevoegen() => BedrijfsNaam != "" && BeginWaarde != 0 && ActueleWaarde != 0;
//Methode om te bepalen of een aandeel gewijzigd of verwijdert kan worden.
private bool KanAandeelVerwijderenUpdate() => CurrentPortefeuille != null && SelecteerdeAandeel != null;
#endregion
}
} |
using System.IO;
using DelftTools.TestUtils;
using NUnit.Framework;
using SharpMap.Extensions.Layers;
namespace SharpMap.Extensions.Tests.Layers
{
[TestFixture]
public class BingLayerTest
{
[Test]
public void Clone()
{
var map = new Map();
var layer = new BingLayer();
map.Layers.Add(layer);
var clone = (BingLayer)layer.Clone();
Assert.IsNull(clone.Map);
}
[Test]
public void CacheDirectoryIsDefined()
{
BingLayer.CacheLocation
.Should("Cache directory is defined")
.EndWith(@"cache_bing");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace proj12.View.Controls
{
/// <summary>
/// Interaction logic for Joystick.xaml
/// </summary>
public partial class Joystick : UserControl
{
public delegate void EmptyJoystickEventHandler(Joystick sender);
public delegate void OnScreenJoystickEventHandler(Joystick sender, VirtualJoystickEventArgs args);
public event EmptyJoystickEventHandler Released;
public event EmptyJoystickEventHandler Captured;
private Point StartingPosition;
private double canvasWidth, canvasHeight;
private readonly Storyboard centerKnob;
public Joystick()
{
InitializeComponent();
Knob.MouseMove += KnobMoved;
Knob.MouseLeftButtonUp += KnobLeft;
Knob.MouseLeftButtonDown += KnobPressed;
centerKnob = Knob.Resources["CenterKnob"] as Storyboard;
}
private void KnobPressed(object sender, MouseButtonEventArgs e)
{
StartingPosition = e.GetPosition(Base);
canvasHeight = Base.ActualHeight - KnobBase.ActualHeight;
canvasWidth = Base.ActualWidth - KnobBase.ActualWidth;
Captured?.Invoke(this);
Knob.CaptureMouse();
centerKnob.Stop();
}
private void KnobLeft(object sender, MouseButtonEventArgs e)
{
Knob.ReleaseMouseCapture();
centerKnob.Begin();
}
private void KnobMoved(object sender, MouseEventArgs e)
{
if (Knob.IsMouseCaptured == false)
{
return;
}
Point newPosition = e.GetPosition(Base);
Point toMove = new Point(newPosition.X - StartingPosition.X, newPosition.Y - StartingPosition.Y);
double distance = Math.Round(Math.Sqrt(toMove.X * toMove.X + toMove.Y * toMove.Y));
if (distance >= (canvasHeight / 2) || distance >= (canvasWidth / 2))
{
return;
}
knobPosition.Y = toMove.Y;
knobPosition.X = toMove.X;
}
private void centerKnob_Completed(object sender, EventArgs e)
{
Released?.Invoke(this);
}
}
public class VirtualJoystickEventArgs
{
public double Aileron { get; set; }
public double Elevator { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameOverScript : MonoBehaviour {
[TextArea (1,20)]
public List<string> Letter = new List<string>();
public WriteLetterbyLetter write;
public string option;
string text;
private void Start()
{
PlayerManager._Instance.OnStealing(null);
write = GetComponent<WriteLetterbyLetter>();
if (PlayerManager._Instance != null)
{
if (PlayerManager._Instance.Energy <= 0)
{
text = Letter[1];
}
else if (PlayerManager._Instance.HP <= 0)
{
text = Letter[2];
}
else
{
text = Letter[0];
}
}
write.message = text;
write.WriteLetter();
}
}
|
using Sentry;
using Sentry.Extensibility;
namespace Samples.AspNetCore.Mvc;
public class SpecialExceptionProcessor : SentryEventExceptionProcessor<SpecialException>
{
protected override void ProcessException(
SpecialException exception,
SentryEvent sentryEvent)
{
sentryEvent.AddBreadcrumb("Processor running on special exception.");
sentryEvent.SetTag("IsSpecial", exception.IsSpecial.ToString());
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.Animations;
public class MenuManager : MonoBehaviour
{
public GameObject mainMenu;
public GameObject selectMenu;
public GameObject optionsMenu;
private string mainMenuName;
public bool isMainMenu;
private GameManager gameManager;
//public GameObject GameOver;
//public GameObject GameCredits;
private void Start()
{
mainMenu.SetActive(false);
if (isMainMenu)
{
ActivateMainMenu();
}
gameManager = FindObjectOfType<GameManager>().GetComponent<GameManager>();
}
private void Update()
{
Scene currentScene = SceneManager.GetActiveScene();
mainMenuName = currentScene.name;
}
public void ActivateMainMenu()
{
mainMenu.SetActive(true);
selectMenu.SetActive(false);
optionsMenu.SetActive(false);
}
public void ActivateSelectMenu()
{
selectMenu.SetActive(true);
mainMenu.SetActive(false);
optionsMenu.SetActive(false);
}
public void ActivateCombatSystem()
{
gameManager.LoadCombatScene();
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace LeetCodeTests
{
public abstract class Problem_0027
{
/*
Given an array and a value, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
*/
public static void Test()
{
Solution sol = new Solution();
/*
var input = new int[] { 2, 7, 11, 15 };
Console.WriteLine($"Input array: {string.Join(", ", input)}");
*/
var nums = new int[] { 3, 2, 2, 3 };
var val = 3;
Console.WriteLine($"For array '{Utils.PrintArray(nums)}' and val '{val}': new array length is {sol.RemoveElement(nums, val)}");
nums = new int[] { 1, 2, 7, 4, 5, 6, 7, 7, 7, 7, 7 };
val = 7;
Console.WriteLine($"For array '{Utils.PrintArray(nums)}' and val '{val}': new array length is {sol.RemoveElement(nums, val)} (wait 5)");
/*
Submission Result: Wrong Answer
Input:[1] 1
Output:[1]
Expected:[]
*/
nums = new int[] { 1};
val = 1;
Console.WriteLine($"For array '{Utils.PrintArray(nums)}' and val '{val}': new array length is {sol.RemoveElement(nums, val)} (wait 0)");
nums = new int[] { 1, 1, 1, 1, 1, 1, 1};
val = 1;
Console.WriteLine($"For array '{Utils.PrintArray(nums)}' and val '{val}': new array length is {sol.RemoveElement(nums, val)} (wait 0)");
/*
Submission Result: Wrong Answer
Input:[4,5] 5
Output:[4,5]
Expected:[4]
*/
nums = new int[] { 4, 5};
val = 5;
Console.WriteLine($"For array '{Utils.PrintArray(nums)}' and val '{val}': new array length is {sol.RemoveElement(nums, val)} (wait 0)");
nums = new int[] { 1, 2, 3, 4, 5, 6 };
val = 7;
Console.WriteLine($"For array '{Utils.PrintArray(nums)}' and val '{val}': new array length is {sol.RemoveElement(nums, val)} (wait 6)");
}
public class Solution
{
public int RemoveElement(int[] nums, int val)
{
if ((nums == null) || (nums.Length == 0))
return 0;
int left = 0;
int right = nums.Length - 1;
while (left <= right)
{
if (nums[left] == val)
{
while ((right > left) && (nums[right] == val))
right--;
nums[left] = nums[right];
right--;
}
left++;
}
if (nums[0] == val)
return 0;
return right+1;
}
}
}//public abstract class Problem_
} |
using System;
using System.Collections.Generic;
using System.Text;
using CSConsoleRL.Entities;
using CSConsoleRL.Components;
using SFML.System;
namespace CSConsoleRL.Helpers
{
public enum EnumGameState
{
MainMenu,
RegularGame,
Console,
Targeting
}
public sealed class GameStateHelper
{
private readonly Dictionary<string, object> _gameState;
public EnumGameState GameState { get; private set; }
public Vector2i CameraCoords { get; private set; }
public bool DebugMode { get; private set; }
public GameStateHelper()
{
_gameState = new Dictionary<string, object>();
GameState = EnumGameState.RegularGame;
DebugMode = true;
}
public void SetGameState(EnumGameState newState)
{
GameState = newState;
}
public void SetDebugMode(bool debug)
{
DebugMode = debug;
}
public void SetCameraCoords(int x, int y)
{
CameraCoords = new Vector2i(x, y);
}
public T GetVar<T>(string key)
{
if (!_gameState.ContainsKey(key))
{
throw new Exception(String.Format(@"GameStateHelper GetVar was called for variable '{0}'
that doesn't exist", key));
}
var varValue = _gameState[key];
if (varValue is T)
{
return (T)varValue;
}
else
{
throw new Exception(String.Format(@"GameStateHelper GetVar was called for variable '{0}'
that exists but is a different type than specified", key));
}
}
public void SetVar(string key, object val)
{
if (_gameState.ContainsKey(key))
{
var temp = _gameState[key];
if (temp.GetType() == val.GetType())
{
_gameState[key] = val;
}
else
{
throw new Exception(String.Format(@"GameStateHelper SetVar was called for variable '{0}'
type '{1}', but the variable already has a value with type '{2}'", key, val.GetType(), temp.GetType()));
}
}
else
{
_gameState.Add(key, val);
}
}
}
}
|
using System;
namespace NeuralNetLibrary.components.activators
{
[Serializable]
public class ThresholdActivation : ActivationFunction
{
private double threshold;
public ThresholdActivation(double threshold)
{
this.threshold = threshold;
}
public double Equation(double weight)
{
if (weight > threshold)
return 1;
return 0;
}
public double Derivative(double weight)
{
return 0;
}
public string GetName()
{
return "ThresholdActivation";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.ModLoader;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.ID;
namespace StarlightRiver.Tiles.Vitric
{
class VitricCrystalBig : ModTile
{
public override bool Autoload(ref string name, ref string texture)
{
texture = "StarlightRiver/Invisible";
return true;
}
public override void SetDefaults()
{
Main.tileSolid[Type] = false;
minPick = int.MaxValue;
dustType = ModContent.DustType<Dusts.Air>();
}
public override void DrawEffects(int i, int j, SpriteBatch spriteBatch, ref Color drawColor, ref int nextSpecialDrawIndex)
{
Texture2D tex = ModContent.GetTexture("StarlightRiver/Tiles/Vitric/CrystalOver1");
spriteBatch.Draw(tex, (new Vector2(i, j) + Helper.TileAdj) * 16 - Main.screenPosition, tex.Frame(), Color.White * 0.95f, 0, Vector2.Zero, 1, 0, 0);
}
}
class VitricCrystalCollision : ModTile
{
public override bool Autoload(ref string name, ref string texture)
{
texture = "StarlightRiver/Invisible";
return true;
}
public override void SetDefaults()
{
Main.tileSolid[Type] = true;
TileID.Sets.DrawsWalls[Type] = true;
minPick = int.MaxValue;
soundStyle = SoundID.CoinPickup;
dustType = ModContent.DustType<Dusts.Air>();
}
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BaseModels
{
public class Produto
{
public int ProdutoID { get; set; }
[Required]
[StringLength(20)]
public string Nome { get; set; }
public string Descricao { get; set; }
[Required]
public string Ativo { get; set; }
// -- Relacionamento Categoria --> Produto
[ForeignKey("_Categoria")]
public int CategoriaID { get; set; }
public virtual Categoria _Categoria { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SlideShareAPI
{
public static class UploadDate
{
public static String Any = "any";
public static String Week = "week";
public static String Month = "month";
public static String Yeah = "year";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using IRAPShared;
using IRAP.Global;
namespace IRAP.Entity.MDM
{
/// <summary>
/// 站点产品状态
/// </summary>
public class WIPStationProductionStatus
{
private int ordinal = 0;
private int t107LeafID = 0;
private string t107Code = "";
private string t107Name = "";
private int t102LeafID_InProduction = 0;
private string t102Code_InProduction = "";
private string pwoNo_InExecution = "";
private string containerNo = "";
private string containerNo_Output = "";
private byte[] t107Image;
private Image t107Picture = null;
private string nextPWOToExecute = "";
private string nextContainerNo = "";
private string atStoreLocCode = "";
private string dstStoreLocCode = "";
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 工位叶标识
/// </summary>
public int T107LeafID { get; set; }
/// <summary>
/// 工位代码
/// </summary>
public string T107Code { get; set; }
/// <summary>
/// 工位名称
/// </summary>
public string T107Name { get; set; }
/// <summary>
/// 正在生产的产品叶标识
/// </summary>
public int T102LeafID_InProduction { get; set; }
/// <summary>
/// 正在生产的产品编号
/// </summary>
public string T102Code_InProduction { get; set; }
/// <summary>
/// 正在执行的生产工单号
/// </summary>
public string PWONo_InExecution { get; set; }
/// <summary>
/// 正在执行工单签发时间
/// </summary>
public int PWOCreatedUnixTime_Current { get; set; }
/// <summary>
/// 待加工容器编号
/// </summary>
public string ContainerNo { get; set; }
/// <summary>
/// 已加工容器编号
/// </summary>
public string ContainerNo_Output { get; set; }
/// <summary>
/// 工位图片流
/// </summary>
public byte[] T107Image
{
get { return t107Image; }
set
{
t107Image = value;
try
{
t107Picture = Tools.BytesToImage(value);
}
finally { }
}
}
/// <summary>
/// 工位图片
/// </summary>
[IRAPORMMap(ORMMap = false)]
public Image T107Picture
{
get { return t107Picture; }
}
/// <summary>
/// 接下来要执行的生产工单
/// </summary>
public string NextPWOToExecute { get; set; }
/// <summary>
/// 下一张工单签发时间
/// </summary>
public int PWOCreatedUnixTime_Next { get; set; }
/// <summary>
/// 下一个工单的容器号
/// </summary>
public string NextContainerNo { get; set; }
/// <summary>
/// 下一个工单在制品/原材料获取位置
/// </summary>
public string AtStoreLocCode { get; set; }
/// <summary>
/// 当前工序完工后的目标存放库位
/// </summary>
public string DstStoreLocCode { get; set; }
/// <summary>
/// 正在生产的工序叶标识
/// </summary>
public int T216LeafID { get; set; }
/// <summary>
/// 正在生产的设备叶标识
/// </summary>
public int T133LeafID { get; set; }
/// <summary>
/// SPC 控制图类型:0=不控制;373564=彩虹图;373565=XBar-R图
/// </summary>
public int T47LeafID { get; set; }
/// <summary>
/// SPC 控制的参数叶标识
/// </summary>
public int T20LeafID { get; set; }
/// <summary>
/// 控制线下限(XBar-R图有效)
/// </summary>
public long LCL { get; set; }
/// <summary>
/// 控制线上限(XBar-R图有效)
/// </summary>
public long UCL { get; set; }
/// <summary>
/// 控制线设置日期
/// </summary>
public string CLSetDate { get; set; }
public WIPStationProductionStatus Clone()
{
WIPStationProductionStatus rlt = MemberwiseClone() as WIPStationProductionStatus;
if (rlt.t107Picture == null)
rlt.t107Picture = Tools.BytesToImage(rlt.t107Image);
return rlt;
}
}
} |
using System;
using System.Threading;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using CSBaseLib;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Logging;
namespace OMKServer
{
public class MainServer : AppServer<ClientSession, OMKBinaryRequestInfo>
{
public static OMKServerOption ServerOption;
public static SuperSocket.SocketBase.Logging.ILog MainLogger;
private SuperSocket.SocketBase.Config.IServerConfig m_Config;
PacketProcessor MainPacektProcessor = new PacketProcessor();
RoomManager RoomMgr = new RoomManager();
// MainServer 생성자 선언 및 이벤트 연결
public MainServer() : base(new DefaultReceiveFilterFactory<ReceiveFilter, OMKBinaryRequestInfo>())
{
NewSessionConnected += new SessionHandler<ClientSession>(OnConnected); // 1. 접속 연결
SessionClosed += new SessionHandler<ClientSession, CloseReason>(OnClosed); // 2. 접속 해제
NewRequestReceived += new RequestHandler<ClientSession, OMKBinaryRequestInfo>(OnPacketReceived); // 3. 송신
}
// 네트워크 설정(Configuration) 초기화
public void InitConfig(OMKServerOption option)
{
ServerOption = option;
m_Config = new ServerConfig
{
Name = option.Name,
Ip = "Any",
Port = option.Port,
Mode = SocketMode.Tcp,
MaxConnectionNumber = option.MaxConnectionNumber,
MaxRequestLength = option.MaxRequestLength,
ReceiveBufferSize = option.ReceiveBufferSize,
SendBufferSize = option.SendBufferSize
};
}
// 네트워크 설정 및 서버 생성
public void CreateStartServer()
{
try
{
bool bResult = Setup(new RootConfig(), m_Config, logFactory: new NLogLogFactory());
if (bResult == false)
{
MainLogger.Error("[Error] 서버 네트워크 설정 실패");
return;
}
else
{
// Main Logger 설정
MainLogger = base.Logger;
MainLogger.Info("서버 초기화 성공");
}
CreateComponent();
// SuperSocket Start --> AsyncAccept
Start();
MainLogger.Info("서버 생성 성공");
}
catch (Exception e)
{
MainLogger.Error($"[Error] 서버 생성 실패 : {e.ToString()}");
}
}
public void StopServer()
{
// Super Socket Stop
Stop();
MainPacektProcessor.Destroy();
}
// 네트워크 요소 생성
public ERROR_CODE CreateComponent()
{
ClientSession.CreateIndexPool(m_Config.MaxConnectionNumber);
// Room의 NetSendFunc 델리게이트 함수 연결
// Q> 델리게이트 함수를 쓴 이유 -> 유지보수 상 MainServer를 instance를 할당하거나 static을 하지 않더라도 타 Class에서 사용 용이
Room.NetSendFunc = this.SendData;
RoomMgr.CreateRooms();
// 패킷 프로세서 인스턴스
MainPacektProcessor = new PacketProcessor();
MainPacektProcessor.CreateAndStart(RoomMgr.GetRoomsList(), this);
MainLogger.Info("CreateComponent - Success");
return ERROR_CODE.NONE;
}
public bool SendData(string sessionID, byte[] sendData)
{
var session = GetSessionByID(sessionID);
try
{
if (session == null)
{
return false;
}
session.Send(sendData, 0, sendData.Length);
}
catch (Exception e)
{
// TimeoutException 예외 발생할 수 있음
MainServer.MainLogger.Error($"{e.ToString()}, {e.StackTrace}");
session.SendEndWhenSendingTimeOut();
session.Close();
}
return true;
}
// Receive 받은 대로 Processor Thread 에서 처리
public void Distribute(ServerPacketData requestPacket)
{
MainPacektProcessor.InsertPacket(requestPacket);
}
// '접속'
void OnConnected(ClientSession session)
{
session.AllocSessionIndex();
MainLogger.Info(string.Format("세션 번호 {0} 접속", session.SessionID));
var packet = ServerPacketData.MakeNTFInConnectOrDisConnectClientPacket(true, session.SessionID, session.SessionIndex);
MainLogger.Info("접속 시 세션 번호 : " + session.SessionIndex);
Distribute(packet);
}
// '접속 끊기'
void OnClosed(ClientSession session, CloseReason reason)
{
MainLogger.Info(string.Format("세션 번호 {0} 접속 해제 : {1}", session.SessionID, reason.ToString()));
var packet =
ServerPacketData.MakeNTFInConnectOrDisConnectClientPacket(false, session.SessionID,
session.SessionIndex);
Distribute(packet);
session.FreeSessionIndex(session.SessionIndex);
}
// 'User Action'
void OnPacketReceived(ClientSession session, OMKBinaryRequestInfo reqInfo)
{
MainLogger.Debug(string.Format("세션 번호 {0} 받은 데이터 크기 : {1} ThreadID : {2}",
session.SessionID, reqInfo.Body.Length, Thread.CurrentThread.ManagedThreadId));
var packet = new ServerPacketData();
packet.SessionID = session.SessionID;
packet.SessionIndex = session.SessionIndex;
packet.PackSize = reqInfo.Size;
packet.PacketID = reqInfo.PacketID;
packet.Type = reqInfo.Type;
packet.BodyData = reqInfo.Body;
Distribute(packet);
}
}
} |
using Sparda.Contracts;
using System;
using System.Collections.Generic;
using System.Data.Services;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Sparda.ConnectionsStringProviderContext.DAL.V6.y2017_m8_d22_h12_m13_s54_ms774;
using Sparda.Core.Helpers;
namespace Sparda.Core.Services.Contexts
{
public class MainConnectionStringProviderContext : Sparda.ConnectionsStringProviderContext.DAL.V6.y2017_m8_d22_h12_m13_s54_ms774.ConnectionsStringProviderContext
{
public MainConnectionStringProviderContext()
: base("ConnectionStringProviderContext")
{
}
}
public class MainConnectionStringProviderService : Telerik.OpenAccess.DataServices.OpenAccessDataService<MainConnectionStringProviderContext>
{
[ChangeInterceptor("Connection")]
public void OnChangeInstance(Connection connection, UpdateOperations operations)
{
switch (operations)
{
case UpdateOperations.Add:
case UpdateOperations.Change:
var name = connection.Name.Replace(" ", "_");
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + "#";
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
name = r.Replace(name, "");
connection.Name = name;
EntityTrackingHelper.OnChangeInterceptor(connection, operations);
break;
case UpdateOperations.Delete:
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<Connection>(_service, operations);
}
[ChangeInterceptor("Provider")]
public void OnChangeProvider(Provider provider, UpdateOperations operations)
{
switch (operations)
{
case UpdateOperations.Add:
case UpdateOperations.Change:
EntityTrackingHelper.OnChangeInterceptor(provider, operations);
break;
case UpdateOperations.Delete:
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<Provider>(_service, operations);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using MediatR;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.Framework.OptionsModel;
using Microsoft.Net.Http.Headers;
using SciVacancies.Domain.DataModels;
using SciVacancies.Domain.Enums;
using SciVacancies.ReadModel.Core;
using SciVacancies.WebApp.Commands;
using SciVacancies.WebApp.Engine;
using SciVacancies.WebApp.Engine.CustomAttribute;
using SciVacancies.WebApp.Infrastructure.Identity;
using SciVacancies.WebApp.Queries;
using SciVacancies.WebApp.ViewModels;
using Microsoft.Framework.Logging;
namespace SciVacancies.WebApp.Controllers
{
[ResponseCache(NoStore = true)]
[Authorize]
public class ResearchersController : Controller
{
private readonly IMediator _mediator;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IOptions<AttachmentSettings> _attachmentSettings;
private readonly SciVacUserManager _userManager;
private readonly ILogger _logger;
public ResearchersController(IMediator mediator, IHostingEnvironment hostingEnvironment, IOptions<AttachmentSettings> attachmentSettings, SciVacUserManager userManager, ILoggerFactory loggerFactory)
{
_mediator = mediator;
_hostingEnvironment = hostingEnvironment;
_attachmentSettings = attachmentSettings;
_userManager = userManager;
_logger = loggerFactory.CreateLogger<ResearchersController>();
}
[ResponseCache(NoStore = true)]
[SiblingPage]
[Authorize]
[PageTitle("Информация")]
[BindResearcherIdFromClaims]
[NonActivatedUser]
public IActionResult Account(Guid researcherGuid)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
var preModel = _mediator.Send(new SingleResearcherQuery { ResearcherGuid = researcherGuid });
if (preModel == null)
return RedirectToAction("logout", "account");
var model = Mapper.Map<ResearcherDetailsViewModel>(preModel);
IEnumerable<Education> educations = _mediator.Send(new SelectResearcherEducationsQuery { ResearcherGuid = researcherGuid });
if (educations != null && educations.Count() > 0)
{
model.Educations = Mapper.Map<List<EducationEditViewModel>>(educations);
}
IEnumerable<Publication> publications = _mediator.Send(new SelectResearcherPublicationsQuery { ResearcherGuid = researcherGuid });
if (publications != null && publications.Count() > 0)
{
model.Publications = Mapper.Map<List<PublicationEditViewModel>>(publications);
}
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[ResponseCache(NoStore = true)]
[PageTitle("Изменить данные")]
[BindResearcherIdFromClaims]
public async Task<IActionResult> Edit(Guid researcherGuid)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
var preModel = _mediator.Send(new SingleResearcherQuery { ResearcherGuid = researcherGuid });
if (preModel == null)
return HttpNotFound(); //throw new ObjectNotFoundException();
var model = Mapper.Map<ResearcherEditViewModel>(preModel);
IEnumerable<Education> educations = _mediator.Send(new SelectResearcherEducationsQuery { ResearcherGuid = researcherGuid });
if (educations != null && educations.Count() > 0)
{
model.Educations = Mapper.Map<List<EducationEditViewModel>>(educations);
}
IEnumerable<Publication> publications = _mediator.Send(new SelectResearcherPublicationsQuery { ResearcherGuid = researcherGuid });
if (publications != null && publications.Count() > 0)
{
model.Publications = Mapper.Map<List<PublicationEditViewModel>>(publications);
}
model.Logins = await _userManager.GetLoginsAsync(User.Identity.GetUserId());
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[HttpPost]
[PageTitle("Редактирование информации пользователя")]
[BindResearcherIdFromClaims("authorizedUserGuid")]
public async Task<IActionResult> Edit(ResearcherEditViewModel model, Guid authorizedUserGuid)
{
if (model.Guid == Guid.Empty)
throw new ArgumentNullException(nameof(model), "Отсутствует идентификатор исследователя");
//повторно инициализируем свойство, чтобы не сохранять его на форме
model.Logins = await _userManager.GetLoginsAsync(User.Identity.GetUserId());
if (authorizedUserGuid != model.Guid)
return View("Error", "Вы не можете изменять чужой профиль");
if (ModelState.ErrorCount > 0)
return View(model);
var preModel = _mediator.Send(new SingleResearcherQuery { ResearcherGuid = authorizedUserGuid });
if (preModel == null)
return HttpNotFound(); //throw new ObjectNotFoundException();
var dataModel = Mapper.Map<ResearcherDataModel>(preModel);
var data = Mapper.Map(model, dataModel);//маппинг игнорирует Индивидуальный номер учёного
//отдельно обновляем для "своих" пользователей Инд.Номер учёного, и не обновляем для "чужих" пользователей
if (!model.IsScienceMapUser)
data.ExtNumber = model.ExtNumber;
_mediator.Send(new UpdateResearcherCommand
{
Data = data,
ResearcherGuid = authorizedUserGuid
});
//проверка изменения адреса электронной почты
var currentEmail = (await _userManager.GetEmailAsync(User.Identity.GetUserId()));
if (currentEmail != model.Email)
await _userManager.SetEmailAsync(User.Identity.GetUserId(), model.Email);
return RedirectToAction("account");
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[ResponseCache(NoStore = true)]
[PageTitle("Изменить данные")]
[BindResearcherIdFromClaims]
public IActionResult EditPhoto(Guid researcherGuid)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
var preModel = _mediator.Send(new SingleResearcherQuery { ResearcherGuid = researcherGuid });
if (preModel == null)
return HttpNotFound(); //throw new ObjectNotFoundException();
var model = Mapper.Map<ResearcherEditPhotoViewModel>(preModel);
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[HttpPost]
[PageTitle("Редактирование информации пользователя")]
[BindResearcherIdFromClaims("authorizedUserGuid")]
public IActionResult EditPhoto(ResearcherEditPhotoViewModel model, Guid authorizedUserGuid)
{
if (model.Guid == Guid.Empty)
throw new ArgumentNullException(nameof(model), "Отсутствует идентификатор исследователя");
if (authorizedUserGuid != model.Guid)
return View("Error", "Вы не можете изменять чужой профиль");
if (ModelState.ErrorCount > 0)
return View(model);
if (model.PhotoFile != null)
{
var file = model.PhotoFile;
var fileName = System.IO.Path.GetFileName(ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'));
var fileExtension = fileName
.Split('.')
.Last()
.ToUpper();
//todo: повторяющийся код
//проверяем размеры файлов
if (file.Length > _attachmentSettings.Value.Researcher.MaxItemSize)
ModelState.AddModelError("PhotoFile", $"Размер прикрепленного файла превышает допустимый размер ({_attachmentSettings.Value.Researcher.MaxItemSize / 1000}КБ).");
//проверяем расширения файлов
if (!string.IsNullOrWhiteSpace(_attachmentSettings.Value.Researcher.AllowExtensions) && !_attachmentSettings.Value.Researcher.AllowExtensions.ToUpper().Contains(fileExtension.ToUpper()))
ModelState.AddModelError("PhotoFile", $"Можно добавить только изображение. Допустимые типы файлов: {_attachmentSettings.Value.Researcher.AllowExtensions}");
if (ModelState.ErrorCount > 0)
return View(model);
if (file.Length > 0)
{
var newFileName = $"{authorizedUserGuid}.{fileExtension}";
var filePath =
$"{_hostingEnvironment.WebRootPath}{_attachmentSettings.Value.Researcher.PhisicalPathPart}/{newFileName}";
Directory.CreateDirectory(
$"{_hostingEnvironment.WebRootPath}{_attachmentSettings.Value.Researcher.PhisicalPathPart}/");
using (var image = Image.FromStream(file.OpenReadStream()))
{
Image newImage = null;
if (file.Length > _attachmentSettings.Value.Researcher.MaxItemSize)
{
var scale = ((float)_attachmentSettings.Value.Researcher.MaxItemSize / file.Length);
var newWidth = image.Width * scale;
var newHeight = image.Height * scale;
newImage = ScaleImage(image, (int)newWidth, (int)newHeight);
}
else
newImage = image;
//сценарий-А: сохранить фото на диск
newImage.Save(filePath);
model.ImageName = newFileName;
model.ImageSize = file.Length;
model.ImageExtension = fileExtension;
model.ImageUrl = $"/{newFileName}";
////TODO: сохранение фото в БД (сделать)
//using (var memoryStream = new MemoryStream())
//{
// //фотографии в byte
// byte[] byteData;
// //сценарий-Б: сохранить фото в БД
// ((Image)newImage).Save(memoryStream, ImageFormat.Jpeg);
// byteData = memoryStream.ToArray();
//}
newImage.Dispose();
}
var preModel = _mediator.Send(new SingleResearcherQuery { ResearcherGuid = authorizedUserGuid });
if (preModel == null)
return HttpNotFound(); //throw new ObjectNotFoundException();
var dataModel = Mapper.Map<ResearcherDataModel>(preModel);
var data = Mapper.Map(model, dataModel);
_mediator.Send(new UpdateResearcherCommand
{
Data = data,
ResearcherGuid = authorizedUserGuid
});
}
}
return RedirectToAction("account");
}
private Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var newImage = new Bitmap(maxWidth, maxHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, maxWidth, maxHeight);
return newImage;
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[SiblingPage]
[PageTitle("Мои заявки")]
[BindResearcherIdFromClaims]
[ValidatePagerParameters]
public ViewResult Applications(Guid researcherGuid, int pageSize = 10, int currentPage = 1,
string sortField = ConstTerms.OrderByFieldApplyDate, string sortDirection = ConstTerms.OrderByDescending)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
var source =
_mediator.Send(new SelectPagedVacancyApplicationsByResearcherQuery
{
PageSize = pageSize,
PageIndex = currentPage,
ResearcherGuid = researcherGuid,
OrderBy = new SortFilterHelper().GetSortField<VacancyApplication>(sortField),
OrderDirection = sortDirection
});
var model = new VacancyApplicationsInResearcherIndexViewModel();
if (source.TotalItems > 0)
{
model.Applications = source.MapToPagedList<VacancyApplication, VacancyApplicationDetailsViewModel>();
var innerObjects = _mediator.Send(new SelectPagedVacanciesByGuidsQuery
{
VacancyGuids = model.Applications.Items.Select(c => c.VacancyGuid).Distinct(),
PageSize = 1000,
PageIndex = 1,
OrderBy = ConstTerms.OrderByFieldDate
});
model.Applications.Items.ForEach(
c =>
c.Vacancy = Mapper.Map<VacancyDetailsViewModel>(innerObjects.Items.Single(d => d.guid == c.VacancyGuid)));
}
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[SiblingPage]
[PageTitle("Избранные вакансии")]
[BindResearcherIdFromClaims]
[ValidatePagerParameters]
public ActionResult Favorities(Guid researcherGuid, int pageSize = 10, int currentPage = 1, string sortField = ConstTerms.OrderByFieldPublishDate, string sortDirection = ConstTerms.OrderByDescending)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
var model = new VacanciesFavoritiesInResearcherIndexViewModel
{
Vacancies = _mediator.Send(new SelectPagedFavoriteVacanciesByResearcherQuery
{
PageSize = pageSize,
PageIndex = currentPage,
ResearcherGuid = researcherGuid,
OrderBy = new SortFilterHelper().GetSortField<Vacancy>(sortField),
OrderDirection = sortDirection
}).MapToPagedList(),
AppliedApplications = _mediator.Send(new SelectVacancyApplicationsByResearcherQuery { ResearcherGuid = researcherGuid }).Where(c => c.status != VacancyApplicationStatus.InProcess && c.status != VacancyApplicationStatus.Removed).ToList()
};
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[SiblingPage]
[PageTitle("Подписки")]
[BindResearcherIdFromClaims]
[ValidatePagerParameters]
public ViewResult Subscriptions(Guid researcherGuid, int pageSize = 10, int currentPage = 1)
{
var model = new SearchSubscriptionsInResearcherIndexViewModel
{
PagedItems = _mediator.Send(new SelectPagedSearchSubscriptionsQuery
{
ResearcherGuid = researcherGuid,
PageSize = pageSize,
PageIndex = currentPage
}).MapToPagedList()
};
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[SiblingPage]
[PageTitle("Уведомления")]
[BindResearcherIdFromClaims]
[ValidatePagerParameters]
public ViewResult Notifications(Guid researcherGuid, int pageSize = 10, int currentPage = 1,
string sortField = ConstTerms.OrderByFieldCreationDate, string sortDirection = ConstTerms.OrderByDescending)
{
var model = new NotificationsInResearcherIndexViewModel
{
PagedItems = _mediator.Send(new SelectPagedResearcherNotificationsQuery
{
ResearcherGuid = researcherGuid,
PageSize = pageSize,
PageIndex = currentPage,
OrderBy = new SortFilterHelper().GetSortField<ResearcherNotification>(sortField),
OrderDirection = sortDirection
}).MapToPagedList()
};
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[BindResearcherIdFromClaims]
public ActionResult AddToFavorite(Guid researcherGuid, Guid vacancyGuid)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
if (vacancyGuid == Guid.Empty)
throw new ArgumentNullException(nameof(vacancyGuid));
var model = _mediator.Send(new SingleVacancyQuery { VacancyGuid = vacancyGuid });
//если заявка на готовится к открытию или открыта
if (model.status == VacancyStatus.Published)
{
var favoritesVacancies = _mediator.Send(new SelectFavoriteVacancyGuidsByResearcherQuery
{
ResearcherGuid = researcherGuid
}).ToList();
//если текущей вакансии нет в списке избранных
if (!favoritesVacancies.Contains(vacancyGuid))
_mediator.Send(new AddVacancyToFavoritesCommand { ResearcherGuid = researcherGuid, VacancyGuid = vacancyGuid });
}
return Redirect(HttpContext.Request.Headers["referer"]);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[BindResearcherIdFromClaims]
[PageTitle("Избранная вакансия")]
public IActionResult RemoveFavorite(Guid vacancyGuid, Guid researcherGuid)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
if (vacancyGuid == Guid.Empty)
throw new ArgumentNullException(nameof(vacancyGuid));
var favoritesVacancies = _mediator.Send(new SelectFavoriteVacancyGuidsByResearcherQuery
{
ResearcherGuid = researcherGuid
}).ToList();
if (!favoritesVacancies.Any())
return RedirectToVacancyCardAction(vacancyGuid);
if (favoritesVacancies.All(c => c != vacancyGuid))
return RedirectToVacancyCardAction(vacancyGuid);
var preModel = _mediator.Send(new SingleVacancyQuery { VacancyGuid = vacancyGuid });
var model = Mapper.Map<VacancyDetailsViewModel>(preModel);
return View(model);
}
[Authorize(Roles = ConstTerms.RequireRoleResearcher)]
[HttpPost]
[BindResearcherIdFromClaims]
[PageTitle("Избранная вакансия")]
public IActionResult RemoveFavoritePost(Guid vacancyGuid, Guid researcherGuid)
{
if (researcherGuid == Guid.Empty)
throw new ArgumentNullException(nameof(researcherGuid));
if (vacancyGuid == Guid.Empty)
throw new ArgumentNullException(nameof(vacancyGuid));
var favoritesVacancies = _mediator.Send(new SelectFavoriteVacancyGuidsByResearcherQuery
{
ResearcherGuid = researcherGuid
}).ToList();
if (!favoritesVacancies.Any())
return RedirectToVacancyCardAction(vacancyGuid);
if (favoritesVacancies.All(c => c != vacancyGuid))
return RedirectToVacancyCardAction(vacancyGuid);
if (!ModelState.IsValid)
{
var preModel = _mediator.Send(new SingleVacancyQuery { VacancyGuid = vacancyGuid });
var model = Mapper.Map<VacancyDetailsViewModel>(preModel);
return View("RemoveFavorite", model);
}
_mediator.Send(new RemoveVacancyFromFavoritesCommand { ResearcherGuid = researcherGuid, VacancyGuid = vacancyGuid });
return RedirectToVacancyCardAction(vacancyGuid);
}
private IActionResult RedirectToVacancyCardAction(Guid vacancyGuid)
{
return RedirectToAction("card", "vacancies", new { id = vacancyGuid });
}
}
} |
using System;
using UnityEngine;
using UnityAtoms.MonoHooks;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// IPair of type `<Collision2DGameObject>`. Inherits from `IPair<Collision2DGameObject>`.
/// </summary>
[Serializable]
public struct Collision2DGameObjectPair : IPair<Collision2DGameObject>
{
public Collision2DGameObject Item1 { get => _item1; set => _item1 = value; }
public Collision2DGameObject Item2 { get => _item2; set => _item2 = value; }
[SerializeField]
private Collision2DGameObject _item1;
[SerializeField]
private Collision2DGameObject _item2;
public void Deconstruct(out Collision2DGameObject item1, out Collision2DGameObject item2) { item1 = Item1; item2 = Item2; }
}
} |
using System.Collections.Generic;
using System.Linq;
using ODL.ApplicationServices.DTOModel;
using ODL.ApplicationServices.DTOModel.Load;
using ODL.ApplicationServices.Validation;
namespace ODL.ApplicationServices.Test
{
using NUnit.Framework;
[TestFixture]
public class PersonInputValidatorTests
{
[Test]
public void TestValidate()
{
var person = new PersonInputDTO
{
SystemId = "123456",
Personnummer = "19701230-3456",
Fornamn = "Anders",
Mellannamn = "",
Efternamn = "",
UppdateradDatum = null,
UppdateradAv = null,
SkapadDatum = null,
SkapadAv = ""
};
var validator = new PersonInputValidator();
var brokenRules = validator.Validate(person);
Assert.That(brokenRules.Count, Is.EqualTo(4));
Assert.That(brokenRules.Any(ve => ve.Message.Equals("Fältet 'PersonInputDTO.Efternamn' saknar värde. (Id: 123456)")));
Assert.That(brokenRules.Any(ve => ve.Message.Equals("Fältet 'PersonInputDTO.Personnummer' får innehålla max 12 tecken. (Id: 123456)")));
Assert.That(brokenRules.Any(ve => ve.Message.Equals("Fältet 'PersonInputDTO.SkapadAv' saknar värde. (Id: 123456)")));
Assert.That(brokenRules.Any(ve => ve.Message.Equals("Fältet 'PersonInputDTO.SkapadDatum' saknar värde. (Id: 123456)")));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RimWorld;
using Verse;
using UnityEngine;
namespace DontShaveYourHead
{
[DefOf]
public static class HairDefOf
{
public static HairDef Shaved;
}
}
|
using System;
using System.Text;
using System.Threading;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
namespace Server_CS
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
var onlineCheckerThread = new Thread(OnlineCheckerCycle) {Name = "OnlineCheckerThread"};
onlineCheckerThread.Start();
var saverThread = new Thread(SaverCycle) {Name = "SaverThread"};
saverThread.Start();
}
public IConfiguration Configuration { get; }
/// <summary>
/// Проверка пользователей в сети
/// </summary>
public static void SaverCycle()
{
while (true)
{
JsonWorker.Save(Program.Messages);
JsonWorker.Save(Program.RegDatas);
Thread.Sleep(10000);
}
}
/// <summary>
/// Проверка пользователей в сети
/// </summary>
public static void OnlineCheckerCycle()
{
while (true)
{
foreach (var user in Program.OnlineUsersTimeout)
if (user.Value.AddSeconds(5) < DateTime.Now)
{
Program.OnlineUsers.Remove(user.Key);
Program.Messages.Add(new Message
{
Name = "",
Text = $"{user.Key} left",
Ts = (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds
});
Program.OnlineUsersTimeout.Remove(user.Key);
}
Thread.Sleep(100);
}
}
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
services.AddControllers();
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
} |
namespace TRPO_labe_1.Model
{
public static class FileSettings
{
public static string FilePath { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using TransferData.Business.Dto;
namespace TransferData.Business.Dto
{
[DataContract]
public class CarDamageLevel
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarDamagePart
{
[DataMember(Name = "car_type")]
public string CarType { get; set; }
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarInsurerDamage
{
[DataMember(Name = "car_damage_id")]
public int CarDamageId { get; set; }
[DataMember(Name = "car_damage_level")]
public CarDamageLevel CarDamageLevel { get; set; }
[DataMember(Name = "car_damage_part")]
public CarDamagePart CarDamagePart { get; set; }
[DataMember(Name = "car_damage_part_text")]
public string CarDamagePartText { get; set; }
}
[DataContract]
public class CarDriverLicenseCardType
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class Aumphur
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class District
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class Province
{
[DataMember(Name = "geo_id")]
public int GeoId { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "is_address")]
public bool IsAddress { get; set; }
[DataMember(Name = "is_car_regis")]
public bool IsCarRegis { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class LocationPlace
{
[DataMember(Name = "aumphur")]
public Aumphur Aumphur { get; set; }
[DataMember(Name = "district")]
public District District { get; set; }
[DataMember(Name = "latitude")]
public string Latitude { get; set; }
[DataMember(Name = "longitude")]
public string Longitude { get; set; }
[DataMember(Name = "place")]
public string Place { get; set; }
[DataMember(Name = "province")]
public Province Province { get; set; }
}
[DataContract]
public class Title
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class PersonInfo
{
[DataMember(Name = "first_name")]
public string FirstName { get; set; }
[DataMember(Name = "last_name")]
public string LastName { get; set; }
[DataMember(Name = "title")]
public Title Title { get; set; }
}
[DataContract]
public class CarDriverRelationship
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarInsurerDriver
{
[DataMember(Name = "car_driver_address")]
public string CarDriverAddress { get; set; }
[DataMember(Name = "car_driver_age")]
public int? CarDriverAge { get; set; }
[DataMember(Name = "car_driver_birthday")]
public string CarDriverBirthday { get; set; }
[DataMember(Name = "car_driver_gender")]
public string CarDriverGender { get; set; }
[DataMember(Name = "car_driver_idcard")]
public string CarDriverIdcard { get; set; }
[DataMember(Name = "car_driver_license_card")]
public string CarDriverLicenseCard { get; set; }
[DataMember(Name = "car_driver_license_card_expire_date")]
public string CarDriverLicenseCardExpireDate { get; set; }
[DataMember(Name = "car_driver_license_card_issued_date")]
public string CarDriverLicenseCardIssuedDate { get; set; }
[DataMember(Name = "car_driver_license_card_type")]
public CarDriverLicenseCardType CarDriverLicenseCardType { get; set; }
[DataMember(Name = "car_driver_location")]
public LocationPlace CarDriverLocation { get; set; }
[DataMember(Name = "car_driver_name")]
public string CarDriverName { get; set; }
[DataMember(Name = "car_driver_name_info")]
public PersonInfo CarDriverNameInfo { get; set; }
[DataMember(Name = "car_driver_relation")]
public string CarDriverRelation { get; set; }
[DataMember(Name = "car_driver_relationship")]
public CarDriverRelationship CarDriverRelationship { get; set; }
[DataMember(Name = "car_driver_tel")]
public string CarDriverTel { get; set; }
}
[DataContract]
public class CarBrand
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarCapacity
{
[DataMember(Name = "code")]
public string Code { get; set; }
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarColor
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarModel
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class PolicyInsurer
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name_en")]
public string NameEn { get; set; }
[DataMember(Name = "name_th")]
public string NameTh { get; set; }
}
[DataContract]
public class CarRegisProvince
{
[DataMember(Name = "geo_id")]
public int GeoId { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarType
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class CarInsurerInfo
{
[DataMember(Name = "car_brand")]
public CarBrand CarBrand { get; set; }
[DataMember(Name = "car_capacity")]
public CarCapacity CarCapacity { get; set; }
[DataMember(Name = "car_chassis")]
public string CarChassis { get; set; }
[DataMember(Name = "car_color")]
public CarColor CarColor { get; set; }
[DataMember(Name = "car_engine")]
public string CarEngine { get; set; }
[DataMember(Name = "car_model")]
public CarModel CarModel { get; set; }
[DataMember(Name = "car_policy_enddate")]
public string CarPolicyEnddate { get; set; }
[DataMember(Name = "car_policy_insurer")]
public PolicyInsurer CarPolicyInsurer { get; set; }
[DataMember(Name = "car_policy_no")]
public string CarPolicyNo { get; set; }
[DataMember(Name = "car_policy_owner")]
public string CarPolicyOwner { get; set; }
[DataMember(Name = "car_policy_startdate")]
public string CarPolicyStartdate { get; set; }
[DataMember(Name = "car_policy_type")]
public string CarPolicyType { get; set; }
[DataMember(Name = "car_regis")]
public string CarRegis { get; set; }
[DataMember(Name = "car_regis_province")]
public CarRegisProvince CarRegisProvince { get; set; }
[DataMember(Name = "car_type")]
public CarType CarType { get; set; }
[DataMember(Name = "policy_driver1")]
public string PolicyDriver1 { get; set; }
[DataMember(Name = "policy_driver2")]
public string PolicyDriver2 { get; set; }
}
[DataContract]
public class CarInsurer
{
[DataMember(Name = "car_insurer_damages")]
public IList<CarInsurerDamage> CarInsurerDamages { get; set; }
[DataMember(Name = "car_insurer_driver")]
public CarInsurerDriver CarInsurerDriver { get; set; }
[DataMember(Name = "car_insurer_info")]
public CarInsurerInfo CarInsurerInfo { get; set; }
[DataMember(Name = "summary_damage_insurer_car")]
public int? SummaryDamageInsurerCar { get; set; }
[DataMember(Name = "task_id")]
public string TaskId { get; set; }
}
[DataContract]
public class CarPartyDamage
{
[DataMember(Name = "car_damage_id")]
public int CarDamageId { get; set; }
[DataMember(Name = "car_damage_level")]
public CarDamageLevel CarDamageLevel { get; set; }
[DataMember(Name = "car_damage_part")]
public CarDamagePart CarDamagePart { get; set; }
[DataMember(Name = "car_damage_part_text")]
public string CarDamagePartText { get; set; }
}
[DataContract]
public class CarPartyDriver
{
[DataMember(Name = "car_driver_address")]
public string CarDriverAddress { get; set; }
[DataMember(Name = "car_driver_age")]
public int? CarDriverAge { get; set; }
[DataMember(Name = "car_driver_birthday")]
public string CarDriverBirthday { get; set; }
[DataMember(Name = "car_driver_gender")]
public string CarDriverGender { get; set; }
[DataMember(Name = "car_driver_idcard")]
public string CarDriverIdcard { get; set; }
[DataMember(Name = "car_driver_license_card")]
public string CarDriverLicenseCard { get; set; }
[DataMember(Name = "car_driver_license_card_expire_date")]
public string CarDriverLicenseCardExpireDate { get; set; }
[DataMember(Name = "car_driver_license_card_issued_date")]
public string CarDriverLicenseCardIssuedDate { get; set; }
[DataMember(Name = "car_driver_license_card_type")]
public CarDriverLicenseCardType CarDriverLicenseCardType { get; set; }
[DataMember(Name = "car_driver_location")]
public LocationPlace CarDriverLocation { get; set; }
[DataMember(Name = "car_driver_name")]
public string CarDriverName { get; set; }
[DataMember(Name = "car_driver_name_info")]
public PersonInfo CarDriverNameInfo { get; set; }
[DataMember(Name = "car_driver_relation")]
public string CarDriverRelation { get; set; }
[DataMember(Name = "car_driver_relationship")]
public CarDriverRelationship CarDriverRelationship { get; set; }
[DataMember(Name = "car_driver_tel")]
public string CarDriverTel { get; set; }
}
[DataContract]
public class CarPartyInfo
{
[DataMember(Name = "car_brand")]
public CarBrand CarBrand { get; set; }
[DataMember(Name = "car_capacity")]
public CarCapacity CarCapacity { get; set; }
[DataMember(Name = "car_chassis")]
public string CarChassis { get; set; }
[DataMember(Name = "car_color")]
public CarColor CarColor { get; set; }
[DataMember(Name = "car_engine")]
public string CarEngine { get; set; }
[DataMember(Name = "car_model")]
public CarModel CarModel { get; set; }
[DataMember(Name = "car_policy_enddate")]
public string CarPolicyEnddate { get; set; }
[DataMember(Name = "car_policy_insurer")]
public PolicyInsurer CarPolicyInsurer { get; set; }
[DataMember(Name = "car_policy_no")]
public string CarPolicyNo { get; set; }
[DataMember(Name = "car_policy_owner")]
public string CarPolicyOwner { get; set; }
[DataMember(Name = "car_policy_startdate")]
public string CarPolicyStartdate { get; set; }
[DataMember(Name = "car_policy_type")]
public string CarPolicyType { get; set; }
[DataMember(Name = "car_regis")]
public string CarRegis { get; set; }
[DataMember(Name = "car_regis_province")]
public Province CarRegisProvince { get; set; }
[DataMember(Name = "car_type")]
public CarType CarType { get; set; }
[DataMember(Name = "policy_driver1")]
public string PolicyDriver1 { get; set; }
[DataMember(Name = "policy_driver2")]
public string PolicyDriver2 { get; set; }
}
[DataContract]
public class CarParty
{
[DataMember(Name = "car_party_damages")]
public IList<CarPartyDamage> CarPartyDamages { get; set; }
[DataMember(Name = "car_party_driver")]
public CarPartyDriver CarPartyDriver { get; set; }
[DataMember(Name = "car_party_id")]
public string CarPartyId { get; set; }
[DataMember(Name = "car_party_info")]
public CarPartyInfo CarPartyInfo { get; set; }
[DataMember(Name = "summary_damage_car")]
public int? SummaryDamageCar { get; set; }
[DataMember(Name = "task_id")]
public string TaskId { get; set; }
}
[DataContract]
public class PropertyDamage
{
[DataMember(Name = "property_damage_amount")]
public int PropertyDamageAmount { get; set; }
[DataMember(Name = "property_damage_description")]
public string PropertyDamageDescription { get; set; }
[DataMember(Name = "property_damage_id")]
public string PropertyDamageId { get; set; }
[DataMember(Name = "property_damage_name")]
public string PropertyDamageName { get; set; }
[DataMember(Name = "property_damage_owner_address")]
public string PropertyDamageOwnerAddress { get; set; }
[DataMember(Name = "property_damage_owner_location_place")]
public LocationPlace PropertyDamageOwnerLocationPlace { get; set; }
[DataMember(Name = "property_damage_owner_name")]
public string PropertyDamageOwnerName { get; set; }
[DataMember(Name = "property_damage_owner_name_info")]
public PersonInfo PropertyDamageOwnerNameInfo { get; set; }
[DataMember(Name = "property_damage_owner_tel")]
public string PropertyDamageOwnerTel { get; set; }
[DataMember(Name = "property_damage_type")]
public WoundedType PropertyDamageType { get; set; }
[DataMember(Name = "task_id")]
public string TaskId { get; set; }
}
[DataContract]
public class AccidentType
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class WoundedType
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
[DataMember(Name = "type_use")]
public int TypeUse { get; set; }
}
[DataContract]
public class Wounded
{
[DataMember(Name = "task_id")]
public string TaskId { get; set; }
[DataMember(Name = "wounded_accident_amount")]
public int WoundedAccidentAmount { get; set; }
[DataMember(Name = "wounded_accident_type")]
public AccidentType WoundedAccidentType { get; set; }
[DataMember(Name = "wounded_address")]
public string WoundedAddress { get; set; }
[DataMember(Name = "wounded_age")]
public string WoundedAge { get; set; }
[DataMember(Name = "wounded_description")]
public string WoundedDescription { get; set; }
[DataMember(Name = "wounded_gender")]
public string WoundedGender { get; set; }
[DataMember(Name = "wounded_hospital_name")]
public string WoundedHospitalName { get; set; }
[DataMember(Name = "wounded_id")]
public string WoundedId { get; set; }
[DataMember(Name = "wounded_id_card")]
public string WoundedIdCard { get; set; }
[DataMember(Name = "wounded_location_place")]
public LocationPlace WoundedLocationPlace { get; set; }
[DataMember(Name = "wounded_name")]
public string WoundedName { get; set; }
[DataMember(Name = "wounded_name_info")]
public PersonInfo WoundedNameInfo { get; set; }
[DataMember(Name = "wounded_tel")]
public string WoundedTel { get; set; }
[DataMember(Name = "wounded_type")]
public WoundedType WoundedType { get; set; }
}
[DataContract]
public class TaskFullReportDetail
{
[DataMember(Name = "accident_date")]
public string AccidentDate { get; set; }
[DataMember(Name = "accident_place")]
public string AccidentPlace { get; set; }
[DataMember(Name = "accident_time")]
public string AccidentTime { get; set; }
[DataMember(Name = "car_parties")]
public IList<CarParty> CarParties { get; set; }
[DataMember(Name = "claim_request")]
public string ClaimRequest { get; set; }
[DataMember(Name = "property_damages")]
public IList<PropertyDamage> PropertyDamages { get; set; }
[DataMember(Name = "summary_of_case_accident_detail")]
public string SummaryOfCaseAccidentDetail { get; set; }
[DataMember(Name = "summary_of_case_accident_result_detail")]
public string SummaryOfCaseAccidentResultDetail { get; set; }
[DataMember(Name = "summary_of_case_accident_type_name")]
public string SummaryOfCaseAccidentTypeName { get; set; }
[DataMember(Name = "woundeds")]
public IList<Wounded> Woundeds { get; set; }
}
[DataContract]
public class Claim
{
[DataMember(Name = "claim_accident_date")]
public string ClaimAccidentDate { get; set; }
[DataMember(Name = "claim_request")]
public double? ClaimRequest { get; set; }
[DataMember(Name = "damage_insurer_car")]
public double? DamageInsurerCar { get; set; }
[DataMember(Name = "damage_thirdparty_car")]
public double? DamageThirdpartyCar { get; set; }
[DataMember(Name = "deceased_total")]
public int? DeceasedTotal { get; set; }
[DataMember(Name = "deduct")]
public double? Deduct { get; set; }
[DataMember(Name = "excess")]
public double? Excess { get; set; }
[DataMember(Name = "is_deceased")]
public bool? IsDeceased { get; set; }
[DataMember(Name = "is_same_inform")]
public bool? IsSameInform { get; set; }
[DataMember(Name = "is_wounded")]
public bool? IsWounded { get; set; }
[DataMember(Name = "na_note")]
public string NaNote { get; set; }
[DataMember(Name = "not_inform_detail")]
public string NotInformDetail { get; set; }
[DataMember(Name = "results_case_id")]
public string ResultsCaseId { get; set; }
[DataMember(Name = "task_full_report_detail")]
public TaskFullReportDetail TaskFullReportDetail { get; set; }
[DataMember(Name = "wounded_total")]
public int? WoundedTotal { get; set; }
}
[DataContract]
public class PropertyDamageOwnerLocationPlace
{
[DataMember(Name = "aumphur")]
public Aumphur Aumphur { get; set; }
[DataMember(Name = "district")]
public District District { get; set; }
[DataMember(Name = "latitude")]
public string Latitude { get; set; }
[DataMember(Name = "longitude")]
public string Longitude { get; set; }
[DataMember(Name = "place")]
public string Place { get; set; }
[DataMember(Name = "province")]
public Province Province { get; set; }
}
[DataContract]
public class PropertyDamageType
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "is_active")]
public bool IsActive { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
[DataMember(Name = "type_use")]
public int TypeUse { get; set; }
}
[DataContract]
public class SummaryOfCase
{
[DataMember(Name = "accident_date")]
public string AccidentDate { get; set; }
[DataMember(Name = "accident_date_text")]
public string AccidentDateText { get; set; }
[DataMember(Name = "accident_detail")]
public string AccidentDetail { get; set; }
[DataMember(Name = "accident_location")]
public LocationPlace AccidentLocation { get; set; }
[DataMember(Name = "accident_result_detail")]
public string AccidentResultDetail { get; set; }
[DataMember(Name = "accident_time_text")]
public string AccidentTimeText { get; set; }
[DataMember(Name = "accident_type")]
public AccidentType AccidentType { get; set; }
[DataMember(Name = "contact_card")]
public bool? ContactCard { get; set; }
[DataMember(Name = "copy_dialy")]
public bool? CopyDialy { get; set; }
[DataMember(Name = "document_confess")]
public bool? DocumentConfess { get; set; }
[DataMember(Name = "evidence_party")]
public bool? EvidenceParty { get; set; }
[DataMember(Name = "is_car_act")]
public bool? IsCarAct { get; set; }
[DataMember(Name = "receive_recovery_amount")]
public int? ReceiveRecoveryAmount { get; set; }
[DataMember(Name = "recovery_amount")]
public int? RecoveryAmount { get; set; }
[DataMember(Name = "result_case_id")]
public string ResultCaseId { get; set; }
[DataMember(Name = "schedule_place")]
public string SchedulePlace { get; set; }
[DataMember(Name = "task_id")]
public string TaskId { get; set; }
}
[DataContract]
public class TaskAction
{
[DataMember(Name = "sort")]
public int Sort { get; set; }
[DataMember(Name = "task_action_id")]
public int TaskActionId { get; set; }
[DataMember(Name = "task_action_name")]
public string TaskActionName { get; set; }
}
[DataContract]
public class TaskProcess
{
[DataMember(Name = "task_process_id")]
public string TaskProcessId { get; set; }
[DataMember(Name = "task_process_name")]
public string TaskProcessName { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class TaskType
{
[DataMember(Name = "task_type_id")]
public string TaskTypeId { get; set; }
[DataMember(Name = "task_type_name")]
public string TaskTypeName { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class TaskBikeResult
{
[DataMember(Name = "car_act_no")]
public string CarActNo { get; set; }
[DataMember(Name = "car_brand")]
public CarBrand CarBrand { get; set; }
[DataMember(Name = "car_model")]
public CarModel CarModel { get; set; }
[DataMember(Name = "car_regis")]
public string CarRegis { get; set; }
[DataMember(Name = "car_regis_province")]
public Province CarRegisProvince { get; set; }
[DataMember(Name = "car_year")]
public string CarYear { get; set; }
[DataMember(Name = "claim_accident_detail")]
public string ClaimAccidentDetail { get; set; }
[DataMember(Name = "create_date")]
public string CreateDate { get; set; }
[DataMember(Name = "create_datetime")]
public DateTime? CreateDatetime { get; set; }
[DataMember(Name = "distance")]
public string Distance { get; set; }
[DataMember(Name = "informer_name")]
public string InformerName { get; set; }
[DataMember(Name = "informer_tel")]
public string InformerTel { get; set; }
[DataMember(Name = "informer_tel2")]
public string InformerTel2 { get; set; }
[DataMember(Name = "informer_tel3")]
public string InformerTel3 { get; set; }
[DataMember(Name = "is_assigned")]
public bool IsAssigned { get; set; }
[DataMember(Name = "is_car_act")]
public bool IsCarAct { get; set; }
[DataMember(Name = "policy_claim_no")]
public string PolicyClaimNo { get; set; }
[DataMember(Name = "policy_driver1")]
public string PolicyDriver1 { get; set; }
[DataMember(Name = "policy_driver2")]
public string PolicyDriver2 { get; set; }
[DataMember(Name = "policy_enddate")]
public string PolicyEnddate { get; set; }
[DataMember(Name = "policy_insurer")]
public PolicyInsurer PolicyInsurer { get; set; }
[DataMember(Name = "policy_no")]
public string PolicyNo { get; set; }
[DataMember(Name = "policy_owner")]
public string PolicyOwner { get; set; }
[DataMember(Name = "policy_type")]
public string PolicyType { get; set; }
[DataMember(Name = "schedule_amphur_name")]
public string ScheduleAmphurName { get; set; }
[DataMember(Name = "schedule_date")]
public string ScheduleDate { get; set; }
[DataMember(Name = "schedule_date_text")]
public string ScheduleDateText { get; set; }
[DataMember(Name = "schedule_datetime")]
public DateTime? ScheduleDatetime { get; set; }
[DataMember(Name = "schedule_latitude")]
public string ScheduleLatitude { get; set; }
[DataMember(Name = "schedule_longitude")]
public string ScheduleLongitude { get; set; }
[DataMember(Name = "schedule_place")]
public string SchedulePlace { get; set; }
[DataMember(Name = "schedule_province_name")]
public string ScheduleProvinceName { get; set; }
[DataMember(Name = "schedule_time_text")]
public string ScheduleTimeText { get; set; }
[DataMember(Name = "task_id")]
public string TaskId { get; set; }
[DataMember(Name = "task_process")]
public TaskProcess TaskProcess { get; set; }
[DataMember(Name = "task_type")]
public TaskType TaskType { get; set; }
[DataMember(Name = "update_date")]
public string UpdateDate { get; set; }
[DataMember(Name = "update_date_text")]
public string UpdateDateText { get; set; }
[DataMember(Name = "update_time_text")]
public string UpdateTimeText { get; set; }
[DataMember(Name = "car_insurer")]
public CarInsurer CarInsurer { get; set; }
[DataMember(Name = "car_parties")]
public IList<CarParty> CarParties { get; set; }
[DataMember(Name = "claim")]
public Claim Claim { get; set; }
[DataMember(Name = "property_damages")]
public IList<PropertyDamage> PropertyDamages { get; set; }
[DataMember(Name = "summary_of_case")]
public SummaryOfCase SummaryOfCase { get; set; }
[DataMember(Name = "task_action")]
public TaskAction TaskAction { get; set; }
[DataMember(Name = "task_picture_list")]
public IList<TaskPicture> TaskPictureList { get; set; }
[DataMember(Name = "woundeds")]
public IList<Wounded> Woundeds { get; set; }
[DataMember(Name = "surveyor_charges")]
public IList<APISurveyorCharge> SurveyorCharges { get; set; }
[DataMember(Name = "seic_task_ref")]
public string SEICTaskRef { get; set; }
[DataMember(Name = "claim_distance_value")]
public double ClaimDistanceValue { get; set; }
}
[DataContract]
public class APIPictureType
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sort")]
public int Sort { get; set; }
}
[DataContract]
public class TaskPicture
{
[DataMember(Name = "picture_id")]
public long PictureId { get; set; }
[DataMember(Name = "picture_parent_id")]
public long? PictureParentId { get; set; }
[DataMember(Name = "picture_type")]
public APIPictureType PictureType { get; set; }
[DataMember(Name = "picture_path")]
public string PicturePath { get; set; }
[DataMember(Name = "picture_desc")]
public string PictureDesc { get; set; }
[DataMember(Name = "picture_is_approved")]
public bool? PictureApprove { get; set; }
[DataMember(Name = "picture_reject_comment")]
public string PictureNotApprove { get; set; }
[DataMember(Name = "latitude")]
public string Latitude { get; set; }
[DataMember(Name = "longitude")]
public string Longitude { get; set; }
[DataMember(Name = "sequence")]
public int Sequence { get; set; }
[DataMember(Name = "picture_name")]
public string PictureName { get; set; }
[DataMember(Name = "damage_level_code")]
public string DamageLevelCode { get; set; }
[DataMember(Name = "picture_token")]
public string PictureToken { get; set; }
}
[DataContract]
public class TaskBikeDto
{
[DataMember(Name = "message_body")]
public string MessageBody { get; set; }
[DataMember(Name = "message_title")]
public string MessageTitle { get; set; }
[DataMember(Name = "result")]
public TaskBikeResult Result { get; set; }
[DataMember(Name = "status_code")]
public string StatusCode { get; set; }
[DataMember(Name = "system_error_message")]
public string SystemErrorMessage { get; set; }
}
[DataContract]
public class BaseResult<T>
{
[DataMember(Name = "message_body")]
public string MessageBody { get; set; }
[DataMember(Name = "message_title")]
public string MessageTitle { get; set; }
[DataMember(Name = "result")]
public T Result { get; set; }
[DataMember(Name = "status_code")]
public string StatusCode { get; set; }
[DataMember(Name = "system_error_message")]
public string SystemErrorMessage { get; set; }
}
public class GetTasksForTransferDataToThirdPartyResult
{
[DataMember(Name = "tasks")]
public IList<string> Tasks { get; set; }
}
}
|
using System.Collections.Generic;
using iSukces.Code.AutoCode;
using Xunit;
namespace iSukces.Code.Tests
{
public class ClassCreationTests
{
[Fact]
public void T01_Should_create_class()
{
var c = new CsFile();
var type = TypeProvider.FromType(typeof(ParentGeneric<>.Nested));
var cache = new Dictionary<TypeProvider, CsClass>();
c.GetOrCreateClass(type);
var code = c.GetCode();
Assert.Equal(@"// ReSharper disable All
namespace iSukces.Code.Tests
{
partial class ParentGeneric<T>
{
partial class Nested
{
}
}
}
", code, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
[Fact]
public void T02_Should_add_comment()
{
var c = new CsFile();
var type = TypeProvider.FromType(typeof(ParentGeneric<>.Nested));
var cache = new Dictionary<TypeProvider, CsClass>();
var myClass = c.GetOrCreateClass(type);
myClass.AddComment("Line");
{
var p = myClass.AddProperty("Count", "int");
p.AddComment("line1");
p.AddComment("line2");
}
var code = c.GetCode();
Assert.Equal(@"// ReSharper disable All
namespace iSukces.Code.Tests
{
partial class ParentGeneric<T>
{
// Line
partial class Nested
{
/*
line1
line2
*/
public int Count { get; set; }
}
}
}
", code, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
}
}
internal class ParentGeneric<T>
{
public class Nested
{
}
}
} |
using System;
namespace KemengSoft.UTILS.RemoteDebug
{
public class TrustedConnection
{
/// <summary>
/// 信任的IP
/// </summary>
public string Ip { get; set; }
/// <summary>
/// 信任的Id
/// </summary>
public string Id { get; set; }
/// <summary>
/// 信任的时间
/// </summary>
public DateTime TrustTime { get; set; }
}
}
|
// Generated by Xamasoft JSON Class Generator
// http://www.xamasoft.com/json-class-generator
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Entrata.Model.Requests
{
public class Auth
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
}
public class Params
{
[JsonProperty("propertyId")]
public string PropertyId { get; set; }
}
public class Method
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("params")]
public Params Params { get; set; }
}
public class EntrataRequest
{
[JsonProperty("auth")]
public Auth Auth { get; set; }
[JsonProperty("requestId")]
public int RequestId { get; set; }
[JsonProperty("method")]
public Method Method { get; set; }
}
}
|
namespace TripDestination.Services.Data
{
using System;
using Contracts;
using System.Linq;
using TripDestination.Data.Common;
using TripDestination.Data.Models;
public class TripCommentServices : ITripCommentServices
{
private IDbRepository<TripComment> trimpCommentRepositories;
public TripCommentServices(IDbRepository<TripComment> trimpCommentRepositories)
{
this.trimpCommentRepositories = trimpCommentRepositories;
}
public void Delete(int id)
{
var tripComment = this.GetById(id);
if (tripComment == null)
{
throw new Exception("Tripm comment not found.");
}
this.trimpCommentRepositories.Delete(tripComment);
this.trimpCommentRepositories.Save();
}
public TripComment Edit(int id, string text)
{
var tripComment = this.GetById(id);
if (tripComment == null)
{
throw new Exception("User comment not found.");
}
tripComment.Text = text;
this.trimpCommentRepositories.Save();
return tripComment;
}
public IQueryable<TripComment> GetAll()
{
return this.trimpCommentRepositories.All();
}
private TripComment GetById(int id)
{
return this.trimpCommentRepositories
.All()
.Where(uc => uc.Id == id)
.FirstOrDefault();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.Sconit.Entity.Exception;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Web.Models;
using com.Sconit.Entity.INV;
using com.Sconit.Entity.VIEW;
using com.Sconit.Service;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.ORD;
using AutoMapper;
using com.Sconit.Utility.Report;
using com.Sconit.Entity;
namespace com.Sconit.Web.Controllers.INV
{
public class TransferHuController : WebAppBaseController
{
//public IGenericMgr genericMgr { get; set; }
//public IFlowMgr flowMgr { get; set; }
//public IOrderMgr orderMgr { get; set; }
public IHuMgr huMgr { get; set; }
//public IReportGen reportGen { get; set; }
[SconitAuthorize(Permissions = "Url_TransferHu_View")]
public ActionResult New()
{
TempData["Hu"] = new List<Hu>();
return View();
}
[HttpPost]
[SconitAuthorize(Permissions = "Url_TransferHu_View")]
public void HuScan(string HuId)
{
IList<Hu> hulist = (IList<Hu>)TempData["Hu"];
try
{
if(hulist!=null){
var q = hulist.Where(v => v.HuId == HuId).ToList();
if (q.Count > 0)
{
throw new BusinessException(@Resources.ORD.TransferHu.TransferHu_ExceptionHuid);
}
}
IList<Hu> hu = genericMgr.FindAll<Hu>(" from Hu where HuId=?",HuId);
if (hu.Count == 0)
{
throw new BusinessException(HuId + @Resources.ORD.TransferHu.TransferHu_HuidIsNullOrEmpty);
}
hulist.Add(hu[0]);
}
catch (BusinessException ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write(ex.GetMessages()[0].GetMessageString());
}
TempData["Hu"] = hulist;
}
[GridAction]
[SconitAuthorize(Permissions = "Url_TransferHu_View")]
public ActionResult _SelectTransferHuDetail()
{
IList<Hu> huList = new List<Hu>();
if (TempData["Hu"] != null)
{
huList = (IList<Hu>)TempData["Hu"];
}
TempData["Hu"] = huList;
return View(new GridModel(huList));
}
public ActionResult _ViewHuDetailList()
{
return View();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_TransferHu_View")]
public ActionResult _DeleteHuDetail(string id)
{
IList<Hu> hu = (IList<Hu>)TempData["Hu"];
var q = hu.Where(v => v.HuId != id).ToList();
TempData["Hu"] = q;
return View(new GridModel(q));
}
[GridAction]
[SconitAuthorize(Permissions = "Url_TransferHu_View")]
public ActionResult CreateTransferHu(string effectiveDate, string Flow)
{
IList<Hu> hulist = null;
IList<string> strList = new List<string>();
try
{
hulist = (IList<Hu>)TempData["Hu"];
foreach (Hu hu in hulist)
{
strList.Add(hu.HuId);
}
string Order = orderMgr.CreateHuTransferOrder(Flow, strList, Convert.ToDateTime(effectiveDate));
object obj = Resources.EXT.ControllerLan.Con_TransferOrderNumber + Order + Resources.EXT.ControllerLan.Con_GeneratedSuccessfully;
return Json(new { status = obj }, "text/plain");
}
catch (BusinessException ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write(ex.GetMessages()[0].GetMessageString());
}
TempData["Hu"] = hulist;
return Content("");
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TesteInputForm.Models;
namespace TesteInputForm.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
var credentials = GetSessionCredentials();
return View();
}
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Login([FromForm] Credencial data)
{
HttpContext.Session.Set("token", Encoding.UTF8.GetBytes(data.Token));
HttpContext.Session.Set("funcional", Encoding.UTF8.GetBytes(data.Funcional));
return RedirectToAction(nameof(Privacy));
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
private Credencial GetSessionCredentials()
{
if (HttpContext.Session.TryGetValue("token", out byte[] tokenB)
&& HttpContext.Session.TryGetValue("funcional", out byte[] funcional))
{
return new Credencial
{
Token = Encoding.UTF8.GetString(tokenB),
Funcional = Encoding.UTF8.GetString(funcional)
};
};
return null;
}
}
public class Credencial
{
public string Token { get; set; }
public string Funcional { get; set; }
}
}
|
using MySelf_InterfacesNew.Objects;
var person = new Person("Illia");
person.Move();
var animal = new Animal();
animal.Name = "Wolf";
animal.Move();
var plane = new Plane();
plane.Fly(); |
using UnityEngine;
using System.Collections;
public class RandomClick : MonoBehaviour {
public GameObject[] suit;
public void RandomPilih () {
int i = Random.Range (0,2);
suit [i].GetComponent<ButtonInput> ().OnClick ();
}
}
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Library.Model;
namespace Library.Interfaces
{
public interface IDataFiller
{
List<Person> GetPeopleList();
Dictionary<string, Item> GetItemsList();
ObservableCollection<Event> GetEventsList();
List<StateDescription> GetStatesList();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Timelogger.Api.Entities;
namespace Timelogger.Api.BL
{
public class NormalInvoiceCalculationRule : IInvoiceCalculationRule
{
/// <summary>
/// Calculating the invoice and returning the bill amount - normal caculation
/// </summary>
/// <returns></returns>
public decimal CalculateInvoice(InvoiceParameters parameters)
{
return (parameters.Hours * parameters.Rate);
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using PhotonInMaze.Common;
using PhotonInMaze.Common.Flow;
using PhotonInMaze.Provider;
using PhotonInMaze.Common.Controller;
using PhotonInMaze.Common.Model;
namespace PhotonInMaze.Maze {
internal partial class MazeController : FlowUpdateBehaviour, IMazeController {
public Dictionary<int, IMazeCell> Wormholes { get; private set; } = new Dictionary<int, IMazeCell>();
public HashSet<IMazeCell> BlackHolesPositions { get; private set; }
public HashSet<IMazeCell> WhiteHolesPositions { get; private set; }
private Optional<GameObject> CreateHole(HoleType type, IMazeCell cell, Transform cellGameObject, ref byte counter) {
if(cell.Walls.Count < 3) {
return Optional<GameObject>.Empty();
}
GameObject hole = null;
counter++;
if(!cell.IsStartCell() && !cell.IsGoal && counter == 5) {
if(type == HoleType.Black) {
GameObject blackHolePrototype = MazeObjectsProvider.Instance.GetBlackHole();
hole = Instantiate(blackHolePrototype, cellGameObject);
hole.name = string.Format("BlackHole_{0}_{1}", cell.Row, cell.Column);
} else if(type == HoleType.White) {
GameObject whiteHolePrefab = MazeObjectsProvider.Instance.GetWhiteHole();
hole = Instantiate(whiteHolePrefab, cellGameObject);
hole.name = string.Format("WhiteHole_{0}_{1}", cell.Row, cell.Column);
}
int sortingOrder = System.Math.Abs(hole.transform.GetInstanceID());
while(sortingOrder > short.MaxValue) {
sortingOrder -= short.MaxValue;
}
counter = 1;
}
return Optional<GameObject>.OfNullable(hole);
}
private Dictionary<int, IMazeCell> CreateWormholes(List<ObjectMazeCell> blackholes, List<ObjectMazeCell> whiteholes) {
int length;
length = CalculateSizeOfWormholes(blackholes, whiteholes);
System.Random random = new System.Random();
Dictionary<int, IMazeCell> wormholes = new Dictionary<int, IMazeCell>();
blackholes = blackholes.GetRange(0, length).OrderBy(x => random.Next()).ToList();
whiteholes = whiteholes.GetRange(0, length).OrderBy(x => random.Next()).ToList();
BlackHolesPositions = new HashSet<IMazeCell>();
WhiteHolesPositions = new HashSet<IMazeCell>();
for(int i = 0; i < length; i++) {
int blackHoleId = blackholes[i].gameObject.transform.GetInstanceID();
IMazeCell whiteHoleCell = whiteholes[i].cell;
wormholes.Add(blackHoleId, whiteHoleCell);
WhiteHolesPositions.Add(whiteHoleCell);
BlackHolesPositions.Add(blackholes[i].cell);
}
return wormholes;
}
private static int CalculateSizeOfWormholes(List<ObjectMazeCell> blackholes, List<ObjectMazeCell> whiteholes) {
int length;
if(whiteholes.Count < blackholes.Count) {
length = whiteholes.Count;
for(int i = whiteholes.Count; i < blackholes.Count; i++) Destroy(blackholes[i].gameObject);
} else if(blackholes.Count > whiteholes.Count) {
length = blackholes.Count;
for(int i = blackholes.Count; i < whiteholes.Count; i++) Destroy(whiteholes[i].gameObject);
} else {
length = blackholes.Count;
}
return length;
}
public bool IsWhiteHolePosition(IMazeCell newCell) {
return WhiteHolesPositions.Contains(newCell);
}
public bool IsBlackHolePosition(IMazeCell newCell) {
return BlackHolesPositions.Contains(newCell);
}
public IMazeCell GetWormholeExit(int blackHoleId) {
return Wormholes[blackHoleId];
}
}
} |
using System;
using CustomConversion.Helper;
namespace CustomConversion
{
public class Demo3
{
public static void Run()
{
// Converting an int to a Square.
Square sq2 = (Square)90;
Console.WriteLine("sq2 = {0}", sq2);
// Converting a Square to an int.
int side = (int)sq2;
Console.WriteLine("Side length of sq2 = {0}", side);
/** OUTPUT **/
/***********************************
# sq2 = [Length = 90]
# Side length of sq2 = 90
***********************************/
Console.WriteLine();
// Implicit cast OK!
// converting Square type to Rectangle type can be done implicitly
// as it is defined by the implicit operator
Square s3 = new Square { Length= 7};
Rectangle rect2 = s3;
Console.WriteLine("rect2 = {0}", rect2);
// Anyway, explicit cast syntax is still OK!
Square s4 = new Square {Length = 3};
Rectangle rect3 = (Rectangle)s4;
Console.WriteLine("rect3 = {0}", rect3);
/** OUTPUT **/
/***********************************
# rect2 = [Width = 14; Height = 7]
# rect3 = [Width = 6; Height = 3]
***********************************/
}
}
} |
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.Data.Metadata;
using gView.Framework.FDB;
using gView.Framework.Geometry;
using gView.Framework.IO;
using gView.Framework.system;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
namespace gView.DataSources.CosmoDb
{
//[RegisterPlugIn("8119C1CA-B8E1-4C55-B828-922966A56540")]
public class CosmoDbDataset : DatasetMetadata, IFeatureDataset2, IFeatureDatabase
{
internal DocumentClient _client = null;
private List<IDatasetElement> _layers;
private const string SpatialCollectionRefName = "spatial_collections_ref";
private const string FeatureCollectionNamePoints = "feature_collection_points";
private const string FeatureCollectionNameLines = "feature_collection_lines";
private const string FeatureCollectionNamePolygons = "feature_collection_polygons";
private DocumentCollection _spatialCollectionRef = null;
private DocumentCollection
_featureCollection_points = null,
_featureCollection_lines = null,
_featureCollection_polygons = null;
#region IFeatureDataset
public Task<int> CreateDataset(string name, ISpatialReference sRef)
{
throw new NotImplementedException();
}
async public Task<int> CreateFeatureClass(string dsname, string fcname, IGeometryDef geomDef, IFieldCollection fields)
{
try
{
if (_client == null || _spatialCollectionRef == null)
{
throw new Exception("No spatial collection reference. Open database before running CreateFeatureClass method");
}
var datasetElement = await Element(fcname);
if (datasetElement != null)
{
throw new Exception($"Featureclass {fcname} already exists");
}
var result = await _client.CreateDocumentAsync(_spatialCollectionRef.SelfLink,
new Json.SpatialCollectionItem(geomDef, fields)
{
Name = fcname
});
return 1;
}
catch (Exception ex)
{
LastException = ex;
LastErrorMessage = ex.Message;
return 0;
}
}
public Task<IFeatureDataset> GetDataset(string name)
{
throw new NotImplementedException();
}
public Task<bool> DeleteDataset(string dsName)
{
throw new NotImplementedException();
}
public Task<bool> DeleteFeatureClass(string fcName)
{
throw new NotImplementedException();
}
public Task<bool> RenameDataset(string name, string newName)
{
throw new NotImplementedException();
}
public Task<bool> RenameFeatureClass(string name, string newName)
{
throw new NotImplementedException();
}
public Task<IFeatureCursor> Query(IFeatureClass fc, IQueryFilter filter)
{
return Task.FromResult<IFeatureCursor>(new CosmoDbFeatureCursor((CosmoDbFeatureClass)fc, filter));
}
public Task<string[]> DatasetNames()
{
throw new NotImplementedException();
}
public bool Create(string name)
{
throw new NotImplementedException();
}
public Task<bool> Open(string name)
{
throw new NotImplementedException();
}
public Task<bool> Insert(IFeatureClass fClass, IFeature feature)
{
return Insert(fClass, new List<IFeature>(new IFeature[] { feature }));
}
async public Task<bool> Insert(IFeatureClass fClass, List<IFeature> features)
{
try
{
var featureCollection = GetFeatureCollection(fClass.GeometryType);
if (_client == null || featureCollection == null)
{
throw new Exception("No feature collection. Open database before running CreateFeatureClass method");
}
int fieldCount = fClass.Fields.Count;
var documentCollection = new DocumentCollection();
int degreeOfParallelism = 5;
var containers = new List<ExpandoObject>[degreeOfParallelism];
for (int i = 0; i < degreeOfParallelism; i++)
{
containers[i] = new List<ExpandoObject>();
}
int counter = 0;
foreach (var feature in features)
{
var expandoObject = new ExpandoObject();
var expandoDict = (IDictionary<string, object>)expandoObject;
expandoDict["_fc"] = fClass.Name;
if (feature.Shape != null)
{
expandoDict["_shape"] = feature.Shape.ToAzureGeometry();
}
for (int f = 0; f < fieldCount; f++)
{
var field = fClass.Fields[f];
if (field.type == FieldType.ID ||
field.type == FieldType.Shape)
{
continue;
}
var fieldValue = feature.FindField(field.name);
if (fieldValue != null)
{
expandoDict[fieldValue.Name] = fieldValue.Value;
}
}
containers[counter % degreeOfParallelism].Add(expandoObject);
//var result = await _client.CreateDocumentAsync(featureCollection.SelfLink, expandoObject);
counter++;
}
Task[] tasks = new Task[5];
for (int i = 0; i < degreeOfParallelism; i++)
{
tasks[i] = Task.Factory.StartNew(async (object index) =>
{
foreach (var expandoObjet in containers[(int)index])
{
var result = await _client.CreateDocumentAsync(featureCollection.SelfLink, expandoObjet);
}
}, (object)i);
}
await Task.WhenAll(tasks);
return true;
}
catch (Exception ex)
{
LastException = ex;
LastErrorMessage = ex.Message;
return false;
}
}
public Task<bool> Update(IFeatureClass fClass, IFeature feature)
{
throw new NotImplementedException();
}
public Task<bool> Update(IFeatureClass fClass, List<IFeature> features)
{
throw new NotImplementedException();
}
public Task<bool> Delete(IFeatureClass fClass, int oid)
{
throw new NotImplementedException();
}
public Task<bool> Delete(IFeatureClass fClass, string where)
{
throw new NotImplementedException();
}
#endregion
#region IFeatureDataset2
public string ConnectionString { get; private set; }
public string DatasetGroupName => "CosmoDb Spatial Database";
public string DatasetName { get; private set; }
public string ProviderName => "gViewGIS";
public DatasetState State { get; private set; }
public string Query_FieldPrefix => String.Empty;
public string Query_FieldPostfix => String.Empty;
public IDatabase Database => this;
public string LastErrorMessage { get; set; }
public Exception LastException { get; private set; }
public int SuggestedInsertFeatureCountPerTransaction => throw new NotImplementedException();
public Task AppendElement(string elementName)
{
return Task.CompletedTask;
}
public void Dispose()
{
_featureCollection_points = _spatialCollectionRef = null;
_client.Dispose();
}
async public Task<IDatasetElement> Element(string title)
{
var result = _client.CreateDocumentQuery<Json.SpatialCollectionItem>(_spatialCollectionRef.SelfLink)
.Where(d => d.Name == title)
.AsEnumerable<Json.SpatialCollectionItem>()
.FirstOrDefault();
if (result == null)
{
return null;
}
return new DatasetElement(await CosmoDbFeatureClass.Create(this, result))
{
Title = result.Name
};
}
async public Task<List<IDatasetElement>> Elements()
{
if (_layers != null)
{
return _layers;
}
List<IDatasetElement> layers = new List<IDatasetElement>();
foreach (var collectionItem in _client.CreateDocumentQuery<Json.SpatialCollectionItem>(_spatialCollectionRef.SelfLink).AsEnumerable())
{
layers.Add(new DatasetElement(await CosmoDbFeatureClass.Create(this, collectionItem)));
}
_layers = layers;
return _layers;
}
async public Task<IDataset2> EmptyCopy()
{
var dataset = new CosmoDbDataset();
await dataset.SetConnectionString(ConnectionString);
await dataset.Open();
return dataset;
}
public Task<IEnvelope> Envelope()
{
return Task.FromResult<IEnvelope>(new Envelope());
}
internal ISpatialReference _spatialReference = null;
public Task<ISpatialReference> GetSpatialReference()
{
return Task.FromResult<ISpatialReference>(_spatialReference);
}
async public Task<bool> LoadAsync(IPersistStream stream)
{
if (_layers != null)
{
_layers.Clear();
}
await this.SetConnectionString((string)stream.Load("connectionstring", ""));
return await this.Open();
}
public void Save(IPersistStream stream)
{
stream.SaveEncrypted("connectionstring", this.ConnectionString);
}
async public Task<bool> Open()
{
try
{
_client = new DocumentClient(
new Uri(ConnectionString.ExtractConnectionStringParameter("AccountEndpoint")),
ConnectionString.ExtractConnectionStringParameter("AccountKey"));
var database = _client.CreateDatabaseQuery()
.Where(db => db.Id == ConnectionString.ExtractConnectionStringParameter("Database"))
.AsEnumerable()
.FirstOrDefault();
if (database == null)
{
throw new Exception($"Database {ConnectionString.ExtractConnectionStringParameter("Database")} not exits");
}
_spatialCollectionRef = _client.CreateDocumentCollectionQuery(database.SelfLink)
.Where(col => col.Id == SpatialCollectionRefName)
.AsEnumerable()
.FirstOrDefault();
if (_spatialCollectionRef == null)
{
var partitionKey = new PartitionKeyDefinition();
partitionKey.Paths.Add("/name");
var response = await _client.CreateDocumentCollectionAsync(
database.SelfLink,
new DocumentCollection()
{
Id = SpatialCollectionRefName,
PartitionKey = partitionKey
});
_spatialCollectionRef = response.Resource;
}
#region Points Collection
_featureCollection_points = _client.CreateDocumentCollectionQuery(database.SelfLink)
.Where(col => col.Id == FeatureCollectionNamePoints)
.AsEnumerable()
.FirstOrDefault();
if (_featureCollection_points == null)
{
IndexingPolicy indexingPolicyWithSpatialEnabled = new IndexingPolicy
{
IncludedPaths = new System.Collections.ObjectModel.Collection<IncludedPath>()
{
new IncludedPath
{
Path = "/*",
Indexes = new System.Collections.ObjectModel.Collection<Index>()
{
new SpatialIndex(DataType.Point),
new RangeIndex(DataType.Number) { Precision = -1 },
new RangeIndex(DataType.String) { Precision = -1 }
}
}
}
};
var partitionKey = new PartitionKeyDefinition();
partitionKey.Paths.Add("/_fc");
var response = await _client.CreateDocumentCollectionAsync(
database.SelfLink,
new DocumentCollection()
{
Id = FeatureCollectionNamePoints,
PartitionKey = partitionKey,
IndexingPolicy = indexingPolicyWithSpatialEnabled
});
// ToDo: Create Spatial Index
_featureCollection_points = response.Resource;
}
#endregion
#region Lines Collection
_featureCollection_lines = _client.CreateDocumentCollectionQuery(database.SelfLink)
.Where(col => col.Id == FeatureCollectionNameLines)
.AsEnumerable()
.FirstOrDefault();
if (_featureCollection_lines == null)
{
IndexingPolicy indexingPolicyWithSpatialEnabled = new IndexingPolicy
{
IncludedPaths = new System.Collections.ObjectModel.Collection<IncludedPath>()
{
new IncludedPath
{
Path = "/*",
Indexes = new System.Collections.ObjectModel.Collection<Index>()
{
new SpatialIndex(DataType.LineString),
new RangeIndex(DataType.Number) { Precision = -1 },
new RangeIndex(DataType.String) { Precision = -1 }
}
}
}
};
var partitionKey = new PartitionKeyDefinition();
partitionKey.Paths.Add("/_fc");
var response = await _client.CreateDocumentCollectionAsync(
database.SelfLink,
new DocumentCollection()
{
Id = FeatureCollectionNameLines,
PartitionKey = partitionKey,
IndexingPolicy = indexingPolicyWithSpatialEnabled
});
_featureCollection_lines = response.Resource;
}
#endregion
#region Polygons Collection
_featureCollection_polygons = _client.CreateDocumentCollectionQuery(database.SelfLink)
.Where(col => col.Id == FeatureCollectionNamePolygons)
.AsEnumerable()
.FirstOrDefault();
if (_featureCollection_polygons == null)
{
IndexingPolicy indexingPolicyWithSpatialEnabled = new IndexingPolicy
{
IncludedPaths = new System.Collections.ObjectModel.Collection<IncludedPath>()
{
new IncludedPath
{
Path = "/*",
Indexes = new System.Collections.ObjectModel.Collection<Index>()
{
new SpatialIndex(DataType.Point),
new SpatialIndex(DataType.Polygon),
new RangeIndex(DataType.Number) { Precision = -1 },
new RangeIndex(DataType.String) { Precision = -1 }
}
}
}
};
var partitionKey = new PartitionKeyDefinition();
partitionKey.Paths.Add("/_fc");
var response = await _client.CreateDocumentCollectionAsync(
database.SelfLink,
new DocumentCollection()
{
Id = FeatureCollectionNamePolygons,
PartitionKey = partitionKey,
IndexingPolicy = indexingPolicyWithSpatialEnabled
});
_featureCollection_polygons = response.Resource;
}
#endregion
_spatialReference = SpatialReference.FromID("epsg:4326");
}
catch (Exception ex)
{
this.LastErrorMessage = ex.Message;
return false;
}
return true;
}
public Task RefreshClasses()
{
return Task.CompletedTask;
}
public Task<bool> SetConnectionString(string connectionString)
{
this.ConnectionString = connectionString;
return Task.FromResult(true);
}
public void SetSpatialReference(ISpatialReference sRef)
{
_spatialReference = sRef;
}
#endregion
internal DocumentCollection GetFeatureCollection(GeometryType geomType)
{
switch (geomType)
{
case GeometryType.Point:
case GeometryType.Multipoint:
return _featureCollection_points;
case GeometryType.Polyline:
return _featureCollection_lines;
case GeometryType.Polygon:
return _featureCollection_polygons;
default:
throw new Exception($"There is no collection for geometry-type '{geomType.ToString()}'");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerScienceFinal
{
class TreeNODE
{
public int data;
public TreeNODE left = null;
public TreeNODE right = null;
public TreeNODE(int Data)
{
data = Data;
}
// hàm kiểm tra giá trị nhập vào có trùng với giá trị đã có trong tree hay chưa
public bool isEqual(int Data)
{
return (data == Data);
}
// thêm phần tử phía sau node
public void Insert(int Data)
{
if (isEqual(Data))
{
return;
}
if (data > Data)
{
if (left == null)
left = new TreeNODE(Data);
else
left.Insert(Data);
}
else if (data < Data)
{
if (right == null)
right = new TreeNODE(Data);
else
right.Insert(Data);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Target), typeof(Speed), typeof(Collision))]
public class Bullet : MonoBehaviour
{
public Vector2 Direction;
public GameObject Shooter;
private void Update()
{
transform.Translate(Direction * Time.deltaTime * GetComponent<Speed>().value);
if (GetComponent<Target>() != null && Shooter != null && Shooter.GetComponent<Target>() != null)
GetComponent<Target>().Tag = Shooter.GetComponent<Target>().Tag;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OrangeApple.WPF.ViewModels;
using ReactiveUI;
namespace OrangeApple.WPF.Views
{
/// <summary>
/// Interaction logic for WelcomeView.xaml
/// </summary>
public partial class WelcomeView : UserControl, IViewFor<WelcomeViewModel>
{
public WelcomeView()
{
InitializeComponent();
this.WhenActivated(() =>
{
/* COOLSTUFF: Setting up the View
*
* Whenever we're Navigated to, we want to set up some bindings.
* In particular, we want to Subscribe to the HelloWorld command
* and whenever the ViewModel invokes it, we will pop up a
* Message Box.
*/
// Make XAML Bindings be relative to our ViewModel
DataContext = ViewModel;
return new[] {Disposable.Empty};
});
}
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (WelcomeViewModel)value; }
}
public WelcomeViewModel ViewModel
{
get { return (WelcomeViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel", typeof(WelcomeViewModel), typeof(WelcomeView), new PropertyMetadata(null));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsPresentation;
using System.Device.Location;
namespace lab2_2
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<MapObject> objs = new List<MapObject>();
List<PointLatLng> pts = new List<PointLatLng>();
Route route = null;
Human human = null;
Car car = null;
// public GMapMarker carMarker = null;
public GMapMarker humanMarker = null;
GMapMarker dst;
public MainWindow()
{
InitializeComponent();
}
private void MapLoaded(object sender, RoutedEventArgs e)
{
// настройка доступа к данным
GMaps.Instance.Mode = AccessMode.ServerAndCache;
// установка провайдера карт
Map.MapProvider = GMapProviders.YandexMap;
// установка зума карты
Map.MinZoom = 2;
Map.MaxZoom = 17;
Map.Zoom = 15;
// установка фокуса карты
Map.Position = new PointLatLng(55.012823, 82.950359);
// настройка взаимодействия с картой
Map.MouseWheelZoomType = MouseWheelZoomType.MousePositionAndCenter;
Map.CanDragMap = true;
Map.DragButton = MouseButton.Left;
}
private void Map_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
PointLatLng point = Map.FromLocalToLatLng((int)e.GetPosition(Map).X, (int)e.GetPosition(Map).Y);
if (CHm.IsChecked == true)
{
pts.Add(point);
if (objType.SelectedIndex > -1)
{
if (objType.SelectedIndex == 0)
{
car = new Car(objTitle.Text, pts[0]);
objs.Add(car);
if (human != null)
{
car.Arrived += human.CarArrived;
human.passSeated += passSeated;
}
}
if (objType.SelectedIndex == 1)
{
human = new Human(objTitle.Text, pts[0]);
objs.Add(human);
if (car != null)
{
car.Arrived += human.CarArrived;
human.passSeated += passSeated;
}
}
if (objType.SelectedIndex == 2)
{
if (human != null)
{
human.moveTo(point);
dst = new GMapMarker(point)
{
Shape = new Image
{
Width = 40, // ширина маркера
Height = 40, // высота маркера
ToolTip = "dest",
Source = new BitmapImage(new Uri("pack://application:,,,/Resources/Loc.png")), // картинка
RenderTransform = new TranslateTransform { X = -20, Y = -20 } // картинка
}
};
}
}
pts = new List<PointLatLng>();
}
Map.Markers.Clear();
objectList.Items.Clear();
foreach (MapObject cm in objs)
{
Map.Markers.Add(cm.GetMarker());
objectList.Items.Add(cm.GetTitle());
}
Map.Markers.Add(dst);
}
}
private void CHm_Checked(object sender, RoutedEventArgs e)
{
if (CHm.IsChecked == true)
{
NCHm.IsChecked = false;
objTitle.IsEnabled = true;
objType.IsEnabled = true;
//AddM.IsEnabled = true;
}
}
private void NCHm_Checked(object sender, RoutedEventArgs e)
{
if (NCHm.IsChecked == true)
{
CHm.IsChecked = false;
objTitle.IsEnabled = false;
objType.IsEnabled = false;
// AddM.IsEnabled = false;
}
}
private void ObjectList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (objectList.SelectedIndex > -1)
{
PointLatLng p = objs[objectList.SelectedIndex].GetFocus();
Map.Position = p;
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
objectList.UnselectAll();
objectList.Items.Clear();
foreach (MapObject mapObject in objs)
{
if (mapObject.GetTitle().Contains(poisk.Text))
{
objectList.Items.Add(mapObject.GetTitle());
}
}
}
private void RoutMap_Click(object sender, RoutedEventArgs e)
{
if (dst != null)
{
Map.Markers.Add(car.moveTo(human.GetFocus()));
car.Follow += Car_Follow;
}
else
{
MessageBox.Show("Определите пункт назначения.");
}
}
private void Car_Follow(object sender, EventArgs e)
{
Car car = (Car)sender;
car.Arrived += human.CarArrived;
Map.Position = car.GetFocus();
}
public void passSeated(object sender, EventArgs e)
{
var pass = (Human)sender;
car.setPass(pass);
Application.Current.Dispatcher.Invoke(delegate {
Map.Markers.Add (car.moveTo(pass.getDestination()));
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AdventureGameTEst.Extension_Methods;
namespace AdventureGameTEst.Classes
{
public class Inventory : Base
{
public int Id { get; set; }
public bool Key { get; set; }
public bool CanTake { get; set; }
public Inventory(int itemId, string itemName, string itemDescription, bool canTake, bool key)
{
Id = itemId;
Name = itemName;
Description = itemDescription;
Key = key;
CanTake = canTake;
}
public static List<Inventory> InventoryList()
{
List<Inventory> list = new List<Inventory>();
Inventory bucket = new Inventory(0, "Bucket", "You found a bucket.It reeks but maybe there's a use for it?", true, false);
Inventory painting = new Inventory(1, "Painting", "A painting of my great idol, Adobe Gitler", false, false);
Inventory bigPlant = new Inventory(2, "Big Plant", "This plant is almost as big as me. It sits in a white flower pot. How does it grow so much when there's no sunlight here?", false, false);
Inventory smallPlant = new Inventory(3, "Small Plant", "This plant is about a foot tall, but it has spiky vines. Seems pretty fitting for a prison.", false, false);
Inventory copperKey = new Inventory(4, "Copper Key", "A copper key. I wonder where it goes.", true, true);
Inventory couch = new Inventory(5, "Couch", "The couch sits 6 people. It's beside the wall and you can see that someone has forgotten to paint the wall behind it.", false, false);
Inventory table = new Inventory(6, "Table", "An ordinary wood table, can seat four people.", false, false);
Inventory chairs = new Inventory(7, "Chairs", "Normal wood chairs. Could possibly be used to climb somewhere.", true, false);
Inventory teeth = new Inventory(8, "Teeth", "Sharp, yellow teeth.", true, false);
Inventory tapestry = new Inventory(9, "Tapestry", "It shows some kind of tunnel, with many small spiders and one big spider descending on a man.", false, false);
Inventory rug = new Inventory(10, "Rug", "A dirty rug with blood stains all over it.", false, false);
Inventory bookShelf = new Inventory(11, "Book Shelf", "A heavy book shelf with lots of books in it. Obviously, most of them are covered in books except for Harry Potter and 50 Shades of Grey.", false, false);
Inventory harryPotterBook = new Inventory(12, "Harry Potter Book", "Harry Potter and The Prisoner of Azkaban. It has been read a LOT.", true, false);
Inventory fiftyShadesBook = new Inventory(13, "50 Shades of Grey Book", "Wow, this book is falling apart! Must be really popular.", true, false);
Inventory benchPress = new Inventory(14, "Bench Press", "A normal bench press.", false, false);
Inventory kettlebells = new Inventory(15, "Kettlebells", "40 pound kettlebells. A swing to the head could kill a man!", true, false);
Inventory oldRug = new Inventory(16, "Old Rug", "A really old rug.", false, false);
Inventory ironKey = new Inventory(17, "Iron Key", "An iron key. I wonder where it goes.", true, true);
list.ListAdd(bucket, painting, bigPlant, smallPlant, copperKey, couch, table, chairs, teeth, tapestry, rug,
bookShelf, harryPotterBook, fiftyShadesBook, benchPress, kettlebells, oldRug, ironKey);
return list;
}
}
/*Olika föremål vi ska ha med
Entrance: Bucket - ska kunna ta med den men ingen nytta.
SouthEastRoom: Painting - ska kunna undersöka om det finns något bakom den.
SouthWestRoom: Inget.
EastRoom: Two plants - Ska kunna undersöka båda. En av dem ska innehålla en nyckel.
WestRoom: Couch - Ska kunna undersöka bakom soffan. Inget ska finnas.
NorthEastRoom: Table, chairs, teeth - Ska kunna undersöka. En stol samt tänder kan tas med.
NorthRoom: Tapestry, rug, book shelf - ska alla kunna undersökas. Preliminärt ska man hitta hemliga nyckelhål bakom bokhyllan.
Ska kunna ta böcker från bokhyllan.
NorthWestRoom: Bench press, kettlebells, rug ska kunna undersökas. Ska kunna ta kettlebell. Under mattan ska det finnas en nyckel.
*/
/*Item descriptions:
0 Bucket = "You found a bucket. It reeks but maybe there's a use for it?"
1 Painting = "A painting of my great idol, Adobe Gitler"
3 Big Plant = "This plant is almost as big as me. It sits in a white flower pot. How does it grow so much when there's no
sunlight here?"
4 Small Plant = "This plant is about a foot tall, but it has spiky vines. Seems pretty fitting for a prison."
5 Copper Key = "A copper key. I wonder where it goes."
6 Couch = "The couch sits 6 people. It's beside the wall and you can see that someone has forgotten to paint the wall behind it."
7 Table = "An ordinary wood table, can seat four people."
8 Chairs = "Normal wood chairs. Could possibly be used to climb somewhere."
9 Teeth = "Sharp, yellow teeth."
10 Tapestry = "It shows some kind of tunnel, with many small spiders and one big spider descending on a man."
11 Rug = "A dirty rug with blood stains all over it."
12 Book shelf = "A heavy book shelf with lots of books in it. Obviously, most of them are covered in books except for Harry Potter and 50 Shades of Grey."
13 Harry Potter book = "Harry Potter and The Prisoner of Azkaban. It has been read a LOT."
14 50 Shades of Grey = "Wow, this book is falling apart! Must be really popular."
15 Bench press = "A normal bench press."
16 Kettlebells = "40 pound kettlebells. A swing to the head could kill a man!"
17 Rug2 = "A really old rug."
18 Iron Key = "An iron key. I wonder where it goes."
*/
//Use
//Inspect
}
|
namespace gView.Framework.Symbology
{
public interface IBrushColor
{
GraphicsEngine.ArgbColor FillColor { get; set; }
}
}
|
namespace Sneaking
{
using System;
using System.Collections.Generic;
using System.Text;
public class Startup
{
public static void Main(string[] args)
{
Execute();
}
private static void Execute()
{
var n = int.Parse(Console.ReadLine());
var matrix = new List<char[]>();
var playerRow = 0;
var playerCol = 0;
for (int i = 0; i < n; i++)
{
matrix.Add(Console.ReadLine().ToCharArray());
for (int j = 0; j < matrix[i].Length; j++)
{
if (matrix[i][j] == 'S')
{
playerRow = i;
playerCol = j;
}
}
}
var directions = Console.ReadLine();
for (int i = 0; i < directions.Length; i++)
{
matrix[playerRow][playerCol] = '.';
MoveEnemies(matrix);
if (matrix[playerRow][playerCol] == 'd' ||
matrix[playerRow][playerCol] == 'b')
{
matrix[playerRow][playerCol] = 'S';
}
for (int j = 0; j < matrix[playerRow].Length; j++)
{
if (matrix[playerRow][j] == 'N')
{
matrix[playerRow][j] = 'X';
matrix[playerRow][playerCol] = 'S';
PrintMatrix(matrix, "Nikoladze killed!");
return;
}
}
for (int j = 0; j < playerCol; j++)
{
if (matrix[playerRow][j] == 'b')
{
matrix[playerRow][playerCol] = 'X';
PrintMatrix(matrix, $"Sam died at {playerRow}, {playerCol}");
return;
}
}
for (int j = playerCol + 1; j < matrix[playerRow].Length; j++)
{
if (matrix[playerRow][j] == 'd')
{
matrix[playerRow][playerCol] = 'X';
PrintMatrix(matrix, $"Sam died at {playerRow}, {playerCol}");
return;
}
}
switch (directions[i])
{
case 'U':
playerRow--;
break;
case 'D':
playerRow++;
break;
case 'L':
playerCol--;
break;
case 'R':
playerCol++;
break;
case 'W':
break;
default:
break;
}
matrix[playerRow][playerCol] = 'S';
for (int j = 0; j < matrix[playerRow].Length; j++)
{
if (matrix[playerRow][j] == 'N')
{
matrix[playerRow][j] = 'X';
matrix[playerRow][playerCol] = 'S';
PrintMatrix(matrix, "Nikoladze killed!");
return;
}
}
}
}
private static void PrintMatrix(List<char[]> matrix, string message)
{
var builder = new StringBuilder();
builder.AppendLine(message);
for (int i = 0; i < matrix.Count; i++)
{
for (int j = 0; j < matrix[i].Length; j++)
{
builder.Append(matrix[i][j]);
}
builder.AppendLine();
}
Console.WriteLine(builder);
}
private static void MoveEnemies(List<char[]> matrix)
{
for (int i = 0; i < matrix.Count; i++)
{
for (int j = 0; j < matrix[i].Length; j++)
{
if (matrix[i][j] == 'd')
{
if (j == 0)
{
matrix[i][j] = 'b';
}
else
{
matrix[i][j - 1] = 'd';
matrix[i][j] = '.';
}
break;
}
else if (matrix[i][j] == 'b')
{
if (j == matrix[i].Length - 1)
{
matrix[i][j] = 'd';
}
else
{
matrix[i][j + 1] = 'b';
matrix[i][j] = '.';
}
break;
}
}
}
}
}
} |
using Common.Enums;
using Common.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LokalniKontroler
{
public static class LocalPowerSimulator
{
public static Random r = new Random();
public static void SimulateLocal()
{
double added = 0;
double subbed = 0;
while (Data.RunningFlag)
{
foreach (Generator g in Data.Generators.Where(gen => gen.Control == EControl.LOCAL))
{
added = g.CurrentPower + g.CurrentPower * 0.1;
subbed = g.CurrentPower - g.CurrentPower * 0.1;
if ((r.Next(0, 2) == 0 || added > g.MaxPower) && subbed >= g.MinPower)
{
g.CurrentPower = subbed;
}
else if (added <= g.MaxPower)
{
g.CurrentPower = added;
}
}
Data.Dbg.UpdatePower(Data.Generators.Where(gen => gen.Control == EControl.LOCAL).ToList());
Thread.Sleep(2000);
}
}
public static void RunRemote()
{
Dictionary<int, Thread> threads = new Dictionary<int, Thread>();
while (Data.RunningFlag)
{
foreach (Generator g in Data.Generators.Where(gen => gen.Control == EControl.REMOTE))
{
if (!threads.ContainsKey(g.Id))
{
threads.Add(g.Id, new Thread(() => SetpointGeneratorUpdater(g.Id)));
threads[g.Id].Start();
}
else if(!threads[g.Id].IsAlive)
{
threads.Remove(g.Id);
}
}
Thread.Sleep(1000);
}
foreach(KeyValuePair<int, Thread> t in threads)
{
t.Value.Join();
}
}
private static void SetpointGeneratorUpdater(int genId)
{
Generator g;
DateTime now;
TimeSpan dueTime;
int i;
bool found;
while (Data.RunningFlag)
{
g = Data.Dbg.GetGenerator(genId);
if (g.Control == EControl.LOCAL)
{
break;
}
if (g.Setpoints.Count > 0)
{
now = DateTime.Now;
i = 0;
found = false;
g.Setpoints.ForEach(sp =>
{
if (sp.Date > now)
{
found = true;
return;
}
i++;
});
if (found)
{
dueTime = g.Setpoints[i].Date - now;
Thread.Sleep(dueTime);
if (Data.Dbg.GetGenerator(genId).Control == EControl.LOCAL)
{
break;
}
if (g.State == EState.OFFLINE)
{
g.State = EState.ONLINE;
}
g.CurrentPower = g.Setpoints[i].Value;
Data.Dblc.SaveChanges(g);
}
else
{
g.CurrentPower = 0;
g.State = EState.OFFLINE;
Data.Dblc.SaveChanges(g);
Thread.Sleep(2000);
}
}
else
{
Thread.Sleep(2000);
}
}
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerHealth : Health {
public Sprite fullHeart;
public Sprite halfHeart;
public Sprite emptyHeart;
[Tooltip("Time in seconds to wait after the player dies before returning to the main menu.")]
public float delayAfterDeath = 4f;
// Required when the player dies (change state / disable)
private PlayerController movementController;
private SpriteRenderer firstHeart;
private SpriteRenderer secondHeart;
private SpriteRenderer thirdHeart;
protected override void Start () {
base.Start();
movementController = GetComponent<PlayerController>();
SetHeartReferences();
}
void Update () {
// Set the hearts in the health panel
SetHeartsFromHealth();
if (isDead)
StartCoroutine(ReturnToMainMenu());
}
private IEnumerator ReturnToMainMenu() {
yield return new WaitForSeconds(delayAfterDeath);
Application.LoadLevel(Application.loadedLevelName);
}
// Gets references to the sprite renderers for the health hearts in the UI so that we can change the sprites
private void SetHeartReferences () {
GameObject healthPanel = GameObject.FindGameObjectWithTag(GameConstants.HealthPanelTag);
firstHeart = healthPanel.transform.GetChild(0).GetComponent<SpriteRenderer>();
secondHeart = healthPanel.transform.GetChild(1).GetComponent<SpriteRenderer>();
thirdHeart = healthPanel.transform.GetChild(2).GetComponent<SpriteRenderer>();
}
public override bool RemoveHealth(int damage) {
bool damaged = base.RemoveHealth(damage);
return damaged;
}
public override bool AddHealth(int health) {
bool healed = base.AddHealth(health);
return healed;
}
public override void DestroyCharacter() {
base.DestroyCharacter();
movementController.enabled = false; // Turn off the controls
}
// Ugly!
private void SetHeartsFromHealth () {
// Amount of health equal to half a heart (there are 3 hearts)
float halfHeartValue = startingHealth / 6;
if (currentHealth <= 0) {
SetHearts(emptyHeart, emptyHeart, emptyHeart);
} else if (currentHealth > 0 && currentHealth <= halfHeartValue) {
SetHearts(halfHeart, emptyHeart, emptyHeart);
} else if (currentHealth <= halfHeartValue * 2) {
SetHearts(fullHeart, emptyHeart, emptyHeart);
} else if (currentHealth <= halfHeartValue * 3) {
SetHearts(fullHeart, halfHeart, emptyHeart);
} else if (currentHealth <= halfHeartValue * 4) {
SetHearts(fullHeart, fullHeart, emptyHeart);
} else if (currentHealth <= halfHeartValue * 5) {
SetHearts(fullHeart, fullHeart, halfHeart);
} else if (currentHealth <= halfHeartValue * 6) {
SetHearts(fullHeart, fullHeart, fullHeart);
}
}
private void SetHearts(Sprite first, Sprite second, Sprite third) {
firstHeart.sprite = first;
secondHeart.sprite = second;
thirdHeart.sprite = third;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MatrixOperatorOverloading
{
public class Dictionary
{
private List<string> words;
public Dictionary(string file)
{
words = new List<string>();
string[] lines = System.IO.File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
words.Add(lines[i]);
}
}
public string FindClosest (string toFind)
{
string stored_min = "";
int min = int.MaxValue;
int ed;
foreach (string s in words)
{
ed = EditDistance.ED(toFind, s);
if (ed == 0)
{
return s;
}
else
{
if (ed < min)
{
min = ed;
stored_min = s;
}
}
}
return stored_min;
}
}
}
|
namespace StringConcatenation
{
using System;
public class StartUp
{
public static void Main()
{
char delimeter = char.Parse(Console.ReadLine());
string evenOdd = Console.ReadLine();
int number = int.Parse(Console.ReadLine());
string sumStrings = "";
for (int i = 1; i <= number; i++)
{
string word = Console.ReadLine();
if (evenOdd == "even" && i % 2 == 0)
sumStrings += word + delimeter;
if (evenOdd == "odd" && i % 2 == 1)
sumStrings += word + delimeter;
}
sumStrings = sumStrings.Remove(sumStrings.Length - 1);
Console.WriteLine(sumStrings);
}
}
}
|
namespace HobbyGenCoreTest
{
using System.Linq;
using HobbyGen.Controllers.Managers;
using HobbyGenCoreTest.Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Test class for testing hobby persistence
/// </summary>
[TestClass]
public class HobbyTest : DatabaseTest
{
private HobbyManager hManager;
private UserManager uManager;
/// <summary>
/// Resets the database context
/// </summary>
protected override void ResetContext()
{
base.ResetContext();
this.hManager = new HobbyManager(this.context);
this.uManager = new UserManager(this.context);
}
/// <summary>
/// Check if a hobby can be made
/// </summary>
[TestMethod]
public void HobbyCreationTest()
{
// Create hobby
this.hManager.CreateHobby("Abc");
// Let's switch to a different data context
this.ResetContext();
// Get hobbies
var hobby = this.hManager.GetByName("Abc");
Assert.IsNotNull(hobby, "No hobby with name Abc found");
}
/// <summary>
/// Check if a hobby can be deleted
/// </summary>
[TestMethod]
public void HobbyDeletionTest()
{
// Create hobby
this.HobbyCreationTest();
var hobby = this.hManager.GetAll().FirstOrDefault();
Assert.IsNotNull(hobby, "No hobby found to delete");
// Delete hobby
this.hManager.DeleteHobby(hobby.Name);
var deletedHobby = this.hManager.GetByName(hobby.Name);
Assert.IsNull(deletedHobby, "Hobby was not deleted");
}
/// <summary>
/// Check if a hobby can be deleted from users indirectly
/// </summary>
[TestMethod]
public void BigHobbyDeletionTest()
{
// Create users with hobby
var hobby = "Minecraft";
var deletHobby = "Fortnite";
this.uManager.CreateUser("Bob Bobbington", new string[] { hobby, deletHobby });
this.uManager.CreateUser("Steve", new string[] { hobby });
this.uManager.CreateUser("Hendrik", new string[] { deletHobby });
this.uManager.CreateUser("Bobbius", new string[] { hobby, deletHobby });
this.uManager.CreateUser("Bobbard", new string[] { hobby, deletHobby });
// Let's switch to a different data context
this.ResetContext();
// Assert the numbers are correct at start
var hCount = this.uManager.SearchByHobby(new string[] { hobby }); // 4
var dhCount = this.uManager.SearchByHobby(new string[] { deletHobby }); // 4
// 4 made, none deleted
Assert.AreEqual(4, hCount.Count());
// 4 made as well
Assert.AreEqual(4, hCount.Count());
// Let's switch to a different data context
this.ResetContext();
// Delete the hobby
this.hManager.DeleteHobby(deletHobby);
var deletedHobby = this.hManager.GetByName(deletHobby);
Assert.IsNull(deletedHobby, "Hobby was not deleted");
// Assert that there's less users with hobby "deletHobby" and same for hobby "hobby"
hCount = this.uManager.SearchByHobby(new string[] { hobby }); // 4
dhCount = this.uManager.SearchByHobby(new string[] { deletHobby }); // 0
// 4 made, none deleted
Assert.AreEqual(4, hCount.Count());
// all deleted, so none found
Assert.IsFalse(dhCount.Any());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace StringReplicator.Core.Operations.Format
{
public class LineFormattingRequest
{
public string FormatString { get; set; }
public Object[] Arguments { get; set; }
}
} |
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace BerdziskoBot.Modules
{
public class ToolsModule : ModuleBase<SocketCommandContext>
{
[Command("clear"), RequireUserPermission(GuildPermission.ManageMessages)]
public async Task Clear(int count)
{
var messages = await Context.Channel.GetMessagesAsync(count).FlattenAsync();
foreach (var message in messages)
{
await Context.Channel.DeleteMessageAsync(message);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RigidbodyEventHandler : TimeEventHandler
{
public Rigidbody target;
private RigidbodyEvent lastEvent;
public override void ApplyEvent(TimeEvent timeEvent, bool reverse)
{
lastEvent = (RigidbodyEvent)timeEvent;
}
public override void UpdateEventHandler()
{
if (lastEvent != null)
{
target.velocity = lastEvent.velocity;
target.angularVelocity = lastEvent.angularVelocity;
target.isKinematic = lastEvent.isKinematic;
lastEvent = null;
}
RigidbodyEvent newEvent = new RigidbodyEvent();
newEvent.velocity = target.velocity;
newEvent.angularVelocity = target.angularVelocity;
newEvent.isKinematic = target.isKinematic;
TimeController.instance.AddEvent(newEvent, this);
}
}
public class RigidbodyEvent : TimeEvent
{
public Vector3 velocity;
public Vector3 angularVelocity;
public bool isKinematic;
} |
using GraphicalEditor.Enumerations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GraphicalEditor.DTO
{
public class DivideRenovationDTO
{
public BaseRenovationDTO baseRenovation { get; set; }
public string FirstRoomDescription { get; set; }
public string SecondRoomDescription { get; set; }
public TypeOfMapObject FirstRoomType { get; set; }
public TypeOfMapObject SecondRoomType { get; set; }
public DivideRenovationDTO()
{
}
public DivideRenovationDTO(BaseRenovationDTO baseRenovation, string firstRoomDescription, string secondRoomDescription, TypeOfMapObject firstRoomType, TypeOfMapObject secondRoomType)
{
this.baseRenovation = baseRenovation;
FirstRoomDescription = firstRoomDescription;
SecondRoomDescription = secondRoomDescription;
FirstRoomType = firstRoomType;
SecondRoomType = secondRoomType;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Fields;
using FakeItEasy;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentFields.Settings;
using Xunit;
namespace DFC.ServiceTaxonomy.UnitTests.GraphSync.GraphSyncers.Fields.NumericFieldGraphSyncerTests
{
public class NumericFieldGraphSyncerAddSyncComponentsTestsBase : FieldGraphSyncer_AddSyncComponentsTestsBase
{
public NumericFieldSettings NumericFieldSettings { get; set; }
public NumericFieldGraphSyncerAddSyncComponentsTestsBase()
{
NumericFieldSettings = new NumericFieldSettings();
A.CallTo(() => ContentPartFieldDefinition.GetSettings<NumericFieldSettings>()).Returns(NumericFieldSettings);
ContentFieldGraphSyncer = new NumericFieldGraphSyncer();
}
[Fact]
public async Task AddSyncComponents_Scale0NumericInContent_IntAddedToMergeNodeCommandsProperties()
{
const string value = "123.0";
const int expectedValue = 123;
//todo: JValue's type is being set to Object. code under test doesn't rely on it being Float like within oc, but should arrange as close to oc as possible
//todo: make sure type is set correctly in all unit tests
ContentItemField = JObject.Parse($"{{\"Value\": {value}}}");
NumericFieldSettings.Scale = 0;
await CallAddSyncComponents();
IDictionary<string, object?> expectedProperties = new Dictionary<string, object?>
{{_fieldName, expectedValue}};
Assert.Equal(expectedProperties, MergeNodeCommand.Properties);
}
[Fact]
public async Task AddSyncComponents_Scale1NumericInContent_DecimalAddedToMergeNodeCommandsProperties()
{
const string value = "123.4";
const decimal expectedValue = 123.4m;
ContentItemField = JObject.Parse($"{{\"Value\": {value}}}");
NumericFieldSettings.Scale = 1;
await CallAddSyncComponents();
IDictionary<string, object?> expectedProperties = new Dictionary<string, object?>
{{_fieldName, expectedValue}};
Assert.Equal(expectedProperties, MergeNodeCommand.Properties);
}
[Fact]
public async Task AddSyncComponents_NullNumericInContent_NumericNotAddedToMergeNodeCommandsProperties()
{
ContentItemField = JObject.Parse("{\"Value\": null}");
await CallAddSyncComponents();
IDictionary<string, object?> expectedProperties = new Dictionary<string, object?>();
Assert.Equal(expectedProperties, MergeNodeCommand.Properties);
}
//todo: assert that nothing else is done to the commands
//todo: assert that SyncNameProvider's contenttype is not set
}
}
|
using Kendo.Mvc;
using Sparda.Contracts;
using Sparda.Core.Services;
using Sparda.Core.Services.Contexts;
using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Telerik.OpenAccess;
namespace Sparda.Core.Models
{
public class Service : IService
{
#region Fields
private const string rightFormat = "{0}_{1}";
private Dictionary<string, Right> rights;
#endregion
public Service(string name, string owner, int? version, bool shareSettings, bool isPublic, CustomDataServiceHostFactory dataServiceHostFactory, Type genericTypeOpenAccessDataService)
{
this.DisplayName = name;
this.ShareSettings = shareSettings;
this.IsPublic = isPublic;
this.Name = name;
this.Owner = owner;
this.Version = version;
this.DataServiceHostFactory = dataServiceHostFactory;
this.GenericTypeOpenAccessDataService = genericTypeOpenAccessDataService;
}
#region Properties
public bool IsPublic { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public int? Version { get; set; }
public string DisplayName { get; set; }
public bool ShareSettings { get; set; }
public Type GenericTypeOpenAccessDataService { get; set; }
public CustomDataServiceHostFactory DataServiceHostFactory { get; set; }
public Service MainService { get; set; }
#endregion
#region Methods
public Type GetServiceContext()
{
Type contextType = null;
Type currentType = this.GenericTypeOpenAccessDataService;
while (contextType == null && currentType != null)
{
contextType = currentType.GenericTypeArguments.FirstOrDefault();
currentType = currentType.BaseType;
}
return contextType;
}
public void SetAccessRights(Dictionary<string, AccessRights> accessRights)
{
//this.accessRights = accesRights;
//if (accesRights != null)
//{
// accesRights.TryGetValue(string.Empty, out this.globalAccessRights);
//}
//else
//{
// this.globalAccessRights = null;
//}
this.rights = null;
if (accessRights != null)
{
this.rights = new Dictionary<string, Right>();
foreach (var keyValuePair in accessRights)
{
if (keyValuePair.Value.Get != null && keyValuePair.Value.Get.HasCompositeFilter())
{
this.rights[string.Format(rightFormat, keyValuePair.Key, "Get")] = keyValuePair.Value.Get;
}
if (keyValuePair.Value.Add != null && keyValuePair.Value.Add.HasCompositeFilter())
{
this.rights[string.Format(rightFormat, keyValuePair.Key, "Add")] = keyValuePair.Value.Add;
}
if (keyValuePair.Value.Change != null && keyValuePair.Value.Change.HasCompositeFilter())
{
this.rights[string.Format(rightFormat, keyValuePair.Key, "Change")] = keyValuePair.Value.Change;
}
if (keyValuePair.Value.Delete != null && keyValuePair.Value.Delete.HasCompositeFilter())
{
this.rights[string.Format(rightFormat, keyValuePair.Key, "Delete")] = keyValuePair.Value.Delete;
}
if (keyValuePair.Value.None != null && keyValuePair.Value.None.HasCompositeFilter())
{
this.rights[string.Format(rightFormat, keyValuePair.Key, "None")] = keyValuePair.Value.None;
}
}
}
}
public string GetRightKey(string entityName, string actionName)
{
return string.Format(rightFormat, entityName, actionName);
}
public Expression<Func<T, bool>> GetExpression<T>(UpdateOperations? operations = null)
{
var entityName = typeof(T).Name;
Expression<Func<T, bool>> expression = (e) => true;
Right right = null;
if (this.rights != null)
{
var actionName = operations.HasValue ? operations.Value.ToString() : "Get";
if (!this.rights.TryGetValue(string.Format(rightFormat, entityName, actionName), out right))
{
this.rights.TryGetValue(string.Format(rightFormat, string.Empty, actionName), out right);
}
}
return right != null ? right.ToExpression<T>() : expression;
}
public Expression<Func<T, bool>> QueryInterceptor<T>(string entityName)
{
return this.GetExpression<T>();
}
public Expression<Func<T, bool>> QueryInterceptor<T>()
{
return this.GetExpression<T>();
}
public void ChangeInterceptor<T>(string entityName, object entity, UpdateOperations operations)
{
this.ChangeInterceptor<T>(entity, operations);
}
public void ChangeInterceptor<T>(object entity, UpdateOperations operations)
{
var tracking = entity as IEntityTracking;
var user = HttpContext.Current.User;
var expression = this.GetExpression<T>(operations).Compile();
switch (operations)
{
case UpdateOperations.Add:
if (!(bool)expression.DynamicInvoke(entity))
{
throw new DataServiceException(403, "Add (Create,POST) operation forbidden !");
}
EntityTrackingHelper.OnChangeInterceptor(tracking, operations);
break;
case UpdateOperations.Change:
if (!(bool)expression.DynamicInvoke(entity))
{
throw new DataServiceException(403, "Change (UPDATE,PUT) operation forbidden !");
}
EntityTrackingHelper.OnChangeInterceptor(tracking, operations);
break;
case UpdateOperations.Delete:
if (!(bool)expression.DynamicInvoke(entity))
{
throw new DataServiceException(403, "Delete operation forbidden !");
}
if (tracking != null)
{
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, tracking.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(403, "Delete operation forbidden, you don't own it !");
}
}
break;
case UpdateOperations.None:
if (!(bool)expression.DynamicInvoke(entity))
{
throw new DataServiceException(403, "None operation forbidden !");
}
break;
default:
break;
}
this.Notify<T>(operations);
}
private void Notify<T>(UpdateOperations operations)
{
IRealtimeNotifier notifier = ServiceLocator.GetInstance<IRealtimeNotifier>();
if (notifier != null)
{
if (operations == UpdateOperations.Add)
{
notifier.EntityChanged<T>(this, typeof(T).Name, operations);
}
else if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
{
notifier.EntityChanged<T>(this, HttpContext.Current.Request.Url.Segments.Last(), operations);
}
}
}
[Obsolete]
public void ChangeAccessRightInterceptor(string entityName, UpdateOperations operations)
{
//if (this.globalAccessRights != null)
//{
// var user = HttpContext.Current.User;
// switch (operations)
// {
// case UpdateOperations.Add:
// if (!this.HasRight(this.globalAccessRights.Add))
// {
// throw new DataServiceException(403, "Add (Create,POST) operation forbidden !");
// }
// break;
// case UpdateOperations.Change:
// if (!this.HasRight(this.globalAccessRights.Change))
// {
// throw new DataServiceException(403, "Change (UPDATE,PUT) operation forbidden !");
// }
// break;
// case UpdateOperations.Delete:
// if (!this.HasRight(this.globalAccessRights.Delete))
// {
// throw new DataServiceException(403, "Delete operation forbidden !");
// }
// break;
// case UpdateOperations.None:
// if (!this.HasRight(this.globalAccessRights.None))
// {
// throw new DataServiceException(403, "None operation forbidden !");
// }
// break;
// default:
// break;
// }
//}
}
[Obsolete]
public void ChangeInterceptor(string entityName, OpenAccessContext context, object entity, UpdateOperations operations)
{
}
[Obsolete]
public bool QueryAccessRightInterceptor(string entityName)
{
//AccessRights accessRight = null;
//if (this.accessRights != null)
//{
// //this.accessRights.TryGetValue(entityName, out accessRight);
// if (accessRight == null)
// {
// accessRight = this.globalAccessRights;
// }
// return this.HasRight(accessRight.Get);
//}
//if (this.globalAccessRights != null)
//{
// return this.HasRight(this.globalAccessRights.Get);
//}
return true;
}
#endregion
}
}
|
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
namespace RRExpress.Common {
public class BearerMessageHandler : MessageProcessingHandler {
private string Token;
public BearerMessageHandler(string token)
: base(new HttpClientHandler()) {
this.Token = token;
}
protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken) {
//添加 Bearer 认证请求头
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.Token);
return request;
}
protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) {
return response;
}
}
}
|
using ipScan.Base;
using System;
using System.Collections.Generic;
namespace ipScan.Base
{
interface ITasksChecking
{
DateTime LastTime { get; }
TimeSpan loopTime { get; }
int SleepTime { get; set; }
bool MySearchTasksStartedAll { get;}
void Check();
void Stop();
bool Pause();
void Pause(bool IsPaused);
bool ChangeSearchTaskRange(int Index);
bool IsStarting { get; set; }
int TasksCount { get; }
}
}
|
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 Prise_Note
{
public partial class Button_menu : Form
{
bool etat = false;
choix_etiquette menu_etiquette = new choix_etiquette(new Point(0, 0));
public static form1 menu_principal;
public static int button_menu_width;
public Button_menu()
{
InitializeComponent();
this.Width = Screen.PrimaryScreen.WorkingArea.Right;
this.Height = Screen.PrimaryScreen.WorkingArea.Bottom;
this.BackColor = Color.Black;
this.TransparencyKey = Color.Black;
this.Location = new Point(0, 0);
Open_menu.Size = new Size(this.Width / 30, this.Height / 5);
button_menu_width = Open_menu.Width;
Open_menu.Location = new Point(Screen.PrimaryScreen.WorkingArea.Right - Open_menu.Width, (Screen.PrimaryScreen.WorkingArea.Bottom / 2) - Open_menu.Height / 2);
menu_principal = new form1(menu_etiquette, this);
}
public void Open_menu_Click(object sender, EventArgs e)
{
menu_principal.Close_color();
Methode_to_close();
}
public void Methode_to_close()
{
if (!etat)
{
menu_principal.Show();
this.Refresh();
do
{
Open_menu.Location = new Point(Open_menu.Location.X - 1, Open_menu.Location.Y);
menu_principal.Location = new Point(menu_principal.Location.X - 1, menu_principal.Location.Y);
System.Threading.Thread.Sleep(0);
} while (Open_menu.Location.X != Screen.PrimaryScreen.WorkingArea.Left);
this.TopMost = true;
etat = true;
menu_principal.clear_list_tags();
}
else
{
if (menu_principal.Visible == true)
{
this.Refresh();
do
{
Open_menu.Location = new Point(Open_menu.Location.X + 1, Open_menu.Location.Y);
menu_principal.Location = new Point(menu_principal.Location.X + 1, menu_principal.Location.Y);
} while (Open_menu.Location.X != Screen.PrimaryScreen.WorkingArea.Right - Open_menu.Width);
menu_principal.Hide();
etat = false;
menu_etiquette.clear_list();
menu_principal.clear_list_tags();
}
else
{
do
{
Open_menu.Location = new Point(Open_menu.Location.X + 1, Open_menu.Location.Y);
menu_etiquette.Location = new Point(menu_etiquette.Location.X + 1, menu_etiquette.Location.Y);
} while (Open_menu.Location.X != Screen.PrimaryScreen.WorkingArea.Right - Open_menu.Width);
menu_principal.Location = new Point(Screen.PrimaryScreen.WorkingArea.Right, 0);
menu_etiquette.Hide();
etat = false;
menu_etiquette.clear_list();
menu_principal.clear_list_tags();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using App.Core.Interfaces.Dto;
using Newtonsoft.Json;
namespace App.Core.Interfaces.Errors
{
public enum StatusCode
{
InternalError = -1,
Ok = 0,
// Parsing/validation.
RequestParsingError = 100,
ValidationError = 101,
// Auth.
WrongCredentialsError = 200,
EmailAlreadyTakenError = 201,
SessionExpiredError = 202,
InvalidSessionTokenError = 203,
// Users.
UserNotFoundError = 300,
// Chats.
ChatNotFoundError = 400,
// Messages.
MessageNotFoundError = 500,
}
public class ServiceException : Exception
{
public StatusCode Code { get; set; }
public List<ErrorDto> Errors { get; set; } = new List<ErrorDto>();
}
} |
using NeuralNetLibrary.components.activators;
using System;
namespace NeuralNetLibrary.components
{
[Serializable]
public class Neuron
{
public ActivationFunction Activator { get; }
private double weightedSum;
public double[] InputWeights { get; set; }
public bool IsBias { get; }
public double Output { get; set; }
public double Derivative { get; private set; }
public double OutputError { get; set; }
private Neuron(ActivationFunction activator, bool isBias)
{
Activator = activator;
IsBias = isBias;
}
public static Neuron CreateBias(ActivationFunction activator)
{
return new Neuron(activator, true)
{
Output = 1
};
}
public static Neuron CreateNeuron(ActivationFunction activator, int numberOfInputs)
{
double[] inputWeights = null;
if (numberOfInputs > 0)
{
Random rand = new Random();
inputWeights = new double[numberOfInputs];
for (int i = 0; i < numberOfInputs; i++)
inputWeights[i] = rand.NextDouble() - 0.5;
}
return new Neuron(activator, false)
{
Output = 0,
InputWeights = inputWeights
};
}
private void calculateWeightsSum(double[] sourceOutputs)
{
weightedSum = 0;
for (int i = 0; i < InputWeights.Length; i++)
weightedSum += InputWeights[i] * sourceOutputs[i];
}
public void Activate(double[] sourceOutputs)
{
calculateWeightsSum(sourceOutputs);
Output = Activator.Equation(weightedSum);
Derivative = Activator.Derivative(Output);
}
}
}
|
using System;
using System.Globalization;
using Tomelt.ContentManagement;
using Tomelt.ContentManagement.FieldStorage.InfosetStorage;
namespace Tomelt.MediaLibrary.Models {
public class DocumentPart : ContentPart {
public long Length {
get { return Convert.ToInt64(this.As<InfosetPart>().Get("DocumentPart", "Length", "Value"), CultureInfo.InvariantCulture); }
set { this.As<InfosetPart>().Set("DocumentPart", "Length", "Value", Convert.ToString(value, CultureInfo.InvariantCulture)); }
}
}
} |
using UnityEngine;
using System.Collections;
using VRStandardAssets.Utils;
using UnityEngine.VR;
namespace Shounds.IObj
{
public class IObjTransform : MonoBehaviour
{
public Vector3 m_IObjInitPos;
public KeyCode TransformExitKey = KeyCode.Escape;
[SerializeField] private float m_IObjMoveDamping = 0.5f;
[Tooltip("Defaults to this objs transform")]
[SerializeField] private Transform m_TargetIObj; // Reference to the transform of the target to toggle transform coroutine.
[Tooltip("Defaults to MainCam")]
[SerializeField] private Transform m_Camera; // Reference to the camera's transform.
[Tooltip("Defaults to this obj requires VRInteractiveItem")]
[SerializeField] private VRInteractiveItem m_InteractiveItem; // Reference to the camera's transform.
private const float k_ExpDampingCoef = -20f; // The coefficient used to damp the movement of the flyer.
public bool m_IsTransforming; // Whether the IObj is being transformed.
private bool m_GazeOver; // Whether the user is looking at the VRInteractiveItem currently.
private void Awake()
{
// set vars to what's on this OBJ if none set
if (!m_InteractiveItem)
m_InteractiveItem = transform.GetComponent<VRInteractiveItem>();
if (!m_TargetIObj)
m_TargetIObj = transform;
if (!m_Camera)
m_Camera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>().transform;
}
private void OnEnable ()
{
m_InteractiveItem.OnOver += HandleOver;
m_InteractiveItem.OnOut += HandleOut;
}
private void OnDisable ()
{
m_InteractiveItem.OnOver -= HandleOver;
m_InteractiveItem.OnOut -= HandleOut;
}
private void HandleOver()
{
m_GazeOver = true;
}
private void HandleOut()
{
m_GazeOver = false;
}
public void ToggleTransform()
{
// If the user is looking at the rendering of the scene when the radial's selection finishes, activate the button.
if (m_GazeOver && !m_IsTransforming)
{
InitTransform();
}
else if (m_GazeOver && m_IsTransforming)
{
InterruptAndSave();
}
}
public void InitTransform()
{
// The transformah is now running.
m_IsTransforming = true;
m_IObjInitPos = m_TargetIObj.position;
// Start the transfomah moving.
StartCoroutine(MoveIObj());
}
public void CancelTransform()
{
// Stop dem transformz.
m_IsTransforming = false;
m_TargetIObj.position = m_IObjInitPos;
}
public void InterruptAndCancel()
{
m_IsTransforming = false;
StopAllCoroutines();
m_TargetIObj.position = m_IObjInitPos;
}
public void InterruptAndSave()
{
m_IsTransforming = false;
StopAllCoroutines();
}
public void SaveTransform()
{
// The game is no longer running.
m_IsTransforming = false;
}
public IEnumerator MoveIObj()
{
while (m_IsTransforming)
{
/*
if (Input.GetKeyDown(TransformExitKey) && m_IsTransforming)
{
InterruptAndCancel();
}
*/
#if !UNITY_EDITOR
Quaternion rotation = InputTracking.GetLocalRotation(VRNode.Head);
var delta = Input.GetAxis ("Mouse Y");
#else
var delta = Input.GetAxis("Mouse ScrollWheel");
Quaternion rotation = m_Camera.localRotation;
#endif
m_TargetIObj.Translate((Vector3.forward * delta), m_Camera.transform);
//something
float TargetIObjDistance = Vector3.Distance(m_TargetIObj.position, m_Camera.position);
Vector3 MoveTo = m_Camera.position + (rotation * Vector3.forward) * TargetIObjDistance;
m_TargetIObj.position = Vector3.Lerp(m_TargetIObj.position, MoveTo,
m_IObjMoveDamping * (1f - Mathf.Exp(k_ExpDampingCoef * Time.deltaTime)));
// Wait until next frame.
yield return null;
}
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace API_ASPNET_CORE.Models.Usuarios
{
public class LoginViewModelInput
{
[Required(ErrorMessage = "Login obrigatório")]
public string Login { get; set; }
[Required(ErrorMessage = "Senha obrigatória")]
public string Senha { get; set; }
}
}
|
using Abp.Authorization;
using Abp.NHibernate.Repositories;
namespace Abp.Zero.NHibernate.Repositories
{
public class PermissionSettingRepository : NhRepositoryBase<PermissionSetting, long>, IPermissionSettingRepository
{
}
} |
using Microsoft.EntityFrameworkCore.Migrations;
namespace CleverScheduleProject.Migrations
{
public partial class AddressCordsUpdatedToDoubles : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<double>(
name: "Lon",
table: "Addresses",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
migrationBuilder.AlterColumn<double>(
name: "Lat",
table: "Addresses",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Lon",
table: "Addresses",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(double),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Lat",
table: "Addresses",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(double),
oldNullable: true);
}
}
}
|
using System.Collections.Generic;
using DevExpress.Utils;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using PhuLiNet.Plugin.Menu;
using Techical.Icons;
namespace PhuLiNet.Window.MainApplication.Extenders
{
internal class TreeListExtender : IMenuExtender
{
private readonly TreeList _treeList;
private readonly List<IMenuItem> _menuList;
private ImageCollection _selectImageCollection;
public TreeListExtender(TreeList treeList, List<IMenuItem> menuList)
{
_treeList = treeList;
_menuList = menuList;
}
#region IMenuExtender Members
public void Extend()
{
CreateImageCollection();
_treeList.BeginUnboundLoad();
foreach (IMenuItem mi in _menuList)
{
CreateNode(mi, null);
}
if (_menuList.Count == 1)
{
_treeList.ExpandAll();
}
_treeList.EndUnboundLoad();
}
public void Clear()
{
_treeList.Nodes.Clear();
}
#endregion
private void CreateImageCollection()
{
_selectImageCollection = new ImageCollection();
_selectImageCollection.AddImage(IconManager.GetBitmap(EIcons.folder_16));
_selectImageCollection.AddImage(IconManager.GetBitmap(EIcons.window_info_16));
_selectImageCollection.AddImage(IconManager.GetBitmap(EIcons.oracleforms_16));
_treeList.SelectImageList = _selectImageCollection;
}
private TreeListNode CreateNode(IMenuItem menuItem, TreeListNode parentNode)
{
return CreateApplicationNode(menuItem, parentNode);
}
private TreeListNode CreateApplicationNode(IMenuItem menuItem, TreeListNode parentNode)
{
string caption = menuItem.Caption;
var newNode = _treeList.AppendNode(new object[] { caption }, parentNode);
newNode.Tag = menuItem;
if (menuItem.Image != null)
{
_selectImageCollection.AddImage(menuItem.Image);
newNode.ImageIndex = _selectImageCollection.Images.Count - 1;
newNode.SelectImageIndex = _selectImageCollection.Images.Count - 1;
}
else
{
newNode.ImageIndex = 1;
newNode.SelectImageIndex = 1;
}
return newNode;
}
private TreeListNode CreateMenuNode(IMenuItem menuItem, TreeListNode parentNode)
{
var newNode = _treeList.AppendNode(new object[] { menuItem.Caption }, parentNode);
newNode.Tag = menuItem;
if (menuItem.Image != null)
{
_selectImageCollection.AddImage(menuItem.Image);
newNode.ImageIndex = _selectImageCollection.Images.Count - 1;
newNode.SelectImageIndex = _selectImageCollection.Images.Count - 1;
}
else
{
newNode.ImageIndex = 0;
}
return newNode;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Plus1.Models
{
public class SubSubCategory
{
[Key]
public string Name { get; set; }
public string ParentName { get; set; }
public virtual SubCategory Parent { get; set; }
public string Image { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stringkezeles
{
class Program
{
static string abc = "abcdefghijklmnopqrstuvwxyz";
static void Main(string[] args)
{
string[] stringek = new string[5];
for (int i = 0; i < stringek.Length; i++)
{
stringek[i] = Console.ReadLine();
}
Console.WriteLine();
for (int i = 0; i < stringek.Length; i++)
{
Console.WriteLine(stringek[i]);
}
Rendezes(stringek);
Console.WriteLine();
for (int i = 0; i < stringek.Length; i++)
{
Console.WriteLine(stringek[i]);
}
Console.ReadLine();
}
static int CharIndex(string s, char a)
{
int i = 0;
while (s[i] != a)
{
i++;
}
return i;
}
static int StringNagyobb(string s1, string s2)
{
int i;
for (i = 0; i < s1.Length; i++)
{
if (s1[i] != s2[i])
{
break;
}
}
if (CharIndex(abc, s1[i]) < CharIndex(abc, s2[i]))
{
return 1;
}
else if (CharIndex(abc, s1[i]) > CharIndex(abc, s2[i]))
{
return 2;
}
return 0;
}
static void Csere(int i, int j, string[] s)
{
string ideiglenes = s[i];
s[i] = s[j];
s[j] = ideiglenes;
}
static void Rendezes(string[] s)
{
for (int i = 0; i < s.Length - 1; i++)
{
for (int j = i + 1; j < s.Length; j++)
{
if (StringNagyobb(s[i], s[j]) == 2)
{
Csere(i, j, s);
}
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pickupable : MonoBehaviour
{
public float interactRadius = 3.0f;
void Start(){
}
/*void OnDrawGizmosSelected(){
Debug.Log("gizmosdrawcalled");
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position,interactRadius);
}*/
void OnMouseDown(){
Debug.Log("funcao");
Destroy(gameObject);
}
}
|
using FluentValidation;
using INOTE.Core.Domain;
using INOTE.Core.EntityValidator;
using INOTE.View;
using INOTE.View.Pages;
using INOTE.ViewModel.Commands;
using INOTE.ViewModel.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace INOTE.ViewModel
{
public class LoginVM : ViewModelBase
{
public User User { get; set; }
private string _errorText;
public string ErrorText
{
get { return _errorText; }
set
{
_errorText = value;
OnPropertyChanged("ErrorText");
}
}
private ICommand _navigateRegisterPageCommand;
public ICommand NavigateRegisterPageCommand
{
get
{
if (_navigateRegisterPageCommand == null)
{
_navigateRegisterPageCommand = new RelayCommand(
this.NavigateRegisterPage
);
}
return _navigateRegisterPageCommand;
}
}
private ICommand _loginCommand;
public ICommand LoginCommand
{
get
{
if(_loginCommand == null)
{
_loginCommand = new RelayCommand(this.Login);
}
return _loginCommand;
}
}
public LoginVM()
{
MainWindow.SetMainToolbarVisibility(false);
User = new User();
}
private void Login()
{
UserValidator validator = new UserValidator();
var validationResult = validator.Validate(User, o => { o.IncludeRuleSets("Login"); });
if(validationResult.IsValid)
{
var loggedInUser = UnitOfWork.Users.Login(User);
if (loggedInUser != null)
{
Frame.Navigate(new NotesPage(loggedInUser));
}
else
{
ErrorText = "Invalid Credential";
}
}
else
{
// show first error message
ErrorText = validationResult.Errors[0].ErrorMessage;
}
}
public void NavigateRegisterPage()
{
Frame.Navigate(new RegisterPage());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laboratorio5v2
{
class CirculoColoridoPreenchido : CirculoColorido
{
private string minhaCor;
public string Cor
{
get
{
return minhaCor;
}
set
{
minhaCor = value;
}
}
public CirculoColoridoPreenchido()
{
minhaCor = "Verde";
}
public CirculoColoridoPreenchido(double x, double y, double r, string p) : base(x, y, r)
{
minhaCor = p;
}
public override string ToString()
{
return base.ToString() + " cor=" + Cor;
}
}
}
|
namespace Euler.Regions
{
public class OneTouchDevice : ITouchDevice
{
public int[][] GetScreenState()
{
return new int[][]{
new []{1, 1, 1, 1, 1},
new []{1, 1, 1, 1, 1},
new []{1, 1, 1, 1, 1},
new []{1, 1, 1, 1, 1},
new []{1, 1, 1, 1, 1}
};
}
}
} |
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using WebsiteManagerPanel.Data.Entities;
using WebsiteManagerPanel.Data.Configurations.BaseConfigurations;
namespace WebsiteManagerPanel.Data.Configurations
{
public class RoleGroupConfiguration : EntityTypeConfiguration<RoleGroup>
{
public override void ConfigureEntity(EntityTypeBuilder<RoleGroup> builder)
{
}
}
}
|
using System;
namespace Na_vase_taimera
{
class Program
{
static void Main(string[] args)
{
int time = int.Parse(Console.ReadLine());
if ((time< 1)||(time > 65535))
{
Console.WriteLine("ERROR");
}
for (int k=time; k > 0; k--)
{
Console.WriteLine(k);
for (int i = 9999; i < -9999; i--)
{
for (int j = 7275; j > 0; j--)
{
double a = ((i % 47) / 23) / 31;
}
}Console.Clear();
}
Console.WriteLine("END OF TIMER");
}
}
}
|
using System.Text;
namespace csharp {
public class ReverseNumber {
public int Reverse(int number) {
bool isNegative = false;
if (number < 0) {
number = number * -1;
isNegative = true;
}
int result;
StringBuilder sb = new StringBuilder();
while (number > 0) {
sb.Append(number % 10);
number = number / 10;
}
int.TryParse(sb.ToString(), out result);
return !isNegative ? result : -result;
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class ButtonsScript : MonoBehaviour
{
private const float RepeatRate = 0.2f;
public Text LevelText;
private int lvlToLoad;
public GameObject exitScr;
private void Start()
{
lvlToLoad = GameManager.instance.lastOpenedLevel;
LevelText.text = lvlToLoad.ToString();
}
private void Update()
{
if (lvlToLoad < 1) lvlToLoad = 1;
if (lvlToLoad > GameManager.instance.lastOpenedLevel)
lvlToLoad = GameManager.instance.lastOpenedLevel;
if (lvlToLoad > 1 || lvlToLoad < GameManager.instance.lastOpenedLevel)
{
LevelText.text = lvlToLoad.ToString();
}
if (Input.GetKeyDown(KeyCode.Escape))
{
ToggleFadeScr();
}
}
public void Play()
{
AudioManager.instance.Play("Click");
SceneManager.LoadScene(lvlToLoad);
}
public void PrevLvl()
{
lvlToLoad--;
}
public void NextLvl()
{
lvlToLoad++;
}
public void Quit()
{
Application.Quit();
}
public void ToggleFadeScr()
{
exitScr.SetActive(!exitScr.activeSelf);
}
public void HoldNextLvl()
{
InvokeRepeating("NextLvl", 0f, RepeatRate);
}
public void UnHoldLvl()
{
CancelInvoke();
}
public void HoldPrevLvl()
{
InvokeRepeating("PrevLvl", 0f, RepeatRate);
}
public void OpenTwitter()
{
Application.OpenURL("https://twitter.com/Fataler_");
}
} |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace VoxelSpace.Input {
public class InputHandle {
public static InputHandle Active { get; private set; }
public bool IsActive => Active == this && G.Game.IsActive;
static KeyboardState _keyboardState;
static KeyboardState _lastKeyboardState;
static MouseState _mouseState;
static MouseState _lastMouseState;
static int _scrollDelta;
public int ScrollDelta => IsActive ? _scrollDelta : 0;
public bool IsCursorVisible = true;
public bool IsCursorClipped = false;
public Vector2 CursorPosition => new Vector2(_mouseState.X, _mouseState.Y);
static Stack<InputHandle> _stack = new Stack<InputHandle>();
public void MakeActive() {
Active = this;
Update();
}
public void PushActive() {
_stack.Push(Active);
MakeActive();
}
public static void PopActive() {
_stack.Pop().MakeActive();
}
public static void Update() {
_lastKeyboardState = _keyboardState;
_keyboardState = Keyboard.GetState();
_lastMouseState = _mouseState;
_mouseState = Mouse.GetState();
_scrollDelta = 0;
if (_mouseState.ScrollWheelValue > _lastMouseState.ScrollWheelValue) _scrollDelta ++;
if (_mouseState.ScrollWheelValue < _lastMouseState.ScrollWheelValue) _scrollDelta --;
MouseUtil.SetIsCursorClipped(Active.IsCursorClipped);
}
public bool IsKeyDown(Keys key) => IsActive && _keyboardState.IsKeyDown(key);
public bool IsKeyUp(Keys key) => IsActive && _keyboardState.IsKeyUp(key);
public bool WasKeyPressed(Keys key)
=> IsActive && _keyboardState.IsKeyDown(key) && !_lastKeyboardState.IsKeyDown(key);
public bool WasKeyReleased(Keys key)
=> IsActive && _keyboardState.IsKeyUp(key) && !_lastKeyboardState.IsKeyUp(key);
public bool IsMouseButtonDown(MouseButton button) {
if (!IsActive) return false;
switch (button) {
case MouseButton.Left: return _mouseState.LeftButton == ButtonState.Pressed;
case MouseButton.Right: return _mouseState.RightButton == ButtonState.Pressed;
case MouseButton.Middle: return _mouseState.MiddleButton == ButtonState.Pressed;
}
return false;
}
public bool IsMouseButtonUp(MouseButton button) {
if (!IsActive) return false;
switch (button) {
case MouseButton.Left: return _mouseState.LeftButton == ButtonState.Released;
case MouseButton.Right: return _mouseState.RightButton == ButtonState.Released;
case MouseButton.Middle: return _mouseState.MiddleButton == ButtonState.Released;
}
return false;
}
public bool WasMouseButtonPressed(MouseButton button) {
if (!IsActive) return false;
switch (button) {
case MouseButton.Left: return _mouseState.LeftButton == ButtonState.Pressed && _lastMouseState.LeftButton != ButtonState.Pressed;
case MouseButton.Right: return _mouseState.RightButton == ButtonState.Pressed && _lastMouseState.RightButton != ButtonState.Pressed;
case MouseButton.Middle: return _mouseState.MiddleButton == ButtonState.Pressed && _lastMouseState.MiddleButton != ButtonState.Pressed;
}
return false;
}
public bool WasMouseButtonReleased(MouseButton button) {
if (!IsActive) return false;
switch (button) {
case MouseButton.Left: return _mouseState.LeftButton == ButtonState.Released && _lastMouseState.LeftButton != ButtonState.Released;
case MouseButton.Right: return _mouseState.RightButton == ButtonState.Released && _lastMouseState.RightButton != ButtonState.Released;
case MouseButton.Middle: return _mouseState.MiddleButton == ButtonState.Released && _lastMouseState.MiddleButton != ButtonState.Released;
}
return false;
}
}
public enum MouseButton { Left, Right, Middle }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// MyNode 的摘要说明
/// </summary>
[Serializable]
public class MyNode
{
private int NodeID;
private string Name;
private double Weight;
private int ParentID;
private int Rank;
private double WeightSum;
private Double Grade;
private Double GradeSum;
private int TemplateID;
private string Information;
public MyNode()
{
}
public MyNode(int nodeID, string name, double weight, int parentID, int rank, double weightSum, string information)
{
this.NodeID = nodeID;
this.Name = name;
this.Weight = weight;
this.ParentID = parentID;
this.Rank = rank;
this.WeightSum = weightSum;
this.Information = information;
}
public MyNode(int nodeID, string name, double weight, int parentID, int rank, Double grade, int templateID, string information)
{
this.NodeID = nodeID;
this.Name = name;
this.Weight = weight;
this.ParentID = parentID;
this.Rank = rank;
this.Grade = grade;
this.TemplateID = templateID;
this.Information = information;
}
public int getNodeID()
{
return this.NodeID;
}
public void setNodeID(int nodeID)
{
this.NodeID = nodeID;
}
public string getName()
{
return this.Name;
}
public void setName(string name)
{
this.Name = name;
}
public double getWeight()
{
return this.Weight;
}
public void setWeight(double weight)
{
this.Weight = weight;
}
public int getParentID()
{
return this.ParentID;
}
public void setParentID(int parentID)
{
this.ParentID = parentID;
}
public int getRank()
{
return this.Rank;
}
public void setRank(int rank)
{
this.Rank = rank;
}
public double getWeightSum()
{
return this.WeightSum;
}
public void setWeightSum(double weightSum)
{
this.WeightSum = weightSum;
}
public Double getGrade()
{
return this.Grade;
}
public void setGrade(Double grade)
{
this.Grade = grade;
}
public Double getGradeSum()
{
return this.GradeSum;
}
public void setGradeSum(Double gradeSum)
{
this.GradeSum = gradeSum;
}
public int getTemplateID()
{
return this.TemplateID;
}
public void setTemplateID(int templateID)
{
this.TemplateID = templateID;
}
public string getInformation()
{
return this.Information;
}
public void setInformation(string information)
{
this.Information = information;
}
} |
using System.Collections.Generic;
using AutoMapper;
using DAL.Entity;
using Shared.DTO;
namespace BL.Helper
{
public class EntityToDtoMapper
{
IMapper Mapper;
public EntityToDtoMapper()
{
MapperConfiguration config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Member, MemberDTO>().ReverseMap();
cfg.CreateMap<House, HouseDTO>().ReverseMap();
cfg.CreateMap<Person, PersonDTO>().ReverseMap();
});
Mapper = config.CreateMapper();
}
public Member MemberDTOToMemberMapper(MemberDTO memberDTO)
{
return Mapper.Map<Member>(memberDTO);
}
public IEnumerable<Member> MemberDTOToMemberMapper(IEnumerable<MemberDTO> memberDTOS)
{
return Mapper.Map<IEnumerable<Member>>(memberDTOS);
}
public MemberDTO MemberToMemberDTOMapper(Member member)
{
return Mapper.Map<MemberDTO>(member);
}
public IEnumerable<MemberDTO> MemberToMemberDTOMapper(IEnumerable<Member> members)
{
return Mapper.Map<IEnumerable<MemberDTO>>(members);
}
//*****************************************************************//
public House HouseDTOToHouseMapper(HouseDTO houseDTO)
{
return Mapper.Map<House>(houseDTO);
}
public IEnumerable<House> HouseDTOToHouseMapper(IEnumerable<HouseDTO> houseDTOS)
{
return Mapper.Map<IEnumerable<House>>(houseDTOS);
}
public HouseDTO HouseToHouseDTOMapper(House house)
{
return Mapper.Map<HouseDTO>(house);
}
public IEnumerable<HouseDTO> HouseToHouseDTOMapper(IEnumerable<House> houses)
{
return Mapper.Map<IEnumerable<HouseDTO>>(houses);
}
//************************************************************//
public Person PersonDTOToPersonMapper(PersonDTO personDTO)
{
return Mapper.Map<Person>(personDTO);
}
public IEnumerable<Person> PersonDTOToPersonMapper(IEnumerable<PersonDTO> personDTOS)
{
return Mapper.Map<IEnumerable<Person>>(personDTOS);
}
public PersonDTO PersonToPersonDTOMapper(Person person)
{
return Mapper.Map<PersonDTO>(person);
}
public IEnumerable<PersonDTO> PersonToPersonDTOMapper(IEnumerable<Person> persons)
{
return Mapper.Map<IEnumerable<PersonDTO>>(persons);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.ACC;
namespace com.Sconit.Entity.ISS
{
[Serializable]
public partial class IssueTypeToUserDetail : EntityBase, IAuditable
{
#region O/R Mapping Properties
//[Display(Name = "Id", ResourceType = typeof(Resources.ISS.IssueTypeToUserDetail))]
public Int32 Id { get; set; }
[Display(Name = "IssueTypeTo", ResourceType = typeof(Resources.ISS.IssueTypeToUserDetail))]
public IssueTypeToMaster IssueTypeTo { get; set; }
[Display(Name = "User", ResourceType = typeof(Resources.ISS.IssueTypeToUserDetail))]
public User User { get; set; }
[Display(Name = "IsEmail", ResourceType = typeof(Resources.ISS.IssueTypeToUserDetail))]
public Boolean IsEmail { get; set; }
[Display(Name = "IsSMS", ResourceType = typeof(Resources.ISS.IssueTypeToUserDetail))]
public Boolean IsSMS { get; set; }
public Int32 CreateUserId { get; set; }
[Display(Name = "Common_CreateUserName", ResourceType = typeof(Resources.SYS.Global))]
public string CreateUserName { get; set; }
[Display(Name = "Common_CreateDate", ResourceType = typeof(Resources.SYS.Global))]
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
[Display(Name = "Common_LastModifyUserName", ResourceType = typeof(Resources.SYS.Global))]
public string LastModifyUserName { get; set; }
[Display(Name = "Common_LastModifyDate", ResourceType = typeof(Resources.SYS.Global))]
public DateTime LastModifyDate { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
IssueTypeToUserDetail another = obj as IssueTypeToUserDetail;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using UnityEngine;
[CreateAssetMenu(fileName = "InputConfig", menuName = "Config/InputConfig", order = 1)]
public class InputConfig : ScriptableObject
{
public string moveForwardBack = "Vertical";
public string moveRightLeft = "Horizontal";
public string camPan ="Mouse X";
public string camPitch ="Mouse Y";
public string camZoom ="Mouse ScrollWheel";
public string toggleZoom = "";
public string interact = "A_1";
public bool useMouse = false;
public float camZoomSensitivity = 1;
public float camTurnSensitivity = 1;
}
|
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Text_Adventure
{
public class Rooms
{
public List<Room> rooms = new List<Room>();
public Rooms()
{
rooms = GetRoom();
}
public class Room
{
public int number {get; set;}
public string name {get; set;}
public string description {get; set;}
public int north {get; set;}
public int east {get; set;}
public int south {get; set;}
public int west {get; set;}
}
public List<Room> GetRoom()
{
string filepath = "./json/rooms.json";
using (StreamReader r = new StreamReader(filepath))
{
string json = r.ReadToEnd();
List<Room> item = JsonConvert.DeserializeObject<List<Room>>(json);
return item;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapControl : MonoBehaviour {
// 0 = absent;
// 1 = top left corner;
// 2 = fill screen.
public int map_position;
private Camera cam;
public Material backgroundMat;
public Material wallOutlineMat;
bool resetting = false;
void Start() {
cam = GetComponent<Camera> ();
}
float _x, _y;
float timeheld = 0f;
bool clear_position_toggle = false;
// Update is called once per frame
void Update () {
if (Input.GetKeyUp (KeyCode.Tab)) {
if (clear_position_toggle) {
clear_position_toggle = false;
} else {
map_position++;
timeheld = 0f;
if (map_position >= 3) {
map_position = 0;
}
}
}
_x = Mathf.Abs(cam.rect.x);
if (map_position == 0) {
_x = 0f;
} else if (map_position == 1) {
_x = .5f;
} else if (map_position == 2) {
if (Mathf.Abs(_x) < .02f) {
_x = 0f;
} else {
_x = Mathf.Lerp (_x, 0f, .3f);
}
}
if (map_position == 0) {
cam.rect = new Rect (0f, 0f, 0f, 0f);
} else if (map_position == 1) {
cam.rect = new Rect (-_x, _x, 1f, 3f);
} else if (map_position == 2) {
cam.rect = new Rect (-_x, _x, 1f, 3f);
}
if (Input.GetKey (KeyCode.Tab)) {
if (timeheld <= .6f) {
timeheld += Time.deltaTime;
} else {
clear_position_toggle = true;
Color c = backgroundMat.color;
c.a = Mathf.Lerp (c.a, 1f, .2f);
backgroundMat.color = c;
c = wallOutlineMat.color;
c.a = Mathf.Lerp (c.a, 1f, .2f);
wallOutlineMat.color = c;
}
} else if (Input.GetKeyUp (KeyCode.Tab)) {
resetting = true;
timeheld = 0f;
} else if (resetting) {
Color c = backgroundMat.color;
c.a = Mathf.Lerp (c.a, .15f, .2f);
backgroundMat.color = c;
c = wallOutlineMat.color;
c.a = Mathf.Lerp (c.a, .15f, .2f);
wallOutlineMat.color = c;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LCode
{
// 输入: "babad"
//输出: "bab"
//注意: "aba" 也是一个有效答案。
class LCode5
{
public string LongestPalindrome(string s)
{
int maxLenth = 0;
int idx_i=0;
int idx_j=0;
int[][] f = new int[s.Length][];
for (int i = 0; i < s.Length; i++)
{
f[i][i] = 1;
}
for (int i = 0; i < s.Length; i++)
{
for (int k= 1; k < s.Length - i; k++)
{
int j = i + k;
if (s[i] == s[j])
{
f[i][j] = f[i + 1][j - 1] + 2;
if (f[i][j] > maxLenth)
{
idx_i = i + 1;
idx_j = j - 1;
}
}
else
{
if (f[i][j] > maxLenth)
{
idx_i = i + 1;
idx_j = j - 1;
}
f[i][j] = Math.Max(f[i + 1][j], f[i][j - 1]);
}
}
}
return s.Substring(idx_i, idx_j - idx_i + 1);
}
}
}
|
using System.Runtime.CompilerServices;
using System.Windows.Automation;
namespace UIAFramework
{
public class UICustom : ControlBase
{
public UICustom() { }
public UICustom(string condition, string treescope, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
: base(condition, treescope, type, memberName)
{
ParentBase.controlType = Common.GetControlType("custom");
}
public UICustom(string condition, string treescope, AutomationElement ae, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
: base(condition, treescope, ae, type, memberName)
{
ParentBase.controlType = Common.GetControlType("custom");
}
public UICustom(string treePath, bool isPath, [CallerMemberName] string memberName = "")
: base(treePath, isPath, memberName)
{
ParentBase.controlType = Common.GetControlType("custom");
}
public UICustom(string treePath, bool isPath, AutomationElement ae, [CallerMemberName] string memberName = "")
: base(treePath, isPath, ae, memberName)
{
ParentBase.controlType = Common.GetControlType("custom");
}
public UICustom(AutomationElement ae, [CallerMemberName] string memberName = "")
: base(ae, memberName)
{
ParentBase.controlType = Common.GetControlType("custom");
}
public UICustom(string condition, string treescope, bool isMultipleControl, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
:base(condition,treescope,isMultipleControl,type,memberName)
{
ParentBase.controlType = Common.GetControlType("custom");
}
public UICustom(string condition, string treescope, AutomationElement ae, bool isMultipleControl, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
: base(condition, treescope,ae, isMultipleControl, type, memberName)
{
ParentBase.controlType = Common.GetControlType("custom");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ALFC_SOAP.Data
{
class BookInfo
{
}
}
|
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using DFrame;
using PM = DAV.ProgramMonitor;
namespace DPYM
{
/// <summary>
/// 场景,主要功能分为三步:
/// 1、加载
/// 2、运行(是否暂停等自行定义)
/// 3、切换下一场景
/// </summary>
public class DScene : MonoBehaviour
{
/* 接口 */
/// <summary>
/// 创建场景对象(需要用 new 重新声明)
/// </summary>
/// <param name="objNameIn"></param>
public static DScene Create(SceneParam paramIn)
{
// 创建对象
GameObject sceneObj = new GameObject(paramIn.objectName);
DontDestroyOnLoad(sceneObj);
// 增加场景组件
DScene scene = null;
switch (paramIn.sceneType)
{
case ESceneType.Bonus:
scene = sceneObj.AddComponent<BonusScene>();
break;
case ESceneType.Title:
scene = sceneObj.AddComponent<TitleScene>();
break;
default:
DLogger.MDE(string.Format("[FATAL] DScene.Create : Un-known or un-supported scene type : {0}.",paramIn.sceneType));
break;
}
scene.Initialize(paramIn);
return scene;
}
/// <summary>
/// 当前场景
/// </summary>
public static DScene current
{
get
{
return _current;
}
}
/* 内部接口 */
// 场景管理
/// <summary>
/// 加载 .unity 场景
/// </summary>
internal void LoadUnityScene()
{
if (null == _unityName)
{
DLogger.MDE("[FATAL] DScene.LoadUnityScene : scene name is empty, which should be initialized when scene is created.");
}
SceneManager.LoadScene(_unityName);
}
// 场景切换
/// <summary>
/// 用本场景接管游戏控制权(不需要外部调用)
/// </summary>
internal void TakeOver()
{
DScene loser = __current;
__current = this;
OnTakeOver();
if (null != loser)
{
loser.OnLostControl();
}
}
/// <summary>
/// 关闭此场景
/// </summary>
internal virtual void Close()
{
Destroy(gameObject);
}
/* 属性 */
/// <summary>
/// 场景状态
/// </summary>
public SceneState state
{
get
{
return _state;
}
}
// 外部场景命令
/// <summary>
/// 检查场景命令通道是否开启
/// </summary>
public bool isChannelOpen
{
get { return _channelSwitch; }
}
/// <summary>
/// 场景命令是否已经获取
/// </summary>
public bool isCommandRecieved
{
get
{
return isCommandAvailable;
}
}
/// <summary>
/// 检测命令是否有效
/// </summary>
/// <returns></returns>
public bool isCommandAvailable
{
get
{
return CheckCommandAvailability();
}
}
/* 内部接口 */
// 场景命令相关操作
/// <summary>
/// 打开场景切换通道
/// </summary>
internal void OpenChannel()
{
_command.Disable();
_channelSwitch = true;
}
/// <summary>
/// 关闭场景切换通道
/// </summary>
internal void CloseChannel()
{
_channelSwitch = false;
}
/// <summary>
/// 申请执行操作
/// </summary>
internal void ApplyFor(Command commandIn)
{
DLogger.MD(string.Format("[INFO] DScene.ApplyFor : command recieved >>> {0} .", commandIn));
if (CheckCommandAvailability(commandIn))
{
_command = commandIn;
CloseChannel();
}
else
{
DLogger.MDE("[FATAL] Dscene.ApplyFor : command not available.");
}
}
/// <summary>
/// 执行场景命令
/// </summary>
internal virtual void Apply()
{
if(!isCommandRecieved)
{
DLogger.MDE("[FATAL] DScene.Apply : Command must be set before being applied.");
}
// 具体的工作留给子类完成
}
/* 引擎处理 */
/// <summary>
/// 完成初始化
/// </summary>
protected virtual void Awake()
{
// 初始化场景状态
_state = new SceneState(this);
}
/// <summary>
/// 进入场景的处理
/// </summary>
protected virtual void Start()
{
}
/// <summary>
/// 更新场景
/// </summary>
protected virtual void Update()
{
_state.Update();
}
/// <summary>
/// 销毁时的处理
/// </summary>
protected virtual void OnDestroy()
{
if (this == __current)
{
__current = null;
}
}
/* 具体操作 */
/// <summary>
/// 场景初始化操作
/// </summary>
/// <param name="paramIn"></param>
protected virtual void Initialize(SceneParam paramIn)
{
__unityName = paramIn.unityName;
__sceneType = paramIn.sceneType;
__map = paramIn.map;
}
// 场景命令
/// <summary>
/// 检测接收到的命令的有效性
/// </summary>
/// <returns></returns>
protected bool CheckCommandAvailability()
{
return CheckCommandAvailability(_command);
}
/// <summary>
/// 检测命令的有效性
/// </summary>
/// <param name="CCmd"></param>
/// <returns></returns>
protected virtual bool CheckCommandAvailability(Command CCmd)
{
// 处理过程中注意考虑命令的优先级
switch (CCmd.ID)
{
case ECommand.Unavailable:
return false;
case ECommand.SceneCommand_SceneTrans:
DLogger.MD("[ERROR] DScene.CheckCommandAvailability : Scene transmit param should be checked here.");
return true;
default:
return false;
}
}
/* 响应 */
// 场景切换
/// <summary>
/// 获取场景控制权时候的响应
/// </summary>
protected virtual void OnTakeOver()
{
}
/// <summary>
/// 拾取场景控制权
/// </summary>
protected virtual void OnLostControl()
{
}
/* 私有组件 */
// 场景管理
/// <summary>
/// 场景的状态
/// </summary>
protected SceneState _state;
/// <summary>
/// 当前场景
/// </summary>
protected static DScene _current
{
get
{
return __current;
}
}
// 场景命令
/// <summary>
/// 场景切换命令当前是否可用(开关)
/// </summary>
protected bool _channelSwitch = false;
/// <summary>
/// 场景切换命令参数(这里采用基本类,由实际使用和设置的单位负责具体类型)
/// </summary>
protected Command _command
{
get { return __command; }
set
{
// 正常设置参数,需要保证参数设置开关打开
if (_channelSwitch)
{
__command = value;
}
else
{
DLogger.MD("[WARNING] DScene._command : Command channel should be opened before set.");
}
}
}
// 场景参数
/// <summary>
/// 此场景的 .unity 文件名
/// </summary>
protected string _unityName
{
get
{
return __unityName;
}
}
/// <summary>
/// 用以进行场景管理的场景类
/// </summary>
protected ESceneType _sceneType
{
get
{
return __sceneType;
}
}
/// <summary>
/// 地图,场景关联地图
/// </summary>
protected Map _map
{
get
{
return __map;
}
}
/* 子类不可见 */
// 场景管理
private static DScene __current = null;
// 场景命令
/// <summary>
/// 场景命令
/// </summary>
private Command __command;
// 场景参数
/// <summary>
/// 此场景的 .unity 文件名
/// </summary>
private string __unityName;
/// <summary>
/// 用以进行场景管理的场景类
/// </summary>
private ESceneType __sceneType;
/// <summary>
/// 地图,场景关联地图
/// </summary>
private Map __map;
}
}
|
using System;
using System.Collections.Generic;
using KartLib;
using KartLib.Views.AlcoDeclModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AxiDeclTest
{
[TestClass]
public class TestAxiDecl
{
[TestMethod]
public void TestDecl()
{
var alcoDeclData = new AlcoDeclData
{
AlcoDeclRecords = new List<AlcoDeclRecord> {new AlcoDeclRecord {BeginRestF6 = 0}},
AlcoDeclRecordsF2 = new List<AlcoDeclRecordF2> {new AlcoDeclRecordF2 {FirmName = "Шляпа"}},
CurrDeclType = DeclType.Alco,
DateBegin = new DateTime(2015,1,1),
DateEnd = new DateTime(2015,3,31)
//Тут надо заполнить недостощие поля
};
var builder = new XmlBuilder(alcoDeclData) {AlcoTypes = new List<AlcoType>()};
builder.CreateXml(@"c:\temp\text.xml");
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.