text stringlengths 13 6.01M |
|---|
namespace WQMField.Model
{
using System.Collections.Generic;
using WQMStation.Comm;
public class Field
{
private int _iD;
private string _name;
private string _sT;
private string _password;
private string _mN;
private string _protocolName;
private string _protocolDll;
private IList<Center> _centers = new List<Center>();
private IList<Variable> _variables = new List<Variable>();
private IField _fieldDriver;
public virtual int ID
{
get
{
return _iD;
}
set
{
_iD = value;
}
}
/// <summary>
/// The name of the field.
/// </summary>
public virtual string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
/// <summary>
/// The station type of the field.
/// </summary>
public virtual string ST
{
get
{
return _sT;
}
set
{
_sT = value;
}
}
/// <summary>
/// The password of the field.
/// </summary>
public virtual string Password
{
get
{
return _password;
}
set
{
_password = value;
}
}
/// <summary>
/// The number code of the field.
/// </summary>
public virtual string MN
{
get
{
return _mN;
}
set
{
_mN = value;
}
}
public virtual string ProtocolName
{
get
{
return _protocolName;
}
set
{
_protocolName = value;
}
}
public virtual string ProtocolDll
{
get
{
return _protocolDll;
}
set
{
_protocolDll = value;
}
}
/// <summary>
/// The centers that this filed should connect to.
/// </summary>
public virtual IList<Center> Centers
{
get { return _centers; }
set { _centers = value; }
}
/// <summary>
/// The variables contained in the filed.
/// </summary>
public virtual IList<Variable> Variables
{
get { return _variables; }
set { _variables = value; }
}
public virtual void LoadDriver()
{
}
public virtual void AddCenters()
{
}
public virtual IField FieldDriver
{
get { return _fieldDriver; }
set { _fieldDriver = value; }
}
}
}
|
using System.Collections.Generic;
using JqD.Infrustruct;
using JqD.Infrustruct.Enums;
namespace JqueryDapper.ViewModels.Work
{
public class WorkPageViewModel
{
public List<WorkViewModel> Works { get; set; }
public Pagination Pagination { get; set; }
}
public class WorkViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public Enums.Category Category { get; set; }
public string Remark { get; set; }
public string CreateUser { get; set; }
public string CreateDate { get; set; }
}
} |
using System;
using System.Linq;
using Bindable.Linq.Collections;
using Bindable.Linq.Helpers;
using Bindable.Linq.Interfaces;
using Bindable.Linq.Threading;
namespace Bindable.Linq.Framework
{
public class InMemoryEntityStore<TEntity, TIdentity> : DispatcherBound, IEntityStore<TEntity, TIdentity> where TEntity : class
{
private readonly BindableCollection<WeakReference> _itemReferences;
private readonly IIdentifier<TEntity, TIdentity> _identifier;
public InMemoryEntityStore(IDispatcher dispatcher, IIdentifier<TEntity, TIdentity> identifier)
: base(dispatcher)
{
_itemReferences = new BindableCollection<WeakReference>(dispatcher);
_identifier = identifier;
}
public IBindableCollection<TEntity> GetAll()
{
AssertDispatcherThread();
return _itemReferences.Select(weak => weak.Target as TEntity).Where(entity => entity != null);
}
public void Add(TEntity entity)
{
AssertDispatcherThread();
_itemReferences.Add(new WeakReference(entity, true));
}
public void Remove(TEntity entity)
{
AssertDispatcherThread();
var reference = _itemReferences.ToList().Where(weak => weak.Target == entity).FirstOrDefault();
if (reference != null)
{
_itemReferences.Remove(reference);
}
}
public TEntity Get(TIdentity identity)
{
AssertDispatcherThread();
return GetAll().ToList().Where(entity => _identifier.GetIdentity(entity).Equals(identity)).FirstOrDefault();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ppadial.dotnet.Network;
namespace MonkeyWol.Web.Services
{
public sealed class WakeService : IWakeService
{
private readonly IOptions<MonkeyWolSettings> _settings;
private readonly ILogger<WakeService> _logger;
public WakeService(IOptions<MonkeyWolSettings> settings, ILogger<WakeService> logger)
{
_settings = settings;
_logger = logger;
}
#region IWakeService
public void Wake(params string[] machineName)
{
// TODO: Think about what to do if a machine fails to wake up, stop everything? or continue
// maybe a configuration value as part of the feature
foreach (var machine in machineName)
{
Wake(machine);
}
}
public void Wake(string machineName)
{
// Trimming MachineName since machine names can't contains whitespaces
machineName = machineName.Trim();
_logger.LogDebug($"Looking for {machineName} in all configured wakes");
// 1. Get the mac address from the list of aliases in config
var macAddress = _settings.Value.Wakes.Where(o => o.Aliases.Contains(machineName, StringComparer.OrdinalIgnoreCase)).FirstOrDefault();
if (macAddress == null)
throw new KeyNotFoundException($"Machine {machineName} was not found in configured wakes, aborting");
_logger.LogDebug("MacAddress found for machineName");
// 2. Send wake message
var wakeOnLan = new WakeOnLan();
wakeOnLan.Port = macAddress.Packet;
wakeOnLan.BroadcastAddress = BroadcastAddress.Parse(macAddress.Broadcast);
_logger.LogInformation($"Sending WOL Magic packet to broadcast {macAddress.Broadcast} and port {macAddress.Packet} for mac {macAddress.Mac}");
// Send!
wakeOnLan.Wake(macAddress.Mac);
}
#endregion
}
}
|
using UnityEngine;
public class RandomAnimation : MonoBehaviour
{
void Start()
{
var animator = GetComponentInChildren<Animator>();
animator.Update(Random.value);
}
}
|
using Gym.Lib.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Gym.Lib.Services.Security
{
public class AuthService : BaseService, IAuthService
{
public AuthService(gymEntities db) : base(db)
{
}
#region Utils
internal static string CalculateHash(string password)
{
var bytes = Encoding.UTF8.GetBytes(password);
var hashedPwd = HashAlgorithm.Create("MD5").ComputeHash(bytes);
return BitConverter.ToString(hashedPwd).Replace("-", "").ToLower();
}
#endregion
//public bool RegisterUser(string name, string lastname, string email, string password, out int customerId)
//{
// customerId = 0;
// if (CheckIfCustomerAlreadyExists(email))
// {
// throw new CustomerAlreadyExistsException(email);
// }
// var customer = new Customer
// {
// Email = email,
// Name = name,
// Surname = lastname,
// PasswordEncrypted = CalculateHash(password)
// };
// db.Customer.Add(customer);
// db.SaveChanges();
// customerId = customer.Id;
// return true;
//}
public string ValidateUser(string email, string password, out int userId)
{
userId = 0;
var user = db.User.FirstOrDefault(u => u.Email.ToLower() == email.ToLower());
if (user == null)
return "No User found with this email";
var hashedPwd = CalculateHash(password);
bool isValid = hashedPwd == user.PasswordEncrypted;
if (!isValid)
return "Check provided password";
userId = user.Id;
return null;
}
public User GetUserById(int userId)
{
return db.User.FirstOrDefault(c => c.Id == userId);
}
public bool CheckIfUserAlreadyExists(string email)
{
return db.User.FirstOrDefault(x => x.Email == email) != null;
}
}
}
|
using System;
using System.Net.Http;
using System.Collections.Generic;
using FbPageManager.Models;
namespace FbPageManager.Utilities
{
public static class PageManagerUtilities
{
//Currently in memory, but should be in DB.
static Dictionary<string, PageManagerSession> Sessions = new Dictionary<string, PageManagerSession>();
public static void SaveSessionInfo(string userInfo, string sessionInfo)
{
var sessionData = new PageManagerSession
{
AccessToken = (string)Newtonsoft.Json.Linq.JObject.Parse(sessionInfo)["authResponse"]["accessToken"]
};
Sessions[userInfo] = sessionData;
}
/**
* Makes a call to the Facebook APIs to create a page post, and calls the provided callback function
* when the API call is complete.
*
* Note that the callback function expects no arguments.
*
* Parameters:
* accessToken: The Facebook access token for use in querying the API
* postContent: A string representing the page post's content.
* isPublished: A boolean stating whether this is supposed to be a published post.
*
* This function should not return anything.
*/
public static void CreatePost(
string pageId,
string accessToken,
string postContent,
bool isPublished)
{
var resource = pageId + "/feed";
var data = "message=" + postContent;
if (!isPublished)
data += "&published=false";
var response = HttpUtility.PostRequest(accessToken, resource, data);
if (response != null && response.IsSuccessStatusCode)
{
var responseContent = response.Content;
var apiResponse = Newtonsoft.Json.Linq.JObject.Parse(responseContent.ReadAsStringAsync().Result);
}
}
public static void UpdatePost(
string postId,
string accessToken,
string postContent,
bool isPublished)
{
var data = "message=" + postContent;
if (isPublished)
data += "&published=true";
else
data += "&published=false";
var response = HttpUtility.PostRequest(accessToken, postId, data);
if (response != null && response.IsSuccessStatusCode)
{
var responseContent = response.Content;
var apiResponse = Newtonsoft.Json.Linq.JObject.Parse(responseContent.ReadAsStringAsync().Result);
}
}
public static PageManagerPagePostsInfo ReadUnpublishedPosts(string pageId, string accessToken, string nextPageUrl = "")
{
var result = new PageManagerPagePostsInfo();
HttpResponseMessage response = null;
if (!string.IsNullOrEmpty(nextPageUrl))
{
response = HttpUtility.GetRequest(nextPageUrl);
}
else
{
var resource = pageId + "/promotable_posts";
var filter = "is_published=false";
response = HttpUtility.GetRequest(accessToken, resource, filter);
}
if (response != null && response.IsSuccessStatusCode)
{
var responseContent = response.Content;
var apiResponse = Newtonsoft.Json.Linq.JObject.Parse(responseContent.ReadAsStringAsync().Result);
foreach (var feed in apiResponse["data"])
{
result.Data.Add(
new PageManagerPagePost
{
Message = (string)feed["message"],
DatePosted = (string)feed["created_time"],
Id = (string)feed["id"],
IsPublished = false
}
);
}
result.NextPageUrl = (apiResponse["paging"]["next"] != null ? (string)apiResponse["paging"]["next"] : null);
}
return result;
}
/**
* Makes a call to the Facebook APIs to read all posts and unpublished posts from a page, and calls the provided
* callback function when the API call is complete.
*
* Note that the callback function expects an array of objects in the following format:
* { message: "a message", datePosted: "2017-08-26 11:36:00", isPublished: false }
* (The date format doesn't need to match exactly but should include the date and time.)
*
* Parameters:
* accessToken: The Facebook access token for use in querying the API
*
* This function should not return anything.
*/
public static PageManagerPagePostsInfo ReadPost(string pageId, string accessToken, string nextPageUrl = "")
{
var result = new PageManagerPagePostsInfo();
var url = string.Empty;
HttpResponseMessage response = null;
if(!string.IsNullOrEmpty(nextPageUrl))
{
response = HttpUtility.GetRequest(nextPageUrl);
}
else{
var resource = pageId + "/posts";
var fields = "comments,message,created_time,reactions";
response = HttpUtility.GetRequest(accessToken, resource, string.Empty, fields);
}
if (response != null && response.IsSuccessStatusCode)
{
var responseContent = response.Content;
var apiResponse = Newtonsoft.Json.Linq.JObject.Parse(responseContent.ReadAsStringAsync().Result);
foreach (var feed in apiResponse["data"])
{
result.Data.Add(
new PageManagerPagePost
{
Message = (string)feed["message"],
DatePosted = (string)feed["created_time"],
Id = (string)feed["id"],
NumberOfComments = ((Newtonsoft.Json.Linq.JObject)feed["comments"] != null ? ((Newtonsoft.Json.Linq.JArray)feed["comments"]["data"]).Count : 0),
NumberOfReactions = ((Newtonsoft.Json.Linq.JObject)feed["reactions"] != null ? ((Newtonsoft.Json.Linq.JArray)feed["reactions"]["data"]).Count : 0),
IsPublished = true
}
);
}
result.NextPageUrl = (apiResponse["paging"]["next"] != null ? (string)apiResponse["paging"]["next"] : null);
}
return result;
}
public static IList<PageManagerPageInfo> GetPageList(string userInfo)
{
var result = new List<PageManagerPageInfo>();
var resource = userInfo + "/accounts";
var fields = "id,name,access_token,picture";
var response = HttpUtility.GetRequest(Sessions[userInfo].AccessToken, resource, string.Empty, fields);
if (response != null && response.IsSuccessStatusCode)
{
var responseContent = response.Content;
var apiResponse = Newtonsoft.Json.Linq.JObject.Parse(responseContent.ReadAsStringAsync().Result);
foreach (var page in apiResponse["data"])
{
result.Add(
new PageManagerPageInfo
{
Id = (string)page["id"],
Name = (string)page["name"],
AccessToken = (string)page["access_token"],
PictureUrl = (string)page["picture"]["data"]["url"]
}
);
}
}
return result;
}
public static IList<PageManagerPageInsight> GetPageSummary(string pageId, string accessToken)
{
var result = new List<PageManagerPageInsight>();
var resource = pageId + "/insights";
var filter = "metric=page_fans,page_views_total,page_total_actions,page_fan_removes_unique,page_fan_adds_unique,page_fan_adds&period=week";
var response = HttpUtility.GetRequest(accessToken, resource, filter);
if (response != null && response.IsSuccessStatusCode)
{
var responseContent = response.Content;
var apiResponse = Newtonsoft.Json.Linq.JObject.Parse(responseContent.ReadAsStringAsync().Result);
foreach (var page in apiResponse["data"])
{
var pageInsight =
new PageManagerPageInsight
{
Id = (string)page["id"],
Name = (string)page["name"],
Period = (string)page["period"],
Title = (string)page["title"],
Description = (string)page["description"]
};
pageInsight.Values = new List<ValueInfo>();
foreach (var value in page["values"])
{
var valueInfo = new ValueInfo
{
Value = (string)value["value"],
EndTime = (string)value["end_time"]
};
pageInsight.Values.Add(valueInfo);
}
result.Add(pageInsight);
}
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DungeonGame
{
class Battle
{
// public void PrintAllStats(Player player1, Attributes monster)
// {
// player1.PrintAttributes();
// Console.WriteLine(" ");
// monster.PrintAttributes();
// Console.WriteLine(" ");
// }
// public void MonsterBattle(Attributes hero, IList<Attributes> monster, int monIndex)
// {
// Keys keys = new Keys();
// while (monster[monIndex].HP > 0 && hero.HP > 0)
// {
// PrintAllStats(hero, monster);
// hero.Turn(Choice(), monster);
// if (monster.HP > 0)
// {
// monster.MonsterTurn(hero);
// IsHeroDead(hero);
// }
// }
// Console.WriteLine(monster.Name + " was killed!");
// }
// private void IsHeroDead(Attributes hero)
// {
// throw new NotImplementedException();
// }
// public int Choice()
// {
// int Choice = 0;
// string[] BattleOptions = new string[] { "Attack", "Block", "Dodge", "Item" };
// while (true)
// {
// Console.Clear();
// for (int i = 0; i < BattleOptions.Length; i++)
// {
// if (Choice == 1)
// {
// Console.ForegroundColor = ConsoleColor.Red;
// }
// Console.WriteLine("{0}-{1}", i, BattleOptions[i]);
// if (Choice == 1)
// {
// Console.ResetColor();
// }
// }
// var KeyPressed = Console.ReadKey();
// if (KeyPressed.Key == ConsoleKey.DownArrow)
// {
// if (Choice != BattleOptions.Length - 1)
// {
// Choice++;
// }
// }
// else if (KeyPressed.Key == ConsoleKey.UpArrow)
// {
// if (Choice != 0)
// {
// Choice--;
// }
// }
// if (KeyPressed.Key == ConsoleKey.Enter)
// {
// Console.Clear();
// return Choice;
// }
// }
// }
// public void PrintAttributes()
// {
// Console.WriteLine("Name:" + Name);
// Console.WriteLine("HP:" + HP);
// Console.WriteLine("AP:" + AP);
// Console.WriteLine("Symbol:" + Symbol);
// }
// internal void MonsterTurn(Attributes hero)
// {
// throw new NotImplementedException();
// }
// public void Turn(int choice, Attributes monster)
// {
// if (choice == 1)
// {
// Attack(monster);
// Console.WriteLine("You attacked " + monster.Name);
// }
// if (choice == 2)
// {
// Block(monster);
// Console.WriteLine("You block " + monster.Name + "'s attack");
// }
// if (choice == 3)
// {
// Dodge(monster);
// Console.WriteLine("You dodge " + monster.Name + "'s attack");
// }
// if (choice == 4)
// {
// useItem();
// Console.WriteLine("You used ");
// }
// }
// private void UseItem()
// {
// throw new NotImplementedException();
// }
// private void Dodge(Attributes monster)
// {
// throw new NotImplementedException();
// }
// private void Block(Attributes monster)
// {
// HP += monster.AP;
// }
// private void Attack(Attributes monster)
// {
// monster.HP -= AP;
// }
// private Attributes FindMonster()
// {
// throw new NotImplementedException();
// }
}
}
|
using System;
using doob.Scripter.Shared;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace doob.Scripter
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddScripter(this IServiceCollection services, Action<ScripterContext> options)
{
options(new ScripterContext(services));
services.TryAddTransient<EngineProvider>();
services.TryAddTransient<IScripterModuleRegistry, ScripterModuleRegistry>();
return services;
}
}
}
|
using Innouvous.Utils;
using Innouvous.Utils.MVVM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using ToDo.Client.Core.Lists;
namespace ToDo.Client.ViewModels
{
class EditListWindowViewModel : ViewModel
{
private Window window;
private TaskList existing;
public bool Cancelled { get; private set; }
public string Title
{
get
{
return (!HasExisting ? "Add" : "Edit") + " List";
}
}
public EditListWindowViewModel(Window window, TaskList existing = null)
{
this.window = window;
Cancelled = true;
if (existing != null)
LoadTaskList(existing);
}
private void LoadTaskList(TaskList list)
{
existing = list;
Name = existing.Name;
Description = existing.Description;
SelectedListType = ConvertType(existing.Type);
RaisePropertyChanged("Title");
RaisePropertyChanged("CanEditType");
}
private bool HasExisting
{
get
{
return existing != null;
}
}
private string ConvertType(ListType type)
{
switch (type)
{
case ListType.ToDo:
return ToDo;
case ListType.Project:
return Project;
default:
throw new NotSupportedException(type.ToString());
}
}
private ListType ConvertType(string type)
{
switch (type)
{
case ToDo:
return ListType.ToDo;
case Project:
return ListType.Project;
default:
throw new NotSupportedException(type);
}
}
#region Properties and Commands
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
RaisePropertyChanged();
}
}
private string description;
public string Description
{
get
{
return description;
}
set
{
description = value;
RaisePropertyChanged();
}
}
/*
public bool CanEditType
{
get
{
return HasExisting ? false : true;
}
}
*/
private const string Project = "Project";
private const string ToDo = "To Do List";
//TODO: Change to manager, allow loading
private readonly List<string> listTypes = new List<string>()
{
Project,
ToDo
};
private string selectedListType;
public string SelectedListType
{
get
{
return selectedListType;
}
set
{
selectedListType = value;
RaisePropertyChanged();
}
}
public List<string> ListTypes
{
get
{
return listTypes;
}
}
public ICommand CancelCommand
{
get
{
return new CommandHelper(() => window.Close());
}
}
public ICommand SaveCommand
{
get
{
return new CommandHelper(Save);
}
}
private void Save()
{
try
{
TaskList newList = new TaskList(Name, Description, ConvertType(SelectedListType));
var type = ConvertType(SelectedListType);
if (existing != null)
Workspace.API.UpdateList(existing, Name, Description, type);
else
Workspace.API.InsertList(Name, Description, type);
Cancelled = false;
window.Close();
}
catch (Exception e)
{
Workspace.Instance.RejectChanges();
MessageBoxFactory.ShowError(e);
}
}
#endregion
}
}
|
namespace SGDE.Domain.Converters
{
#region Using
using System.Collections.Generic;
using System.Linq;
using Entities;
using ViewModels;
#endregion
public class RoleConverter
{
public static RoleViewModel Convert(Role role)
{
if (role == null)
return null;
var roleViewModel = new RoleViewModel
{
id = role.Id,
addedDate = role.AddedDate,
modifiedDate = role.ModifiedDate,
iPAddress = role.IPAddress,
name = role.Name
};
return roleViewModel;
}
public static List<RoleViewModel> ConvertList(IEnumerable<Role> roles)
{
return roles?.Select(role =>
{
var model = new RoleViewModel
{
id = role.Id,
addedDate = role.AddedDate,
modifiedDate = role.ModifiedDate,
iPAddress = role.IPAddress,
name = role.Name
};
return model;
})
.ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication.Core.IService;
namespace WebApplication.Service
{
public class UserService : IUserService
{
public string Welcome()
{
return "Hai";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PresenterLibrary.Common;
namespace PresenterLibrary.Views
{
public interface IRemindAddingView:IView
{
TimeSpan? RemindAfterBefore { get; set; }
DateTime RemindUntil { get; set; }
RemindRadioValues HowToRemind { get; set; }
int SelectedValue { get; }
event EventHandler AddRemind;
event Action<int> DeleteRemind;
event EventHandler Back;
event Action<int> PanelConfirm;
event EventHandler PanelBack;
void AdditemToReminders(DateTime RemindDate);
void RemoveSelectedItem_From_RemindersList(int RemoveIndex);
void FirstPanelInitialization(int WhichOne, string[] ComboElementsIn = null);
//void SetTimersList(string El, List<ModelMVPDataBasePart.EventTimeTable> BindList);
}
}
|
#region 版本说明
/*****************************************************************************
*
* 项 目 :
* 作 者 : 李金坪
* 创建时间 : 2014/11/18 13:31:16
*
* Copyright (C) 2008 - 鹏业软件公司
*
*****************************************************************************/
#endregion
using System;
using System.Collections;
using System.Text;
using Castle.Windsor;
using NUnit.Framework;
using PengeSoft.Data;
using PengeSoft.Enterprise.Appication;
using PengeSoft.WorkZoneData;
using PengeSoft.Common;
using PengeSoft.Common.Exceptions;
using PengeSoft.Auther;
using PengeSoft.Auther.RightCheck;
using PengeSoft.CMS.BaseDatum;
namespace PengeSoft.CMS.BaseDatumTest
{
[TestFixture]
public class ModelInfoServerSvrTest
{
private IWindsorContainer _container;
private IModelInfoServerSvr _svr;
private IRightCheck _auther;
[SetUp]
public void SetUp()
{
if (_container == null)
{
_container = ComponentManager.GetInstance();
//_container.AddComponent("ModelInfoServer", typeof(IModelInfoServer), typeof(ModelInfoServer));
}
_auther = (IRightCheck)_container[typeof(IRightCheck)];
_auther.Active = true;
_svr = (IModelInfoServerSvr)_container[typeof(IModelInfoServerSvr)];
//_auther = new AutherUseRightCheck();
//_auther.Login("127.0.0.1", "zprk", "");
}
[TearDown]
public void Finished()
{
_svr = null;
}
/// <summary>
/// 获取模块列表
/// </summary>
[Test]
void GetModelList()
{
Console.WriteLine("GetModelList未实现");
/*
string Uid = "";
string PageName = "";
ModelInfoList ret = _svr.GetModelList(Uid, PageName);
//Assert.IsNotNull(ret, "执行失败");
*/
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JogoDaVelha;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace JogoDaVelhaWebAPI.Controllers
{
[Produces("application/json")]
[Route("api/JogoDaVelha")]
public class JogoDaVelhaController : Controller
{
static TabuleiroJogo Jogo { get; set; }
[HttpGet("{jogador}/{posX}/{posY}")]
public String Jogar(int jogador, int posX, int posY)
{
Jogo.Jogar(jogador, posX, posY);
switch (Jogo.VerificarGanhador())
{
case 0:
return "Jogo em andamento!";
case -1:
return "Jogo terminou empatado!";
case 1:
return "Jogador 1 venceu!";
case 2:
return "Jogador 2 venceu!";
}
return "";
}
[HttpGet("Reset")]
public String Reiniciar()
{
Jogo = new TabuleiroJogo();
return "Jogo Reiniciado!";
}
[HttpGet()]
public TabuleiroJogo Get()
{
return Jogo;
}
}
} |
namespace DxMessaging.Core.MessageBus
{
using Core;
using System;
using Messages;
using UnityEngine;
/// <summary>
/// Description of a general purpose message bus that provides both registration, de-registration, and broadcast capabilities
/// </summary>
public interface IMessageBus
{
/// <summary>
/// The registration log of all messaging registrations for this MessageBus.
/// </summary>
RegistrationLog Log { get; }
/// <summary>
/// Registers the specified MessageHandler to receive UntargetedMessages of the specified type.
/// </summary>
/// <typeparam name="T">Specific type of UntargetedMessages to register for.</typeparam>
/// <param name="messageHandler">MessageHandler to register to accept UntargetedMessages of the specified type.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to receive messages.</returns>
Action RegisterUntargeted<T>(MessageHandler messageHandler) where T : IUntargetedMessage;
/// <summary>
/// Registers the specified MessageHandler to receive TargetedMessages of the specified type.
/// The message will only be routed to the properly identified MessageHandler.
/// </summary>
/// <typeparam name="T">Specific type of TargetedMessages to register for.</typeparam>
/// <param name="messageHandler">MessageHandler to register to accept TargetedMessages of the specified type.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to receive messages.</returns>
Action RegisterTargeted<T>(MessageHandler messageHandler) where T : ITargetedMessage;
/// <summary>
/// Registers the specified MessageHandler to receive TargetedMessages of the specified type for the specified target.
/// </summary>
/// <typeparam name="T">Specific type of TargetedMessages to register for.</typeparam>
/// <param name="target">Target of messages to listen for.</param>
/// <param name="messageHandler">MessageHandler to register the TargetedMessages of the specified type.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to receive the messages.</returns>
Action RegisterTargeted<T>(InstanceId target, MessageHandler messageHandler) where T : ITargetedMessage;
/// <summary>
/// Registers the specified MessageHandler to receive TargetedMessages of the specified type.
/// This registration IGNORES the targeting of the TargetedMessage.
/// </summary>
/// <typeparam name="T">Specific type of TargetedMessages to register for.</typeparam>
/// <param name="messageHandler">MessageHandler to register to accept all TargetedMessages of the specified type.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to receive messages.</returns>
Action RegisterTargetedWithoutTargeting<T>(MessageHandler messageHandler) where T : ITargetedMessage;
/// <summary>
/// Registers the specified MessageHandler to receive BroadcastMessages of the specified type from the provided source.
/// </summary>
/// <typeparam name="T">Type of the BroadcastMessage to register.</typeparam>
/// <param name="source">InstanceId of the source for BroadcastMessages to listen to.</param>
/// <param name="messageHandler">MessageHandler to register to accept BroadcastMessages.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to receive messages.</returns>
Action RegisterSourcedBroadcast<T>(InstanceId source, MessageHandler messageHandler) where T : IBroadcastMessage;
/// <summary>
/// Registers the specified MessageHandler to receive BroadcastMessages of the specified type from ALL sources.
/// This registration IGNORES the source of the BroadcastMessage.
/// </summary>
/// <typeparam name="T">Type of the BroadcastMessage to register.</typeparam>
/// <param name="messageHandler">MessageHandler to register to accept BroadcastMessages.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to receive messages.</returns>
Action RegisterSourcedBroadcastWithoutSource<T>(MessageHandler messageHandler) where T : IBroadcastMessage;
/// <summary>
/// Registers the specified MessageHandler to receive ALL messages.
/// It doesn't matter if the message is Targeted or Untargeted, this MessageHandler will be invoked for it.
/// </summary>
/// <param name="messageHandler">MessageHandler to register to accept all messages.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to receive messages.</returns>
Action RegisterGlobalAcceptAll(MessageHandler messageHandler);
/// <summary>
/// Registers the specified MessageHandler and transformer function as an interceptor for Messages of type T.
/// Whenever messages of that type are sent, interceptors will be ran in order, transforming that message into
/// new, mutated types. The message at the end of the transformations will be then sent to registered message handlers.
/// </summary>
/// <note>
/// Transformer function can return null to "cancel" the message being sent.
/// </note>
/// <typeparam name="T">Type of message to intercept.</typeparam>
/// <param name="transformer">Transformation function to run on messages of the chosen type.</param>
/// <returns>The de-registration action. Should be invoked when the handler no longer wants to intercept messages.</returns>
Action RegisterIntercept<T>(Func<T, T> transformer) where T : IMessage;
/// <summary>
/// Broadcasts an Untargeted message to all listeners registered to this bus.
/// </summary>
/// <param name="typedMessage">Message to broadcast.</param>
void UntargetedBroadcast(IUntargetedMessage typedMessage);
/// <summary>
/// Broadcasts a TargetedMessage to all listeners registered to this bus.
/// </summary>
/// <param name="target">Target to send the message to.</param>
/// <param name="typedMessage">Message to broadcast.</param>
void TargetedBroadcast(InstanceId target, ITargetedMessage typedMessage);
/// <summary>
/// Broadcasts a BroadcastMessage to all listeners registered to this bus.
/// </summary>
/// <param name="source">Source of the message.</param>
/// <param name="typedMessage">Message to broadcast.</param>
void SourcedBroadcast(InstanceId source, IBroadcastMessage typedMessage);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManageAppleStore_DTO
{
public class EmployeesDTO : PersonDTO
{
private string _StrPassword;
private string _StrEmployeeOfTypeID;
private decimal _DecSalary;
public EmployeesDTO() : base()
{
_StrPassword = string.Empty;
_StrEmployeeOfTypeID = string.Empty;
_DecSalary = 0;
}
public EmployeesDTO(string strID, string strFullName, int iIDCard, string strNumberPhone, string strEmail, DateTime dTBirthDay, string strGender, string strAddress, bool bStatus, string strPassword, string strEmployeeOfTypeID, decimal decSalary) : base(strID, strFullName, iIDCard, strNumberPhone, strEmail, dTBirthDay, strGender, strAddress, bStatus)
{
_StrPassword = strPassword;
_StrEmployeeOfTypeID = strEmployeeOfTypeID;
_DecSalary = decSalary;
}
public string StrPassword { get => _StrPassword; set => _StrPassword = value; }
public string StrEmployeeOfTypeID { get => _StrEmployeeOfTypeID; set => _StrEmployeeOfTypeID = value; }
public decimal DecSalary { get => _DecSalary; set => _DecSalary = value; }
}
}
|
namespace PurificationPioneer.Network.Const
{
public static class ServiceType
{
public const int Auth = 1;
public const int System = 2;
public const int Logic = 3;
}
} |
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Windows;
using System.Windows.Input;
using JetBrains;
using KaVE.Commons.Utils.IO;
using KaVE.VS.FeedbackGenerator.Utils.Logging;
namespace KaVE.VS.FeedbackGenerator.UserControls.TrayNotification
{
/// <summary>
/// Interaction logic for HardBalloonPopup.xaml
/// </summary>
public partial class HardBalloonPopup
{
public HardBalloonPopup(ILogManager logManager)
{
InitializeComponent();
SetPopupMessage(logManager);
}
private void SetPopupMessage(ILogManager logManager)
{
var size = logManager.LogsSizeInBytes.FormatSizeInBytes();
Message.Text = Properties.PopupNotification.InformationHardpopup.FormatEx(size);
}
private void Wizard_Button_OnClick(object sender, RoutedEventArgs e)
{
OpenUploadWizard();
}
private void ImgClose_MouseDown(object sender, MouseButtonEventArgs e)
{
ClosePopup();
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.EntityFrameworkCore;
using BlockchainAppAPI.DataAccess.Configuration;
using BlockchainAppAPI.Models.Configuration;
using BlockchainAppAPI.Models.Search;
namespace BlockchainAppAPI.Logic.Search
{
public class SearchCompiler
{
private SystemContext _context;
public SearchCompiler(SystemContext context)
{
this._context = context;
}
public async Task<SearchObject> Compile(string searchName)
{
SearchObject search = await this._context.SearchObjects.
Include(so => so.Selections).
Where(so => so.Name == searchName).
FirstOrDefaultAsync();
List<string> fieldList = this.compileFieldList(search);
string selectClause = this.compileSelectClause(search);
string fromClause = this.compileFromClause(search);
string whereClause = this.compileWhereClause(search);
string groupByClause = this.compileGroupByClause(search);
string orderByClause = this.compileOrderByClause(search);
search.CompiledQuery = $@"
SELECT {selectClause}
FROM {fromClause}
{(whereClause != null ? $"WHERE {whereClause}" : "")}
{(groupByClause != null ? $"GROUP BY {groupByClause}" : "")}
ORDER BY {orderByClause}
OFFSET @start ROWS
FETCH NEXT (@end - @start + 1) ROWS ONLY
";
if(groupByClause != null) {
search.CompiledCountQuery = $@"
SELECT COUNT(*)
FROM (
SELECT {selectClause}
FROM {fromClause}
{(whereClause != null ? $"WHERE {whereClause}" : "")}
GROUP BY {groupByClause}
) t1
";
}
else {
search.CompiledCountQuery = $@"
SELECT COUNT(*)
FROM {fromClause}
{(whereClause != null ? $"WHERE {whereClause}" : "")}
";
}
search.CompiledFieldList = fieldList;
search.IsValid = true;
return search;
}
private List<string> compileFieldList(SearchObject search)
{
List<Selection> selections = search.Selections;
return selections.Select(s => {
return $"{s.ObjectFieldName}";
}).ToList();
}
private string compileSelectClause(SearchObject search)
{
List<Selection> selections = search.Selections;
return String.Join(
",",
selections.Select(s => {
if(s.Aggregate != null && s.Aggregate.Trim() != "") {
return $"{s.Aggregate}([{s.ObjectFieldName}]) as [{s.Aggregate}_{s.ObjectFieldName}]";
}
return $"[{s.ObjectFieldName}] as [{s.ObjectFieldName}]";
}
));
}
private string compileFromClause(SearchObject search)
{
return $"{search.ModuleName}_{search.ObjectName}";
}
private string compileWhereClause(SearchObject search)
{
return null;
}
private string compileGroupByClause(SearchObject search)
{
if(!search.Selections.Exists(s =>
s.Aggregate != null &&
s.Aggregate.Trim() != ""
)) {
return null;
}
List<Selection> selections = search.Selections.Where(s =>
s.Aggregate == null ||
s.Aggregate.Trim() == ""
).ToList();
return String.Join(
",",
selections.Select(s => {
return $"[{s.ObjectFieldName}]";
}
));
}
private string compileOrderByClause(SearchObject search)
{
return search.Selections.First().ObjectFieldName + " ASC";
}
}
} |
using UnityEngine;
namespace Riggingtools.Skeletons
{
// ELF From VOLA source
public class FrameTimeSource : MonoBehaviour
{
// Start is called before the first frame update
[Tooltip("Current frame playing")]
public int frame = 0;
[Tooltip("Frame to start from")]
public int start_frame = 0;
[Tooltip("End frame (inclusive)")]
public int end_frame = 0;
[Tooltip("Framerate")]
public float frames_per_second = 30.0f;
public bool looping = true;
[Tooltip("How long to delay when looping, in seconds")]
public float loop_delay = 1.0f;// loop delay in seconds
[Tooltip("Delay countdown, in seconds")]
public float loop_delay_countdown = 1.0f;
public bool paused = false;
public bool random = false;
[Tooltip("Show default player control buttons on the top left of the UI.")]
public bool ShowGUIButtons = true;
System.Random rng = new System.Random();
float t = 0;// keeps fractional time
int updated_frame = 0;
void MyUpdate()
{
if (!Application.isPlaying) return;
if (Time.frameCount == updated_frame) return;
updated_frame = Time.frameCount;
if (paused) return;
if (random)
{
frame = rng.Next(start_frame, end_frame + 1);
}
float dt = Time.deltaTime;
if (loop_delay_countdown > 0.0f)
{
loop_delay_countdown -= dt;
return;
}
else
{
// adjust overshoot
dt += loop_delay_countdown;
loop_delay_countdown = 0.0f;
}
float fps = frames_per_second;
bool backwards = false;
if (fps < 0)
{
fps = -fps;
backwards = true;
}
if (fps < 1E-6) return;
t += dt;
int d_frame = (int)Mathf.Floor(t * fps);
t -= d_frame / fps;
frame += backwards ? -d_frame : d_frame;
if (frame < start_frame)
{
frame = end_frame;
loop_delay_countdown = loop_delay;
}
else
if (frame > end_frame)
{
frame = start_frame;
loop_delay_countdown = loop_delay;
}
}
void Start()
{
frame = start_frame;
}
// Update is called once per frame
void Update()
{
if (Application.isPlaying)
{
MyUpdate();
if (Input.GetKeyDown("space"))
{
paused = !paused;
}
}
}
public void MovePlayersToFrame(int Sentframe)
{
frame = Sentframe;
//MovePlayers();
}
public int GetFrame()
{
MyUpdate();
return frame;
}
public void OnGUI()
{
if (!ShowGUIButtons) return;
GUILayout.BeginVertical("Box");
if (GUILayout.Button(paused ? "Resume" : "Pause"))
{
paused = !paused;
}
if (GUILayout.Button("Play 1 fps"))
{
paused = false;
frames_per_second = 1;
}
if (GUILayout.Button("Play 5 fps"))
{
paused = false;
frames_per_second = 5;
}
if (GUILayout.Button("Play 30 fps"))
{
paused = false;
frames_per_second = 30;
}
if (GUILayout.Button("+1 frame"))
{
frame += 1;
if (frame >= end_frame) frame = start_frame;
}
if (GUILayout.Button("-1 frame"))
{
frame -= 1;
if (frame < start_frame) frame = end_frame;
}
GUILayout.EndVertical();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DungeonGame
{
class Collision
{
/// <summary>
/// Checks whether or not the hero is touching a border or wall.
/// </summary>
/// <param name="heroX"></param>
/// <param name="heroY"></param>
/// <param name="walls"></param>
/// <returns></returns>
public bool checkHeroWall(int heroX, int heroY, IList<Obstacles[]> walls, int borderX, int borderY)
{
// Checks if Hero is touching a wall (not border)
for (int i = 0; i < walls.Count; i++)
{
for(int j = 0; j < walls[i].Length; j++)
if (heroX.Equals(walls[i][j].X) && heroY.Equals(walls[i][j].Y) || heroX.Equals(walls[i][j].X2) && heroY.Equals(walls[i][j].Y))
return true;
}
// Checks Top border
for(int i = 0; i < (borderX + 5); i++)
{
if (heroX.Equals(i) && heroY.Equals(5)) // I don't like hardcoding 5
return true;
}
// Checks Bottom border
for (int i = 0; i < (borderX + 5); i++)
{
if (heroX.Equals(i) && heroY.Equals(borderY + 4)) // I don't like hardcoding 4.
return true;
}
// Checks Left border
for (int i = 0; i < (borderY + 5); i++)
{
if (heroX.Equals(5) && heroY.Equals(i)) // I don't like hardcoding 5.
return true;
}
// Checks Right border
for (int i = 0; i < (borderY + 5); i++)
{
if (heroX.Equals(borderX + 5) && heroY.Equals(i)) // I don't like hardcoding 5.
return true;
}
return false;
}
/// <summary>
/// Checks if a monster and hero are on the same X Y position.
/// If so it returns true. This will start a battle.
/// </summary>
/// <param name="monster"></param>
/// <param name="heroX"></param>
/// <param name="heroY"></param>
/// <returns></returns>
public bool checkHeroMon(IList<Attributes> monster, int heroX, int heroY)
{
for (int i = 0; i < monster.Count; i++)
{
if (heroX.Equals(monster[i].X) && heroY.Equals(monster[i].Y))
return true;
}
return false;
}
/// <summary>
/// Checks to see if the monster is at the same position a the wall.
/// If the monster is at the same position as a wall, the monster can't pass.
/// </summary>
/// <param name="monster"></param>
/// <param name="heroX"></param>
/// <param name="heroY"></param>
/// <param name="walls"></param>
/// <param name="borderX"></param>
/// <param name="borderY"></param>
/// <returns></returns>
public bool checkMonsterWall(IList<Attributes> monster, int heroX, int heroY, IList<Obstacles[]> walls, int borderX, int borderY)
{
// Checks Top Border
for (int i = 0; i < (borderX + 5); i++)
{
for(int j = 0; j < monster.Count; j++)
if (monster[j].X.Equals(i) && monster[j].Equals(5)) // I don't like hardcoding 5
return true;
}
// Checks Bottom Border
for (int i = 0; i < (borderX + 5); i++)
{
for (int j = 0; j < monster.Count; j++)
if (monster[j].X.Equals(i) && monster[j].Equals(borderY + 4))
return true;
}
// Checks Left border
for (int i = 0; i < (borderY + 5); i++)
{
for (int j = 0; j < monster.Count; j++)
if (monster[j].X.Equals(5) && monster[j].Equals(i))
return true;
}
// Checks Right border
for (int i = 0; i < (borderY + 5); i++)
{
for (int j = 0; j < monster.Count; j++)
if (monster[j].X.Equals(borderX + 5) && monster[j].Equals(i))
return true;
}
// Checks if a monstser is touching another monster
for (int i = 0; i < monster.Count; i++)
{
for(int j = 0; j < monster.Count - 1; j++)
{
if(i!=j)
{
if (monster[i].X.Equals(monster[j].X) && monster[i].Y.Equals(monster[j].Y))
return true;
}
}
}
// Checks if monster is touching a wall (not border)
for (int i = 0; i < walls.Count; i++)
{
for (int j = 0; j < walls[i].Length; j++)
{
for (int k = 0; k < monster.Count; k++)
{
// Changed this TODO
if (monster[k].X.Equals(walls[i][j].X) && monster[k].Y.Equals(walls[i][j].Y) || monster[k].X.Equals(walls[i][j].X2) && monster[k].Y.Equals(walls[i][j].Y))
return true;
}
}
}
return false;
}
/// <summary>
/// Checks if the walls are touching other walls before it actually
/// saves or prints the wall. This also checks to make sure that each
/// wall has an opening to allow monsters or players to get through.
/// </summary>
/// <param name="walls"></param>
/// <param name="wallX"></param>
/// <param name="wallY"></param>
/// <returns></returns>
public bool checkWall(IList<Obstacles[]> walls, int wallX, int wallY)
{
for (int i = 0; i < walls.Count; i++)
{
for (int j = 0; j < walls[i].Length; j++)
{
for (int k = 0; k < 10; k++)
{
if (walls[i][j].X.Equals(wallX) && walls[i][j].Y.Equals(wallY))
return true;
if(walls[i][j].X2.Equals(wallX) && walls[i][j].Y.Equals(wallY))
return true;
if ((walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1)))
return true;
if ((walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1)))
return true;
if ((walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1)))
return true;
if ((walls[i][j].X.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1)) || (walls[i][j].X.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1)))
return true;
if ((walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1)) || (walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1)))
return true;
if ((walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1)))
return true;
if ((walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY + 1)) || (walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY + 1)))
return true;
if ((walls[i][j].X2.Equals(wallX - 1) && walls[i][j].Y.Equals(wallY - 1)) || (walls[i][j].X2.Equals(wallX + 1) && walls[i][j].Y.Equals(wallY - 1)))
return true;
}
}
}
return false;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
float eDlay;
float dTimer;
public GameObject enemyPrefab;
// Start is called before the first frame update
void Start()
{
eDlay = 2;
dTimer = 0;
}
// Update is called once per frame
void Update()
{
dTimer += Time.deltaTime;
if (dTimer >= eDlay)
{
dTimer -= eDlay;
float enemySapwnRand = Random.Range(-8,8);
Instantiate(enemyPrefab, new Vector3(enemySapwnRand, 6, 0),Quaternion.identity);
//랜덤한 x좌표 위치에서 에너미를 생성한다
}
}
}
|
/*
* Copyright (c) The Game Learner
* https://connect.unity.com/u/rishabh-jain-1-1-1
* https://www.linkedin.com/in/rishabh-jain-266081b7/
*
* created on - #CREATIONDATE#
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
[RequireComponent(typeof(Collider))]
public class DoubleLazerTurretHandler : MonoBehaviour,IGridObject
{
public float ratationSpeed = 5;
public int lazerSize = 5;
public Transform turretTrans;
public float lazerHeight = 0.5f;
private Collider myCollider;
private LineRenderer lazerLine;
private Vector3 startLazerPoint;
private Vector3 endLazerPoint;
private Vector3 lazerOrigin;
#region IgridObject
int index;
int x;
int y;
public int GetIndex()
{
return index;
}
public string GetJsonData()
{
return "";
}
public void GetXY(out int x, out int y)
{
x = this.x;
y = this.y;
}
public void Initialize(string jsonData)
{
}
public void SetIndex(int index)
{
this.index = index;
}
public void SetXY(int x, int y)
{
this.x = x;
this.y = y;
}
#endregion
private void Start()
{
myCollider = GetComponent<Collider>();
lazerLine = GetComponent<LineRenderer>();
startLazerPoint = new Vector3();
endLazerPoint = new Vector3();
lazerOrigin = turretTrans.position;
lazerOrigin.y = lazerHeight;
}
void Update()
{
if (turretTrans.gameObject.activeSelf)
{
turretTrans.Rotate(Vector3.up, ratationSpeed * Time.deltaTime);
startLazerPoint = turretTrans.position + (turretTrans.forward * lazerSize);
startLazerPoint.y = lazerHeight;
endLazerPoint = turretTrans.position + (turretTrans.forward * lazerSize * -1);
endLazerPoint.y = lazerHeight;
CheckLazerLength();
lazerLine.SetPosition(0, startLazerPoint);
lazerLine.SetPosition(1, endLazerPoint);
}
}
void CheckLazerLength()
{
RaycastHit startHitPoint;
if(Physics.Raycast(lazerOrigin, turretTrans.forward, out startHitPoint, lazerSize))
{
startLazerPoint = startHitPoint.point;
if(startHitPoint.collider.transform == GameSettings.instance.playerTransform){
GameManager.instance.GameOver();
}
}
RaycastHit endHitPoint;
if (Physics.Raycast(lazerOrigin, (-1 * turretTrans.forward), out endHitPoint, lazerSize))
{
endLazerPoint = endHitPoint.point;
if(endHitPoint.collider.transform == GameSettings.instance.playerTransform){
GameManager.instance.GameOver();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CCC
{
}
public class csProperty : MonoBehaviour
{
private int health = 30;
//Property
public int Health
{
get
{
return health;
}
private set
{
health = value;
}
}
// Start is called before the first frame update
void Start()
{
print(Health);
Health = 50;
print(Health);
//(cf) MonoBehaviour 이거 때문에 null 나온다...
csCsharpStudy aaa = new csCsharpStudy();
Debug.Log(aaa);
// 마찬가지
csProperty bbb = new csProperty();
Debug.Log(bbb);
CCC ccc = new CCC();
Debug.Log(ccc);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace filter.framework.utility
{
/// <summary>
/// 哈希加密
/// </summary>
public sealed class HashHelper
{
private static MD5 md5MD5Algorithm;
private static SHA1 sha1Algorithm;
/// <summary>
/// MD5算法
/// </summary>
private static MD5 MD5Algorithm
{
get
{
if (md5MD5Algorithm == null)
{
md5MD5Algorithm = new MD5CryptoServiceProvider();
}
return md5MD5Algorithm;
}
}
private static SHA1 SHA1Algorithm
{
get
{
if (sha1Algorithm == null)
{
sha1Algorithm = new SHA1CryptoServiceProvider();
}
return sha1Algorithm;
}
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="content"></param>
/// <returns>加密后的Base64编码</returns>
public static string MD5(string content)
{
var result = GetHash(content, MD5Algorithm);
return result == null ? string.Empty : Convert.ToBase64String(result);
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="content"></param>
/// <returns>加密后返回十六进制数据</returns>
public static string MD5Hex(string content)
{
var result = GetHash(content, MD5Algorithm);
return result == null ? string.Empty : ToHex(result);
}
/// <summary>
/// SHA1加密
/// </summary>
/// <param name="content"></param>
/// <returns>加密后的Base64编码</returns>
public static string SHA1(string content)
{
var result = GetHash(content, SHA1Algorithm);
return result == null ? string.Empty : Convert.ToBase64String(result);
}
/// <summary>
/// SHA1加密
/// </summary>
/// <param name="content"></param>
/// <returns>加密后的十六进制数据</returns>
public static string SHA1Hex(string content)
{
var result = GetHash(content, MD5Algorithm);
return result == null ? string.Empty : ToHex(result);
}
private static byte[] GetHash(string content, HashAlgorithm hashAlgorithm)
{
if (hashAlgorithm != null)
{
byte[] data = Encoding.UTF8.GetBytes(content);
return hashAlgorithm.ComputeHash(data);
}
return null;
}
private static string ToHex(byte[] bytes)
{
if (bytes != null)
{
StringBuilder builder = new StringBuilder();
foreach (var b in bytes)
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
return null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PopUpMessage : MonoBehaviour
{
public Text text;
public Text textTransparent;
public float scaleFactor = 1.0f;
public float lifeTime = 1.5f;
// Start is called before the first frame update
void Start()
{
Destroy(gameObject, lifeTime);
}
// Update is called once per frame
void Update()
{
scaleTextOverTime();
}
void scaleTextOverTime()
{
RectTransform rect = textTransparent.rectTransform;
rect.localScale = new Vector3(rect.localScale.x + scaleFactor*Time.deltaTime, rect.localScale.y + scaleFactor * Time.deltaTime, rect.localScale.z);
textTransparent.color = new Color(textTransparent.color.r, textTransparent.color.g, textTransparent.color.b, textTransparent.color.a - scaleFactor * 2 * Time.deltaTime);
text.color = new Color(text.color.r, text.color.g, text.color.b, text.color.a - scaleFactor * 0.8f * Time.deltaTime);
}
public void setText(string newText)
{
text.text = newText;
textTransparent.text = newText;
}
}
|
using Shop.Data.DataModels;
using Shop.Data.Repozitory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shop.Data
{
public interface IUnitOfWork
{
void Save();
EFClientRepository EFClientRepository { get;}
EFTransacyionRepository EFTransacyionRepository { get; }
EFCategoryRepository EFCategoryRepository { get; }
}
public class UnitOfWork:IDisposable,IUnitOfWork
{
private bool disposed = false;
private ShopDataModel context = new ShopDataModel();
private EFClientRepository _eFClientRepository;
private EFTransacyionRepository _eFTransacyionRepository;
private EFCategoryRepository _eFCategoryRepository;
public virtual EFClientRepository EFClientRepository
{
get
{
if (_eFClientRepository == null)
{
_eFClientRepository = new EFClientRepository(context);
}
return _eFClientRepository;
}
}
public EFTransacyionRepository EFTransacyionRepository
{
get
{
if (_eFTransacyionRepository == null)
{
_eFTransacyionRepository = new EFTransacyionRepository(context);
}
return _eFTransacyionRepository;
}
}
public virtual EFCategoryRepository EFCategoryRepository
{
get
{
if (_eFCategoryRepository == null)
{
_eFCategoryRepository = new EFCategoryRepository(context);
}
return _eFCategoryRepository;
}
}
public void Save()
{
context.SaveChanges();
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RabbitMQ.Producer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Whatsdown_Location_Service.Logic;
using Whatsdown_Location_Service.Model;
namespace Whatsdown_Location_Service.Controllers
{
[Route("api/location")]
[ApiController]
public class LocationController : ControllerBase
{
LocationLogic logic;
RabbitMQProducer mQProducer;
ILogger logger;
public LocationController(ILogger<LocationController> logger)
{
this.logic = new LocationLogic();
this.logger = logger;
/* this.mQProducer = new RabbitMQProducer("amqp://guest:guest@localhost:5672");*/
}
[HttpGet]
public async Task<IActionResult> GetLocationFromIp(string ip)
{
IActionResult response;
try
{
this.logger.LogDebug($"Attempting to get location from ip: {1}", ip);
string result = await logic.GetLocationFromIPAsync(ip);
/* mQProducer.Publish(fox);*/
response = Ok(new { response = result });
return response;
}
catch (ArgumentException ex)
{
return BadRequest(ex.Message);
}catch(Exception ex)
{
return Unauthorized();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Colors;
[assembly: CommandClass(typeof(ASI_DOTNET.Column))]
[assembly: CommandClass(typeof(ASI_DOTNET.Truss))]
[assembly: CommandClass(typeof(ASI_DOTNET.Frame))]
[assembly: CommandClass(typeof(ASI_DOTNET.Beam))]
[assembly: CommandClass(typeof(ASI_DOTNET.Rail))]
[assembly: CommandClass(typeof(ASI_DOTNET.Stair))]
[assembly: CommandClass(typeof(ASI_DOTNET.Ladder))]
namespace ASI_DOTNET
{
class Column
{
// Auto-impl class properties
private Database db;
public double height { get; private set; }
public double width { get; private set; }
public double baseHeight { get; set; }
public double baseWidth { get; private set; }
public string name { get; private set; }
public string layerName { get; set; }
public ObjectId id { get; private set; }
// Other class properties
private string baseOrient;
public string baseplateOrientation
{
get { return baseOrient; }
set
{
this.baseOrient = value;
if (baseHeight > 0) this.name = "Column - " + height + "in - " + width + "x" + baseWidth + " (" + value + ")";
else this.name = "Column - " + height + "x" + width + " (" + value + ")";
}
}
// Public constructor
public Column(Database db,
double height,
double width,
double baseWidth)
{
Color layerColor;
this.db = db;
this.height = height;
this.width = width;
this.baseWidth = baseWidth;
// Set defaults
this.baseHeight = 0.75;
// Set name and column layer
if (baseHeight > 0)
{
this.name = "Column - " + height + "in - " + width + "x" + baseWidth;
this.layerName = "3D-Mezz-Column";
layerColor = Utils.ChooseColor("black");
}
else
{
this.name = "Column - " + height + "x" + width;
this.layerName = "3D-Rack-Column";
layerColor = Utils.ChooseColor("teal");
}
// Create column layer (if necessary)
Utils.CreateLayer(db, layerName, layerColor);
}
public void Build()
{
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
if (acBlkTbl.Has(name))
{
// Retrieve object id
this.id = acBlkTbl[name];
}
else
{
// Create new block (record)
using (BlockTableRecord acBlkTblRec = new BlockTableRecord())
{
acBlkTblRec.Name = name;
// Set the insertion point for the block
acBlkTblRec.Origin = new Point3d(0, 0, 0);
// Calculate locations
Vector3d cVec = Point3d.Origin.GetVectorTo(
new Point3d(width / 2, width / 2, (height + baseHeight) / 2));
Vector3d bVec = BaseplateLocation(baseOrient, baseWidth, width, baseHeight);
if (baseHeight > 0)
{
// Create the 3D solid baseplate
Solid3d bPlate = new Solid3d();
bPlate.SetDatabaseDefaults();
bPlate.CreateBox(baseWidth, baseWidth, baseHeight);
// Position the baseplate
bPlate.TransformBy(Matrix3d.Displacement(bVec));
// Set block object properties
Utils.SetObjectProperties(bPlate);
// Add baseplate to block
acBlkTblRec.AppendEntity(bPlate);
}
// Create the 3D solid column
Solid3d column = new Solid3d();
column.SetDatabaseDefaults();
column.CreateBox(width, width, height - baseHeight);
// Position the column
column.TransformBy(Matrix3d.Displacement(cVec));
// Set block object properties
Utils.SetObjectProperties(column);
// Add column to block
acBlkTblRec.AppendEntity(column);
/// Add Block to Block Table and close Transaction
acBlkTbl.UpgradeOpen();
acBlkTbl.Add(acBlkTblRec);
acTrans.AddNewlyCreatedDBObject(acBlkTblRec, true);
}
// Set block id property
this.id = acBlkTbl[name];
}
// Save the new object to the database
acTrans.Commit();
}
}
private static Vector3d BaseplateLocation(string baseOrient,
double baseWidth,
double columnWidth,
double baseHeight)
{
Point3d middle;
switch (baseOrient)
{
case "+X":
middle = new Point3d(baseWidth / 2, columnWidth / 2, baseHeight / 2);
break;
case "-X":
middle = new Point3d(columnWidth - (baseWidth / 2), columnWidth / 2, baseHeight / 2);
break;
case "+Y":
middle = new Point3d(columnWidth / 2, baseWidth / 2, baseHeight / 2);
break;
case "-Y":
middle = new Point3d(columnWidth / 2, columnWidth - (baseWidth / 2), baseHeight / 2);
break;
case "+X+Y":
middle = new Point3d(baseWidth / 2, baseWidth / 2, baseHeight / 2);
break;
case "+X-Y":
middle = new Point3d(baseWidth / 2, columnWidth - (baseWidth / 2), baseHeight / 2);
break;
case "-X+Y":
middle = new Point3d(columnWidth - (baseWidth / 2), baseWidth / 2, baseHeight / 2);
break;
case "-X-Y":
middle = new Point3d(columnWidth - (baseWidth / 2), columnWidth - (baseWidth / 2), baseHeight / 2);
break;
default:
middle = new Point3d(columnWidth / 2, columnWidth / 2, baseHeight / 2);
break;
}
return Point3d.Origin.GetVectorTo(middle);
}
[CommandMethod("ColumnPrompt")]
public static void ColumnPrompt()
{
// Get the current document and database, and start a transaction
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Prepare prompt for the column height
PromptDoubleResult cHeightRes;
PromptDistanceOptions cHeightOpts = new PromptDistanceOptions("");
cHeightOpts.Message = "\nEnter the column height: ";
cHeightOpts.DefaultValue = 96;
cHeightOpts.AllowZero = false;
cHeightOpts.AllowNegative = false;
// Prepare prompt for the column width
PromptDoubleResult cWidthRes;
PromptDistanceOptions cWidthOpts = new PromptDistanceOptions("");
cWidthOpts.Message = "\nEnter the column diameter: ";
cWidthOpts.DefaultValue = 6;
cWidthOpts.AllowZero = false;
cWidthOpts.AllowNegative = false;
// Prepare prompt for the baseplate diameter
PromptDoubleResult bWidthRes;
PromptDistanceOptions bWidthOpts = new PromptDistanceOptions("");
bWidthOpts.Message = "\nEnter the baseplate diameter: ";
bWidthOpts.DefaultValue = 14;
bWidthOpts.AllowZero = false;
bWidthOpts.AllowNegative = false;
// Prepare prompt for other options
PromptResult cOthersRes;
PromptKeywordOptions cOthersOpts = new PromptKeywordOptions("");
cOthersOpts.Message = "\nOptions: ";
cOthersOpts.Keywords.Add("BaseplateHeight");
cOthersOpts.Keywords.Add("BaseplateOrientation");
cOthersOpts.AllowArbitraryInput = false;
cOthersOpts.AllowNone = true;
// Prepare prompt for the baseplate height
PromptDoubleResult bHeightRes;
PromptDistanceOptions bHeightOpts = new PromptDistanceOptions("");
bHeightOpts.Message = "\nEnter the baseplate height: ";
bHeightOpts.DefaultValue = 0.75;
bHeightOpts.AllowNegative = false;
// Prepare first prompt for the baseplate orientation
PromptResult bMainOrientRes;
PromptKeywordOptions bMainOrientOpts = new PromptKeywordOptions("");
bMainOrientOpts.Message = "\nChoose baseplate orientation: ";
bMainOrientOpts.Keywords.Add("CEnter");
bMainOrientOpts.Keywords.Add("COrner");
bMainOrientOpts.Keywords.Add("Side");
bMainOrientOpts.Keywords.Default = "CEnter";
bMainOrientOpts.AllowArbitraryInput = false;
bMainOrientOpts.AllowNone = false;
// Prepare secondary prompt for the side baseplate orientation
PromptResult bSideOrientRes;
PromptKeywordOptions bSideOrientOpts = new PromptKeywordOptions("");
bSideOrientOpts.Message = "\nChoose baseplate side orientation: ";
bSideOrientOpts.Keywords.Add("+X");
bSideOrientOpts.Keywords.Add("-X");
bSideOrientOpts.Keywords.Add("+Y");
bSideOrientOpts.Keywords.Add("-Y");
bSideOrientOpts.Keywords.Default = "+X";
bSideOrientOpts.AllowArbitraryInput = false;
bSideOrientOpts.AllowNone = false;
// Prepare secondary prompt for the side baseplate orientation
PromptResult bCornerOrientRes;
PromptKeywordOptions bCornerOrientOpts = new PromptKeywordOptions("");
bCornerOrientOpts.Message = "\nChoose baseplate corner orientation: ";
bCornerOrientOpts.Keywords.Add("+X+Y");
bCornerOrientOpts.Keywords.Add("+X-Y");
bCornerOrientOpts.Keywords.Add("-X+Y");
bCornerOrientOpts.Keywords.Add("-X-Y");
bCornerOrientOpts.Keywords.Default = "+X+Y";
bCornerOrientOpts.AllowArbitraryInput = false;
bCornerOrientOpts.AllowNone = false;
// Prompt for column height
cHeightRes = acDoc.Editor.GetDistance(cHeightOpts);
if (cHeightRes.Status != PromptStatus.OK) return;
double cHeight = cHeightRes.Value;
// Prompt for column diameter
cWidthRes = acDoc.Editor.GetDistance(cWidthOpts);
if (cWidthRes.Status != PromptStatus.OK) return;
double cWidth = cWidthRes.Value;
// Prompt for baseplate diameter
bWidthRes = acDoc.Editor.GetDistance(bWidthOpts);
if (bWidthRes.Status != PromptStatus.OK) return;
double bWidth = bWidthRes.Value;
// Create column block
Column columnBlock = new Column(db: acCurDb,
height: cHeight,
width: cWidth,
baseWidth: bWidth);
// Prompt for other options
cOthersRes = acDoc.Editor.GetKeywords(cOthersOpts);
// Exit if the user presses ESC or cancels the command
if (cOthersRes.Status == PromptStatus.Cancel) return;
while (cOthersRes.Status == PromptStatus.OK)
{
switch (cOthersRes.StringResult)
{
case "BaseplateHeight":
bHeightRes = acDoc.Editor.GetDistance(bHeightOpts);
if (bHeightRes.Status != PromptStatus.OK) return;
columnBlock.baseHeight = bHeightRes.Value;
break;
case "BaseplateOrientation":
bMainOrientRes = acDoc.Editor.GetKeywords(bMainOrientOpts);
if (bMainOrientRes.Status == PromptStatus.Cancel) return;
else
{
switch (bMainOrientRes.StringResult)
{
case "CEnter":
break;
case "Side":
bSideOrientRes = acDoc.Editor.GetKeywords(bSideOrientOpts);
if (bSideOrientRes.Status == PromptStatus.Cancel) return;
columnBlock.baseplateOrientation = bSideOrientRes.StringResult;
break;
case "COrner":
bCornerOrientRes = acDoc.Editor.GetKeywords(bCornerOrientOpts);
if (bCornerOrientRes.Status == PromptStatus.Cancel) return;
columnBlock.baseplateOrientation = bCornerOrientRes.StringResult;
break;
default:
Application.ShowAlertDialog("Invalid Keyword: " + bMainOrientRes.StringResult);
break;
}
}
break;
default:
Application.ShowAlertDialog("Invalid Keyword: " + cOthersRes.StringResult);
break;
}
// Re-prompt for keywords
cOthersRes = acDoc.Editor.GetKeywords(cOthersOpts);
// Exit if the user presses ESC or cancels the command
if (cOthersRes.Status == PromptStatus.Cancel) return;
}
// Build column
columnBlock.Build();
}
}
class Truss
{
// Auto-impl class properties
private Database db;
public double trussLength { get; private set; }
public double trussHeight { get; private set; }
public double chordWidth { get; private set; }
public double chordThickness { get; private set; }
public double chordNearEndLength { get; private set; }
public double chordFarEndLength { get; private set; }
public double bottomChordLength { get; private set; }
public double rodDiameter { get; private set; }
public double rodEndLength { get; private set; }
public double rodMidLength { get; private set; }
public double rodEndAngle { get; private set; }
public double rodMidAngle { get; private set; }
public string name { get; private set; }
public string orientation { get; private set; }
public string layerName { get; private set; }
public ObjectId id { get; private set; }
// Public constructor
public Truss(Database db,
Dictionary<string, double> data,
string orient = "X Axis")
{
this.db = db;
this.trussLength = data["trussLength"];
this.trussHeight = data["trussHeight"];
this.chordWidth = data["chordWidth"];
this.chordThickness = data["chordThickness"];
this.chordNearEndLength = data["chordNearEndLength"];
this.chordFarEndLength = data["chordFarEndLength"];
this.rodDiameter = data["rodDiameter"];
this.rodEndAngle = data["rodEndAngle"];
this.rodMidAngle = data["rodMidAngle"];
this.orientation = orient;
this.name = "Truss - " + trussLength + "x" + trussHeight;
// Calculate truss bottom length
this.bottomChordLength = trussLength - chordNearEndLength - chordFarEndLength
- 2 * (trussHeight - 3 * chordWidth) * Math.Tan(rodEndAngle)
+ 2 * rodDiameter / Math.Cos(rodEndAngle);
// Calculate end rod length
this.rodEndLength = (trussHeight - 2 * chordWidth) / Math.Cos(rodEndAngle);
// Calculate mid rod length
this.rodMidLength = (trussHeight - chordWidth) / Math.Cos(rodMidAngle);
// Create beam layer (if necessary)
this.layerName = "3D-Mezz-Truss";
Color layerColor = Utils.ChooseColor("black");
Utils.CreateLayer(db, layerName, layerColor);
}
public void Build()
{
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
if (acBlkTbl.Has(name))
{
// Retrieve object id
this.id = acBlkTbl[name];
}
else
{
using (BlockTableRecord acBlkTblRec = new BlockTableRecord())
{
acBlkTblRec.Name = name;
// Set the insertion point for the block
acBlkTblRec.Origin = new Point3d(0, 0, 0);
// Create top chords
Solid3d cTop1 = TrussTopChord(trussLength, chordWidth,
chordThickness, rodDiameter, orientation);
Solid3d cTop2 = TrussTopChord(trussLength, chordWidth,
chordThickness, rodDiameter, orientation, mirror: true);
// Add top chords to block
acBlkTblRec.AppendEntity(cTop1);
acBlkTblRec.AppendEntity(cTop2);
// Create end chords
Solid3d cEndNear1 = TrussEndChord(trussLength, chordNearEndLength,
chordWidth, chordThickness, rodDiameter, "near", orientation);
Solid3d cEndNear2 = TrussEndChord(trussLength, chordNearEndLength,
chordWidth, chordThickness, rodDiameter, "near", orientation, mirror: true);
Solid3d cEndFar1 = TrussEndChord(trussLength, chordFarEndLength,
chordWidth, chordThickness, rodDiameter, "far", orientation);
Solid3d cEndFar2 = TrussEndChord(trussLength, chordFarEndLength,
chordWidth, chordThickness, rodDiameter, "far", orientation, mirror: true);
// Add end chords to block
acBlkTblRec.AppendEntity(cEndNear1);
acBlkTblRec.AppendEntity(cEndNear2);
acBlkTblRec.AppendEntity(cEndFar1);
acBlkTblRec.AppendEntity(cEndFar2);
// Create bottom chords
Solid3d cBottom1 = TrussBottomChord(trussLength, trussHeight, chordWidth,
chordThickness, bottomChordLength, rodDiameter, orientation);
Solid3d cBottom2 = TrussBottomChord(trussLength, trussHeight, chordWidth,
chordThickness, bottomChordLength, rodDiameter, orientation, mirror: true);
// Add top chords to block
acBlkTblRec.AppendEntity(cBottom1);
acBlkTblRec.AppendEntity(cBottom2);
// Create truss end rods
Solid3d rEndNear = TrussEndRod(trussHeight, chordWidth, chordNearEndLength,
rodEndLength, rodDiameter, rodEndAngle, orientation);
Solid3d rEndFar = TrussEndRod(trussHeight, chordWidth, trussLength - chordFarEndLength,
rodEndLength, rodDiameter, -rodEndAngle, orientation);
// Add top chords to block
acBlkTblRec.AppendEntity(rEndNear);
acBlkTblRec.AppendEntity(rEndFar);
// Create and add truss end rods
TrussMidRods(acBlkTblRec, trussHeight, chordWidth,
rodDiameter, rodMidLength, rodMidAngle,
rodIntersectPoint(rEndNear, rodDiameter, rodEndAngle, orientation, "near"),
rodIntersectPoint(rEndFar, rodDiameter, rodEndAngle, orientation, "far"),
orientation);
/// Add Block to Block Table and close Transaction
acBlkTbl.UpgradeOpen();
acBlkTbl.Add(acBlkTblRec);
acTrans.AddNewlyCreatedDBObject(acBlkTblRec, true);
}
// Set block id property
this.id = acBlkTbl[name];
}
// Save the new object to the database
acTrans.Commit();
}
}
private static Solid3d CreateTrussChord(double x1,
double x2,
double y1,
double y2,
double length,
double rotateAngle,
Vector3d rotateAxis,
Vector3d chordVector,
bool mirror = false)
{
// Create polyline of chord profile
Polyline chordPoly = new Polyline();
chordPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
chordPoly.AddVertexAt(1, new Point2d(x1, 0), 0, 0, 0);
chordPoly.AddVertexAt(2, new Point2d(x1, y1), 0, 0, 0);
chordPoly.AddVertexAt(3, new Point2d(x2, y1), 0, 0, 0);
chordPoly.AddVertexAt(4, new Point2d(x2, y2), 0, 0, 0);
chordPoly.AddVertexAt(5, new Point2d(0, y2), 0, 0, 0);
chordPoly.Closed = true;
// Create the 3D solid top chord(s)
Solid3d chord = Utils.ExtrudePolyline(chordPoly, length);
// Position the top chord
chord.TransformBy(Matrix3d.Rotation(rotateAngle, rotateAxis, Point3d.Origin));
chord.TransformBy(Matrix3d.Displacement(chordVector));
if (mirror == true)
{
chord.TransformBy(Matrix3d.Mirroring(new Plane(Point3d.Origin, rotateAxis)));
}
// Set block object properties
Utils.SetObjectProperties(chord);
return chord;
}
private static Solid3d TrussTopChord(double trussLength,
double chordWidth,
double chordThickness,
double rodDiameter,
string orientation,
bool mirror = false)
{
// Variable stubs
Vector3d rotateAxis;
double rotateAngle;
Vector3d chordVec;
double cX1;
double cX2;
double cY1;
double cY2;
// Calculate truss values
if (orientation == "X-Axis")
{
rotateAxis = Vector3d.YAxis;
rotateAngle = Math.PI / 2;
chordVec = new Vector3d(0, rodDiameter / 2, chordWidth * 2);
cX1 = chordWidth;
cX2 = chordThickness;
cY1 = chordThickness;
cY2 = chordWidth;
}
else // assume y orientation
{
rotateAxis = Vector3d.XAxis;
rotateAngle = -Math.PI / 2;
chordVec = new Vector3d(rodDiameter / 2, 0, chordWidth * 2);
cX1 = chordWidth;
cX2 = chordThickness;
cY1 = chordThickness;
cY2 = chordWidth;
}
return CreateTrussChord(cX1, cX2, cY1, cY2, trussLength, rotateAngle,
rotateAxis, chordVec, mirror: mirror);
}
private static Solid3d TrussEndChord(double trussLength,
double chordLength,
double chordWidth,
double chordThickness,
double rodDiameter,
string placement = "near",
string orientation = "Y-Axis",
bool mirror = false)
{
// Variable stubs
double chordLocation;
Vector3d rotateAxis;
double rotateAngle;
Vector3d chordVec;
double cX1;
double cX2;
double cY1;
double cY2;
// Calculate truss values
if (placement == "far")
{
chordLocation = trussLength - chordLength;
}
else
{
chordLocation = 0;
}
if (orientation == "X-Axis")
{
rotateAxis = Vector3d.YAxis;
rotateAngle = Math.PI / 2;
chordVec = new Vector3d(chordLocation, rodDiameter / 2, 0);
cX1 = -chordWidth;
cX2 = -chordThickness;
cY1 = chordThickness;
cY2 = chordWidth;
}
else // assume y orientation
{
rotateAxis = Vector3d.XAxis;
rotateAngle = -Math.PI / 2;
chordVec = new Vector3d(rodDiameter / 2, chordLocation, 0);
cX1 = chordWidth;
cX2 = chordThickness;
cY1 = -chordThickness;
cY2 = -chordWidth;
}
return CreateTrussChord(cX1, cX2, cY1, cY2, chordLength, rotateAngle,
rotateAxis, chordVec, mirror: mirror);
}
private static Solid3d TrussBottomChord(double trussLength,
double trussHeight,
double chordWidth,
double chordThickness,
double chordLength,
double rodDiameter,
string orientation = "Y-Axis",
bool mirror = false)
{
// Variable stubs
Vector3d rotateAxis;
double rotateAngle;
Vector3d chordVec;
double cX1;
double cX2;
double cY1;
double cY2;
if (orientation == "X-Axis")
{
rotateAxis = Vector3d.YAxis;
rotateAngle = Math.PI / 2;
chordVec = new Vector3d((trussLength - chordLength) / 2,
rodDiameter / 2,
-(trussHeight - 2 * chordWidth));
cX1 = -chordWidth;
cX2 = -chordThickness;
cY1 = chordThickness;
cY2 = chordWidth;
}
else // assume y orientation
{
rotateAxis = Vector3d.XAxis;
rotateAngle = -Math.PI / 2;
chordVec = new Vector3d(rodDiameter / 2,
(trussLength - chordLength) / 2,
-(trussHeight - 2 * chordWidth));
cX1 = chordWidth;
cX2 = chordThickness;
cY1 = -chordThickness;
cY2 = -chordWidth;
}
return CreateTrussChord(cX1, cX2, cY1, cY2, chordLength, rotateAngle,
rotateAxis, chordVec, mirror: mirror);
}
private static Solid3d CreateTrussRod(double rodDiameter,
double rodLength,
Vector3d rodLocation,
double rodAngle,
Vector3d rotateAxis)
{
// Create rod
Solid3d rod = new Solid3d();
try
{
// Draw rod
rod.CreateFrustum(rodLength, rodDiameter / 2, rodDiameter / 2, rodDiameter / 2);
// Rotate rod
rod.TransformBy(Matrix3d.Rotation(rodAngle, rotateAxis, Point3d.Origin));
rod.TransformBy(Matrix3d.Displacement(rodLocation));
}
catch (Autodesk.AutoCAD.Runtime.Exception Ex)
{
Application.ShowAlertDialog("There was a problem creating the rod:\n" +
"Rod Length = " + rodLength + "\n" +
"Rod Diameter = " + rodDiameter + "\n" +
Ex.Message + "\n" +
Ex.StackTrace);
}
// Set block object properties
Utils.SetObjectProperties(rod);
return rod;
}
private static Tuple<double, double> rodIntersectPoint(Solid3d rod,
double rodDiameter,
double rodAngle,
string orient,
string location)
{
// Declare variable stubs
double dPoint = 0;
double hPoint = 0;
// Choose distance point
if (location == "near")
{
if (orient == "X-Axis")
{
dPoint = rod.Bounds.Value.MaxPoint.X;
}
else if (orient == "Y-Axis")
{
dPoint = rod.Bounds.Value.MaxPoint.Y;
}
}
else if (location == "far")
{
if (orient == "X-Axis")
{
dPoint = rod.Bounds.Value.MinPoint.X;
}
else if (orient == "Y-Axis")
{
dPoint = rod.Bounds.Value.MinPoint.Y;
}
}
// Calculate Z (height) coordinate
hPoint = rod.Bounds.Value.MinPoint.Z + rodDiameter * Math.Sin(Math.Abs(rodAngle));
return Tuple.Create(dPoint, hPoint);
}
private static void TrussMidRods(BlockTableRecord btr,
double trussHeight,
double chordWidth,
double rodDiameter,
double rodLength,
double rodAngle,
Tuple<double, double> nearPt,
Tuple<double, double> farPt,
string orient = "Y-Axis")
{
// Declare variable stubs
Vector3d rodNearEndVec;
Vector3d rodFarEndVec;
Vector3d rotateAxis;
double rotateAngle;
// Calculate mid rod vertical location
double rodVerticalLocation = 2 * chordWidth - trussHeight / 2;
// Calculate mid rod horizontal length (for loop)
double rodHorizontalLength = rodLength * Math.Sin(rodAngle)
+ rodDiameter / Math.Cos(rodAngle);
// Calculate near and far mid rod locations
double rodNearHorizontalLocation = (nearPt.Item1 + rodDiameter / (2 * Math.Cos(rodAngle)))
- Math.Tan(-rodAngle) * (nearPt.Item2 - rodVerticalLocation);
double rodFarHorizontalLocation = (farPt.Item1 - rodDiameter / (2 * Math.Cos(rodAngle)))
+ Math.Tan(rodAngle) * (rodVerticalLocation - farPt.Item2);
if (orient == "X-Axis")
{
rodNearEndVec = new Vector3d(rodNearHorizontalLocation,
0,
rodVerticalLocation);
rodFarEndVec = new Vector3d(rodFarHorizontalLocation,
0,
rodVerticalLocation);
rotateAxis = Vector3d.YAxis;
rotateAngle = -rodAngle;
}
else
{
rodNearEndVec = new Vector3d(0,
rodNearHorizontalLocation,
rodVerticalLocation);
rodFarEndVec = new Vector3d(0,
rodFarHorizontalLocation,
rodVerticalLocation);
rotateAxis = Vector3d.XAxis;
rotateAngle = rodAngle;
}
// Create mid end rods
Solid3d rodNear = CreateTrussRod(rodDiameter, rodLength,
rodNearEndVec, rotateAngle, rotateAxis);
Solid3d rodFar = CreateTrussRod(rodDiameter, rodLength,
rodFarEndVec, -rotateAngle, rotateAxis);
// Add mid end rods to block
btr.AppendEntity(rodNear);
btr.AppendEntity(rodFar);
// Loop to create remaining rods
double space = rodIntersectPoint(rodFar, rodDiameter, rotateAngle, orient, "far").Item1
- rodIntersectPoint(rodNear, rodDiameter, rotateAngle, orient, "near").Item1;
while (space >= rodHorizontalLength)
{
// Switch rotate angle (alternates rod angles)
rotateAngle = -rotateAngle;
// Calculate near and far rod locations
rodNearHorizontalLocation = rodIntersectPoint(rodNear, rodDiameter, rotateAngle, orient, "near").Item1
+ rodHorizontalLength / 2;
rodFarHorizontalLocation = rodIntersectPoint(rodFar, rodDiameter, rotateAngle, orient, "far").Item1
- rodHorizontalLength / 2;
if (orient == "X-Axis")
{
rodNearEndVec = new Vector3d(rodNearHorizontalLocation,
0,
rodVerticalLocation);
rodFarEndVec = new Vector3d(rodFarHorizontalLocation,
0,
rodVerticalLocation);
}
else
{
rodNearEndVec = new Vector3d(0,
rodNearHorizontalLocation,
rodVerticalLocation);
rodFarEndVec = new Vector3d(0,
rodFarHorizontalLocation,
rodVerticalLocation);
}
// Create near mid rod
rodNear = CreateTrussRod(rodDiameter, rodLength,
rodNearEndVec, rotateAngle, rotateAxis);
btr.AppendEntity(rodNear);
space -= rodHorizontalLength;
// Re-check available space (break if no more space)
if (space < rodHorizontalLength) { break; }
// Create far mid rod (if space allows)
rodFar = CreateTrussRod(rodDiameter, rodLength,
rodFarEndVec, -rotateAngle, rotateAxis);
btr.AppendEntity(rodFar);
space -= rodHorizontalLength;
}
}
private static Solid3d TrussEndRod(double trussHeight,
double chordWidth,
double rodStartLocation,
double rodLength,
double rodDiameter,
double rodAngle,
string orient = "Y-Axis")
{
// Declare variable stubs
Vector3d rodVec;
Vector3d rotateAxis;
double rotateAngle;
// Calculate end rod locations
double rodHorizontalOffset = Math.Sign(rodAngle) * ((trussHeight - 3 * chordWidth)
* Math.Tan(Math.Abs(rodAngle)) - rodDiameter / Math.Cos(Math.Abs(rodAngle))) / 2;
double rodVerticalLocation = chordWidth - (trussHeight - chordWidth) / 2;
double rodHorizontalLocation = rodStartLocation + rodHorizontalOffset;
if (orient == "X-Axis")
{
rodVec = new Vector3d(rodHorizontalLocation, 0, rodVerticalLocation);
rotateAxis = Vector3d.YAxis;
rotateAngle = -rodAngle;
}
else
{
rodVec = new Vector3d(0, rodHorizontalLocation, rodVerticalLocation);
rotateAxis = Vector3d.XAxis;
rotateAngle = rodAngle;
}
Solid3d rod = CreateTrussRod(rodDiameter, rodLength,
rodVec, rotateAngle, rotateAxis);
return rod;
}
[CommandMethod("TrussPrompt")]
public static void TrussPrompt()
{
// Initialize data dictionary
Dictionary<string, double> trussData = new Dictionary<string, double>();
// Initialize prompt check variable
bool viable = false;
// Some default values (could be arguments)
trussData.Add("trussLength", 240); // truss length
trussData.Add("trussHeight", 1); // truss height
trussData.Add("chordWidth", 1.25); // chord width
trussData.Add("chordThickness", 0.125); // chord thickness
trussData.Add("chordNearEndLength", 8); // chord end piece length (sits on column/beam)
trussData.Add("chordFarEndLength", 8); // chord end piece length (sits on column/beam)
trussData.Add("rodDiameter", 0.875); // truss rod diameter
double rEndAngle = 60; // end rod angle (from vertical)
double rMidAngle = 35; // middle rod angles (from vertical)
trussData.Add("rodEndAngle", rEndAngle.ToRadians());
trussData.Add("rodMidAngle", rMidAngle.ToRadians());
string orientation = "X-Axis"; // truss orientation
// Declare prompt variables
PromptDoubleResult tLengthRes;
PromptDoubleResult tHeightRes;
PromptResult tOthersRes;
PromptResult tOrientRes;
PromptDoubleResult cWidthRes;
PromptDistanceOptions tLengthOpts = new PromptDistanceOptions("");
PromptDistanceOptions tHeightOpts = new PromptDistanceOptions("");
PromptKeywordOptions tOthersOpts = new PromptKeywordOptions("");
PromptKeywordOptions tOrientOpts = new PromptKeywordOptions("");
PromptDistanceOptions cWidthOpts = new PromptDistanceOptions("");
// Get the current document and database, and start a transaction
// !!! Move this outside function
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Prepare prompt for the truss length
tLengthOpts.Message = "\nEnter the truss length: ";
tLengthOpts.DefaultValue = 240;
// Prepare prompt for the truss height
tHeightOpts.Message = "\nEnter the truss height: ";
tHeightOpts.DefaultValue = 18;
// Prepare prompt for other options
tOthersOpts.Message = "\nTruss Options: ";
tOthersOpts.Keywords.Add("Orientation");
tOthersOpts.Keywords.Add("ChordWidth");
//tOthersOpts.Keywords.Add("NearChordLength");
//tOthersOpts.Keywords.Add("FarChordLength");
//tOthersOpts.Keywords.Add("NearTab");
//tOthersOpts.Keywords.Add("FarTab");
//tOthersOpts.Keywords.Add("EndRodAngle");
//tOthersOpts.Keywords.Add("MiddleRodAngle");
tOthersOpts.AllowArbitraryInput = false;
tOthersOpts.AllowNone = true;
// Prepare prompt for the truss orientation
tOrientOpts.Message = "\nEnter truss orientation: ";
tOrientOpts.Keywords.Add("X-Axis");
tOrientOpts.Keywords.Add("Y-Axis");
tOrientOpts.Keywords.Default = "X-Axis";
tOrientOpts.AllowArbitraryInput = false;
// Prepare prompt for the chord width
cWidthOpts.Message = "\nEnter the chord width: ";
cWidthOpts.DefaultValue = 1.25;
while (viable == false)
{
// Prompt for the truss length
tLengthRes = acDoc.Editor.GetDistance(tLengthOpts);
trussData["trussLength"] = tLengthRes.Value;
if (tLengthRes.Status == PromptStatus.Cancel) return;
// Prompt for the truss height
tHeightRes = acDoc.Editor.GetDistance(tHeightOpts);
trussData["trussHeight"] = tHeightRes.Value;
if (tHeightRes.Status == PromptStatus.Cancel) return;
// Prompt for other options
tOthersRes = acDoc.Editor.GetKeywords(tOthersOpts);
// Exit if the user presses ESC or cancels the command
if (tOthersRes.Status == PromptStatus.Cancel) return;
while (tOthersRes.Status == PromptStatus.OK)
{
switch (tOthersRes.StringResult)
{
case "Orientation":
tOrientRes = acDoc.Editor.GetKeywords(tOrientOpts);
orientation = tOrientRes.StringResult;
if (tOrientRes.Status != PromptStatus.OK) return;
break;
case "ChordWidth":
cWidthRes = acDoc.Editor.GetDistance(cWidthOpts);
trussData["chordWidth"] = cWidthRes.Value;
if (cWidthRes.Status == PromptStatus.Cancel) return;
break;
default:
Application.ShowAlertDialog("Invalid Keyword");
break;
}
// Re-prompt for keywords
tOthersRes = acDoc.Editor.GetKeywords(tOthersOpts);
// Exit if the user presses ESC or cancels the command
if (tOthersRes.Status == PromptStatus.Cancel) return;
}
// Check viability of truss length
double rodEndLengthHorizontal = (trussData["trussHeight"] - 2 * trussData["chordWidth"])
/ Math.Cos(trussData["rodEndAngle"]);
double chordBreakHorizontal = ((trussData["trussHeight"] - 3 * trussData["chordWidth"])
* Math.Tan(trussData["rodEndAngle"]) - trussData["rodDiameter"]
/ Math.Cos(trussData["rodEndAngle"]));
double rodMidWidthHorizontal = trussData["rodDiameter"] / (2 * Math.Cos(trussData["rodMidAngle"]));
if (trussData["trussLength"] < trussData["chordNearEndLength"] + trussData["chordFarEndLength"]
+ (chordBreakHorizontal + rodEndLengthHorizontal) + rodMidWidthHorizontal)
{
// Display error
Application.ShowAlertDialog("Warning: Truss length is too short\n" +
"Must be greater than " +
(trussData["chordNearEndLength"] + trussData["chordFarEndLength"]
+ (chordBreakHorizontal + rodEndLengthHorizontal) + rodMidWidthHorizontal)
+ " inches");
}
else if (trussData["trussHeight"] <= trussData["chordWidth"] * 4)
{
// Display error
Application.ShowAlertDialog("Warning: Truss height is too short.");
}
else
{
viable = true;
}
}
// Create Truss block
Truss mezzTruss = new Truss(db: acCurDb,
data: trussData,
orient: orientation);
mezzTruss.Build();
}
}
class Frame
{
// Auto-impl class properties
private Database db;
public double height { get; private set; }
public double width { get; private set; }
public double diameter { get; private set; }
public string name { get; private set; }
public string layerName { get; set; }
public ObjectId id { get; private set; }
// Public constructor
public Frame(Database db,
double height = 96,
double width = 42,
double diameter = 3)
{
this.db = db;
this.height = height;
this.width = width;
this.diameter = diameter;
this.name = "Frame - " + height + "x" + width;
// Create beam layer (if necessary)
this.layerName = "3D-Rack-Frame";
Color layerColor = Utils.ChooseColor("teal");
Utils.CreateLayer(db, layerName, layerColor);
}
public void Build()
{
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
if (acBlkTbl.Has(name))
{
// Retrieve object id
this.id = acBlkTbl[name];
}
else
{
using (BlockTableRecord acBlkTblRec = new BlockTableRecord())
{
acBlkTblRec.Name = name;
// Set the insertion point for the block
acBlkTblRec.Origin = new Point3d(0, 0, 0);
// Add frame posts to the block table record
for (double dist = diameter; dist <= width; dist += width - diameter)
{
Solid3d Post = framePost(height, diameter, dist);
acBlkTblRec.AppendEntity(Post);
}
// Calculate cross-bracing
Dictionary<string, double> braceData = calcBraces(height, diameter);
// Add horizontal cross-braces
horizontalBraces(acBlkTblRec, height, diameter, braceData);
// Add angled cross-braces to the block
angleBraces(acBlkTblRec, height, diameter, braceData);
/// Add Block to Block Table and close Transaction
acBlkTbl.UpgradeOpen();
acBlkTbl.Add(acBlkTblRec);
acTrans.AddNewlyCreatedDBObject(acBlkTblRec, true);
}
// Set block id property
this.id = acBlkTbl[name];
}
// Save the new object to the database
acTrans.Commit();
}
}
// Build frame post
private Solid3d framePost(double height,
double diameter,
double distance)
{
Solid3d Post = new Solid3d();
Post.SetDatabaseDefaults();
// Create the 3D solid frame post
Post.CreateBox(diameter, diameter, height);
// Find location for post
Point3d pMid = new Point3d(diameter / 2, distance - diameter / 2, height / 2);
Vector3d pVec = Point3d.Origin.GetVectorTo(pMid);
// Position the post
Post.TransformBy(Matrix3d.Displacement(pVec));
// Set block object properties
Utils.SetObjectProperties(Post);
return Post;
}
private Dictionary<string, double> calcBraces(double height,
double diameter)
{
// Initialize dictionary
Dictionary<string, double> data = new Dictionary<string, double>();
// Calculate cross-bracing
double bNum;
double bSpace = 0;
double bAngle = Math.PI;
double bSize = 1;
double bEndSpace = 8;
for (bNum = 1; bNum <= Math.Floor((height - bEndSpace) / 12); bNum++)
{
bSpace = Math.Floor(((height - bEndSpace) - (bNum + 1) * bSize) / bNum);
bAngle = Math.Atan2(bSpace - bSize, width - (2 * diameter));
if ((bAngle < Math.PI / 3))
{
break;
}
}
data.Add("num", bNum);
data.Add("size", bSize);
data.Add("space", bSpace);
data.Add("angle", bAngle);
data.Add("leftover", height - ((bNum + 1) * bSize) - (bNum * bSpace));
return data;
}
// Build frame post
private void horizontalBraces(BlockTableRecord btr,
double height,
double diameter,
Dictionary<string, double> data)
{
/// Add horizontal cross-braces to the block
for (int i = 1; i <= Convert.ToInt32(data["num"]) + 1; i++)
{
Solid3d brace = new Solid3d();
brace.SetDatabaseDefaults();
// Create the 3D solid horizontal cross brace
brace.CreateBox(data["size"], width - 2 * diameter, data["size"]);
// Find location for brace
Point3d bMid = new Point3d(diameter / 2, width / 2,
data["leftover"] / 2 + ((data["space"] + data["size"]) * (i - 1)) + data["size"] / 2);
Vector3d bVec = Point3d.Origin.GetVectorTo(bMid);
// Position the brace
brace.TransformBy(Matrix3d.Displacement(bVec));
// Set block object properties
Utils.SetObjectProperties(brace);
btr.AppendEntity(brace);
}
}
private void angleBraces(BlockTableRecord btr,
double height,
double diameter,
Dictionary<string, double> data)
{
// Create polyline of brace profile and rotate to correct orienation
Polyline bPoly = new Polyline();
bPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
bPoly.AddVertexAt(1, new Point2d(data["size"], 0), 0, 0, 0);
bPoly.AddVertexAt(2, new Point2d(data["size"], data["size"]), 0, 0, 0);
bPoly.AddVertexAt(3, new Point2d(0, data["size"]), 0, 0, 0);
bPoly.Closed = true;
bPoly.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
/// Create sweep path
Line bPath = new Line(Point3d.Origin, new Point3d(0, width - 2 * diameter, data["space"] - data["size"]));
/// Create swept cross braces
for (int i = 1; i <= Convert.ToInt32(data["num"]); i++)
{
// Create swept brace at origin
Solid3d aBrace = Utils.SweepPolylineOverLine(bPoly, bPath);
// Calculate location
double aBxLoc = (diameter / 2) - (data["size"] / 2);
double aByLoc = diameter;
double aBzLoc = data["leftover"] / 2 + data["size"] * i + data["space"] * (i - 1);
/// Even braces get rotated 180 deg and different x and y coordinates
if (i % 2 == 0)
{
aBrace.TransformBy(Matrix3d.Rotation(Math.PI, Vector3d.ZAxis, Point3d.Origin));
aBxLoc = (diameter / 2) + (data["size"] / 2);
aByLoc = width - diameter;
}
// Create location for brace
Point3d aMid = new Point3d(aBxLoc, aByLoc, aBzLoc);
Vector3d aVec = Point3d.Origin.GetVectorTo(aMid);
// Position the brace
aBrace.TransformBy(Matrix3d.Displacement(aVec));
// Set block object properties
Utils.SetObjectProperties(aBrace);
// Add brace to block
btr.AppendEntity(aBrace);
}
}
[CommandMethod("FramePrompt")]
public static void FramePrompt()
{
// Get the current document and database, and start a transaction
// !!! Move this outside function
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Prompt for the frame height
PromptDoubleResult heightRes;
PromptDistanceOptions heightOpts = new PromptDistanceOptions("");
heightOpts.Message = "\nEnter the frame height: ";
heightOpts.DefaultValue = 96;
heightRes = acDoc.Editor.GetDistance(heightOpts);
double height = heightRes.Value;
// Exit if the user presses ESC or cancels the command
if (heightRes.Status != PromptStatus.OK) return;
// Prompt for the frame width
PromptDoubleResult widthRes;
PromptDistanceOptions widthOpts = new PromptDistanceOptions("");
widthOpts.Message = "\nEnter the frame width: ";
widthOpts.DefaultValue = 36;
widthRes = acDoc.Editor.GetDistance(widthOpts);
double width = widthRes.Value;
// Exit if the user presses ESC or cancels the command
if (widthRes.Status != PromptStatus.OK) return;
// Prompt for the frame diameter
PromptDoubleResult diameterRes;
PromptDistanceOptions diameterOpts = new PromptDistanceOptions("");
diameterOpts.Message = "\nEnter the frame width: ";
diameterOpts.DefaultValue = 3.0;
diameterRes = acDoc.Editor.GetDistance(diameterOpts);
double diameter = diameterRes.Value;
// Exit if the user presses ESC or cancels the command
if (diameterRes.Status != PromptStatus.OK) return;
// Create Frame block
Frame rackFrame = new Frame(db: acCurDb,
height: height,
width: width,
diameter: diameter);
rackFrame.Build();
}
}
class Beam
{
// Auto-impl class properties
private Database db;
public double length { get; private set; }
public double height { get; private set; }
public double width { get; private set; }
public double step { get; private set; }
public double thickness { get; private set; }
public string name { get; private set; }
public string orientation { get; private set; }
public string style { get; private set; }
public string layerName { get; set; }
public Color layerColor { get; set; }
public ObjectId id { get; private set; }
// Public constructor
public Beam(Database db,
double length = 96,
double height = 3,
double width = 2,
string orient = "X-Axis",
string style = "Box")
{
this.db = db;
this.length = length;
this.height = height;
this.width = width;
this.orientation = orient;
this.style = style;
this.name = "Beam - " + length + "x" + height + "x" + width;
}
public void Build()
{
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
if (acBlkTbl.Has(name))
{
// Retrieve object id
this.id = acBlkTbl[name];
}
else
{
// Create new block (record)
using (BlockTableRecord acBlkTblRec = new BlockTableRecord())
{
acBlkTblRec.Name = name;
// Set the insertion point for the block
acBlkTblRec.Origin = new Point3d(0, 0, 0);
// Create beam profile
Polyline beamPoly = beamProfile(height,
width,
style: style,
beamThickness: thickness,
orient: orientation);
// Create beam path
Line beamLine = beamPath(length, orientation);
// Create beam
Solid3d beamSolid = Utils.SweepPolylineOverLine(beamPoly, beamLine);
// Set block properties
Utils.SetObjectProperties(beamSolid);
// Add entity to Block Table Record
acBlkTblRec.AppendEntity(beamSolid);
/// Add Block to Block Table and Transaction
acBlkTbl.UpgradeOpen();
acBlkTbl.Add(acBlkTblRec);
acTrans.AddNewlyCreatedDBObject(acBlkTblRec, true);
}
// Set block id property
this.id = acBlkTbl[name];
}
// Save the new object to the database
acTrans.Commit();
}
}
// Draw beam profile
private Polyline beamProfile(double height,
double width,
string style = "Box",
double stepSize = 0.75,
double beamThickness = 0.75,
string orient = "X-Axis")
{
int i = 0;
/// Create polyline of brace profile and rotate to correct orienation
Polyline poly = new Polyline();
if (style == "Step")
{
poly.AddVertexAt(i, new Point2d(0, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, width - stepSize), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + stepSize, width - stepSize), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + stepSize, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(0, width), 0, 0, 0);
}
else if (style == "Box")
{
poly.AddVertexAt(i, new Point2d(0, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(0, width), 0, 0, 0);
}
else if (style == "IBeam")
{
poly.AddVertexAt(i, new Point2d(0, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-beamThickness, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-beamThickness, (width - beamThickness) / 2), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + beamThickness, (width - beamThickness) / 2), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + beamThickness, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + beamThickness, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + beamThickness, (width + beamThickness) / 2), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-beamThickness, (width + beamThickness) / 2), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-beamThickness, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(0, width), 0, 0, 0);
}
else if (style == "CChannel")
{
poly.AddVertexAt(i, new Point2d(0, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, 0), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + beamThickness, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-height + beamThickness, beamThickness), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-beamThickness, beamThickness), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(-beamThickness, width), 0, 0, 0);
poly.AddVertexAt(i++, new Point2d(0, width), 0, 0, 0);
}
poly.Closed = true;
poly.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.YAxis, Point3d.Origin));
// Rotate beam profile if necessary
if (orient == "Y-Axis")
{
poly.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.ZAxis, Point3d.Origin));
}
return poly;
}
private Line beamPath(double length,
string orient)
{
Line path;
if (orient == "Y-Axis")
{
path = new Line(Point3d.Origin, new Point3d(0, length, 0));
}
else // X-Axis (default)
{
path = new Line(Point3d.Origin, new Point3d(length, 0, 0));
}
return path;
}
[CommandMethod("BeamPrompt")]
public static void BeamPrompt()
{
// Get the current document and database, and start a transaction
// !!! Move this outside function
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Prepare prompt for the beam length
PromptDoubleResult lengthRes;
PromptDistanceOptions lengthOpts = new PromptDistanceOptions("");
lengthOpts.Message = "\nEnter the beam length: ";
lengthOpts.DefaultValue = 96;
// Prepare prompt for the beam height
PromptDoubleResult heightRes;
PromptDistanceOptions heightOpts = new PromptDistanceOptions("");
heightOpts.Message = "\nEnter the beam height: ";
heightOpts.DefaultValue = 3;
// Prepare prompt for the beam width
PromptDoubleResult widthRes;
PromptDistanceOptions widthOpts = new PromptDistanceOptions("");
widthOpts.Message = "\nEnter the beam width: ";
widthOpts.DefaultValue = 2;
// Prepare prompt for other options
PromptResult bOthersRes;
PromptKeywordOptions bOthersOpts = new PromptKeywordOptions("");
bOthersOpts.Message = "\nBeam Options: ";
bOthersOpts.Keywords.Add("Orientation");
bOthersOpts.Keywords.Add("Thickness");
bOthersOpts.Keywords.Add("Style");
bOthersOpts.AllowArbitraryInput = false;
bOthersOpts.AllowNone = true;
// Prepare prompt for the beam orientation
PromptResult bOrientRes;
PromptKeywordOptions bOrientOpts = new PromptKeywordOptions("");
bOrientOpts.Message = "\nEnter beam orientation: ";
bOrientOpts.Keywords.Add("X-Axis");
bOrientOpts.Keywords.Add("Y-Axis");
bOrientOpts.Keywords.Default = "X-Axis";
bOrientOpts.AllowArbitraryInput = false;
// Prepare prompt for the beam thickness
PromptDoubleResult thickRes;
PromptDistanceOptions thickOpts = new PromptDistanceOptions("");
thickOpts.Message = "\nEnter the beam thickness: ";
thickOpts.DefaultValue = 0.75;
// Prepare prompt for the beam style
PromptResult bStyleRes;
PromptKeywordOptions bStyleOpts = new PromptKeywordOptions("");
bStyleOpts.Message = "\nEnter beam style: ";
bStyleOpts.Keywords.Add("Step");
bStyleOpts.Keywords.Add("Box");
bStyleOpts.Keywords.Add("IBeam");
bStyleOpts.Keywords.Add("CChannel");
bStyleOpts.Keywords.Default = "Box";
bStyleOpts.AllowArbitraryInput = false;
// Prompt for beam length
lengthRes = acDoc.Editor.GetDistance(lengthOpts);
if (lengthRes.Status != PromptStatus.OK) return;
double length = lengthRes.Value;
// Prompt for beam height
heightRes = acDoc.Editor.GetDistance(heightOpts);
if (heightRes.Status != PromptStatus.OK) return;
double height = heightRes.Value;
// Prompt for beam width
widthRes = acDoc.Editor.GetDistance(widthOpts);
if (widthRes.Status != PromptStatus.OK) return;
double width = widthRes.Value;
// Create beam
Beam solidBeam = new Beam(db: acCurDb,
length: length,
height: height,
width: width);
// Prompt for other options
bOthersRes = acDoc.Editor.GetKeywords(bOthersOpts);
// Exit if the user presses ESC or cancels the command
if (bOthersRes.Status == PromptStatus.Cancel) return;
while (bOthersRes.Status == PromptStatus.OK)
{
switch (bOthersRes.StringResult)
{
case "Orientation":
bOrientRes = acDoc.Editor.GetKeywords(bOrientOpts);
solidBeam.orientation = bOrientRes.StringResult;
if (bOrientRes.Status != PromptStatus.OK) return;
break;
case "Thickness":
thickRes = acDoc.Editor.GetDistance(thickOpts);
solidBeam.thickness = thickRes.Value;
if (thickRes.Status != PromptStatus.OK) return;
break;
case "Style":
bStyleRes = acDoc.Editor.GetKeywords(bStyleOpts);
solidBeam.style = bStyleRes.StringResult;
if (bStyleRes.Status == PromptStatus.Cancel) return;
break;
default:
Application.ShowAlertDialog("Invalid Keyword");
break;
}
// Re-prompt for keywords
bOthersRes = acDoc.Editor.GetKeywords(bOthersOpts);
// Exit if the user presses ESC or cancels the command
if (bOthersRes.Status == PromptStatus.Cancel) return;
}
// Build beam
solidBeam.Build();
}
}
class Rail
{
// Auto-impl class properties
public Database db { get; private set; }
public Point3dCollection points { get; private set; }
public double height { get; set; }
public int numSections { get; private set; }
public int tiers { get; set; }
public double[] tierHeight { get; set; }
public double postWidth { get; private set; }
public double defaultRailLength { get; set; }
public double railWidth { get; private set; }
public string layerName { get; set; }
public List<bool> firstPost { get; set; }
public List<bool> lastPost { get; set; }
public bool kickPlate { get; set; }
public List<Line> pathSections { get; private set; }
public List<double> pathOrientation { get; private set; }
public double postOrientation { get; private set; }
public double kickplateHeight { get; set; }
public double kickplateWidth { get; set; }
// Public constructor
public Rail(Database db,
Point3dCollection pts)
{
Color layerColor;
this.db = db;
this.points = pts;
this.numSections = points.Count - 1;
// Set some defaults
// postOrientation = 1 --> left of section line
// postOrientation = -1 --> right of section line
this.height = 42;
this.defaultRailLength = 96;
this.postOrientation = 1;
this.postWidth = 1.5;
this.kickPlate = true;
// Create beam layer (if necessary)
this.layerName = "3D-Mezz-Rail";
layerColor = Utils.ChooseColor("yellow");
Utils.CreateLayer(db, layerName, layerColor);
// Initialize lists
this.pathSections = new List<Line>();
this.pathOrientation = new List<double>();
this.firstPost = new List<bool>();
this.lastPost = new List<bool>();
}
private void Calculations()
{
// Loop over number of railing sections for initial calculations
for (int s = 0; s < numSections; s++)
{
// Get current path section
this.pathSections.Add(new Line(points[s], points[s + 1]));
// Path horizontal orientation (phi in polar coordinates)
this.pathOrientation.Add(Utils.PolarAnglePhi(pathSections[s]));
// Set first post defaults
// All subsequent sections do not need first post (from last post of previous section)
if (s > 0) this.firstPost.Add(false);
else this.firstPost.Add(true);
// Set last post defaults
this.lastPost.Add(true);
}
// Loop over number of railing sections for detailed section calculations
for (int s = 0; s < numSections; s++)
{
// Move section start & end points to correct point on last post
if (s != 0)
{
// Straight sections
if (pathOrientation[s] == pathOrientation[s - 1])
{
this.pathSections[s].StartPoint = pathSections[s].StartPoint + new Vector3d(
-postWidth * Math.Cos(pathOrientation[s]),
-postWidth * Math.Sin(pathOrientation[s]),
0);
}
// Right hand turn
else if (Math.Sin(pathOrientation[s] - pathOrientation[s - 1]) < 0)
{
this.pathSections[s - 1].EndPoint = pathSections[s - 1].EndPoint + new Vector3d(
postWidth * Math.Cos(pathOrientation[s - 1]),
postWidth * Math.Sin(pathOrientation[s - 1]),
0);
this.pathSections[s].StartPoint = pathSections[s].StartPoint + new Vector3d(
-postWidth * Math.Cos(pathOrientation[s]),
-postWidth * Math.Sin(pathOrientation[s]),
0);
Application.ShowAlertDialog("Section " + (s + 1) + "\nMoved startpoint " +
new Vector3d(-postWidth * Math.Cos(pathOrientation[s]), -postWidth * Math.Sin(pathOrientation[s]), 0));
}
}
}
}
public void Build()
{
// Declare variables
RailSection section;
// Run calculations
Calculations();
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
// Open the Block table record Model space for write
BlockTableRecord modelBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;
// Loop over number of railing sections
for (int s = 0; s < numSections; s++)
{
section = new RailSection(modelBlkTblRec,
acTrans,
pathSections[s],
postOrientation,
layerName);
// Rail height option
section.height = height;
// Default rail length option
section.defaultRailLength = defaultRailLength;
// First and last post options
if (!firstPost[s]) section.firstPost = false;
if (!lastPost[s]) section.lastPost = false;
// Kickplate options
if (!kickPlate) section.kickPlate = false;
section.Build();
}
// Save the transaction
acTrans.Commit();
}
}
[CommandMethod("RailPrompt")]
public static void RailPrompt()
{
// Declare variables
Point3dCollection pts = new Point3dCollection();
bool? kickPlate = null;
double? orientation = null;
double? railHeight = null;
double? railLength = null;
// Get the current document and database, and start a transaction
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
// Prepare prompt for points
PromptPointResult ptRes;
PromptPointOptions ptOpts = new PromptPointOptions("");
ptOpts.SetMessageAndKeywords("\nEnter point or [Height/Length/Kickplate/PostOrientation]",
"Height Length Kickplate PostOrientation");
ptOpts.AllowNone = true;
// Prepare prompt for kickplates
PromptResult kickplateRes;
PromptKeywordOptions kickplateOpts = new PromptKeywordOptions("");
kickplateOpts.Message = "\nInclude kickplate? ";
kickplateOpts.Keywords.Add("True");
kickplateOpts.Keywords.Add("False");
kickplateOpts.Keywords.Default = "True";
kickplateOpts.AllowArbitraryInput = false;
// Prepare prompt for post orientation
PromptResult orientRes;
PromptKeywordOptions orientOpts = new PromptKeywordOptions("");
orientOpts.Message = "\nPost on which side? ";
orientOpts.Keywords.Add("Left");
orientOpts.Keywords.Add("Right");
orientOpts.Keywords.Default = "Left";
orientOpts.AllowArbitraryInput = false;
// Prepare prompt for rail height
PromptDoubleResult heightResult;
PromptDoubleOptions heightOpts = new PromptDoubleOptions("");
heightOpts.Message = "\nEnter the rail height: ";
heightOpts.DefaultValue = 42;
heightOpts.AllowNegative = false;
heightOpts.AllowNone = false;
heightOpts.AllowZero = false;
// Prepare prompt for rail length
PromptDoubleResult lengthResult;
PromptDoubleOptions lengthOpts = new PromptDoubleOptions("");
lengthOpts.Message = "\nEnter the target rail length: ";
lengthOpts.DefaultValue = 96;
lengthOpts.AllowNegative = false;
lengthOpts.AllowNone = false;
lengthOpts.AllowZero = false;
do
{
ptRes = doc.Editor.GetPoint(ptOpts);
if (ptRes.Status == PromptStatus.Cancel) return;
if (ptRes.Status == PromptStatus.Keyword)
switch (ptRes.StringResult)
{
case "Height":
heightResult = doc.Editor.GetDouble(heightOpts);
if (heightResult.Value > 60)
{
Application.ShowAlertDialog("Invalid rail height: too high." +
"\nCannot be greater than 60 inches");
return;
}
else if (heightResult.Value < 30)
{
Application.ShowAlertDialog("Invalid rail height: too low." +
"\nCannot be less than 30 inches");
return;
}
else
{
railHeight = heightResult.Value;
}
break;
case "Length":
lengthResult = doc.Editor.GetDouble(lengthOpts);
railLength = lengthResult.Value;
break;
case "KickPlate":
kickplateRes = doc.Editor.GetKeywords(kickplateOpts);
if (kickplateRes.Status != PromptStatus.OK) return;
if (kickplateRes.StringResult == "False") kickPlate = false;
break;
case "PostOrientation":
orientRes = doc.Editor.GetKeywords(orientOpts);
if (orientRes.Status != PromptStatus.OK) return;
if (orientRes.StringResult == "Left") orientation = 1;
else orientation = -1;
break;
default:
break;
}
else if (ptRes.Status == PromptStatus.OK)
{
pts.Add(ptRes.Value);
ptOpts.BasePoint = ptRes.Value;
ptOpts.UseBasePoint = true;
ptOpts.UseDashedLine = true;
}
} while (ptRes.Status != PromptStatus.None);
if (ptRes.Status != PromptStatus.None) return;
// Initialize rail system
Rail rail = new Rail(db, pts);
// Deal with rail height input
if (railHeight.HasValue) rail.height = (double)railHeight;
// Deal with rail length input
if (railLength.HasValue) rail.defaultRailLength = (double)railLength;
// Deal with kickplate input
if (kickPlate.HasValue) rail.kickPlate = (bool)kickPlate;
// Deal with post orientation input
if (orientation.HasValue) rail.postOrientation = (double)orientation;
// Build rail
rail.Build();
}
}
class RailSection
{
// Auto-impl class properties
public BlockTableRecord blkTblRec { get; private set; }
public Transaction acTrans { get; private set; }
public Line pathSection { get; private set; }
public double height { get; set; }
public int tiers { get; set; }
public double[] tierHeight { get; set; }
public double postWidth { get; private set; }
public double defaultRailLength { get; set; }
public double defaultOrientation { get; set; }
public double railWidth { get; private set; }
public string layerName { get; private set; }
public bool firstPost { get; set; }
public bool lastPost { get; set; }
public bool kickPlate { get; set; }
public double pathOrientation { get; private set; }
public double pathVerticalAngle { get; private set; }
public double postOrientation { get; private set; }
public double sectionRails { get; private set; }
public double railLength { get; private set; }
public double kickplateHeight { get; private set; }
public double kickplateWidth { get; private set; }
// Public constructor
public RailSection(BlockTableRecord rec,
Transaction tr,
Line section,
double side,
string layerName)
{
// Set options to object properties
this.blkTblRec = rec;
this.acTrans = tr;
this.pathSection = section;
this.postOrientation = side;
this.layerName = layerName;
// Set some defaults
this.height = 42;
this.postWidth = 1.5;
this.railWidth = 1.5;
this.defaultRailLength = 96;
this.kickplateHeight = 4;
this.kickplateWidth = 0.25;
this.firstPost = true;
this.lastPost = true;
//Path horizontal orientation(phi in polar coordinates)
this.pathOrientation = Utils.PolarAnglePhi(pathSection);
//Path vertical orientation(theta in polar coordinates)
this.pathVerticalAngle = Utils.PolarAngleTheta(pathSection);
// Kickplate defaults (true in flat sections)
if (Math.Round(Utils.ToDegrees(pathVerticalAngle), 0) == 90) this.kickPlate = true;
else this.kickPlate = false;
}
private void ErrorCheck() {
// Error checks for section length (must be at least 2 post widths)
// Post width corrected for vertical angle
if (pathSection.Length < (2 * (postWidth / Math.Sin(pathVerticalAngle))))
{
throw new System.Exception("Invalid railing section: too short." +
"\nFrom (" + pathSection.StartPoint.X + ", " + pathSection.StartPoint.Y + ", " + pathSection.StartPoint.Z + ") " +
"\to (" + pathSection.EndPoint.X + ", " + pathSection.EndPoint.Y + ", " + pathSection.EndPoint.Z + ")");
}
// Check that section is not too steep (45 degrees or PI / 4 radians from horizontal)
if (pathVerticalAngle < (Math.PI / 4) && pathVerticalAngle > (3 * Math.PI / 4))
{
throw new System.Exception("Invalid railing section: too steep (must be < 45)." +
"\nFrom (" + pathSection.StartPoint.X + ", " + pathSection.StartPoint.Y + ", " + pathSection.StartPoint.Z + ") " +
"\to (" + pathSection.EndPoint.X + ", " + pathSection.EndPoint.Y + ", " + pathSection.EndPoint.Z + ")" +
"\nAngle (from horizontal): " + (90 - pathVerticalAngle.ToDegrees()));
}
// Check that post orientation is valid
if (Math.Abs(postOrientation) != 1)
{
throw new System.Exception("Invalid argument in CreatePost..." +
"\nside must equal 1 || -1" +
"\nside = " + postOrientation);
}
}
private void Calculations() {
// Tier heights
this.tierHeight = new double[2] { Math.Round(height / 2, 0) + railWidth, height };
this.tiers = tierHeight.GetLength(0);
// Calculate rail sections and length (per section)
this.sectionRails = Math.Max(1, Math.Round(pathSection.Length / (defaultRailLength - postWidth)));
this.railLength = ((pathSection.Length - ((sectionRails + 1) *
(postWidth / Math.Sin(pathVerticalAngle)))) / sectionRails);
}
public void Build()
{
// Declare variables
Solid3d post;
Solid3d rail;
Solid3d kickplateSolid;
Vector3d startVector;
Entity tempEnt;
double numPosts = 0;
// Error checking
try
{
ErrorCheck();
}
catch (System.Exception ex)
{
Application.ShowAlertDialog(ex.Message);
return;
}
// Run calculations
Calculations();
// Create post
post = CreatePost(height, postWidth, pathVerticalAngle, pathOrientation, postOrientation);
post.Layer = layerName;
// Create rail section
rail = CreateRail(railLength, railWidth, pathVerticalAngle, pathOrientation, postOrientation);
rail.Layer = layerName;
// Create kickplate
kickplateSolid = CreateKickplate(railLength, kickplateHeight, kickplateWidth, pathVerticalAngle,
pathOrientation, postOrientation);
kickplateSolid.Layer = layerName;
// Position first post (if necessary) and add to model and transaction
startVector = pathSection.StartPoint - Point3d.Origin;
numPosts++;
if (firstPost)
{
tempEnt = post.GetTransformedCopy(Matrix3d.Displacement(startVector));
blkTblRec.AppendEntity(tempEnt);
acTrans.AddNewlyCreatedDBObject(tempEnt, true);
}
// Loop over other rail sections
for (int i = 1; i <= sectionRails; i++)
{
// Position rails and add to model and transaction
foreach (double t in tierHeight)
{
// Pass true to RailLocation if no first post
tempEnt = rail.GetTransformedCopy(Matrix3d.Displacement(
startVector.Add(RailLocation(t, postWidth, pathVerticalAngle,
pathOrientation))));
blkTblRec.AppendEntity(tempEnt);
acTrans.AddNewlyCreatedDBObject(tempEnt, true);
}
// Postition kickplate and add to model and transaction
if (kickPlate)
{
tempEnt = kickplateSolid.GetTransformedCopy(Matrix3d.Displacement(
startVector.Add(KickplateLocation(postWidth, kickplateHeight,
pathVerticalAngle, pathOrientation))));
blkTblRec.AppendEntity(tempEnt);
acTrans.AddNewlyCreatedDBObject(tempEnt, true);
}
// Account for lastPost
if (i == sectionRails && !lastPost) continue;
else
{
// Determine base point for next post
startVector = pathSection.GetPointAtDist((railLength * i) +
((postWidth / Math.Sin(pathVerticalAngle)) * numPosts)) - Point3d.Origin;
// Position post and add to model and transaction
tempEnt = post.GetTransformedCopy(Matrix3d.Displacement(startVector));
numPosts++;
blkTblRec.AppendEntity(tempEnt);
acTrans.AddNewlyCreatedDBObject(tempEnt, true);
}
}
}
private static Solid3d CreatePost(double height,
double width,
double vAngle,
double oAngle,
double side)
{
// Calculate angle offset
double offset = width / Math.Tan(vAngle);
// Create polyline of rail post profile
Polyline postPoly = new Polyline();
postPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
postPoly.AddVertexAt(1, new Point2d(width, offset), 0, 0, 0);
postPoly.AddVertexAt(2, new Point2d(width, height + offset), 0, 0, 0);
postPoly.AddVertexAt(3, new Point2d(0, height), 0, 0, 0);
postPoly.Closed = true;
// Create the post
Solid3d post = Utils.ExtrudePolyline(postPoly, -side * width);
// Position the post vertically
post.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// Rotate the post
post.TransformBy(Matrix3d.Rotation(oAngle, Vector3d.ZAxis, Point3d.Origin));
return post;
}
private static Solid3d CreateRail(double length,
double width,
double vAngle,
double oAngle,
double side)
{
// Calculate angle offset
double vOffset = length * Math.Cos(vAngle);
// Create polyline of rail profile
Polyline railPoly = new Polyline();
railPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
railPoly.AddVertexAt(1, new Point2d(0, width), 0, 0, 0);
railPoly.AddVertexAt(2, new Point2d(length * Math.Sin(vAngle), width - vOffset), 0, 0, 0);
railPoly.AddVertexAt(3, new Point2d(length * Math.Sin(vAngle), -vOffset), 0, 0, 0);
railPoly.Closed = true;
// Create the rail
Solid3d rail = Utils.ExtrudePolyline(railPoly, side * width);
// Position the rail vertically
rail.TransformBy(Matrix3d.Rotation(-Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// Rotate the rail
rail.TransformBy(Matrix3d.Rotation(oAngle, Vector3d.ZAxis, Point3d.Origin));
return rail;
}
private static Vector3d RailLocation(double height,
double width,
double vAngle,
double oAngle)
{
// Declare variables
double x = 0;
double y = 0;
double z = 0;
// Calculate angle offset
double offset = width / Math.Tan(vAngle);
// Point coordinates
x = width * Math.Cos(oAngle);
y = width * Math.Sin(oAngle);
z = offset + height;
return new Vector3d(x, y, z);
}
private static Solid3d CreateKickplate(double length,
double height,
double width,
double vAngle,
double oAngle,
double side)
{
// Calculate angle offset
double vOffset = length * Math.Cos(vAngle);
// Create polyline of rail profile
Polyline kickplatePoly = new Polyline();
kickplatePoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
kickplatePoly.AddVertexAt(1, new Point2d(0, height), 0, 0, 0);
kickplatePoly.AddVertexAt(2, new Point2d(length * Math.Sin(vAngle), height - vOffset), 0, 0, 0);
kickplatePoly.AddVertexAt(3, new Point2d(length * Math.Sin(vAngle), -vOffset), 0, 0, 0);
kickplatePoly.Closed = true;
// Create the rail
Solid3d kickplate = Utils.ExtrudePolyline(kickplatePoly, side * width);
// Position the rail vertically
kickplate.TransformBy(Matrix3d.Rotation(-Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// Rotate the rail
kickplate.TransformBy(Matrix3d.Rotation(oAngle, Vector3d.ZAxis, Point3d.Origin));
return kickplate;
}
private static Vector3d KickplateLocation(double postWidth,
double height,
double vAngle,
double oAngle)
{
// Declare variables
double x;
double y;
double z;
// Calculate height offset
z = height + postWidth / Math.Tan(vAngle);
// Point coordinates
x = postWidth * Math.Cos(oAngle);
y = postWidth * Math.Sin(oAngle);
return new Vector3d(x, y, z);
}
}
class Stair
{
// Auto-impl class properties
public Database db { get; private set; }
public double height { get; private set; }
public double width { get; private set; }
public double idealRise { get; set; }
public double idealRun { get; set; }
public double treadOverlap { get; set; }
public int numRisers { get; private set; }
public double rise { get; private set; }
public double run { get; private set; }
public double totalRise { get; private set; }
public double totalRun { get; private set; }
public double stringerWidth { get; set; }
public double stringerDepth { get; set; }
public double treadHeight { get; set; }
public bool treadTop { get; set; }
public string name { get; private set; }
public ObjectId id { get; private set; }
// Vector in stair "right" direction (looking up stairs)
public Vector3d widthVector { get; set; }
public string layerName { get; set; }
// Other properties
private double? _stairAngle = null;
private Point3d _basePoint;
private Point3d _topPoint;
private bool _defineTopPoint;
private Vector3d _lengthVector;
public double? stairAngle
{
get
{
if (_stairAngle.HasValue)
{
return Utils.ToDegrees((double)_stairAngle);
}
else
{
return null;
}
}
set
{
this._stairAngle = Utils.ToRadians((double)value);
}
}
public Point3d stairTopPoint
{
get { return _topPoint; }
set
{
this._topPoint = value;
this._defineTopPoint = true;
}
}
public Point3d stairBasePoint
{
get { return _basePoint; }
set
{
this._basePoint = value;
this._defineTopPoint = false;
}
}
// Vector in stair "down" direction
public Vector3d stairLengthVector
{
get { return _lengthVector; }
set
{
this._lengthVector = value.UnitVector();
}
}
// Public constructor
public Stair(Database db,
double height,
double width)
{
Color layerColor;
this.db = db;
this.height = height;
this.width = width;
// Set some defaults
this.idealRun = 11;
this.idealRise = 7;
this.stringerWidth = 1.5;
this.stringerDepth = 12;
this.treadHeight = 1;
this.treadOverlap = 0;
this._defineTopPoint = false;
this.treadTop = false;
this.stairLengthVector = -Vector3d.XAxis;
this.stairBasePoint = Point3d.Origin;
this.widthVector = -Vector3d.YAxis;
// Create stair layer (if necessary)
this.layerName = "3D-Mezz-Egress";
layerColor = Utils.ChooseColor("teal");
Utils.CreateLayer(db, layerName, layerColor);
// Create name for block
this.name = "Stair - " + height + "x" + width;
}
public void Calculation()
{
if (treadTop)
{
// Calculate number of risers based on ideal rise (add one more rise than normal)
this.numRisers = Convert.ToInt32(Math.Max(1, Math.Round(height / idealRise)) + 1);
// Calculate final stair riser
this.rise = height / (numRisers - 1);
// Set total rise height of stairs
this.totalRise = numRisers * rise;
// Edit name for block
this.name = "Stair (TopTread) - " + height + "x" + width;
}
else
{
// Set total rise height of stairs to equal target height
this.totalRise = height;
// Calculate number of risers based on ideal rise
this.numRisers = Convert.ToInt32(Math.Max(1, Math.Round(totalRise / idealRise)));
// Calculate final stair riser
this.rise = totalRise / numRisers;
}
if (stairAngle.HasValue)
{
// Set stair tread run based off stair angle
this.run = ((totalRise / Math.Tan((double)_stairAngle)) + ((numRisers - 2) * treadOverlap)) / numRisers;
// Perform length calculations based off stair angle
this.totalRun = run * (numRisers - 1) - ((numRisers - 2) * treadOverlap);
}
else
{
// Set stair tread run (horizontal distance) as ideal
this.run = idealRun;
// Calculate stair length
this.totalRun = (numRisers - 1) * run - ((numRisers - 2) * treadOverlap);
// Set stair angle
this._stairAngle = Math.Atan2(totalRise, numRisers * run);
}
// Move base point if defining point is top
if (_defineTopPoint)
{
this._basePoint = _topPoint.Add(new Vector3d(
(totalRun * stairLengthVector.X),
(totalRun * stairLengthVector.Y),
-totalRise));
}
else
{
this._topPoint = _basePoint.Add(new Vector3d(
(totalRun * -stairLengthVector.X),
(totalRun * -stairLengthVector.Y),
totalRise));
}
// Set width vector based on length vector
this.widthVector = new Vector3d(
Math.Round(stairLengthVector.RotateBy(Math.PI / 2, Vector3d.ZAxis).X, 0),
Math.Round(stairLengthVector.RotateBy(Math.PI / 2, Vector3d.ZAxis).Y, 0),
Math.Round(stairLengthVector.RotateBy(Math.PI / 2, Vector3d.ZAxis).Z, 0));
}
public void Build()
{
// Declare variables
Solid3d stringer;
Solid3d tread;
Vector3d locationVector;
Entity tempEnt;
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
if (acBlkTbl.Has(name))
{
// Retrieve object id
this.id = acBlkTbl[name];
}
else
{
// Create new block (record)
using (BlockTableRecord acBlkTblRec = new BlockTableRecord())
{
acBlkTblRec.Name = name;
// Set the insertion point for the block
acBlkTblRec.Origin = new Point3d(0, 0, 0);
// Create stringer
stringer = CreateStringer(totalRise, totalRun, rise,
run, stringerWidth, stringerDepth, stairLengthVector, widthVector);
// Create stair tread
tread = CreateTread(width, stringerWidth, run, treadHeight,
stairLengthVector, widthVector);
// Add first stringer to model and transaction
locationVector = stairBasePoint - Point3d.Origin;
tempEnt = stringer.GetTransformedCopy(Matrix3d.Displacement(locationVector));
// Set block object properties
Utils.SetObjectProperties(tempEnt);
// Add object to block
acBlkTblRec.AppendEntity(tempEnt);
// Add second stringer to model and transaction
tempEnt = stringer.GetTransformedCopy(Matrix3d.Displacement(locationVector.Add(
new Vector3d(((width - stringerWidth) * widthVector.X),
((width - stringerWidth) * widthVector.Y),
0))));
// Set block object properties
Utils.SetObjectProperties(tempEnt);
// Add object to block
acBlkTblRec.AppendEntity(tempEnt);
// Loop over stair treads
for (int i = 1; i < numRisers; i++)
{
tempEnt = tread.GetTransformedCopy(Matrix3d.Displacement(locationVector.Add(
new Vector3d(
(stringerWidth * widthVector.X) +
((i - 1) * (run - treadOverlap) * -stairLengthVector.X) +
((stairLengthVector.CrossProduct(widthVector).X) * (i * rise)),
(stringerWidth * widthVector.Y) +
((i - 1) * (run - treadOverlap) * -stairLengthVector.Y) +
((stairLengthVector.CrossProduct(widthVector).X) * (i * rise)),
(stringerWidth * widthVector.Z) +
((i - 1) * (run - treadOverlap) * -stairLengthVector.Z) +
((stairLengthVector.CrossProduct(widthVector).Z) * (i * rise))))));
// Set block object properties
Utils.SetObjectProperties(tempEnt);
// Add object to block
acBlkTblRec.AppendEntity(tempEnt);
}
// Add Block to Block Table and close Transaction
acBlkTbl.UpgradeOpen();
acBlkTbl.Add(acBlkTblRec);
acTrans.AddNewlyCreatedDBObject(acBlkTblRec, true);
}
// Set block id property
this.id = acBlkTbl[name];
}
// Save the new object to the database
acTrans.Commit();
}
}
private static Solid3d CreateStringer(double height,
double length,
double stairHeight,
double stairDepth,
double stringerWidth,
double stringerDepth,
Vector3d lengthVector,
Vector3d widthVector)
{
// Calculate stair angle and stringer offsets
double stairAngle = Math.Atan2(height, length + stairDepth);
double vOffset = (stringerDepth - (stairDepth * Math.Sin(stairAngle))) / Math.Cos(stairAngle);
double hOffset = (stringerDepth - (stairHeight * Math.Cos(stairAngle))) / Math.Sin(stairAngle);
// Create polyline of stringer profile (laying down in sector 1 of X/Y)
Polyline stringerPoly = new Polyline();
stringerPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
stringerPoly.AddVertexAt(1, new Point2d(0, stairHeight), 0, 0, 0);
stringerPoly.AddVertexAt(2, new Point2d(length, height), 0, 0, 0);
stringerPoly.AddVertexAt(3, new Point2d(length, height - stairHeight - vOffset), 0, 0, 0);
stringerPoly.AddVertexAt(4, new Point2d(hOffset, 0), 0, 0, 0);
stringerPoly.Closed = true;
// Create the stringer (into positive Z)
Solid3d stringer = Utils.ExtrudePolyline(stringerPoly, stringerWidth);
// Position the stringer vertically
stringer.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// Position stringer based on width vector (if width vector is not default/right)
if ((lengthVector.CrossProduct(widthVector)) == -Vector3d.ZAxis)
{
stringer.TransformBy(Matrix3d.Displacement(new Vector3d(0, stringerWidth, 0)));
}
// Rotate the stringer
stringer.TransformBy(Matrix3d.Rotation(
Vector3d.XAxis.GetAngleTo(-lengthVector, Vector3d.ZAxis),
lengthVector.CrossProduct(widthVector),
Point3d.Origin));
return stringer;
}
private static Solid3d CreateTread(double width,
double stringerWidth,
double stairDepth,
double treadHeight,
Vector3d lengthVector,
Vector3d widthVector)
{
// Calculate tread width
double treadWidth = width - (2 * stringerWidth);
// Create polyline of tread profile
Polyline treadPoly = new Polyline();
treadPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
treadPoly.AddVertexAt(1, new Point2d(0, -treadHeight), 0, 0, 0);
treadPoly.AddVertexAt(2, new Point2d(stairDepth, -treadHeight), 0, 0, 0);
treadPoly.AddVertexAt(3, new Point2d(stairDepth, 0), 0, 0, 0);
treadPoly.Closed = true;
// Create the tread
Solid3d tread = Utils.ExtrudePolyline(treadPoly, treadWidth);
// Position the tread vertically
tread.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// Position tread based on width vector
if (lengthVector.CrossProduct(widthVector) == -Vector3d.ZAxis)
{
tread.TransformBy(Matrix3d.Displacement(new Vector3d(0, treadWidth, 0)));
}
// Rotate the tread
tread.TransformBy(Matrix3d.Rotation(
Vector3d.XAxis.GetAngleTo(-lengthVector, Vector3d.ZAxis), Vector3d.ZAxis, Point3d.Origin));
return tread;
}
[CommandMethod("StairPrompt")]
public static void StairPrompt()
{
// Get the current document and database, and start a transaction
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
// Prepare prompt for the stair height
PromptDoubleResult heightRes;
PromptDistanceOptions heightOpts = new PromptDistanceOptions("");
heightOpts.Message = "\nEnter the stair height: ";
heightOpts.DefaultValue = 108;
// Prepare prompt for the stair width
PromptDoubleResult widthRes;
PromptDistanceOptions widthOpts = new PromptDistanceOptions("");
widthOpts.Message = "\nEnter the stair width: ";
widthOpts.DefaultValue = 36;
// Prepare prompt for other options
PromptResult othersRes;
PromptKeywordOptions othersOpts = new PromptKeywordOptions("");
othersOpts.Message = "\nOptions: ";
othersOpts.Keywords.Add("Angle");
othersOpts.Keywords.Add("TopPoint");
othersOpts.Keywords.Add("BottomPoint");
othersOpts.Keywords.Add("Style");
othersOpts.Keywords.Add("TreadDepth");
othersOpts.Keywords.Add("RiserHeight");
othersOpts.Keywords.Add("Overlap");
othersOpts.AllowArbitraryInput = false;
othersOpts.AllowNone = true;
// Prepare prompt for the stair angle
PromptDoubleResult stairAngleResult;
PromptDoubleOptions stairAngleOpts = new PromptDoubleOptions("");
stairAngleOpts.Message = "\nEnter the stair angle: ";
stairAngleOpts.DefaultValue = 35;
stairAngleOpts.AllowNegative = false;
stairAngleOpts.AllowNone = false;
stairAngleOpts.AllowZero = false;
// Prepare prompt for top point
PromptPointResult topPointResult;
PromptPointOptions topPointOpts = new PromptPointOptions("");
topPointOpts.Message = "\nSelect top point: ";
topPointOpts.AllowNone = true;
// Prepare prompt for bottom point
PromptPointResult bottomPointResult;
PromptPointOptions bottomPointOpts = new PromptPointOptions("");
bottomPointOpts.Message = "\nSelect bottom point: ";
bottomPointOpts.AllowNone = true;
// Prepare prompt for stair orientation (follows top or bottom point prompts)
PromptPointResult vectorPointResult;
PromptPointOptions vectorPointOpts = new PromptPointOptions("");
vectorPointOpts.Message = "\nSelect stair orientation: ";
vectorPointOpts.AllowNone = true;
vectorPointOpts.UseBasePoint = true;
vectorPointOpts.UseDashedLine = true;
// Prepare prompt for other options
PromptResult styleRes;
PromptKeywordOptions styleOpts = new PromptKeywordOptions("");
styleOpts.Message = "\nTop Tread Level at Stair Height?: ";
styleOpts.Keywords.Add("Yes");
styleOpts.Keywords.Add("No");
styleOpts.AllowArbitraryInput = false;
styleOpts.AllowNone = false;
// Prepare prompt for the default riser height
PromptDoubleResult treadDepthResult;
PromptDistanceOptions treadDepthOpts = new PromptDistanceOptions("");
treadDepthOpts.Message = "\nEnter the target tread depth: ";
treadDepthOpts.DefaultValue = 11;
treadDepthOpts.AllowNegative = false;
treadDepthOpts.AllowNone = false;
treadDepthOpts.AllowZero = false;
// Prepare prompt for the default riser height
PromptDoubleResult riserHeightResult;
PromptDistanceOptions riserHeightOpts = new PromptDistanceOptions("");
riserHeightOpts.Message = "\nEnter the target riser height: ";
riserHeightOpts.DefaultValue = 7;
riserHeightOpts.AllowNegative = false;
riserHeightOpts.AllowNone = false;
riserHeightOpts.AllowZero = false;
// Prepare prompt for the stair tread overlap
PromptDoubleResult treadOverlapResult;
PromptDistanceOptions treadOverlapOpts = new PromptDistanceOptions("");
treadOverlapOpts.Message = "\nEnter the tread overlap distance: ";
treadOverlapOpts.DefaultValue = 0;
treadOverlapOpts.AllowNegative = false;
treadOverlapOpts.AllowNone = false;
treadOverlapOpts.AllowZero = true;
// Prompt for stair height
heightRes = doc.Editor.GetDistance(heightOpts);
if (heightRes.Status != PromptStatus.OK) return;
double height = heightRes.Value;
// Prompt for stair width
widthRes = doc.Editor.GetDistance(widthOpts);
if (widthRes.Status != PromptStatus.OK) return;
double width = widthRes.Value;
// Create stair object
Stair staircase = new Stair(db,
height,
width);
// Prompt for other options
do
{
othersRes = doc.Editor.GetKeywords(othersOpts);
if (othersRes.Status == PromptStatus.Cancel) return;
if (othersRes.Status == PromptStatus.OK)
{
switch (othersRes.StringResult)
{
case "Angle":
stairAngleResult = doc.Editor.GetDouble(stairAngleOpts);
if (stairAngleResult.Value > 45)
{
Application.ShowAlertDialog("Invalid stair angle: too steep." +
"\nCannot be greater than 45 degress");
return;
}
else
{
staircase.stairAngle = stairAngleResult.Value;
}
break;
case "TopPoint":
topPointResult = doc.Editor.GetPoint(topPointOpts);
staircase.stairTopPoint = topPointResult.Value;
vectorPointOpts.BasePoint = topPointResult.Value;
vectorPointResult = doc.Editor.GetPoint(vectorPointOpts);
staircase.stairLengthVector = vectorPointResult.Value - topPointResult.Value;
if (!Utils.VerifyOrthogonalAngle(Utils.PolarAnglePhi(staircase._lengthVector)))
{
Application.ShowAlertDialog("Invalid length vector: must be orthogonal.");
return;
}
othersOpts.Keywords[1].Visible = false;
othersOpts.Keywords[2].Visible = false;
break;
case "BottomPoint":
bottomPointResult = doc.Editor.GetPoint(bottomPointOpts);
staircase.stairBasePoint = bottomPointResult.Value;
vectorPointOpts.BasePoint = bottomPointResult.Value;
vectorPointResult = doc.Editor.GetPoint(vectorPointOpts);
staircase.stairLengthVector = bottomPointResult.Value - vectorPointResult.Value;
if (!Utils.VerifyOrthogonalAngle(Utils.PolarAnglePhi(staircase._lengthVector)))
{
Application.ShowAlertDialog("Invalid length vector: must be orthogonal.");
return;
}
othersOpts.Keywords[1].Visible = false;
othersOpts.Keywords[2].Visible = false;
break;
case "Style":
styleRes = doc.Editor.GetKeywords(styleOpts);
if (styleRes.Status == PromptStatus.Cancel) return;
else
{
switch (styleRes.StringResult)
{
case "Yes":
staircase.treadTop = true;
break;
case "No":
staircase.treadTop = false;
break;
default:
break;
}
}
break;
case "TreadDepth":
treadDepthResult = doc.Editor.GetDistance(treadDepthOpts);
if (treadDepthResult.Value < 8)
{
Application.ShowAlertDialog("Invalid tread depth: too narrow.");
return;
}
else if (treadDepthResult.Value > 12)
{
Application.ShowAlertDialog("Invalid tread depth: too deep.");
return;
}
else
{
staircase.idealRun = treadDepthResult.Value;
}
break;
case "RiserHeight":
riserHeightResult = doc.Editor.GetDistance(riserHeightOpts);
if (riserHeightResult.Value < 5)
{
Application.ShowAlertDialog("Invalid riser height: too shallow.");
return;
}
else if (riserHeightResult.Value > 10)
{
Application.ShowAlertDialog("Invalid riser height: too steep.");
return;
}
else
{
staircase.idealRise = riserHeightResult.Value;
}
break;
case "Overlap":
treadOverlapResult = doc.Editor.GetDistance(treadOverlapOpts);
if (treadOverlapResult.Value > staircase.idealRun)
{
Application.ShowAlertDialog("Invalid overlap: too large.");
return;
}
else
{
staircase.treadOverlap = treadOverlapResult.Value;
}
break;
default:
Application.ShowAlertDialog("Invalid Keyword");
break;
}
}
} while (othersRes.Status != PromptStatus.None);
// Calculate stairs
staircase.Calculation();
// Build stairs
staircase.Build();
}
}
class Ladder
{
// Auto-impl class properties
public Database db { get; private set; }
public double height { get; private set; }
public double width { get; private set; }
public double riserHeight { get; private set; }
public double treadDepth { get; set; }
public double length { get; private set; }
public double stringerWidth { get; set; }
public double stringerDepth { get; set; }
public double treadHeight { get; set; }
// Vector in stair "right" direction (looking up stairs)
public Vector3d widthVector { get; set; }
public string layerName { get; set; }
// Other properties
private int _nRisers;
private double _defaultRiserHeight;
private double _ladderAngle;
private Point3d _basePoint;
private Point3d _topPoint;
private Vector3d _lengthVector;
public int numRisers
{
get { return _nRisers; }
set
{
this._nRisers = value;
// Calculate stair height
this.riserHeight = height / value;
}
}
public double defaultRiserHeight
{
get { return _defaultRiserHeight; }
set
{
this._defaultRiserHeight = value;
// Calculate number of stairs
Application.ShowAlertDialog("Height: " + height + "\n" +
"Riser Default: " + value);
this.numRisers = Convert.ToInt32(
Math.Max(1, Math.Round(height / value))
);
}
}
public double angle
{
get { return Utils.ToDegrees(_ladderAngle); }
set
{
this._ladderAngle = Utils.ToRadians(value);
// Calculate ladder horizontal length
this.length = height / Math.Tan(_ladderAngle);
}
}
public Point3d ladderTopPoint
{
get { return _topPoint; }
set
{
this._topPoint = value;
this._basePoint = _topPoint.Add(new Vector3d(
(length * ladderLengthVector.X),
(length * ladderLengthVector.Y),
-height));
}
}
public Point3d ladderBasePoint
{
get { return _basePoint; }
set
{
this._basePoint = value;
this._topPoint = _basePoint.Add(new Vector3d(
(length * -ladderLengthVector.X),
(length * -ladderLengthVector.Y),
height));
}
}
// Vector in stair "down" direction
public Vector3d ladderLengthVector
{
get { return _lengthVector; }
set
{
this._lengthVector = value.UnitVector();
this._basePoint = _topPoint.Add(new Vector3d(
(length * ladderLengthVector.X),
(length * ladderLengthVector.Y),
-height));
this.widthVector = new Vector3d(
Math.Round(ladderLengthVector.RotateBy(Math.PI / 2, Vector3d.ZAxis).X, 0),
Math.Round(ladderLengthVector.RotateBy(Math.PI / 2, Vector3d.ZAxis).Y, 0),
Math.Round(ladderLengthVector.RotateBy(Math.PI / 2, Vector3d.ZAxis).Z, 0));
}
}
// Public constructor
public Ladder(Database db,
double height,
double width)
{
Color layerColor;
this.db = db;
this.height = height;
this.width = width;
// Set some defaults
this.treadDepth = 5;
this.defaultRiserHeight = 10;
this.stringerWidth = 1;
this.stringerDepth = 6;
this.treadHeight = 0.75;
this.angle = 75;
this._lengthVector = -Vector3d.XAxis;
this.ladderBasePoint = Point3d.Origin;
this.widthVector = -Vector3d.YAxis;
// Create beam layer (if necessary)
this.layerName = "3D-Mezz-Egress";
layerColor = Utils.ChooseColor("teal");
Utils.CreateLayer(db, layerName, layerColor);
}
public void Build()
{
// Declare variables
Solid3d stringer;
Solid3d tread;
Vector3d locationVector;
Entity tempEnt;
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
// Open the Block table record Model space for write
BlockTableRecord modelBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;
// Create stringer
stringer = CreateStringer(height, length, _ladderAngle, riserHeight,
stringerWidth, stringerDepth, ladderLengthVector, widthVector);
stringer.Layer = layerName;
// Create stair tread
tread = CreateTread(width, stringerWidth, treadDepth, treadHeight,
ladderLengthVector, widthVector);
tread.Layer = layerName;
// Add first stringer to model and transaction
locationVector = ladderBasePoint - Point3d.Origin;
tempEnt = stringer.GetTransformedCopy(Matrix3d.Displacement(locationVector));
modelBlkTblRec.AppendEntity(tempEnt);
acTrans.AddNewlyCreatedDBObject(tempEnt, true);
// Add second stringer to model and transaction
tempEnt = stringer.GetTransformedCopy(Matrix3d.Displacement(locationVector.Add(
new Vector3d(((width - stringerWidth) * widthVector.X),
((width - stringerWidth) * widthVector.Y),
0))));
modelBlkTblRec.AppendEntity(tempEnt);
acTrans.AddNewlyCreatedDBObject(tempEnt, true);
Application.ShowAlertDialog("Risers: " + numRisers + "\n" +
"height: " + height + "\n" +
"riser height: " + riserHeight + "\n" +
"step: " + ((height - riserHeight) / Math.Tan(_ladderAngle)));
// Loop over stair treads
for (int i = 1; i < numRisers; i++)
{
tempEnt = tread.GetTransformedCopy(Matrix3d.Displacement(locationVector.Add(
new Vector3d(
(stringerWidth * widthVector.X) +
((i - 1) * ((height - riserHeight) / Math.Tan(_ladderAngle) / (numRisers - 1)) * -ladderLengthVector.X) +
((ladderLengthVector.CrossProduct(widthVector).X) * (i * riserHeight)),
(stringerWidth * widthVector.Y) +
((i - 1) * ((height - riserHeight) / Math.Tan(_ladderAngle) / (numRisers - 1)) * -ladderLengthVector.Y) +
((ladderLengthVector.CrossProduct(widthVector).Y) * (i * riserHeight)),
(stringerWidth * widthVector.Z) +
((i - 1) * ((height - riserHeight) / Math.Tan(_ladderAngle) / (numRisers - 1)) * -ladderLengthVector.Z) +
((ladderLengthVector.CrossProduct(widthVector).Z) * (i * riserHeight))))));
modelBlkTblRec.AppendEntity(tempEnt);
acTrans.AddNewlyCreatedDBObject(tempEnt, true);
}
// Save the transaction
acTrans.Commit();
}
}
private static Solid3d CreateStringer(double height,
double length,
double stairAngle,
double stairHeight,
double stringerWidth,
double stringerDepth,
Vector3d lengthVector,
Vector3d widthVector)
{
// Create polyline of stringer profile (laying down in sector 1 of X/Y)
Polyline stringerPoly = new Polyline();
stringerPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
stringerPoly.AddVertexAt(1, new Point2d(0, stairHeight), 0, 0, 0);
stringerPoly.AddVertexAt(2, new Point2d((height - stairHeight) / Math.Tan(stairAngle), height), 0, 0, 0);
stringerPoly.AddVertexAt(3, new Point2d(length, height), 0, 0, 0);
stringerPoly.AddVertexAt(4, new Point2d(length, height - stringerDepth), 0, 0, 0);
stringerPoly.AddVertexAt(5, new Point2d((height - stringerDepth) / Math.Tan(stairAngle), height - stringerDepth), 0, 0, 0);
stringerPoly.AddVertexAt(6, new Point2d(stringerDepth, stringerDepth * Math.Tan(stairAngle)), 0, 0, 0);
stringerPoly.AddVertexAt(7, new Point2d(stringerDepth, 0), 0, 0, 0);
stringerPoly.Closed = true;
// Create the stringer (into positive Z)
Solid3d stringer = Utils.ExtrudePolyline(stringerPoly, stringerWidth);
// Position the stringer vertically
stringer.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// Position stringer based on width vector (if width vector is not default/right)
if ((lengthVector.CrossProduct(widthVector)) == -Vector3d.ZAxis)
{
stringer.TransformBy(Matrix3d.Displacement(new Vector3d(0, stringerWidth, 0)));
}
// Rotate the stringer
stringer.TransformBy(Matrix3d.Rotation(
Vector3d.XAxis.GetAngleTo(-lengthVector, Vector3d.ZAxis),
lengthVector.CrossProduct(widthVector),
Point3d.Origin));
return stringer;
}
private static Solid3d CreateTread(double width,
double stringerWidth,
double stairDepth,
double treadHeight,
Vector3d lengthVector,
Vector3d widthVector)
{
// Calculate tread width
double treadWidth = width - (2 * stringerWidth);
// Create polyline of tread profile
Polyline treadPoly = new Polyline();
treadPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
treadPoly.AddVertexAt(1, new Point2d(0, -treadHeight), 0, 0, 0);
treadPoly.AddVertexAt(2, new Point2d(stairDepth, -treadHeight), 0, 0, 0);
treadPoly.AddVertexAt(3, new Point2d(stairDepth, 0), 0, 0, 0);
treadPoly.Closed = true;
// Create the tread
Solid3d tread = Utils.ExtrudePolyline(treadPoly, treadWidth);
// Position the tread vertically
tread.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// Position tread based on width vector
if (lengthVector.CrossProduct(widthVector) == -Vector3d.ZAxis)
{
tread.TransformBy(Matrix3d.Displacement(new Vector3d(0, treadWidth, 0)));
}
// Rotate the tread
tread.TransformBy(Matrix3d.Rotation(
Vector3d.XAxis.GetAngleTo(-lengthVector, Vector3d.ZAxis), Vector3d.ZAxis, Point3d.Origin));
return tread;
}
//private static Solid3d CreateRail(double height,
// double length,
// double stairAngle,
// double stairHeight,
// double stringerWidth,
// double stringerDepth,
// Vector3d lengthVector,
// Vector3d widthVector)
//{
// // Create polyline of main rail profile (laying down in sector 1 of X/Y)
// Polyline stringerPoly = new Polyline();
// stringerPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
// stringerPoly.AddVertexAt(1, new Point2d(0, stairHeight), 0, 0, 0);
// stringerPoly.AddVertexAt(2, new Point2d((height - stairHeight) / Math.Tan(stairAngle), height), 0, 0, 0);
// stringerPoly.AddVertexAt(3, new Point2d(length, height), 0, 0, 0);
// stringerPoly.AddVertexAt(4, new Point2d(length, height - stringerDepth), 0, 0, 0);
// stringerPoly.AddVertexAt(5, new Point2d((height - stringerDepth) / Math.Tan(stairAngle), height - stringerDepth), 0, 0, 0);
// stringerPoly.AddVertexAt(6, new Point2d(stringerDepth, stringerDepth * Math.Tan(stairAngle)), 0, 0, 0);
// stringerPoly.AddVertexAt(7, new Point2d(stringerDepth, 0), 0, 0, 0);
// stringerPoly.Closed = true;
// // Create the stringer (into positive Z)
// Solid3d stringer = Utils.ExtrudePolyline(stringerPoly, stringerWidth);
// // Position the stringer vertically
// stringer.TransformBy(Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin));
// // Position stringer based on width vector (if width vector is not default/right)
// if ((lengthVector.CrossProduct(widthVector)) == -Vector3d.ZAxis)
// {
// stringer.TransformBy(Matrix3d.Displacement(new Vector3d(0, stringerWidth, 0)));
// }
// // Rotate the stringer
// stringer.TransformBy(Matrix3d.Rotation(
// Vector3d.XAxis.GetAngleTo(-lengthVector, Vector3d.ZAxis),
// lengthVector.CrossProduct(widthVector),
// Point3d.Origin));
// return stringer;
//}
[CommandMethod("LadderPrompt")]
public static void LadderPrompt()
{
// Get the current document and database, and start a transaction
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
// Prepare prompt for the stair height
PromptDoubleResult heightRes;
PromptDistanceOptions heightOpts = new PromptDistanceOptions("");
heightOpts.Message = "\nEnter the stair height: ";
heightOpts.DefaultValue = 108;
// Prepare prompt for the stair width
PromptDoubleResult widthRes;
PromptDistanceOptions widthOpts = new PromptDistanceOptions("");
widthOpts.Message = "\nEnter the stair width: ";
widthOpts.DefaultValue = 24;
// Prepare prompt for other options
PromptResult othersRes;
PromptKeywordOptions othersOpts = new PromptKeywordOptions("");
othersOpts.Message = "\nOptions: ";
othersOpts.Keywords.Add("TopPoint");
othersOpts.Keywords.Add("BottomPoint");
othersOpts.Keywords.Add("RiserHeight");
othersOpts.Keywords.Add("Angle");
othersOpts.AllowArbitraryInput = false;
othersOpts.AllowNone = true;
// Prepare prompt for top point
PromptPointResult topPointResult;
PromptPointOptions topPointOpts = new PromptPointOptions("");
topPointOpts.Message = "\nSelect top point: ";
topPointOpts.AllowNone = true;
// Prepare prompt for bottom point
PromptPointResult bottomPointResult;
PromptPointOptions bottomPointOpts = new PromptPointOptions("");
bottomPointOpts.Message = "\nSelect bottom point: ";
bottomPointOpts.AllowNone = true;
// Prepare prompt for bottom point
PromptPointResult vectorPointResult;
PromptPointOptions vectorPointOpts = new PromptPointOptions("");
vectorPointOpts.Message = "\nSelect stair orientation: ";
vectorPointOpts.AllowNone = true;
vectorPointOpts.UseBasePoint = true;
vectorPointOpts.UseDashedLine = true;
// Prepare prompt for the default riser height
PromptDoubleResult riserHeightResult;
PromptDistanceOptions riserHeightOpts = new PromptDistanceOptions("");
riserHeightOpts.Message = "\nEnter the target riser height: ";
riserHeightOpts.DefaultValue = 7;
riserHeightOpts.AllowNegative = false;
riserHeightOpts.AllowNone = false;
riserHeightOpts.AllowZero = false;
// Prepare prompt for the stair tread overlap
PromptDoubleResult angleResult;
PromptDoubleOptions angleOpts = new PromptDoubleOptions("");
angleOpts.Message = "\nEnter the ladder angle: ";
angleOpts.DefaultValue = 75;
angleOpts.AllowNegative = false;
angleOpts.AllowNone = false;
angleOpts.AllowZero = false;
// Prompt for stair height
heightRes = doc.Editor.GetDistance(heightOpts);
if (heightRes.Status != PromptStatus.OK) return;
double height = heightRes.Value;
// Prompt for stair width
widthRes = doc.Editor.GetDistance(widthOpts);
if (widthRes.Status != PromptStatus.OK) return;
double width = widthRes.Value;
// Create stair object
Ladder shipladder = new Ladder(db,
height,
width);
// Prompt for other options
do
{
othersRes = doc.Editor.GetKeywords(othersOpts);
if (othersRes.Status == PromptStatus.Cancel) return;
if (othersRes.Status == PromptStatus.OK)
{
switch (othersRes.StringResult)
{
case "TopPoint":
topPointResult = doc.Editor.GetPoint(topPointOpts);
shipladder.ladderTopPoint = topPointResult.Value;
vectorPointOpts.BasePoint = topPointResult.Value;
vectorPointResult = doc.Editor.GetPoint(vectorPointOpts);
shipladder.ladderLengthVector = vectorPointResult.Value - topPointResult.Value;
if (!Utils.VerifyOrthogonalAngle(Utils.PolarAnglePhi(shipladder._lengthVector)))
{
Application.ShowAlertDialog("Invalid length vector: must be orthogonal.");
return;
}
othersOpts = new PromptKeywordOptions("");
othersOpts.Message = "\nOptions: ";
othersOpts.Keywords.Add("RiserHeight");
othersOpts.Keywords.Add("TreadOverlap");
othersOpts.AllowArbitraryInput = false;
othersOpts.AllowNone = true;
break;
case "BottomPoint":
bottomPointResult = doc.Editor.GetPoint(bottomPointOpts);
shipladder.ladderBasePoint = bottomPointResult.Value;
vectorPointOpts.BasePoint = bottomPointResult.Value;
vectorPointResult = doc.Editor.GetPoint(vectorPointOpts);
shipladder.ladderLengthVector = bottomPointResult.Value - vectorPointResult.Value;
if (!Utils.VerifyOrthogonalAngle(Utils.PolarAnglePhi(shipladder._lengthVector)))
{
Application.ShowAlertDialog("Invalid length vector: must be orthogonal.");
return;
}
othersOpts = new PromptKeywordOptions("");
othersOpts.Message = "\nOptions: ";
othersOpts.Keywords.Add("RiserHeight");
othersOpts.Keywords.Add("TreadOverlap");
othersOpts.AllowArbitraryInput = false;
othersOpts.AllowNone = true;
break;
case "RiserHeight":
riserHeightResult = doc.Editor.GetDistance(riserHeightOpts);
if (riserHeightResult.Value < 9)
{
Application.ShowAlertDialog("Invalid riser height: too shallow.");
return;
}
else if (riserHeightResult.Value > 11)
{
Application.ShowAlertDialog("Invalid riser height: too steep.");
return;
}
else
{
shipladder.defaultRiserHeight = riserHeightResult.Value;
}
break;
case "Angle":
angleResult = doc.Editor.GetDouble(angleOpts);
if (angleResult.Value > 80)
{
Application.ShowAlertDialog("Invalid angle: too steep.");
return;
}
else if (angleResult.Value < 50)
{
Application.ShowAlertDialog("Invalid angle: too shallow.");
}
else
{
shipladder.angle = angleResult.Value;
}
break;
default:
Application.ShowAlertDialog("Invalid Keyword");
break;
}
}
} while (othersRes.Status != PromptStatus.None);
// Build stairs
shipladder.Build();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
namespace AugmentedReality.Utilities
{
public class LatLongMath
{
public static double GetDistance(GeoCoordinate point1, GeoCoordinate point2)
{
double R = 6371; // km
double dLat = LatLongMath.ToRad(point2.Latitude - point1.Latitude);
double dLon = LatLongMath.ToRad(point2.Longitude - point1.Longitude);
double lat1 = LatLongMath.ToRad(point1.Latitude);
double lat2 = LatLongMath.ToRad(point2.Latitude);
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
double d = R * c;
return d * 1000;
//will return distance in metres
}
public static double GetBearing(GeoCoordinate position, GeoCoordinate point)
{
double dLon = LatLongMath.ToRad(point.Longitude - position.Longitude);
double lat1 = LatLongMath.ToRad(position.Latitude);
double lat2 = LatLongMath.ToRad(point.Latitude);
double y = Math.Sin(dLon) * Math.Cos(lat2);
double x = Math.Cos(lat1) * Math.Sin(lat2) -
Math.Sin(lat1) * Math.Cos(lat2) * Math.Cos(dLon);
double brng = LatLongMath.ToDeg(Math.Atan2(y, x));
return brng;
}
public static double GetCompassBearing(GeoCoordinate position, GeoCoordinate point)
{
return ((GetBearing(position, point) + 360) % 360);
}
public static double ToRad(double angle)
{
return (Math.PI / 180) * angle;
}
public static double ToDeg(double angle)
{
return (180 / Math.PI) * angle;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace AdventOfCode2019
{
public static class Day15
{
public static void RunDay()
{
Console.WriteLine("Day 15");
P1();
P2();
Console.WriteLine("**************");
Console.WriteLine(Environment.NewLine);
}
static char[,] grid = new char[50, 50];
static int[] curPos = new int[] { 25, 25 };
static Facing currentFacing = Facing.north;
static bool stepSuccess;
static StepType stepType = StepType.forward;
static bool complete = false;
static void P1()
{
var lines = Utilities.GetStringFromFile("Day15.txt").SplitLongArrayFromString(',');
var vm = new IntCodeVM(new IntCodeVMConfiguration() { });
vm.WriteProgram(lines);
grid[25, 25] = 'S';
Draw(grid);
vm.WriteInput((long)Facing.north);
//vm.WriteMemory(0, 1);
while (vm.RunProgram() == HALTTYPE.HALT_WAITING)
{
processOutputs(vm);
if (complete)
{
break;
}
//what type of step was taken?
switch (stepType)
{
case StepType.forward:
//was step forward successful? if not turn left
if (!stepSuccess)
{
TurnDirection(Direction.left);
}
//attempt to turn right now.
stepType = StepType.right;
vm.WriteInput((long)GetTurnDirection(Direction.right));
break;
case StepType.right:
//if step was successful change facing and try to turn right again
if (stepSuccess)
{
TurnDirection(Direction.right);
stepType = StepType.right;
vm.WriteInput((long)GetTurnDirection(Direction.right));
}
//step unsuccessful, continue forward.
else
{
vm.WriteInput((long)currentFacing);
stepType = StepType.forward;
}
break;
default:
break;
}
//Draw(grid);
}
Draw(grid);
int[] target = new int[] { 0, 0 };
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
if (grid[i, j] == 'O')
{
target = new int[] { i, j };
}
}
}
var s = new seeker(target, 0, grid, new int[] { 25, 25 }, Facing.north);
var result = s.Seek();
Console.WriteLine($"Min Steps to get to Oxygen Control: {result.Value}");
}
static void P2()
{
grid = new char[50, 50];
curPos = new int[] { 25, 25 };
currentFacing = Facing.north;
stepType = StepType.forward;
complete = false;
var lines = Utilities.GetStringFromFile("Day15.txt").SplitLongArrayFromString(',');
var vm = new IntCodeVM(new IntCodeVMConfiguration() { });
vm.WriteProgram(lines);
grid[25, 25] = 'S';
Draw(grid);
vm.WriteInput((long)Facing.north);
//vm.WriteMemory(0, 1);
while (vm.RunProgram() == HALTTYPE.HALT_WAITING)
{
processOutputs(vm);
if (complete)
{
break;
}
//what type of step was taken?
switch (stepType)
{
case StepType.forward:
//was step forward successful? if not turn left
if (!stepSuccess)
{
TurnDirection(Direction.left);
}
//attempt to turn right now.
stepType = StepType.right;
vm.WriteInput((long)GetTurnDirection(Direction.right));
break;
case StepType.right:
//if step was successful change facing and try to turn right again
if (stepSuccess)
{
TurnDirection(Direction.right);
stepType = StepType.right;
vm.WriteInput((long)GetTurnDirection(Direction.right));
}
//step unsuccessful, continue forward.
else
{
vm.WriteInput((long)currentFacing);
stepType = StepType.forward;
}
break;
default:
break;
}
//Draw(grid);
}
Draw(grid);
int[] target = new int[] { 0, 0 };
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
if (grid[i, j] == 'O')
{
target = new int[] { i, j };
}
}
}
var s = new seeker(new int[] { 0,0 }, 0, grid, target, Facing.south);
var result = s.Seek();
Console.WriteLine($"Max time to fill compartment: {seeker.MaxSteps}");
}
static Facing GetTurnDirection(Direction dir)
{
Facing f = currentFacing;
switch (currentFacing)
{
case Facing.north:
f = (dir == Direction.left ? Facing.west : Facing.east);
break;
case Facing.south:
f = (dir == Direction.left ? Facing.east : Facing.west);
break;
case Facing.west:
f = (dir == Direction.left ? Facing.south : Facing.north);
break;
case Facing.east:
f = (dir == Direction.left ? Facing.north : Facing.south);
break;
}
return f;
}
static void TurnDirection(Direction dir)
{
switch (currentFacing)
{
case Facing.north:
currentFacing = (dir == Direction.left ? Facing.west : Facing.east);
break;
case Facing.south:
currentFacing = (dir == Direction.left ? Facing.east : Facing.west);
break;
case Facing.west:
currentFacing = (dir == Direction.left ? Facing.south : Facing.north);
break;
case Facing.east:
currentFacing = (dir == Direction.left ? Facing.north : Facing.south);
break;
}
}
static void processOutputs(IntCodeVM vm)
{
while (vm.outputs.Count > 0)
{
var tile = vm.outputs.Dequeue();
var nextPos = new int[2];
curPos.CopyTo(nextPos, 0);
//assume step success
stepSuccess = true;
char writeTile = '.';
switch (tile)
{
case 0:
writeTile = '█';
stepSuccess = false; //step unsuccessful
break;
case 1:
writeTile = '.';
break;
case 2:
writeTile = 'O';
break;
default:
break;
}
Facing f = currentFacing;
if (stepType == StepType.right)
{
f = GetTurnDirection(Direction.right);
}
switch (f)
{
case Facing.north:
nextPos[1]--;
break;
case Facing.south:
nextPos[1]++;
break;
case Facing.west:
nextPos[0]--;
break;
case Facing.east:
nextPos[0]++;
break;
default:
break;
}
if (nextPos[0] == 25 && nextPos[1] == 25)
{
complete = true;
return;
}
grid[nextPos[0], nextPos[1]] = writeTile;
if (writeTile != '█')
{
curPos = nextPos;
}
}
}
static void Draw(char[,] grid)
{
Console.Clear();
for (int i = 0; i < grid.GetLength(1); i++)
{
var row = "";
for (int j = 0; j < grid.GetLength(0); j++)
{
row = row + (grid[j, i] == '\0' ? 'X' : grid[j, i]);
}
Console.WriteLine(row);
}
Thread.Sleep(100);
//Console.WriteLine($"Score: {score} ---- Blockes Remaining: {blockcount}");
}
}
public enum Facing
{
north = 1,
south = 2,
west = 3,
east = 4
}
public enum StepType
{
forward = 1,
right = 2
}
public enum Direction
{
left,
right
}
public class seeker
{
public static int MaxSteps = 0;
int steps { get; set; } = 0;
int[] target { get; set; }
Facing currentFacing = Facing.north;
int[] CurrentPos { get; set; }
char[,] grid;
List<seeker> childSeekers = new List<seeker>();
public KeyValuePair<bool, int> Seek()
{
while (true)
{
grid[CurrentPos[0], CurrentPos[1]] = 'Z';
var fls = GetForwardOpenFacings();
if (CurrentPos[0] == target[0] && CurrentPos[1] == target[1])
{
break;
}
switch (fls.Count)
{
case 1:
Move(fls.First());
currentFacing = fls.First();
break;
case 0:
return new KeyValuePair<bool, int>(false, steps);
default:
foreach (var f in fls)
{
childSeekers.Add(new seeker(target, steps+1, grid, GetDirPos(f), f));
}
foreach (var s in childSeekers)
{
var result = s.Seek();
if (result.Key)
{
return result;
}
else
{
if (result.Value > seeker.MaxSteps)
{
seeker.MaxSteps = result.Value;
}
}
}
break;
}
}
return new KeyValuePair<bool, int>(true, steps);
}
int[] GetDirPos(Facing f)
{
int[] newPos = new int[2];
CurrentPos.CopyTo(newPos, 0);
switch (f)
{
case Facing.north:
newPos[1]--;
break;
case Facing.south:
newPos[1]++;
break;
case Facing.west:
newPos[0]--;
break;
case Facing.east:
newPos[0]++;
break;
default:
break;
}
return newPos;
}
void Move(Facing f)
{
switch (f)
{
case Facing.north:
CurrentPos[1]--;
break;
case Facing.south:
CurrentPos[1]++;
break;
case Facing.west:
CurrentPos[0]--;
break;
case Facing.east:
CurrentPos[0]++;
break;
default:
break;
}
steps++;
Draw(grid);
}
bool IsFacingOpen(Facing f)
{
var nextPos = new int[2];
CurrentPos.CopyTo(nextPos, 0);
switch (f)
{
case Facing.north:
nextPos[1]--;
break;
case Facing.south:
nextPos[1]++;
break;
case Facing.west:
nextPos[0]--;
break;
case Facing.east:
nextPos[0]++;
break;
default:
break;
}
var charAtPosition = grid[nextPos[0], nextPos[1]];
return (charAtPosition == '.' || charAtPosition == 'O');
}
List<Facing> GetForwardOpenFacings()
{
List<Facing> fls = new List<Facing>();
fls.Add(Facing.east);
fls.Add(Facing.south);
fls.Add(Facing.west);
fls.Add(Facing.north);
switch (currentFacing)
{
case Facing.north:
fls.Remove(Facing.south);
break;
case Facing.south:
fls.Remove(Facing.north);
break;
case Facing.west:
fls.Remove(Facing.east);
break;
case Facing.east:
fls.Remove(Facing.west);
break;
default:
break;
}
var openFacing = new List<Facing>();
foreach (var f in fls)
{
if (IsFacingOpen(f))
{
openFacing.Add(f);
}
}
return openFacing;
}
Facing GetTurnDirection(Direction dir)
{
Facing f = currentFacing;
switch (currentFacing)
{
case Facing.north:
f = (dir == Direction.left ? Facing.west : Facing.east);
break;
case Facing.south:
f = (dir == Direction.left ? Facing.east : Facing.west);
break;
case Facing.west:
f = (dir == Direction.left ? Facing.south : Facing.north);
break;
case Facing.east:
f = (dir == Direction.left ? Facing.north : Facing.south);
break;
}
return f;
}
void TurnDirection(Direction dir)
{
switch (currentFacing)
{
case Facing.north:
currentFacing = (dir == Direction.left ? Facing.west : Facing.east);
break;
case Facing.south:
currentFacing = (dir == Direction.left ? Facing.east : Facing.west);
break;
case Facing.west:
currentFacing = (dir == Direction.left ? Facing.south : Facing.north);
break;
case Facing.east:
currentFacing = (dir == Direction.left ? Facing.north : Facing.south);
break;
}
}
void Draw(char[,] grid)
{
Console.Clear();
for (int i = 0; i < grid.GetLength(1); i++)
{
var row = "";
for (int j = 0; j < grid.GetLength(0); j++)
{
row = row + (grid[j, i] == '\0' ? 'X' : grid[j, i]);
}
Console.WriteLine(row);
}
Thread.Sleep(10);
//Console.WriteLine($"Score: {score} ---- Blockes Remaining: {blockcount}");
}
public seeker(int[] target, int startingSteps, char[,] grid, int[] pos, Facing initialFacing)
{
steps = startingSteps;
this.target = target;
this.grid = grid;
CurrentPos = pos;
currentFacing = initialFacing;
}
}
}
|
using System;
namespace Xango
{
using Shango.CommandProcessor;
using ConsoleProcessRedirection;
using Shango.Commands;
/// <summary>
/// Summary description for Class1.
/// </summary>
public class XangoApp : ICommandEnvironment
{
public
XangoApp()
{
_Terminal = new ConsoleTerminal();
InternalCommandFactory internalFactory = new InternalCommandFactory(
_Terminal );
_CommandProcessor = new StandardCommandProcessor(
this,
internalFactory,
_Terminal,
50 );
}
#region ICommandEnvironment Members
public void CloseEnvironment()
{
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[MTAThread]
static int Main(string[] args)
{
XangoApp shell = new XangoApp();
return shell.Execute( args );
}
int
Execute( string[] args )
{
string commandLine = "";
foreach ( string argument in args )
{
commandLine += " " + argument;
}
_CommandProcessor.ProcessCommand(
commandLine,
false,
false);
return 0;
}
StandardCommandProcessor _CommandProcessor;
ConsoleTerminal _Terminal;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Handles the cameras for the game
/// Written by Barrington Campbell
/// </summary>
public class CameraManager : MonoBehaviour {
#region Attributes
[SerializeField]
Vector3 menuCameraPosition, gameCemeraPostion; //Different Camera positions (Menu - Main Menu | Game - In Game)
[SerializeField]
float transitionTime;
bool transition; //Tells if there is a camera transition currently going on
#endregion
private void Update()
{
if(transition == true)
{
//Lerp throught the point of view
Camera.main.orthographicSize = Mathf.Lerp(Camera.main.orthographicSize, 12, 0.02f);
//Lerp the position of the camera
float cameraX = Mathf.Lerp(Camera.main.transform.position.x, gameCemeraPostion.x, 0.02f);
float cameraY = Mathf.Lerp(Camera.main.transform.position.y, gameCemeraPostion.y, 0.02f);
float cameraZ = Mathf.Lerp(Camera.main.transform.position.z, gameCemeraPostion.z, 0.02f);
Camera.main.transform.position = new Vector3(cameraX, cameraY, cameraZ);
//Stop the transition once the camera is positioned correctly
if (Camera.main.orthographicSize >= 12 || Camera.main.orthographicSize <= 3)
transition = false;
}
}
/// <summary>
/// Changes the main cameras field of view when switching in between game states
/// </summary>
public void ChangeCameraView(StateManager.GameState state)
{
if (state == StateManager.GameState.Game)
{
transition = true;
}
else if (state == StateManager.GameState.MainMenu)
{
transition = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using SFB;
using UniRx.Async;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Systems{
public static class Picture{
private static Queue<Texture2D>[] assets =
{new Queue<Texture2D>(), new Queue<Texture2D>(), new Queue<Texture2D>()};
private static Texture2D clearTexture;
public static Texture2D ClearTexture => clearTexture;
public static Texture2D GetNextTex2D(Number number){
return assets[(int)number].Dequeue();
}
public static async UniTask LoadAssets(Number number,CancellationToken token){
foreach(var path in await Load(token)){
Debug.Log(path);
token.ThrowIfCancellationRequested();
var tex2D = FilePath2Tex2D(path);
token.ThrowIfCancellationRequested();
if(tex2D==null){continue;}
assets[(int)number].Enqueue(tex2D);
}
clearTexture = Resources.Load<Texture2D>("clear");
}
public static bool HasNextTex2D(Number number){
return assets[(int)number].Any();
}
public static void UnloadAssets(){
Object.DestroyImmediate(clearTexture,true);
foreach(var asset in assets){
foreach(var tex in asset){
Debug.Log(tex);
Object.DestroyImmediate(tex,true);
}
}
Resources.UnloadUnusedAssets();
}
private static async UniTask<IEnumerable<string>> Load(CancellationToken token){
// return await UniTask.Run(() => {
// // using(var ofd = new OpenFileDialog()){
// // ofd.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|All files (*.*)|*.*";
// // ofd.Title = "画像ファイルを指定してください";
// // ofd.ShowDialog();
// // token.ThrowIfCancellationRequested();
// // return ofd.FileNames;
// // }
// var extensions = new[]{
// new ExtensionFilter("Image Files", "png", "jpg", "jpeg")
// };
//
// var path = StandaloneFileBrowser.OpenFilePanel("画像ファイルを指定してください", "", extensions, true);
// return path;
// });
var extensions = new[]{
new ExtensionFilter("Image Files", "png", "jpg", "jpeg")
};
var path = StandaloneFileBrowser.OpenFilePanel("画像ファイルを指定してください", "", extensions, true);
return path;
}
private static Texture2D FilePath2Tex2D(string path){
Texture2D texture;
if(!File.Exists(path)){ return null;}
using(var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)){
var bin = new BinaryReader(fileStream);
var readBinary = bin.ReadBytes((int)bin.BaseStream.Length);
bin.Close();
//横サイズ
var pos = 16;
var width = 0;
for(var i = 0; i < 4; i++){ width = width * 256 + readBinary[pos++]; }
//縦サイズ
var height = 0;
for(var i = 0; i < 4; i++){ height = height * 256 + readBinary[pos++]; }
//byteからTexture2D作成
texture = new Texture2D(1,1);
texture.LoadImage(readBinary);
}
return texture;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using Dnn.ExportImport.Components.Common;
using Dnn.ExportImport.Components.Interfaces;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Localization;
using Newtonsoft.Json;
namespace Dnn.ExportImport.Components.Dto
{
/// <summary>
/// Details of the summary item to show in the export/import summary and progress.
/// </summary>
[JsonObject]
public class SummaryItem : IDateTimeConverter
{
/// <summary>
/// Category of the import/export. Also identifier for localization
/// </summary>
public string Category { get; set; }
/// <summary>
/// Total items to import/export.
/// </summary>
public int TotalItems { get; set; }
/// <summary>
/// Formatted total items.
/// </summary>
public string TotalItemsString => Util.FormatNumber(TotalItems);
/// <summary>
/// Items processed.
/// </summary>
public int ProcessedItems { get; set; }
/// <summary>
/// Is job finished or not yet.
/// </summary>
public bool Completed { get; set; }
/// <summary>
/// Formatted processed items.
/// </summary>
public string ProcessedItemsString => Util.FormatNumber(ProcessedItems);
/// <summary>
/// Progress in percentage.
/// </summary>
public int ProgressPercentage { get; set; }
/// <summary>
/// Order to show on UI.
/// </summary>
public uint Order { get; set; }
public void ConvertToLocal(UserInfo userInfo)
{
//Nothing to convert.
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mediateka.Entity
{
public abstract class BaseElement
{
public string Name { get; set; }
public string FileInfo {get;}
public abstract String getStream();
bool IsStreaming { get; set; }
public override string ToString()
{
return Name;
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Crypto.Parameters;
using commercio.sdk;
using commercio.sacco.lib;
using KellermanSoftware.CompareNetObjects;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace sdk_test
{
[TestClass]
public class CommercioDocHelper_Test
{
[TestMethod]
// "fromWallet()" returns a well-formed "CommercioDoc" object.
public async Task WellFormedCommercioDocFromWallet()
{
//This is the comparison class
CompareLogic compareLogic = new CompareLogic();
NetworkInfo networkInfo = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: "http://localhost:1317");
String mnemonicString = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
List<String> mnemonic = new List<String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
Wallet wallet = Wallet.derive(mnemonic, networkInfo);
String senderDid = wallet.bech32Address;
List<String> recipientDids = new List<String>() { "recipient1", "recipient2" };
String uuid = System.Guid.NewGuid().ToString();
CommercioDocMetadata metadata = new CommercioDocMetadata(
contentUri: "https://example.com/document/metadata",
schema: new CommercioDocMetadataSchema(
uri: "https://example.com/custom/metadata/schema",
version: "7.0.0'"
)
);
CommercioDoc expectedCommercioDoc = new CommercioDoc(
senderDid: senderDid,
recipientDids: recipientDids,
uuid: uuid,
metadata: metadata
);
CommercioDoc commercioDoc = await CommercioDocHelper.fromWallet(
wallet: wallet,
recipients: recipientDids,
id: uuid,
metadata: metadata
);
Assert.AreEqual(compareLogic.Compare(commercioDoc.toJson(), expectedCommercioDoc.toJson()).AreEqual, true);
//Per visualizzare json della classe
var dataString = JsonConvert.SerializeObject(commercioDoc);
}
[TestMethod]
public async Task test_broadcastStdTx()
{
//This is the comparison class
CompareLogic compareLogic = new CompareLogic();
NetworkInfo networkInfo = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: "http://localhost:1317");
//primo mnemonic
String mnemonicString1 = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
List<String> mnemonic = new List<String>(mnemonicString1.Split(" ", StringSplitOptions.RemoveEmptyEntries));
//secondo mnemonic
String mnemonicString2 = "daughter conduct slab puppy horn wrap bone road custom acoustic adjust target price trip unknown agent infant proof whip picnic exact hobby phone spin";
List<String> mnemonic2 = new List<String>(mnemonicString2.Split(" ", StringSplitOptions.RemoveEmptyEntries));
Wallet wallet = Wallet.derive(mnemonic, networkInfo);
Wallet recipientWallet = Wallet.derive(mnemonic2, networkInfo);
List<StdCoin> depositAmount = new List<StdCoin> { new StdCoin(denom: "ucommercio", amount: "10000") };
var dict = new Dictionary<string, object>();
dict.Add("from_address", wallet.bech32Address);
dict.Add("to_address", recipientWallet.bech32Address);
dict.Add("amount", depositAmount);
StdMsg testmsg = new StdMsg("cosmos-sdk/MsgSend", dict);
List <StdMsg> Listtestmsg = new List<StdMsg>();
Listtestmsg.Add(testmsg);
StdFee fee = new StdFee(depositAmount, "200000");
//Invio
try
{
var stdTx = TxBuilder.buildStdTx(Listtestmsg, "", fee);
var signedStdTx = await TxSigner.signStdTx(wallet: wallet, stdTx: stdTx);
var result = await TxSender.broadcastStdTx(wallet: wallet, stdTx: signedStdTx);
if (result.success)
{
Console.WriteLine("Tx send successfully:\n$lcdUrl/txs/${result.hash}");
}
else
{
Console.WriteLine("Tx error message:\n${result.error?.errorMessage}");
}
}
catch (Exception ex)
{
Console.WriteLine("Error while testing Sacco:\n$error");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace knockknock.readify.net
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
ConcurrencyMode = ConcurrencyMode.Multiple,
AddressFilterMode = AddressFilterMode.Any,
Name = "RedPillService",
Namespace = "http://knockknock.readify.net/RedPillService")]
public class RedPillService : IRedPill
{
public const char CHAR_SPACE = ' ';
public ContactDetails WhoAreYou()
{
return new ContactDetails
{
EmailAddress = "maodean@hotmail.com",
FamilyName = "Mao",
GivenName = "Guo",
PhoneNumber = "0433181642"
};
}
public long FibonacciNumber1(long n)
{
if (n < 0) throw new ArgumentOutOfRangeException(string.Format("Invalid number {0}.", n));
if (n == 0) return 0;
if (n == 1) return 1;
//start from 0
long secondLast = 0;
long last = 1;
for (int i = 2; i <= n; i++)
{
last = last + secondLast;
secondLast = last - secondLast;
}
if (last < 0)
{
var ex = new ArgumentOutOfRangeException(string.Format("Invalid number {0}.", n));
throw new FaultException<ArgumentOutOfRangeException>(ex, ex.Message);
}
return last;
}
public long FibonacciNumber(long n)
{
if (n < 0)
{
var ex = new ArgumentOutOfRangeException(string.Format("Invalid number {0}.", n));
throw new FaultException<ArgumentOutOfRangeException>(ex, ex.Message);
}
if (n == 0) return 0;
if (n == 1) return 1;
var fib = new long[,] { { 1, 1 }, { 1, 0 } };
Power(fib, n - 1);
if (fib[0, 0] < 0)
{
var ex = new ArgumentOutOfRangeException(string.Format("Invalid number {0}.", n));
throw new FaultException<ArgumentOutOfRangeException>(ex, ex.Message);
}
return fib[0, 0];
}
private void Power(long[,] fib, long n)
{
if (n == 0 || n == 1) return;
long[,] m = new long[2, 2] { { 1, 1 }, { 1, 0 } };
Power(fib, n / 2);
MultiPly(fib, fib);
if (n % 2 != 0) MultiPly(fib, m);
}
private void MultiPly(long[,] fib, long[,] m)
{
long x = fib[0, 0] * m[0, 0] + fib[0, 1] * m[1, 0];
long y = fib[0, 0] * m[0, 1] + fib[0, 1] * m[1, 1];
long z = fib[1, 0] * m[0, 0] + fib[1, 1] * m[1, 0];
long w = fib[1, 0] * m[0, 1] + fib[1, 1] * m[1, 1];
fib[0,0] = x;
fib[0,1] = y;
fib[1,0] = z;
fib[1,1] = w;
}
public TriangleType WhatShapeIsThis(int a, int b, int c)
{
if (a <= 0 || b <= 0 || c <= 0)
{
return TriangleType.Error;
}
if (a + b < c || a + c < b || b + c < a)
{
return TriangleType.Error;
}
if (a == b && b == c)
{
return TriangleType.Equilateral;
}
if (a == b || a == c || b == c)
{
return TriangleType.Isosceles;
}
return TriangleType.Scalene;
}
/// <summary>
/// Assuming that space will not be considered as a part of words
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public string ReverseWords(string s)
{
//hanlde null
if (s == null)
{
var ex = new ArgumentNullException("value cannot be null");
throw new FaultException<ArgumentNullException>(ex, ex.Message);
}
if (s == string.Empty || s.Length == 1) return s;
StringBuilder retStringBuilder = new StringBuilder();
Stack<char> reversedWord = new Stack<char>();
int spaceCount = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == CHAR_SPACE) //check if char is space
{
if (reversedWord.Count > 0)
{
retStringBuilder.Append(CHAR_SPACE, spaceCount); //add space
retStringBuilder.Append(CharStackToString(reversedWord));
spaceCount = 0;
}
spaceCount++;
}
else
{
reversedWord.Push(s[i]);
}
}
if (spaceCount > 0)
{
retStringBuilder.Append(CHAR_SPACE, spaceCount); //add space
}
if (reversedWord.Count > 0)
{
if (retStringBuilder.Length > 0 && spaceCount == 0) retStringBuilder.Append(CHAR_SPACE); //add space
retStringBuilder.Append(CharStackToString(reversedWord));
}
return retStringBuilder.ToString();
}
private string CharStackToString(Stack<char> charStack)
{
StringBuilder sb = new StringBuilder();
while (charStack.Count > 0)
{
sb.Append(charStack.Pop());
}
return sb.ToString();
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Log.EventLog;
#endregion
namespace DotNetNuke.Services.Localization
{
public class LanguagePackController
{
public static void DeleteLanguagePack(LanguagePackInfo languagePack)
{
// fix DNN-26330 Removing a language pack extension removes the language
// we should not delete language when deleting language pack, as there is just a loose relationship
//if (languagePack.PackageType == LanguagePackType.Core)
//{
// Locale language = LocaleController.Instance.GetLocale(languagePack.LanguageID);
// if (language != null)
// {
// Localization.DeleteLanguage(language);
// }
//}
DataProvider.Instance().DeleteLanguagePack(languagePack.LanguagePackID);
EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGEPACK_DELETED);
}
public static LanguagePackInfo GetLanguagePackByPackage(int packageID)
{
return CBO.FillObject<LanguagePackInfo>(DataProvider.Instance().GetLanguagePackByPackage(packageID));
}
public static void SaveLanguagePack(LanguagePackInfo languagePack)
{
if (languagePack.LanguagePackID == Null.NullInteger)
{
//Add Language Pack
languagePack.LanguagePackID = DataProvider.Instance().AddLanguagePack(languagePack.PackageID,
languagePack.LanguageID,
languagePack.DependentPackageID,
UserController.Instance.GetCurrentUserInfo().UserID);
EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGEPACK_CREATED);
}
else
{
//Update LanguagePack
DataProvider.Instance().UpdateLanguagePack(languagePack.LanguagePackID,
languagePack.PackageID,
languagePack.LanguageID,
languagePack.DependentPackageID,
UserController.Instance.GetCurrentUserInfo().UserID);
EventLogController.Instance.AddLog(languagePack, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.LANGUAGEPACK_UPDATED);
}
}
}
}
|
/*
Written in whole or in part by F
Licensed in whole or in part according to license https://static.princessapollo.se/licenses/mit-t.txt
***
Not meant to make it into any part of the final product
*/
public class Viking : Player
{
public override void Punch()
{
base.Punch();
}
protected override void Update()
{
base.Update();
}
}
|
using PhotoFrame.Domain.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace PhotoFrame.Domain.UseCase
{
/// <summary>
/// アルバムを作成するユースケースを実現する
/// </summary>
// TODO: 仮実装
public class RegistKeyword
{
private readonly IKeywordRepository _keywordRepository;
public RegistKeyword(IKeywordRepository keywordRepository)
{
_keywordRepository = keywordRepository;
}
/// <summary>
/// アルバムの登録
/// </summary>
/// <param name="keyword"></param>
/// <returns>終了状態を数値で返す</returns>
public int Execute(string keywordName)
{
var result = _keywordRepository.Find(keywords => keywords.SingleOrDefault(keyword => keyword.Name == keywordName));
// 登録済みのアルバム名でない場合
if (result == null)
{
var keyword = Keyword.Create(keywordName);
_keywordRepository.Store(keyword);
// 正常終了
return 0;
}
else
{
// 既存のアルバム名
return 1;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
[RequireComponent(typeof(Collider))]
public class WallObject : MonoBehaviour, IGridObject
{
#region Variables
public bool canBeDestroyed;
public Transform wallRenderTrans;
int index;
int x;
int y;
Collider myCollider;
#endregion
#region Interface
public int GetIndex()
{
return index;
}
public string GetJsonData()
{
WallData data = new WallData();
return JsonConvert.SerializeObject(data);
}
public void GetXY(out int x, out int y)
{
x = this.x;
y = this.y;
}
public void Initialize(string jsonData)
{
WallData data = JsonConvert.DeserializeObject<WallData>(jsonData);
}
public void SetIndex(int index)
{
this.index = index;
}
public void SetXY(int x, int y)
{
this.x = x;
this.y = y;
}
#endregion
private void Start()
{
myCollider = GetComponent<Collider>();
}
private void OnCollisionEnter(Collision collision)
{
if(canBeDestroyed && collision.transform == GameSettings.instance.playerTransform)
{
if(wallRenderTrans != null)
{
wallRenderTrans.gameObject.SetActive(false);
}
myCollider.enabled = false;
AudioManager.instance.PlaybreakAblewallClip();
GameObject explosionGo = ObjectPool.instance.GetPooledObject(GameSettings.instance.DestructibleWallVfxPoolIndex);
explosionGo.SetActive(true);
explosionGo.transform.position = transform.position;
}
else{
AudioManager.instance.PlaywallHitClip();
}
}
}
[System.Serializable]
public class WallData{
}
|
using Accounts.Service.Contract.Commands;
using FluentValidation;
namespace Accounts.Service.Authorisers.CompanyAuthorisers
{
public class ReactivateGroupAuthoriser : AbstractValidator<ReactivateGroupCommand>, ICompanyAuthoriser<ReactivateGroupCommand>
{
public ReactivateGroupAuthoriser()
{
RuleFor(x => x.Identity.UserId).Must((instance, excecutingUserId) => instance.OwnerId == excecutingUserId);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.AI;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif
using Object = UnityEngine.Object;
using Random = UnityEngine.Random;
namespace Game
{
public class ProgressBar : MonoBehaviour
{
[SerializeField]
protected Image image;
public Image Image { get { return image; } }
protected virtual void SetUpAnchors()
{
if (image == null) return;
Image.rectTransform.anchorMin = Vector2.zero;
Image.rectTransform.anchorMax = new Vector2(Value, 1f);
}
public virtual float Value
{
get
{
if (image == null)
throw new NullReferenceException("No image set for " + nameof(ProgressBar) + " on " + name);
return Image.rectTransform.anchorMax.x;
}
set
{
if (image == null)
throw new NullReferenceException("No image set for " + nameof(ProgressBar) + " on " + name);
Image.rectTransform.anchorMax = new Vector2(value, Image.rectTransform.anchorMax.y);
if (OnValueChange != null) OnValueChange(Value);
}
}
public delegate void ValueChangeDelegate(float newValue);
public event ValueChangeDelegate OnValueChange;
protected virtual void Reset()
{
var images = GetComponentsInChildren<Image>(true);
for (int i = 0; i < images.Length; i++)
{
if(images[i].name.ToLower().Contains("progress") || images[i].name.ToLower().Contains("value"))
{
image = images[i];
break;
}
}
for (int i = 0; i < images.Length; i++)
{
if (images[i].name.ToLower().Contains("background") || images[i].name.ToLower().Contains("bg"))
continue;
image = images[i];
break;
}
if(image != null)
{
SetUpAnchors();
Value = 0.5f;
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(ProgressBar))]
public class Inspector : Editor
{
new public ProgressBar target;
protected virtual void OnEnable()
{
target = base.target as ProgressBar;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
DrawValue();
}
protected virtual void DrawValue()
{
if (target.image == null)
{
EditorGUILayout.HelpBox("No Image Set", MessageType.Error);
return;
}
target.Value = EditorGUILayout.Slider(target.Value, 0f, 1f);
}
}
#endif
}
} |
using System;
class MainClass
{
public static void Main ()
{
int a = 5;
int b = 10;
Console.WriteLine ("a={0}; b={1}",a,b);
if (a>b) {
} else {
int temp = b;
b = a;
a = temp;
}
Console.WriteLine ("a={0}; b={1}",a,b);
}
} |
using System;
using System.Runtime.Serialization;
using System.Text;
namespace ScreeningTesterWebSite.Models
{
public class InputHireApplicants : ModelBase
{
public String ssn { get; set; }
public String fname { get; set; }
public String mi { get; set; }
public String lname { get; set; }
public String birthdate { get; set; }
public String address { get; set; }
public String city { get; set; }
public String state { get; set; }
public String zip { get; set; }
public String offerdate { get; set; }
public String hiredate { get; set; }
public String startdate { get; set; }
public String termdate { get; set; }
public String hourlyrate { get; set; }
public String position { get; set; }
public void PrepareForInput()
{
this.birthdate = "";
this.hourlyrate = "0";
this.position = "Merchandiser";
this.offerdate = "";
}
#region Override Methods
public override String ProduceXMLStringFromObject()
{
String emID = (this.EmID == null ? "" : this.EmID);
String caID = (this.CandidateID == null ? "" : this.CandidateID);
StringBuilder sb = new StringBuilder(@"<hireapplicants xmlns=""http://www.itaxgroup.com/jobcredits/PartnerWebService/HireApplicants.xsd"">");
sb.AppendLine(@"<applicant externalid=""" + caID + @""" companyid=""" + this.CoID + @""" locationid=""" + this.LoID + @""" id=""" + emID + @""">");
sb.AppendLine(UtilityFunctions.xmlElementString("ssn", this.ssn));
sb.AppendLine(UtilityFunctions.xmlElementString("fname", this.fname));
sb.AppendLine(UtilityFunctions.xmlElementString("mi", this.mi));
sb.AppendLine(UtilityFunctions.xmlElementString("lname", this.lname));
sb.AppendLine(UtilityFunctions.xmlElementString("birthdate", this.birthdate));
sb.AppendLine(UtilityFunctions.xmlElementString("address", this.address));
sb.AppendLine(UtilityFunctions.xmlElementString("city", this.city));
sb.AppendLine(UtilityFunctions.xmlElementString("state", this.state));
sb.AppendLine(UtilityFunctions.xmlElementString("zip", this.zip));
sb.AppendLine(UtilityFunctions.xmlElementString("offerdate", this.offerdate));
sb.AppendLine(UtilityFunctions.xmlElementString("hiredate", this.hiredate));
sb.AppendLine(UtilityFunctions.xmlElementString("startdate", this.startdate));
sb.AppendLine(UtilityFunctions.xmlElementString("hourlyrate", this.hourlyrate));
sb.AppendLine(UtilityFunctions.xmlElementString("position", this.position));
sb.AppendLine("</applicant>");
sb.AppendLine("</hireapplicants>");
return sb.ToString();
}
public override void SetDefaults()
{
// Default Values
if (string.IsNullOrEmpty(this.fname))
{
this.fname = "Roberto";
}
if (string.IsNullOrEmpty(this.lname))
{
this.lname = "Chavez";
}
if (string.IsNullOrEmpty(this.ssn))
{
this.ssn = "589093331";
}
if (string.IsNullOrEmpty(this.address))
{
this.address = "18125 6th Ave";
}
if (string.IsNullOrEmpty(this.city))
{
this.city = "Three Rivers";
}
if (string.IsNullOrEmpty(this.state))
{
this.state = "MI";
}
if (string.IsNullOrEmpty(this.zip))
{
this.zip = "49093";
}
if (string.IsNullOrEmpty(this.hiredate))
{
this.hiredate = "2017-05-07";
}
if (string.IsNullOrEmpty(this.startdate))
{
this.startdate = "2017-05-07";
}
}
#endregion
#region Output Classes / Calls
public HireApplicantsCompactObject GetSerializableObject()
{
HireApplicantsCompactObject retVal = new HireApplicantsCompactObject();
retVal.authentication = new authenticationObj()
{
username = this.UserName,
password = this.UserPW
};
retVal.applicant = new applicantObj()
{
ssn = this.ssn,
fname = this.fname,
mi = this.mi,
lname = this.lname,
birthdate = this.birthdate,
address = this.address,
city = this.city,
state = this.state,
zip = this.zip,
offerdate = StringToNullableDate(this.offerdate),
hiredate = StringToNullableDate(this.hiredate),
startdate = StringToNullableDate(this.startdate),
termdate = StringToNullableDate(this.termdate),
hourlyrate = (String.IsNullOrEmpty(this.hourlyrate) ? 0 : Convert.ToInt32(this.hourlyrate)),
position = this.position,
companyid = Convert.ToInt32(this.CoID),
locationid = this.LoID,
externalid = this.CandidateID,
applicantid = this.EmID
};
return retVal;
}
[DataContract(Name = "RequestHireApplicants")]
public class HireApplicantsCompactObject
{
[DataMember(Name = "authentication")]
public authenticationObj authentication { get; set; }
[DataMember(Name = "applicant")]
public applicantObj applicant { get; set; }
}
[DataContract]
public class authenticationObj
{
[DataMember(Name = "username")]
public String username { get; set; }
[DataMember(Name = "password")]
public String password { get; set; }
}
public class applicantObj
{
[DataMember(Name = "ssn")]
public String ssn { get; set; }
[DataMember(Name = "fname")]
public String fname { get; set; }
[DataMember(Name = "mi")]
public String mi { get; set; }
[DataMember(Name = "lname")]
public String lname { get; set; }
[DataMember(Name = "birthdate")]
public String birthdate { get; set; }
[DataMember(Name = "address")]
public String address { get; set; }
[DataMember(Name = "city")]
public String city { get; set; }
[DataMember(Name = "state")]
public String state { get; set; }
[DataMember(Name = "zip")]
public String zip { get; set; }
[DataMember(Name = "offerdate")]
public DateTime? offerdate { get; set; }
[DataMember(Name = "hiredate")]
public DateTime? hiredate { get; set; }
[DataMember(Name = "startdate")]
public DateTime? startdate { get; set; }
[DataMember(Name = "termdate")]
public DateTime? termdate { get; set; }
[DataMember(Name = "hourlyrate")]
public Int32 hourlyrate { get; set; }
[DataMember(Name = "position")]
public String position { get; set; }
[DataMember(Name = "companyid")]
public Int32 companyid { get; set; }
[DataMember(Name = "locationid")]
public String locationid { get; set; }
[DataMember(Name = "externalid")]
public String externalid { get; set; }
[DataMember(Name = "applicantid")]
public String applicantid { get; set; }
}
#endregion
private DateTime? StringToNullableDate(String dateText)
{
if (String.IsNullOrEmpty(dateText))
{
return null;
}
else
{
DateTime nonNull = Convert.ToDateTime(dateText);
return nonNull as DateTime?;
}
}
}
} |
// MemoryTest.cs
// Author:
// Stephen Shaw <sshaw@decriptor.com>
// Copyright (c) 2011 sshaw
using System;
using NUnit.Framework;
using Agora;
using Agora.Core;
namespace AgoraTests
{
[TestFixture]
public class TestOf_Memory
{
Memory _mem;
[SetUp]
public void Init ()
{
_mem = new Memory ();
}
[Test]
public void WriteInt ()
{
int location = _mem.Write (BitConverter.GetBytes (0));
Assert.AreEqual (0, BitConverter.ToInt32 (_mem.Read (location, sizeof(int)), 0));
}
[Test]
public void WriteByte ()
{
int location = _mem.Write (MemoryHelper.ToArray (Convert.ToByte (97)));
Assert.AreEqual (Convert.ToByte (97), _mem.Read (location, sizeof(byte)) [0]);
}
[Test]
public void ReadInt ()
{
_mem.Write (MemoryHelper.ToArray (Convert.ToByte (97)));
_mem.Write (MemoryHelper.ToArray (42));
_mem.Write (MemoryHelper.ToArray (0));
_mem.Write (MemoryHelper.ToArray (Convert.ToByte (37)));
int location = 1;
Assert.AreEqual (42, BitConverter.ToInt32 (_mem.Read (location, sizeof(int)), 0));
}
[Test]
public void ReadByte ()
{
_mem.Write (BitConverter.GetBytes (Convert.ToByte (97)));
_mem.Write (BitConverter.GetBytes (42));
_mem.Write (BitConverter.GetBytes (0));
_mem.Write (BitConverter.GetBytes (Convert.ToByte (37)));
int location = 10;
Assert.AreEqual (Convert.ToByte (37), _mem.Read (location, sizeof(byte)) [0]);
}
}
}
|
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 System.Windows.Media.Animation;
namespace kiroshiimeNote
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public List<string> notelist;
public MainWindow()
{
InitializeComponent();
var workingArea = System.Windows.SystemParameters.WorkArea;
this.Left = workingArea.Right - this.Width;
this.Top = workingArea.Bottom - this.Height;
if (!System.IO.Directory.Exists("data"))
System.IO.Directory.CreateDirectory("data");
if (!System.IO.File.Exists("data/nl.knote"))
System.IO.File.Create("data/nl.knote");
try
{
notelist = System.IO.File.ReadAllLines("data/nl.knote").ToList();
}
catch
{
MessageBox.Show("UNEXCEPTED ERROR");
}
reloadnotelist();
}
public void addnewnote(string notename){
notelist.Add(notename);
System.IO.File.WriteAllLines("data/nl.knote",notelist.ToArray());
}
private void expandButton_MouseEnter(object sender, RoutedEventArgs e)
{
Storyboard sb = this.FindResource("plusrotateAnimation") as Storyboard;
sb.Begin();
}
private void expandButton_MouseDown(object sender, MouseButtonEventArgs e)
{
//An ugly fix for right-click crash error
try
{
DragMove();
} catch (Exception){ }
}
void expanedButton_Click(object sender, RoutedEventArgs e)
{
if (expandButton_mainText.Text == "展开笔记面板")
{
expandButton_mainText.Text = "收起笔记面板";
plussign.Text = "\ue0a1";
Storyboard sb = this.FindResource("shownotepanelAnimation") as Storyboard;
sb.Begin();
}
else
{
expandButton_mainText.Text = "展开笔记面板";
plussign.Text = "\ue0a0";
Storyboard sb = this.FindResource("hidenotepanelAnimation") as Storyboard;
sb.Begin();
}
}
void reloadnotelist()
{
notelistbox.Items.Clear();
if (notelist.Count() == 0)
{
notelistbox.Items.Add("没有找到笔记 T_T");
}
else
{
foreach (string name in notelist)
{
notelistbox.Items.Add(name);
}
}
}
void plusbutton_Click(object sender, RoutedEventArgs e)
{
uniquekey_generator ukg = new uniquekey_generator();
string nk = ukg.gen(10);
addnewnote("新笔记_" + nk);
reloadnotelist();
}
public void renamenote(string o, string n)
{
notelist[notelist.IndexOf(o)] = n;
System.IO.File.WriteAllLines("data/nl.knote", notelist.ToArray());
try {
System.IO.File.Move("data/note_" + o + ".knote", "data/note_" + n + ".knote");
}
catch
{
}
reloadnotelist();
}
public void updatecontent(string n, string c)
{
System.IO.File.WriteAllText("data/note_" + n + ".knote", c);
}
public void deletenote(string n)
{
System.IO.File.Delete("data/note_" + n + ".knote");
notelist.Remove(n);
System.IO.File.WriteAllLines("data/nl.knote", notelist.ToArray());
reloadnotelist();
}
void notelistbox_DoubleClick(object sender, RoutedEventArgs e)
{
string c = "";
if (System.IO.File.Exists("data/note_" + notelistbox.SelectedValue.ToString() + ".knote"))
c = System.IO.File.ReadAllText("data/note_" + notelistbox.SelectedValue.ToString() + ".knote");
else
System.IO.File.Create("data/note_" + notelistbox.SelectedValue.ToString() + ".knote");
notedisp np = new notedisp(notelistbox.SelectedValue.ToString(),c,this);
np.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public partial class Presentation_Sermons_Default : System.Web.UI.Page
{
string seriesID;
string sermonID;
bool _isSeries;
List<Sermon> sermons = new List<Sermon>();
#region Series Details
//Series Details
string seriesName;
string seriesBy;
string seriesDesc;
public string seriesArtLink;
string seriesArtSmallLink;
DataSet dsSeries;
#endregion
#region Sermon Details
//Sermon Details
string sermonName;
string sermonBy;
string sermonDesc;
string sermonDate;
string sermonImageLink;
public string sermonArtLink;
string sermonAudioLink;
string sermonVideoLink;
DataTable dsSermon;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
try
{
#region Divs Invisibility
divSermonWrap.Visible = false;
divMessage.Visible = false;
divSeriesWrap.Visible = false;
#endregion
#region Set Series and SermonID
if (Request.QueryString["SeriesID"] != null)
seriesID = Request.QueryString["SeriesID"];
if (Request.QueryString["SermonID"] != null)
sermonID = Request.QueryString["SermonID"];
#endregion
#region What details to fetch and display
if (sermonID == null && seriesID == null)
{
sermonID = "latest";
ValidateSermon(sermonID);
}
else if (sermonID != null && seriesID == null)
ValidateSermon(sermonID);
else if (sermonID == null && seriesID != null)
{
ValidateSeries(seriesID);
if (!_isSeries)
{
sermonID = "latest";
ValidateSermon(sermonID);
}
}
else if (sermonID != null && seriesID != null)
ValidateSermon(sermonID);
#endregion
#region Get Series and Sermon Details
if (_isSeries)
GetSeries(seriesID);
if (_isSeries)
{
LoadSeries();
FillSeries();
}
if (!(sermonID == null && seriesID != null))
GetSermon(sermonID);
#endregion
#region Load Series and Sermon Details
if (!(sermonID == null && seriesID != null))
{
LoadSermon();
FillSermon();
}
#endregion
#region Change Title According to the series or sermon
if (seriesID == "0")
Title = sermonName + " by " + sermonBy;
else
{
if (sermonID == null)
Title = "Series - " + seriesName + " by " + seriesBy;
else
Title = sermonName + " of " + seriesName + " series by " + sermonBy;
}
#endregion
}
catch (Exception ex)
{
divMessage.InnerText = ex.Message;
divMessage.Visible = true;
}
}
private void ValidateSeries(string seriesid)
{
//
DataLink link = new DataLink();
if (link.ValidateSeries(seriesid))
_isSeries = true;
else
_isSeries = false;
}
private void ValidateSermon(string sermonid)
{
//
DataLink link = new DataLink();
if (link.ValidateSermon(sermonid))
{
if ((new DataLink()).GetSeriesForSermon(sermonID) != "0")
{
_isSeries = true;
seriesID = (new DataLink()).GetSeriesForSermon(sermonID);
}
}
else
sermonID = "latest";
}
private void GetSeries(string seriesid)
{
DataLink link = new DataLink();
dsSeries = link.GetSeries(seriesid);
}
private void GetSermon(string sermonid)
{
DataLink link = new DataLink();
dsSermon = link.GetSermon(sermonid).Tables[0];
}
private void LoadSeries()
{
#region Load Series Details
seriesName = GetColumnValue(dsSeries, "SeriesName");
seriesDesc = GetColumnValue(dsSeries, "SeriesDescription");
seriesBy = GetColumnValue(dsSeries, "SeriesBy");
seriesArtLink = GetColumnValue(dsSeries, "ArtLink");
seriesArtSmallLink = GetColumnValue(dsSeries, "ArtSmallLink");
#endregion
#region Load the sermons under this series
if (dsSeries.Tables[1].Rows.Count > 0)
{
sermons.Clear();
foreach (DataRow row in dsSeries.Tables[1].Rows)
{
Sermon sermon = new Sermon(
row["SermonID"].ToString(),
row["SermonName"].ToString(),
row["SermonDescription"].ToString(),
row["SermonBy"].ToString(),
row["SermonDate"].ToString(),
row["ImageLink"].ToString(),
row["AudioLink"].ToString(),
row["VideoLink"].ToString(),
row["ArtLink"].ToString(),
row["ArtSmallLink"].ToString());
sermons.Add(sermon);
}
}
#endregion
}
private void LoadSermon()
{
DataLink link = new DataLink();
dsSermon = link.GetSermon(sermonID).Tables[0];
#region Sermon Details Loading
sermonName = GetCV(dsSermon, "SermonName");
sermonBy = GetCV(dsSermon, "SermonBy");
sermonDate = GetCV(dsSermon, "SermonDate");
sermonDesc = GetCV(dsSermon, "SermonDescription");
sermonImageLink = GetCV(dsSermon, "ImageLink");
sermonAudioLink = GetCV(dsSermon, "AudioLink");
sermonVideoLink = GetCV(dsSermon, "VideoLink");
sermonArtLink = GetCV(dsSermon, "ArtLink");
#endregion
}
private void FillSeries()
{
#region Fill Series Details
lblSeriesName.Text = seriesName;
lblSeriesBy.Text = seriesBy;
lblSeriesDesc.Text = seriesDesc;
imgSeriesArt.ImageUrl = seriesArtLink;
imgSeriesArt.AlternateText = seriesName + " - " + seriesBy;
#endregion
#region Fill Sermons Under Series
if (sermons.Count > 0)
{
divSermonsUnderSeries.InnerHtml = "<ul>";
int i = 1;
foreach (Sermon sermon in sermons)
{
divSermonsUnderSeries.InnerHtml += "<li><a href='Default.aspx?SermonID=" + sermon.ID + "'>Part " + i.ToString() + "</a></li>";
i++;
}
divSermonsUnderSeries.InnerHtml += "</ul>";
divSermonsUnderSeries.Visible = true;
}
#endregion
if (_isSeries)
divSeriesWrap.Visible = true;
if (sermonID == null)
divSermonWrap.Visible = false;
}
private void FillSermon()
{
#region Fill Sermon Details
lblSermonTitle.Text = sermonName;
lblSermonSpeaker.Text = sermonBy;
lblSermonDescription.Text = sermonDesc;
lblSermonDate.Text = (Convert.ToDateTime(sermonDate)).ToShortDateString();
if (sermonImageLink != "" && sermonImageLink != null)
imgSermonArt.ImageUrl = sermonImageLink;
else
if (sermonArtLink != "" && sermonArtLink != null)
imgSermonArt.ImageUrl = sermonArtLink;
else
imgSermonArt.ImageUrl = "https://lh4.googleusercontent.com/-9mKI6Mi3dqM/UzGJKjQPcqI/AAAAAAAALCU/VZAZIJrl0X4/w920-h270-no/noSermonArtLessHeight.jpg";
imgSermonArt.AlternateText = sermonName + " - " + sermonBy;
hdYoutubeMain.Value = sermonVideoLink;
divListen.InnerHtml = "<audio controls><source src='" + sermonAudioLink + "'></audio>";
if (sermonAudioLink != "" && sermonAudioLink != null)
{ listenButton.Visible = true; liDownloadButton.Visible = true; liDownloadButton.InnerHtml = "<a href='" + sermonAudioLink + "' download='C3Victory - " + seriesName + " - " + sermonName + "'>Download Audio</a>"; }
else
{ listenButton.Visible = false; liDownloadButton.Visible = false; }
if (sermonVideoLink != "" && sermonVideoLink != null)
liWatchButton.Visible = true;
else
liWatchButton.Visible = false;
#endregion
divSermonWrap.Visible = true;
if (!_isSeries)
divSeriesWrap.Visible = false;
}
private string GetColumnValue(DataSet ds, string columnName)
{
return ds.Tables[0].Rows[0][columnName].ToString();
}
private string GetCV(DataTable dt, string colName)
{
return dt.Rows[0][colName].ToString();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sunny.Lib;
using Sunny.DB.DataContext;
namespace Sunny.DB
{
public class XMLRepository<T> /*: IRepository<T>*/ where T : /*BaseEntity,*/ new()
{
XmlDataContext _context;
/// <summary>
/// Ctor
/// </summary>
/// <param name="?"></param>
public XMLRepository(XmlDataContext context)
{
_context = context;
}
public List<T> Query(string xPath)
{
List<T> list = XMLSerializerHelper.DeserializeListByXPath<T>(xPath, _context.XmlFilePath);
return list;
}
public ResultMessage Insert(T entity)
{
return XMLHelper.Add<T>(entity, _context.XmlFilePath, _context.ParentXPath);
}
public ResultMessage Update(T entity, string xPath)
{
return XMLHelper.Update<T>(entity, _context.XmlFilePath, xPath);
}
public ResultMessage Delete(string xPath)
{
return XMLHelper.Delete(_context.XmlFilePath, xPath);
}
public T Copy(T copyFrom)
{
T copyOne = new T();
var properties = ReflectionHelper.GetPropertiesKeyValuePairs(this, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
(from p in properties select p).ToList().ForEach(pp => ReflectionHelper.SetPropertyValue(copyOne, pp.Key, pp.Value));
return copyOne;
}
}
}
|
using GymBooking.Core.Models;
using GymBooking.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GymBooking.Core
{
public interface IGymClassesRepository
{
void Add(GymClass gymClass);
Task<List<GymClass>> GetAllWithUsersAsync();
bool GetAny(int id);
Task<GymClass> GetAsync(int? id);
Task<List<GymClass>> GetHistoryAsync();
Task<GymClass> GetWithAttendingMembersAsync(int? id);
void Remove(GymClass gymClass);
void Update(GymClass gymClass);
Task<IEnumerable<GymClass>> GetAllAsync();
}
} |
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 NorthCoast
{
public partial class MainMenu : Form
{
public MainMenu()
{
InitializeComponent();
}
#region MenuStripEvents
//Menu Strip events for all pages
private void mainMenuToolStripMenuItem1_Click(object sender, EventArgs e)
{
Form frMainMenu = new MainMenu();
frMainMenu.Show();
this.Hide();
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void addCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmCustomerAdd = new CustomerAdd();
frmCustomerAdd.Show();
this.Hide();
}
private void deleteCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmCustomerDelete = new CustomerDelete();
frmCustomerDelete.Show();
this.Hide();
}
private void updateCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmCustomerUpdate = new CustomerUpdate();
frmCustomerUpdate.Show();
this.Hide();
}
private void addBookingToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmBookingAdd = new BookingAdd();
frmBookingAdd.Show();
this.Hide();
}
private void editBookingsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmBookingEdit = new BookingEdit();
frmBookingEdit.Show();
this.Hide();
}
private void addAccommodationToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmAccommodationAdd = new AccommodationAdd();
frmAccommodationAdd.Show();
this.Hide();
}
private void editAccommodationsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmAccommodationEdit = new AccommodationEdit();
frmAccommodationEdit.Show();
this.Hide();
}
private void addLocationToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmLocationAdd = new LocationAdd();
frmLocationAdd.Show();
this.Hide();
}
private void editLocationsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmLocationEdit = new LocationEdit();
frmLocationEdit.Show();
this.Hide();
}
private void addTypeToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmAccommodationTypeAdd = new AccommodationTypeAdd();
frmAccommodationTypeAdd.Show();
this.Hide();
}
private void editTypesToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmAccommodationTypeEdit = new AccommodationTypeEdit();
frmAccommodationTypeEdit.Show();
this.Hide();
}
private void reportToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmReport = new Report();
frmReport.Show();
this.Hide();
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(@"K:\A2\NorthCoast\NorthCoast\Resources\UserManual.pdf");
}
#endregion
}
}
|
using MisRecetas.Modelo;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Mis_Recetas.Controlador
{
class CmdMedicos
{
public void RegistrarMedico(Medico med)
{
SqlConnection con = new SqlConnection(Conexion.Cn);
con.Open();
var query = "INSERT INTO Medico (Nombre_Medico, Apellido_Medico, Nro_Matricula) VALUES (@nombre, @apellido, @nro_matricula)";
var comando = new SqlCommand(query, con);
comando.Parameters.AddWithValue("nombre", med.Nombre_Medico);
comando.Parameters.AddWithValue("apellido", med.Apellido_Medico);
comando.Parameters.AddWithValue("nro_matricula", med.Nro_Matricula);
comando.ExecuteNonQuery();
con.Close();
}
public void CargarMedicos(DataGridView grilla)
{
SqlConnection con = new SqlConnection(Conexion.Cn);
con.Open();
var query = "SELECT Id_Medico AS 'ID', Nro_Matricula AS 'Matricula', Nombre_Medico AS 'Nombre', Apellido_Medico 'Apellido' FROM Medico";
var comando = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(comando);
DataTable dt = new DataTable();
da.Fill(dt);
grilla.DataSource = dt;
con.Close();
}
public void ActualizarMedico(String matricula, String nombreMedico, String apellidoMedico, int id)
{
SqlConnection con = new SqlConnection(Conexion.Cn);
con.Open();
var query = "UPDATE Medico SET Nro_Matricula = @nromatricula, Nombre_Medico=@nomMedico, Apellido_Medico=@apeMedico WHERE Id_Medico = @id";
var comando = new SqlCommand(query, con);
comando.Parameters.AddWithValue("@nromatricula", matricula);
comando.Parameters.AddWithValue("@nomMedico", nombreMedico);
comando.Parameters.AddWithValue("@apeMedico", apellidoMedico);
comando.Parameters.AddWithValue("@id", id);
comando.ExecuteNonQuery();
con.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Baseball
{
class Pitcher
{
public Pitcher(Ball ball)
{
// hello ball, I understand that you have a BallInPlay event...
// I would like to subscribe to that event.
//
// Please tell your event handler (BallInPlay) to reference
// my ball_BallInPlay event-handler-method to handle the even for me.
ball.BallInPlay += this.ball_BallInPlay;
// AKA
//ball.BallInPlay += new EventHandler<BallEventArgs>(this.ball_BallInPlay);
}
void ball_BallInPlay(object sender, EventArgs e)
{
if (e is BallEventArgs)
{
BallEventArgs ballEventArgs = e as BallEventArgs;
if ((ballEventArgs.Distance < 95) && (ballEventArgs.Trajectory < 60))
CatchBall();
else
CoverFirstBase();
}
}
private void CatchBall()
{
Form1.pitcherResult = "I caught the ball";
}
private void CoverFirstBase()
{
Form1.pitcherResult = "I covered first base";
}
/*
*
*
*/
}//END END
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using smoothie_shack.Models;
using smoothie_shack.Repositories;
namespace smoothie_shack.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SaladsController : Controller
{
// List<Salad> Salads = Program.Salads;
private readonly SaladRepository db;
public SaladsController(SaladRepository repo)
{
db = repo;
}
// GET api/salads
[HttpGet]
public IEnumerable<Salad> Get()
{
return db.GetAll();
}
// GET api/salads/5
[HttpGet("{id}")]
public Salad Get(int id)
{
return db.GetById(id);
}
// POST api/salads
[HttpPost]
public Salad Post([FromBody]Salad newSalad)
{
if (ModelState.IsValid)
{
return db.AddSalad(newSalad);
}
return null;
}
// PUT api/salads/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/salads/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
|
/* This code file is generated by MDSService Proxy Generator tool.
*
* Service Name : MyMailSmsService
* Service version : 1.0.0.0
* Generating date : 2011-04-04 22:07:02
*/
using System;
using MDS.Client;
using MDS.Client.MDSServices;
namespace SampleService
{
/// <summary>
/// This class is a proxy class to use MyMailSmsService service.
/// Service Description: This service is a sample mail/sms service.
/// </summary>
public partial class MyMailSmsServiceProxy : MDSServiceProxyBase
{
#region Constructor
/// <summary>
/// Creates a new instance of MyMailSmsServiceProxy.
/// </summary>
/// <param name="serviceConsumer">Reference to a MDSServiceConsumer object to send/receive MDS messages</param>
/// <param name="remoteEndPoint">Remote application end point to send requests</param>
public MyMailSmsServiceProxy(MDSServiceConsumer serviceConsumer, MDSRemoteAppEndPoint remoteEndPoint)
: base(serviceConsumer, remoteEndPoint, "MyMailSmsService")
{
}
#endregion
#region MyMailSmsService methods
/// <summary>
/// This method is used send an SMS.
/// </summary>
/// <param name="phone">Phone number to send SMS.</param>
/// <param name="smsText">SMS text to be sent.</param>
public void SendSms(string phone, string smsText)
{
InvokeRemoteMethod("SendSms", phone, smsText);
}
/// <summary>
/// No method summary available.
/// </summary>
public void SendEmail(string emailAddress, string header, string body)
{
InvokeRemoteMethod("SendEmail", emailAddress, header, body);
}
/// <summary>
/// No method summary available.
/// </summary>
/// <param name="phone">Phone number to send SMS.</param>
/// <returns>True, if phone number is valid.</returns>
public bool IsValidPhone(string phone)
{
return (bool) InvokeRemoteMethodAndGetResult("IsValidPhone", phone);
}
#endregion
#region Default (predefined) service methods
/// <summary>
/// This method generates client proxy class to use this service. Clients can update it's proxy classes via calling this method remotely.
/// </summary>
/// <param name="namespaceName">Namespace of generating proxy class</param>
/// <returns>Proxy class code to use this service</returns>
public string GenerateProxyClass(string namespaceName)
{
return (string) InvokeRemoteMethodAndGetResult("GenerateProxyClass", namespaceName);
}
/// <summary>
/// This method can be used to check if service is available.
/// </summary>
/// <param name="message">A message to reply</param>
/// <returns>Reply to message as formatted: 'RE: message'</returns>
public string CheckServiceIsAvailable(string message)
{
return (string) InvokeRemoteMethodAndGetResult("CheckServiceIsAvailable", message);
}
#endregion
}
}
|
using System;
namespace App1.Services
{
public interface IDisplaySize
{
double getWidth();
double getHieght();
}
}
|
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using PlebBot.Data.Models;
using PlebBot.Data.Repository;
using System.Threading;
namespace PlebBot
{
public partial class Program
{
private readonly Repository<Server> serverRepo = new Repository<Server>();
private async Task HandleCommandAsync(SocketMessage messageParam)
{
if (!(messageParam is SocketUserMessage message)) return;
var argPos = 0;
var context = new SocketCommandContext(client, message);
var server = await serverRepo.FindByDiscordId((long) context.Guild.Id);
var prefix = server.Prefix;
if (prefix == null) return;
if (!(message.HasStringPrefix(prefix, ref argPos) ||
message.HasMentionPrefix(client.CurrentUser, ref argPos)) || message.Author.IsBot) return;
var result = await commands.ExecuteAsync(context, argPos, ConfigureServices(services));
commands.Log += msg =>
{
if (!(msg.Exception is CommandException ex)) return Task.CompletedTask;
var channel = client.GetChannel(417956085253668864) as ISocketMessageChannel;
channel?.SendMessageAsync("Fuck you <@164102776035475458> fix me!!!!1\n" +
$"{ex.Message}\n\n" +
$"{ex.InnerException.ToString()}\n");
return Task.CompletedTask;
};
}
//[Conditional("DEBUG")]
//private static void Error(IResult result, ICommandContext context)
//{
// if (!result.IsSuccess)
// context.Channel.SendMessageAsync(result.ErrorReason);
//}
private async Task HandleJoinGuildAsync(SocketGuild guild)
{
if (guild == null) return;
var id = (long) guild.Id;
await serverRepo.Add("DiscordId", id);
}
private async Task HandleLeaveGuildAsync(SocketGuild guild)
{
if (guild == null) return;
await serverRepo.DeleteFirst("DiscordId", guild.Id);
}
}
}
|
namespace Benchmark
{
using System;
using System.Linq;
using Benchmark.Benchmarks;
using Benchmark.Collection;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Filters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Order;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Toolchains.CsProj;
internal static class Program
{
private static void Main()
{
//var test = new SkipTakeListBenchmark();
//test.realType = "list";
//test.skip = 10;
//test.take = 50;
//test.collectionSize = 100;
//test.EnumerateAfterwards = false;
//test.Setup();
//test.FastLinq();
//return;
IConfig config = DefaultConfig.Instance
.With(MemoryDiagnoser.Default)
.With(
Job.RyuJitX64
.With(CsProjClassicNetToolchain.Net46))
.With(
new DefaultOrderProvider(
SummaryOrderPolicy.Default,
MethodOrderPolicy.Alphabetical))
//.With(
// new DisjunctionFilter(
// new CategoryFilter("FastLinq_Eager")))
;
//BenchmarkRunner.Run<AllBenchmark>(config);
//BenchmarkRunner.Run<AnyBenchmark>(config);
//BenchmarkRunner.Run<ConcatBenchmark>(config);
//BenchmarkRunner.Run<CountBenchmark>(config);
//BenchmarkRunner.Run<DefaultIfEmptyBenchmark>(config);
//BenchmarkRunner.Run<EnumerableWithCountBenchmark>(config);
//BenchmarkRunner.Run<HashSetBenchmark>(config);
//BenchmarkRunner.Run<ReverseBenchmark>(config);
//BenchmarkRunner.Run<ToArrayBenchmark>(config);
//BenchmarkRunner.Run<ToDictionaryBenchmark>(config);
BenchmarkRunner.Run<RepeatBenchmark>(config);
//BenchmarkRunner.Run<TakeBenchmark>(config);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FastSQL.Core
{
public class QueryResult
{
public string Id { get; set; }
public int RecordsAffected { get; set; }
public IEnumerable<object> Rows { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace miner
{
[Serializable]
public class IndexButton : Button, ISerializable
{
public int x;
public int y;
public IndexButton(int x, int y)
: base()
{
this.x = x;
this.y = y;
}
protected IndexButton(SerializationInfo SiButton, StreamingContext context)
{
this.x = SiButton.GetInt32("x");
this.y = SiButton.GetInt32("y");
base.Size = (Size)SiButton.GetValue("Size", typeof(Size));
base.Location = (Point)SiButton.GetValue("Location", typeof(Point));
base.Name = (String)SiButton.GetString("Name");
base.Text = (String)SiButton.GetString("Text");
base.Tag = (String)SiButton.GetString("Tag");
base.Enabled = (Boolean)SiButton.GetBoolean("Enabled");
base.ForeColor = (Color)SiButton.GetValue("ForeColor", typeof(Color));
}
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter = true)]
public void GetObjectData(SerializationInfo SiButton, StreamingContext context)
{
SiButton.AddValue("x", this.x);
SiButton.AddValue("y", this.y);
SiButton.AddValue("Size", base.Size, base.Size.GetType());
SiButton.AddValue("Location", base.Location, base.Location.GetType());
SiButton.AddValue("Name", base.Name, base.Name.GetType());
SiButton.AddValue("Text", base.Text, base.Text.GetType());
SiButton.AddValue("Tag", base.Tag, base.Tag.GetType());
SiButton.AddValue("Enabled", base.Enabled, base.Enabled.GetType());
SiButton.AddValue("ForeColor", base.ForeColor, base.ForeColor.GetType());
}
}
}
|
namespace Kers.Models.Entities.UKCAReporting
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("zCesTaxExemptFinancialYearLookup")]
public partial class zCesTaxExemptFinancialYearLookup
{
[Key]
public int rID { get; set; }
[StringLength(100)]
public string fYearTitle { get; set; }
}
}
|
using System;
namespace DCL.Maths
{
public struct Fraction: IComparable
{
#region Fields
long num;
uint den;
#endregion
#region Constants
public static readonly Fraction Empty = new Fraction(long.MaxValue, uint.MaxValue);
#endregion
#region Properties
public long Numerator
{
set { num = value; }
get { return num; }
}
public uint Denominator
{
set
{
if (value == 0) throw new DivideByZeroException("denominator");
den = value;
}
get { return den; }
}
#endregion
#region Constructors
public Fraction(long numerator, uint denominator)
{
num = numerator;
if (denominator == 0) throw new DivideByZeroException("denominator");
den = denominator;
}
#endregion
#region Operators
public static Fraction operator +(Fraction l, Fraction r)
{
if (l.Numerator == Empty.Numerator || l.Denominator == Empty.Denominator)
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
{
Fraction f = 0;
return Empty;
}
else
return r;
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return l;
uint CommonDenominator = Common.LCM(l.Denominator, r.Denominator);
Fraction fr = new Fraction(l.Numerator * CommonDenominator / l.Denominator
+ r.Numerator * CommonDenominator / r.Denominator,
CommonDenominator);
return fr.Cancel();
}
public static Fraction operator -(Fraction l, Fraction r)
{
if (l.Numerator == Empty.Numerator || l.Denominator == Empty.Denominator)
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return Empty;
else
return r;
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return l;
uint CommonDenominator = Common.LCM(l.Denominator, r.Denominator);
Fraction fr = new Fraction(l.Numerator * CommonDenominator / l.Denominator
- r.Numerator * CommonDenominator / r.Denominator,
CommonDenominator);
return fr.Cancel();
}
public static Fraction operator *(Fraction l, Fraction r)
{
if (l.Numerator == Empty.Numerator || l.Denominator == Empty.Denominator)
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return Empty;
else
return r;
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return l;
Fraction fr = new Fraction(l.Numerator * r.Numerator,
l.Denominator * r.Denominator);
return fr.Cancel();
}
public static Fraction operator /(Fraction l, Fraction r)
{
return l*r.Reverse();
}
public static Fraction operator +(Fraction f)
{
return new Fraction(f.Numerator, f.Denominator);
}
public static Fraction operator -(Fraction f)
{
if (f.Numerator == Empty.Numerator || f.Denominator == Empty.Denominator)
return f;
return new Fraction(-f.Numerator, f.Denominator);
}
public static Fraction operator ++(Fraction f)
{
if (f.Numerator == Empty.Numerator || f.Denominator == Empty.Denominator)
return f;
return new Fraction(f.Numerator + f.Denominator, f.Denominator);
}
public static Fraction operator --(Fraction f)
{
if (f.Numerator == Empty.Numerator || f.Denominator == Empty.Denominator)
return f;
return new Fraction(f.Numerator - f.Denominator, f.Denominator);
}
public static bool operator ==(Fraction l, Fraction r)
{
return (l.Cancel().Numerator == r.Cancel().Numerator &&
l.Cancel().Denominator == r.Cancel().Denominator) ||
((l.Numerator==Empty.Numerator || l.Denominator==Empty.Denominator) &&
(r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator));
}
public static bool operator >(Fraction l, Fraction r)
{
if (l.Numerator == Empty.Numerator || l.Denominator == Empty.Denominator)
return false;
else if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return true;
if (r.Numerator == 0) return l.Numerator > 0;
if (l.Numerator == 0) return r.Numerator < 0;
uint CommonDenominator = Common.LCM(l.Denominator, r.Denominator);
return l.Numerator * CommonDenominator / l.Denominator >
r.Numerator * CommonDenominator / r.Denominator;
}
public static bool operator >=(Fraction l, Fraction r)
{
if (l.Numerator == Empty.Numerator || l.Denominator == Empty.Denominator)
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return true;
else
return false;
if (r.Numerator == Empty.Numerator || r.Denominator == Empty.Denominator)
return true;
if (r.Numerator == 0) return l.Numerator >= 0;
if (l.Numerator == 0) return r.Numerator <= 0;
uint CommonDenominator = Common.LCM(l.Denominator, r.Denominator);
return l.Numerator * CommonDenominator / l.Denominator >=
r.Numerator * CommonDenominator / r.Denominator;
}
public static bool operator <(Fraction l, Fraction r)
{
return r > l;
}
public static bool operator <=(Fraction l, Fraction r)
{
return r >= l;
}
public static bool operator !=(Fraction l, Fraction r)
{
return !(l == r);
}
#endregion
#region Type casting
public static implicit operator Fraction(long l)
{
return new Fraction(l,1);
}
public static explicit operator Fraction(double d)
{
if (d == 0) return new Fraction(0, 1);
int l = Math.Min(Common.FractionalPartLength(d), 8);//int l = Math.Min(19 - (int)Math.Log10(Math.Abs(d)), 8);
uint dn = (uint)Math.Pow(10, l);
long nm = (long)(d * dn);
Fraction fr = new Fraction(nm, dn);
return fr;//fr.Cancel();
}
public static explicit operator double(Fraction f)
{
if (f.Numerator == Fraction.Empty.Numerator || f.Denominator == Fraction.Empty.Denominator)
return 0;
return (double)f.Numerator / f.Denominator;
}
#endregion
#region Methods
public Fraction Cancel()
{
uint t = Common.GCD((uint)Math.Abs(num), den);
return new Fraction(num/t, den/t);
}
public Fraction Reverse()
{
if (num == 0) throw new DivideByZeroException("denominator");
Fraction f = new Fraction();
if (den == Empty.Denominator) f.Numerator = Empty.Numerator;
else f.Numerator = (num < 0) ? -den : den;
if (num == Empty.Numerator) f.Denominator = Empty.Denominator;
else f.Denominator = (uint)Math.Abs(num);
return f;
}
public Fraction ReduceToDenominator(uint newDenominator)
{
return new Fraction(Numerator * newDenominator / Denominator, newDenominator);
}
public void ToMixedNumber(out long WholePart, out Fraction FractionalPart)
{
if (this.Numerator == Empty.Numerator || this.Denominator == Empty.Denominator)
{
WholePart = 0;
FractionalPart = Empty;
return;
}
bool neg = this.Numerator < 0;
WholePart = this.Numerator / this.Denominator;
FractionalPart = (new Fraction(Math.Abs(this.Numerator) - Math.Abs(WholePart * this.Denominator), this.Denominator)).Cancel();
if (WholePart == 0 && neg)
FractionalPart.Numerator *= -1;
}
public static Fraction FromMixedNumber(long wholePart, Fraction fractionalPart)
{
if (fractionalPart.Numerator == Fraction.Empty.Numerator || fractionalPart.Denominator == Fraction.Empty.Denominator)
return Fraction.Empty;
bool neg = wholePart < 0 || fractionalPart.Numerator < 0;
if (wholePart == 0 && neg) fractionalPart *= -1;
if (wholePart < 0) wholePart *= -1;
Fraction f = wholePart + fractionalPart;
if (neg) f *= -1;
return f;
}
public static Fraction Parse(string str)
{
long nm;
uint dn;
str = str.Trim();
if (str.IndexOf('/') == -1) { nm = long.Parse(str); dn = 1; }
else
{
nm = long.Parse(str.Substring(0, str.IndexOf('/')));
dn = uint.Parse(str.Substring(str.IndexOf('/') + 1, str.Length - str.IndexOf('/')-1));
}
return new Fraction(nm, dn);
}
public static bool TryParse(string str, out Fraction f)
{
try
{
f = Parse(str);
return true;
}
catch
{
f = new Fraction(0,1);
return false;
}
}
public static bool IsEmpty(Fraction f)
{
return f.Numerator == Fraction.Empty.Numerator || f.Denominator == Fraction.Empty.Denominator;
}
#endregion
#region Overridden methods
public override bool Equals(object obj)
{
return (obj is Fraction) && (this == (Fraction)obj);
}
public override int GetHashCode()
{
return (num/den).GetHashCode();
}
public override string ToString()
{
return String.Format("{0}/{1}",
(num == Empty.Numerator) ? "" : num.ToString(),
(den == Empty.Denominator) ? "" : den.ToString());
}
#endregion
#region IComparable interface realization
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (!(obj is Fraction)) throw new ArgumentException();
if (this > (Fraction)obj) return 1;
else if (this < (Fraction)obj) return -1;
else return 0;
}
#endregion
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Client
{
public interface ILanguageClient : ILanguageClientFacade, IDisposable
{
IServiceProvider Services { get; }
IClientWorkDoneManager WorkDoneManager { get; }
IRegistrationManager RegistrationManager { get; }
ILanguageClientWorkspaceFoldersManager WorkspaceFoldersManager { get; }
Task Initialize(CancellationToken token);
Task Shutdown();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap
{
public class QueryBehaviorStatQuery
{
public string CarrierCode { get; set; }
public string BusinessmanCode { get; set; }
public string BusinessType { get; set; }
public string ContactName { get; set; }
public string OperatorName { get; set; }
public DateTime? StartDateTime { get; set; }
public DateTime? EndDateTime { get; set; }
public int PageIndex { get; set; }
public int PageSize { get; set; }
public string Sort { get; set; }
public string Order { get; set; }
}
}
|
namespace Amazon.Suporte.Enum
{
public enum StatusEnum
{
Created,
Resolved,
InProgress,
NotCreatedYet
}
} |
using Microsoft.EntityFrameworkCore;
using PeliculasAPI.DTOs;
using PeliculasAPI.Entidades;
using PeliculasAPI.Utilidades;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PeliculasAPI.Services
{
public class ActorService : IActorService
{
private readonly AppDbContext _dbContext;
private readonly IAlmacenadorArchivos _almacenador;
private readonly string container = "actores";
public ActorService(AppDbContext dbContext, IAlmacenadorArchivos almacenador)
{
_dbContext = dbContext;
_almacenador = almacenador;
}
public IEnumerable<ActorDto> GetAll()
{
return _dbContext.Actores
.Select(a => new ActorDto() {
Id = a.Id,
Nombre = a.Nombre,
Apellido = a.Apellido,
Biografia = a.Biografia,
FechaNacimiento = a.FechaNacimiento,
Foto = a.Foto
});
}
public IQueryable<ActorDto> GetAll(PaginacionDTO paginacion)
{
return _dbContext.Actores.AsQueryable()
.OrderBy(g => g.Nombre)
.Skip((int)((paginacion.PageNumber - 1) * paginacion.PageSize))
.Take((int)paginacion.PageSize)
.Select(g => new ActorDto() { Id = g.Id, Nombre = g.Nombre });
}
public async Task<List<ActorDto>> GetByName(string name)
{
//if(string.IsNullOrWhiteSpace(name)) { return new List<ActorDto>(); }
if (string.IsNullOrWhiteSpace(name))
{
return await _dbContext.Actores
.Select(a => new ActorDto()
{
Id = a.Id,
Nombre = a.Nombre,
Apellido = a.Apellido,
Biografia = a.Biografia,
FechaNacimiento = a.FechaNacimiento,
Foto = a.Foto
})
.OrderBy(x => x.Nombre + ' ' + x.Apellido)
.Take(10)
.ToListAsync();
}
return await _dbContext.Actores
.Where(a => (a.Nombre.Contains(name) || a.Apellido.Contains(name)))
.Select(a => new ActorDto()
{
Id = a.Id,
Nombre = a.Nombre,
Apellido = a.Apellido,
Biografia = a.Biografia,
FechaNacimiento = a.FechaNacimiento,
Foto = a.Foto
})
.Take(10)
.ToListAsync();
}
public ActorDto GetById(int id)
{
return _dbContext.Actores
.Where(g => g.Id == id)
.Select(a => new ActorDto()
{
Id = a.Id,
Nombre = a.Nombre,
Apellido = a.Apellido,
Biografia = a.Biografia,
FechaNacimiento = a.FechaNacimiento,
Foto = a.Foto
})
.FirstOrDefault();
}
public async Task<ActorDto> Update(int id, ActorCreacionDto actorEditado)
{
var actor = await _dbContext.Actores.FindAsync(id);
if (actor is null) return null;
actor.Nombre = actorEditado.Nombre;
actor.Apellido = actorEditado.Apellido;
actor.Biografia = actorEditado.Biografia;
actor.FechaNacimiento = actorEditado.FechaNacimiento;
if (actorEditado.Foto != null)
{
actor.Foto = await _almacenador.EditarArchivo(container, actorEditado.Foto, actor.Foto);
}
await _dbContext.SaveChangesAsync();
return new ActorDto()
{
Nombre = actor.Nombre,
Apellido = actor.Apellido,
Biografia = actor.Biografia,
FechaNacimiento = actor.FechaNacimiento,
Foto = actor.Foto
};
}
public async Task<ActorDto> Create(ActorCreacionDto nuevoActor)
{
var actor = new Actor() {
Nombre = nuevoActor.Nombre,
Apellido = nuevoActor.Apellido,
Biografia = nuevoActor.Biografia,
FechaNacimiento = nuevoActor.FechaNacimiento,
};
if(nuevoActor.Foto != null)
{
actor.Foto = await _almacenador.GuardarArchivo(container, nuevoActor.Foto);
}
await _dbContext.Actores.AddAsync(actor);
await _dbContext.SaveChangesAsync();
return new ActorDto()
{
Id = actor.Id,
Nombre = actor.Nombre,
Apellido = actor.Apellido,
Biografia = actor.Biografia,
FechaNacimiento = actor.FechaNacimiento,
Foto = actor.Foto
};
}
public async Task<bool> Delete(int id)
{
var actor = await _dbContext.Actores.FindAsync(id);
if (actor is null) return false;
_dbContext.Actores.Remove(actor);
if(await _dbContext.SaveChangesAsync() > 0)
{
await _almacenador.BorrarArchivo(actor.Foto, container);
}
return true;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief ディレクトリ。ワーク。
*/
/** NDirectory
*/
namespace NDirectory
{
/** Work
*/
public class Work
{
/** 相対パス。
*/
private string path;
/** アイテム。
*/
private Item item;
/** constructor
*/
public Work(string a_path,Item a_item)
{
/** 相対パス。
*/
this.path = a_path;
/** 追加先。
*/
this.item = a_item;
}
/** 相対パス。取得。
*/
public string GetPath()
{
return this.path;
}
/** アイテム。取得。
*/
public Item GetItem()
{
return this.item;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopsRUs.Domain.Entity;
namespace ShopsRUs.Infrastructure.Services.UserService
{
public interface IUsersService
{
Task<List<User>> GetUsers();
Task<User> GetUserById(long id);
Task<User> GetUserByName(string name);
Task<User> GetUserByNamAndPhone(string name, string phoneNumber);
Task CreateUser(User user);
Task DeActivateUserById(long id);
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Xml.Linq;
using BookStore.Data;
using BookStore.Model;
namespace BookStore.ImportFromXml
{
public class ImportFromXml
{
private const string FileLocation = "../../complex-books.xml";
public static void ImportBooks(XDocument booksXml, IBookStoreData dbContext)
{
var booksList = booksXml.Descendants("book");
foreach (var book in booksList)
{
using (var transaction = dbContext.BeginTransaction())
{
try
{
var bookToAdd = ProcessBook(book, dbContext);
var authors = ProcessAuthors(book, dbContext);
var reviews = ProcessReviews(book, dbContext, bookToAdd);
foreach (var author in authors)
{
bookToAdd.Authors.Add(author);
author.Books.Add(bookToAdd);
}
foreach (var review in reviews)
{
bookToAdd.Reviews.Add(review);
}
dbContext.Books.Add(bookToAdd);
dbContext.SaveChanges();
transaction.Commit();
}
catch (ArgumentNullException ex)
{
transaction.Rollback();
throw ex;
}
catch (ArgumentException ex)
{
transaction.Rollback();
throw ex;
}
catch (DbUpdateException ex)
{
throw new ArgumentException("Cannot insert dublicate ISBN number.");
}
}
}
}
private static Book ProcessBook(XElement bookNode, IBookStoreData dbContext)
{
var bookTitle = bookNode.Descendants("title").FirstOrDefault().Value;
string bookWebSite = null;
if (bookNode.Descendants("web-site").FirstOrDefault() != null)
{
bookWebSite = bookNode.Descendants("web-site").FirstOrDefault().Value;
}
string isbn = null;
if (bookNode.Descendants("isbn").FirstOrDefault() != null)
{
isbn = bookNode.Descendants("isbn").FirstOrDefault().Value;
}
decimal price = 0;
if (bookNode.Descendants("price").FirstOrDefault() != null)
{
price = decimal.Parse(bookNode.Descendants("price").FirstOrDefault().Value);
}
var resultBook = new Book()
{
Title = bookTitle
};
if (bookWebSite != null)
{
resultBook.Website = bookWebSite;
}
if (isbn != null)
{
if (dbContext.Books.Find(x => x.ISBN == isbn).Count() > 0)
{
throw new ArgumentException("ISBN Value must be unique.");
}
resultBook.ISBN = isbn;
}
resultBook.Price = price;
return resultBook;
}
private static ICollection<Author> ProcessAuthors(XElement bookNode, IBookStoreData dbContext)
{
var authorsCollection = bookNode.Elements("authors").Select(author => author.Value);
List<Author> authorsList = new List<Author>();
if (authorsCollection.Count() <= 0)
{
return authorsList;
}
else
{
foreach (var author in authorsCollection)
{
var currentAuthor = dbContext.Authors.Find(x => x.Name == author).FirstOrDefault();
if (currentAuthor == null)
{
currentAuthor = new Author()
{
Name = author,
AuthorType = AuthorType.Book
};
dbContext.Authors.Add(currentAuthor);
}
else if (currentAuthor != null && currentAuthor.AuthorType == AuthorType.Review)
{
currentAuthor.AuthorType = AuthorType.Both;
}
authorsList.Add(currentAuthor);
}
}
return authorsList;
}
private static ICollection<Review> ProcessReviews(XElement bookNode, IBookStoreData dbContext, Book reviewBook)
{
var reviewsCollection = bookNode.Descendants("reviews").Nodes();
List<Review> reviewsList = new List<Review>();
if (reviewsCollection.Count() <= 0)
{
return reviewsList;
}
else
{
foreach (XElement review in reviewsCollection)
{
var reviewDateString = review.Attribute("date") == null ? null : review.Attribute("date").Value;
DateTime reviewDate;
if (!DateTime.TryParse(reviewDateString, out reviewDate))
{
reviewDate = DateTime.Now.Date;
}
var author = review.Attribute("author") == null ? null : review.Attribute("author").Value;
Author reviewAuthor = null;
if (author != null)
{
reviewAuthor = dbContext.Authors.Find(x => x.Name == author).FirstOrDefault();
if (reviewAuthor == null)
{
reviewAuthor = new Author()
{
Name = author,
AuthorType = AuthorType.Review
};
dbContext.Authors.Add(reviewAuthor);
}
else if (reviewAuthor != null && reviewAuthor.AuthorType == AuthorType.Book)
{
reviewAuthor.AuthorType = AuthorType.Both;
}
}
var reviewText = review.Value;
if (string.IsNullOrWhiteSpace(reviewText))
{
throw new ArgumentException("Review must have text.");
}
Review currentReview = new Review()
{
ReviewText = reviewText,
Book = reviewBook,
DateOfCreation = reviewDate
};
if (reviewAuthor != null)
{
currentReview.Author = reviewAuthor;
}
dbContext.Reviews.Add(currentReview);
reviewsList.Add(currentReview);
}
}
return reviewsList;
}
public static void Main()
{
var booksXml = XDocument.Load(FileLocation);
IBookStoreData dbContext = new BookStoreData();
ImportBooks(booksXml, dbContext);
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace VocabularyApi.Migrations
{
public partial class renameField : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Trasncription",
table: "VocabularyWords");
migrationBuilder.AddColumn<string>(
name: "Transcription",
table: "VocabularyWords",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Transcription",
table: "VocabularyWords");
migrationBuilder.AddColumn<string>(
name: "Trasncription",
table: "VocabularyWords",
type: "nvarchar(max)",
nullable: true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace JoveZhao.Framework
{
public static class SectionManager
{
private static Configuration cfg = null;
static Dictionary<string, object> configContainer = new Dictionary<string, object>();
public static T GetConfigurationSection<T>(string name) where T : ConfigurationSection
{
T t = null;
if (!configContainer.ContainsKey(name))
{
cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
t = cfg.GetSection(name) as T;
if (t == null)
throw new NotFoundResourcesException("没有找到节点为:" + name + "的配置项");
configContainer[name] = t;
}
else
{
t = configContainer[name] as T;
}
return t;
}
public static void SaveConfigurationSection(string name)
{
if (cfg == null)
{
cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
cfg.Save();
ConfigurationManager.RefreshSection(name);
configContainer[name] = null;
configContainer.Remove(name);
}
}
}
|
using System;
using System.Collections.Generic;
using NetFabric.Assertive;
using Xunit;
namespace NetFabric.Hyperlinq.UnitTests.Quantifier.Contains
{
public class ValueReadOnlyCollectionTests
{
[Theory]
[MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_ValueType_With_Null_And_NotContains_Must_ReturnFalse(int[] source)
{
// Arrange
var value = int.MaxValue;
var wrapped = Wrap.AsValueReadOnlyCollection(source);
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<int>, Wrap.Enumerator<int>, int>(wrapped, value);
// Assert
_ = result.Must()
.BeFalse();
}
[Theory]
[MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_ReferenceType_With_Null_And_NotContains_Must_ReturnFalse(int[] source)
{
// Arrange
var value = default(string);
var wrapped = Wrap.AsValueReadOnlyCollection(source.AsValueEnumerable().Select(item => item.ToString()).ToArray());
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<string>, Wrap.Enumerator<string>, string>(wrapped, value);
// Assert
_ = result.Must()
.BeFalse();
}
[Theory]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_ValueType_With_Null_And_Contains_Must_ReturnTrue(int[] source)
{
// Arrange
var value = System.Linq.Enumerable.Last(source);
var wrapped = Wrap.AsValueReadOnlyCollection(source);
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<int>, Wrap.Enumerator<int>, int>(wrapped, value);
// Assert
_ = result.Must()
.BeTrue();
}
[Theory]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_ReferenceType_With_Null_And_Contains_Must_ReturnTrue(int[] source)
{
// Arrange
var value = System.Linq.Enumerable.Last(source).ToString();
var wrapped = Wrap.AsValueReadOnlyCollection(source.AsValueEnumerable().Select(item => item.ToString()).ToArray());
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<string>, Wrap.Enumerator<string>, string>(wrapped, value);
// Assert
_ = result.Must()
.BeTrue();
}
[Theory]
[MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_With_DefaultComparer_And_NotContains_Must_ReturnFalse(int[] source)
{
// Arrange
var value = int.MaxValue;
var wrapped = Wrap.AsValueReadOnlyCollection(source);
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<int>, Wrap.Enumerator<int>, int>(wrapped, value, EqualityComparer<int>.Default);
// Assert
_ = result.Must()
.BeFalse();
}
[Theory]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_With_DefaultComparer_And_Contains_Must_ReturnTrue(int[] source)
{
// Arrange
var value = System.Linq.Enumerable.Last(source);
var wrapped = Wrap.AsValueReadOnlyCollection(source);
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<int>, Wrap.Enumerator<int>, int>(wrapped, value, EqualityComparer<int>.Default);
// Assert
_ = result.Must()
.BeTrue();
}
[Theory]
[MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_With_Comparer_And_NotContains_Must_ReturnFalse(int[] source)
{
// Arrange
var value = int.MaxValue;
var wrapped = Wrap.AsValueReadOnlyCollection(source);
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<int>, Wrap.Enumerator<int>, int>(wrapped, value, TestComparer<int>.Instance);
// Assert
_ = result.Must()
.BeFalse();
}
[Theory]
[MemberData(nameof(TestData.Single), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))]
public void Contains_With_Comparer_And_Contains_Must_ReturnTrue(int[] source)
{
// Arrange
var value = System.Linq.Enumerable.Last(source);
var wrapped = Wrap.AsValueReadOnlyCollection(source);
// Act
var result = ValueReadOnlyCollectionExtensions
.Contains<Wrap.ValueReadOnlyCollectionWrapper<int>, Wrap.Enumerator<int>, int>(wrapped, value, TestComparer<int>.Instance);
// Assert
_ = result.Must()
.BeTrue();
}
}
} |
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace NtApiDotNet.Win32.Security.Authentication.Kerberos
{
#pragma warning disable 1591
/// <summary>
/// Kerberos Encryption Type.
/// </summary>
public enum KerberosEncryptionType
{
NULL = 0,
DES_CBC_CRC = 1,
DES_CBC_MD4 = 2,
DES_CBC_MD5 = 3,
DES3_CBC_MD5 = 5,
OLD_DES3_CBC_SHA1 = 7,
SIGN_DSA_GENERATE = 8,
ENCRYPT_RSA_PRIV = 9,
ENCRYPT_RSA_PUB = 10,
DES3_CBC_SHA1 = 16,
AES128_CTS_HMAC_SHA1_96 = 17,
AES256_CTS_HMAC_SHA1_96 = 18,
ARCFOUR_HMAC_MD5 = 23,
ARCFOUR_HMAC_MD5_56 = 24,
ENCTYPE_PK_CROSS = 48,
ARCFOUR_MD4 = -128,
ARCFOUR_HMAC_OLD = -133,
ARCFOUR_HMAC_OLD_EXP = -135,
DES_CBC_NONE = -4096,
DES3_CBC_NONE = -4097,
DES_CFB64_NONE = -4098,
DES_PCBC_NONE = -4099,
DIGEST_MD5_NONE = -4100,
CRAM_MD5_NONE = -4101
}
}
|
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using Random = UnityEngine.Random;
public class Weapon : MonoBehaviour
{
protected int damage = 0;
public virtual void Effect(Hero hero1,Hero hero2)
{
}
public virtual int GetDamage()
{
return this.damage;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
class Code : Weapon
{
Code()
{
this.damage = Random.Range(10, 50);
}
public override int GetDamage()
{
return this.damage;
}
public override void Effect(Hero hero1,Hero hero2)
{
if (this.damage > 25)
Console.WriteLine("人品爆发,造成大量伤害!");
else
Console.WriteLine("出现大量bug,造成少量伤害");
}
}
|
// <copyright file="CityForcast.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace ApiSandbox
{
public class CityForcast
{
public float Long { get; set; }
public float Lat { get; set; }
public string City { get; set; }
}
}
|
using System.Reflection;
[assembly: AssemblyTitle("Hunabku.VSPasteResurrected")]
[assembly: AssemblyDescription("The resurrected version of the famous VSPaste for WLW (by Douglas Stockwell)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hunabku.VSPasteResurrected")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System;
namespace City_Center.Models
{
public class Chat
{
public string UserName
{
get;
set;
}
public string UserMessage
{
get;
set;
}
public string UserFecha
{
get;
set;
}
}
}
|
namespace E09_LargestConnectedArea
{
using System;
public class StartUp
{
private static string[,] labyrinth = new string[,]
{
{"s", "-", "-", "*", "-", "-", "-"},
{"*", "*", "-", "*", "-", "*", "-"},
{"-", "-", "-", "-", "-", "-", "-"},
{"-", "*", "*", "*", "*", "*", "-"},
{"-", "-", "-", "-", "-", "-", "e"},
};
private static int[,] direction = new int[,]
{
{ 1, 0 }, //down
{ 0, 1 }, //right
{ -1, 0 }, //up
{ 0, -1 } //left
};
private static int currentPathLenght = 1;
private static int maxPathLength = 0;
public static void Main(string[] args)
{
Point start = FindStart();
FindAllPaths(start, 1);
Console.WriteLine("Largest area of connected adjecent cells is {0}", maxPathLength);
}
static void FindAllPaths(Point currentPoint, int step)
{
for (int i = 0; i < direction.GetLength(0); i++)
{
int newRow = currentPoint.Row + direction[i, 0];
int newCol = currentPoint.Col + direction[i, 1];
if (InBouds(newRow, newCol))
{
if (IsEnd(new Point(newRow, newCol)))
{
if (currentPathLenght > maxPathLength)
{
maxPathLength = currentPathLenght;
}
currentPathLenght = 1;
}
if (IsFree(newRow, newCol))
{
labyrinth[newRow, newCol] = step.ToString();
currentPathLenght++;
FindAllPaths(new Point(newRow, newCol), ++step);
labyrinth[newRow, newCol] = "-";
step--;
}
}
}
}
static Point FindStart()
{
for (int row = 0; row < labyrinth.GetLength(0); row++)
{
for (int col = 0; col < labyrinth.GetLength(1); col++)
{
if (labyrinth[row, col] == "s")
{
return new Point(row, col);
}
}
}
return new Point();
}
static bool IsEnd(Point point)
{
return labyrinth[point.Row, point.Col] == "e";
}
public static bool InBouds(int row, int col)
{
if (row >= 0
&& col >= 0
&& row < labyrinth.GetLength(0)
&& col < labyrinth.GetLength(1)
&& labyrinth[row, col] != "*")
{
return true;
}
else
{
return false;
}
}
public static bool IsFree(int row, int col)
{
if (labyrinth[row, col] == "-")
{
return true;
}
else
{
return false;
}
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public bool IsGameOver { get; set; }
public static GameManager instance;
public GameObject gameOverText;
public Text scoreText;
int score = 0;
void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
}
// Update is called once per frame
void Update()
{
if (IsGameOver && Input.GetMouseButtonDown(0))
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void Scored()
{
if (IsGameOver)
return;
score++;
scoreText.text = "Score: " + score;
}
public void GameOver()
{
gameOverText.SetActive(true);
IsGameOver = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Drawing;
using System.Diagnostics;
using Microsoft.Win32;
using System.Windows;
using System.Drawing.Imaging;
namespace PengcitUltimateApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Bitmap original = null;
private Bitmap processed = null;
private List<List<int>> chaincodes = new List<List<int>>();
List<String> stringCodes = new List<String>();
//variabel knowledge base
List<String> codeBase = new List<String>();
List<String> labels = new List<String>();
bool ispreprocessed = false;
Color preprocessed = Color.FromArgb(255,255,255);
Color unpreprocessed = Color.FromArgb(0, 0, 0);
public MainWindow()
{
InitializeComponent();
//inisialisasi knowledge base
codeBase.Add("222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222224444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666660000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
codeBase.Add("22222222222322223223223233232333233333433343343434344344434444344444444444454444544454454545454555545555556556556565665665666656666666666676666766766767767677767777707770707707070070007000070000000000001000010001001011010101111011121111212112122122122221");
codeBase.Add("223343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343343445666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667001101101101101101101101101101101101101101101110110110110110110110110110110110110110110110110111011011011011011011011011011011011011011011011101");
codeBase.Add("244444444444444444444444444444444444444444444444444444444444444444444444444343323222224666666666666666666666666666602222212111000000000000000000000000000000000000000000000000000000000000007077766665650121212121212122121");
codeBase.Add("22222444444444444444444444444444444444444444444444444444322222222244444446666666665444444444444444444446666666600000000000000000000766666666666666666666666666666666600000001110110110111011011011101101101101110110110111011011");
codeBase.Add("22222232232332333343343343434434443444434444444444444444444445444454454454454554554555655656566566666676676767777707707070707007007000070000000000000000000010000100010010101010111111112121221");
codeBase.Add("22222223223232333433443444444444544545454554555455555554555555532222222222222222222121444444444444466666666666666666666666666666666666601101111101111011101110110101010100010000000007077777676666665665555546001010101011112121221");
codeBase.Add("222222222222222222222222222245445454454666666666666666666666666654454532222232222322232322332333333434343444444444445445454555555656566566656666666666766676777000010212223232332333232322222121111100000000070707777767767667667666766666666660010010100100100100100101001001");
codeBase.Add("22222222222222222222222222222222224444444454454454454454454454454454454454544544544544544544544546666661001001001001001001001001001001001001001001001001007666666666666666666656665655545000100010001000010");
codeBase.Add("22222222223222323233343434443544445455555656533333333343434444344544445454555565566566566666666666766767677770707000000000101011112112210776777777070700000000001011012111221221");
labels.Add("rectangle");
labels.Add("circle");
labels.Add("triangle");
labels.Add("angka satu");
labels.Add("angka empat");
labels.Add("angka nol");
labels.Add("angka dua");
labels.Add("angka lima");
labels.Add("angka tujuh");
labels.Add("angka delapan");
}
private void button1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Memuat Gambar";
op.Filter = "Semua file grafik|*.jpg;*.jpeg;*.png|" +
"JPEG (jpg, jpeg)|*.jpg;*jpeg|" +
"Portable Network Graphic|*.png";
if (op.ShowDialog() == true)
{
image1.Source = new BitmapImage(new Uri(op.FileName));
original = new Bitmap(op.FileName);
image2.Source = new BitmapImage(new Uri(op.FileName));
processed = new Bitmap(op.FileName);
chaincodes.Clear();
stringCodes.Clear();
ispreprocessed = false;
}
}
private void image1_Drop(object sender, System.Windows.DragEventArgs e)
{
}
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (comboBox2 != null)
{
if (comboBox1.SelectedValue.ToString().Equals("Matrix 1 Degree"))
{
comboBox2.Visibility = Visibility.Visible;
comboBox3.Visibility = Visibility.Hidden;
}
else if (comboBox1.SelectedValue.ToString().Equals("Matrix 2 Degree"))
{
comboBox2.Visibility = Visibility.Hidden;
comboBox3.Visibility = Visibility.Visible;
}
else
{
comboBox2.Visibility = Visibility.Hidden;
comboBox3.Visibility = Visibility.Hidden;
}
}
}
private Bitmap Grayscale(Bitmap image)
{
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
int value = (int)(result.GetPixel(i, j).R * 0.299 + result.GetPixel(i, j).G * 0.587 + result.GetPixel(i, j).B * 0.114);
Color color = Color.FromArgb(value, value, value);
result.SetPixel(i, j, color);
}
}
return result;
}
private Bitmap Sharpen(Bitmap image)
{
int range = 3;
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
int rmax = 0;
int gmax = 0;
int bmax = 0;
for (int ni = i - range / 2; ni < (i + range / 2); ni++)
{
for (int nj = j - range / 2; nj < (j + range / 2); nj++)
{
ni = (ni % image.Width < 0) ? image.Width + ni : ni % image.Width;
nj = (nj % image.Height < 0) ? image.Height + nj : nj % image.Height;
Color color = image.GetPixel(ni, nj);
rmax = (rmax < color.R) ? color.R : rmax;
gmax = (gmax < color.G) ? color.G : gmax;
bmax = (bmax < color.B) ? color.B : bmax;
}
}
result.SetPixel(i, j, Color.FromArgb(rmax, gmax, bmax));
}
}
return result;
}
private Bitmap Contrast(Bitmap image)
{
int rmin = 0;
int rmax = 255;
int gmin = 0;
int gmax = 255;
int bmin = 0;
int bmax = 255;
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
Color color = result.GetPixel(i, j);
rmax = (color.R <= rmax) ? color.R : rmax;
rmin = (color.R >= rmin) ? color.R : rmin;
gmax = (color.G <= gmax) ? color.G : gmax;
gmin = (color.G >= gmin) ? color.G : gmin;
bmax = (color.B <= bmax) ? color.B : bmax;
bmin = (color.B >= bmin) ? color.B : bmin;
}
}
for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
Color color = result.GetPixel(i, j);
int red = 255 * (Math.Abs(color.R - rmax)) / (Math.Abs(rmin - rmax));
int green = 255 * (Math.Abs(color.G - gmax)) / (Math.Abs(gmin - gmax));
int blue = 255 * (Math.Abs(color.B - bmax)) / (Math.Abs(bmin - bmax));
result.SetPixel(i, j, Color.FromArgb(red, green, blue));
}
}
return result;
}
private Bitmap Normalisasi(Bitmap image)
{
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
for (int i = 0; i < image.Height; i++)
{
for (int j = 0; j < image.Width; j++)
{
Color color = result.GetPixel(j, i);
if (color.R < 255 && color.R > 128 || color.G < 255 && color.G > 128 || color.B < 255 && color.B > 128)
{
result.SetPixel(j, i, Color.FromArgb(255, 255, 255));
}
else if (color.R > 0 && color.R <= 128 || color.G > 0 && color.G <= 128 || color.B > 0 && color.B <= 128)
result.SetPixel(j, i, Color.FromArgb(0, 0, 0));
}
}
return result;
}
private Bitmap AddFrame(Bitmap image)
{
Bitmap result = new Bitmap(image.Width + 2, image.Height + 2);
for (int i = 0; i < result.Width; i++)
{
for (int j = 0; j < result.Height; j++)
{
Color color = Color.FromArgb(255, 255, 255);
result.SetPixel(i, j, color);
}
}
// isi pojok
result.SetPixel(0, 0, image.GetPixel(0, 0));
result.SetPixel(result.Width - 1, 0, image.GetPixel(image.Width - 1, 0));
result.SetPixel(0, result.Height - 1, image.GetPixel(0, image.Height - 1));
result.SetPixel(result.Width - 1, result.Height - 1, image.GetPixel(image.Width - 1, image.Height - 1));
// isi pinggiran
// isi tengah
for (int i = 1; i < result.Width - 1; i++)
{
for (int j = 1; j < result.Height - 1; j++)
{
Color color = image.GetPixel(i - 1, j - 1);
result.SetPixel(i, j, color);
}
}
return result;
}
private Bitmap EdgeDiff4(Bitmap image)
{
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
Bitmap framed = AddFrame(result);
for (int i = 1; i < framed.Width - 1; i++)
{
for (int j = 1; j < framed.Height - 1; j++)
{
Color color1;
Color color2;
Color color3;
Color color4;
color1 = Color.FromArgb(Math.Abs(framed.GetPixel(i, j - 1).R - framed.GetPixel(i, j + 1).R),
Math.Abs(framed.GetPixel(i, j - 1).G - framed.GetPixel(i, j + 1).G),
Math.Abs(framed.GetPixel(i, j - 1).B - framed.GetPixel(i, j + 1).B)
);
color2 = Color.FromArgb(Math.Abs(framed.GetPixel(i + 1, j).R - framed.GetPixel(i - 1, j).R),
Math.Abs(framed.GetPixel(i + 1, j).G - framed.GetPixel(i - 1, j).G),
Math.Abs(framed.GetPixel(i + 1, j).B - framed.GetPixel(i - 1, j).B)
);
color3 = Color.FromArgb(Math.Abs(framed.GetPixel(i + 1, j + 1).R - framed.GetPixel(i - 1, j - 1).R),
Math.Abs(framed.GetPixel(i + 1, j + 1).G - framed.GetPixel(i - 1, j - 1).G),
Math.Abs(framed.GetPixel(i + 1, j + 1).B - framed.GetPixel(i - 1, j - 1).B)
);
color4 = Color.FromArgb(Math.Abs(framed.GetPixel(i + 1, j - 1).R - framed.GetPixel(i - 1, j + 1).R),
Math.Abs(framed.GetPixel(i + 1, j - 1).G - framed.GetPixel(i - 1, j + 1).G),
Math.Abs(framed.GetPixel(i + 1, j - 1).B - framed.GetPixel(i - 1, j + 1).B)
);
int rmax = Math.Max(color1.R, Math.Max(color2.R, Math.Max(color3.R, color4.R)));
int gmax = Math.Max(color1.G, Math.Max(color2.G, Math.Max(color3.G, color4.G)));
int bmax = Math.Max(color1.B, Math.Max(color2.B, Math.Max(color3.B, color4.B)));
result.SetPixel(i - 1, j - 1, Color.FromArgb(rmax, gmax, bmax));
}
}
return result;
}
private Bitmap EdgeDiff2(Bitmap image)
{
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
Bitmap framed = AddFrame(result);
for (int i = 1; i < framed.Width - 1; i++)
{
for (int j = 1; j < framed.Height - 1; j++)
{
Color color1;
Color color2;
color1 = Color.FromArgb(Math.Abs(framed.GetPixel(i, j - 1).R - framed.GetPixel(i, j + 1).R),
Math.Abs(framed.GetPixel(i, j - 1).G - framed.GetPixel(i, j + 1).G),
Math.Abs(framed.GetPixel(i, j - 1).B - framed.GetPixel(i, j + 1).B)
);
color2 = Color.FromArgb(Math.Abs(framed.GetPixel(i + 1, j).R - framed.GetPixel(i - 1, j).R),
Math.Abs(framed.GetPixel(i + 1, j).G - framed.GetPixel(i - 1, j).G),
Math.Abs(framed.GetPixel(i + 1, j).B - framed.GetPixel(i - 1, j).B)
);
int rmax = Math.Max(color1.R, color2.R);
int gmax = Math.Max(color1.G, color2.G);
int bmax = Math.Max(color1.B, color2.B);
result.SetPixel(i - 1, j - 1, Color.FromArgb(rmax, gmax, bmax));
}
}
return result;
}
private Bitmap Thinning(Bitmap image) {
Console.WriteLine("masuk thinning");
int a, b;
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
image = Normalisasi(image);
result = Normalisasi(result);
List<System.Drawing.Point> pointsToChange = new List<System.Drawing.Point>();
bool hasChange;
do{
hasChange = false;
for (int j = 1; j + 1 < image.Height; j++){
for(int i = 1; i + 1 < image.Width; i++){
a = getA(image, j, i);
b = getB(image, j, i);
Console.WriteLine("getA = " + a + " getB = " + b);
if ( image.GetPixel(j,i).R == 0 && 2 <= b && b <= 6 && a == 1
&& (image.GetPixel(j-1,i).R * image.GetPixel(j,i+1).R * image.GetPixel(j + 1,i).R == 0)
&& (image.GetPixel(j,i+1).R * image.GetPixel(j+1,i).R * image.GetPixel(j,i-1).R == 0)) {
pointsToChange.Add(new System.Drawing.Point(i, j));
hasChange = true;
}
}
}
foreach (System.Drawing.Point point in pointsToChange) {
result.SetPixel(point.X, point.Y, Color.FromArgb(255,255,255));
}
pointsToChange.Clear();
for (int j = 1; j + 1 < image.Height; j++)
{
for (int i = 1; i + 1 < image.Width; i++)
{
a = getA(image, j, i);
b = getB(image, j, i);
Console.WriteLine("getA = " + a + " getB = " + b);
if (image.GetPixel(j, i).R == 0 && 2 <= b && b <= 6 && a == 1
&& (image.GetPixel(j - 1, i).R * image.GetPixel(j, i + 1).R * image.GetPixel(j, i - 1).R == 0)
&& (image.GetPixel(j - 1, i).R * image.GetPixel(j + 1, i).R * image.GetPixel(j, i - 1).R == 0))
{
pointsToChange.Add(new System.Drawing.Point(i, j));
hasChange = true;
}
}
}
foreach (System.Drawing.Point point in pointsToChange)
{
result.SetPixel(point.X, point.Y, Color.FromArgb(255, 255, 255));
}
pointsToChange.Clear();
} while (hasChange);
return result;
}
private int getA(Bitmap image, int y, int x) {
int count = 0;
//p2 p3
if (image.GetPixel(x, y - 1).R == 255 && image.GetPixel(x + 1, y - 1).R == 0)
{
count++;
}
//p3 p4
if (image.GetPixel(x + 1, y - 1).R == 255 && image.GetPixel(x + 1, y).R == 0)
{
count++;
}
//p4 p5
if (image.GetPixel(x + 1, y).R == 255 && image.GetPixel(x + 1, y + 1).R == 0)
{
count++;
}
//p5 p6
if (image.GetPixel(x + 1, y + 1).R == 255 && image.GetPixel(x, y + 1).R == 0)
{
count++;
}
//p6 p7
if (image.GetPixel(x, y + 1).R == 255 && image.GetPixel(x - 1, y + 1).R == 0)
{
count++;
}
//p7 p8
if (image.GetPixel(x - 1, y + 1).R == 255 && image.GetPixel(x - 1, y).R == 0)
{
count++;
}
//p8 p9
if (image.GetPixel(x - 1, y).R == 255 && image.GetPixel(x - 1, y - 1).R == 0)
{
count++;
}
//p9 p2
if (image.GetPixel(x - 1, y - 1).R == 255 && image.GetPixel(x, y - 1).R == 0)
{
count++;
}
return count;
}
private int getB(Bitmap image, int y, int x) {
return image.GetPixel(x, y - 1).R == 0 ? image.GetPixel(x, y - 1).R : 1 +
image.GetPixel(x + 1, y - 1).R == 0 ? image.GetPixel(x + 1, y - 1).R : 1 +
image.GetPixel(x + 1, y).R == 0 ? image.GetPixel(x + 1, y).R : 1 +
image.GetPixel(x + 1, y + 1).R == 0 ? image.GetPixel(x + 1, y + 1).R : 1 +
image.GetPixel(x, y + 1).R == 0 ? image.GetPixel(x, y + 1).R : 1 +
image.GetPixel(x - 1, y + 1).R == 0 ? image.GetPixel(x - 1, y + 1).R : 1 +
image.GetPixel(x - 1, y).R == 0 ? image.GetPixel(x - 1, y).R : 1 +
image.GetPixel(x - 1, y - 1).R == 0 ? image.GetPixel(x - 1, y - 1).R : 1;
}
private Bitmap ObjectDetection(Bitmap image, Color edge)
{
// 7 0 1
// 6 - 2
// 5 4 3
Console.WriteLine("masuk deteksi");
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
result = Normalisasi(result);
Color[] adjacentColor = new Color[8];
Console.WriteLine("masuk deteksi 2");
System.Drawing.Point startingPoint = new System.Drawing.Point();
for (int i = 0; i < image.Height; i++)
{
for (int j = 0; j < image.Width; j++)
{
Color color = result.GetPixel(j, i);
if (color.R == edge.R && color.G == edge.G && color.B == edge.B)
{
startingPoint.X = j;
startingPoint.Y = i;
goto sini;
}
}
}
return result;
sini:
List<System.Drawing.Point> koords = new List<System.Drawing.Point>();
List<int> chainCode = new List<int>();
int arah = 0;
adjacentColor[0] = result.GetPixel(startingPoint.X, startingPoint.Y - 1);
adjacentColor[1] = result.GetPixel(startingPoint.X + 1, startingPoint.Y - 1);
adjacentColor[2] = result.GetPixel(startingPoint.X + 1, startingPoint.Y);
adjacentColor[3] = result.GetPixel(startingPoint.X + 1, startingPoint.Y + 1);
adjacentColor[4] = result.GetPixel(startingPoint.X, startingPoint.Y + 1);
adjacentColor[5] = result.GetPixel(startingPoint.X - 1, startingPoint.Y + 1);
adjacentColor[6] = result.GetPixel(startingPoint.X - 1, startingPoint.Y);
adjacentColor[7] = result.GetPixel(startingPoint.X - 1, startingPoint.Y - 1);
System.Drawing.Point tujuan = startingPoint;
if(ispreprocessed)
SearchAdjacent(result, ref adjacentColor, ref koords, ref tujuan, ref chainCode, ref arah, Color.FromArgb(255,255,255), Color.FromArgb(0,0,0));
else
SearchAdjacent(result, ref adjacentColor, ref koords, ref tujuan, ref chainCode, ref arah, Color.FromArgb(0, 0, 0), Color.FromArgb(255, 255, 255));
do
{
if (ispreprocessed)
SearchAdjacent(result, ref adjacentColor, ref koords, ref tujuan, ref chainCode, ref arah, Color.FromArgb(255, 255, 255), Color.FromArgb(0, 0, 0));
else
SearchAdjacent(result, ref adjacentColor, ref koords, ref tujuan, ref chainCode, ref arah, Color.FromArgb(0, 0, 0), Color.FromArgb(255, 255, 255));
} while (tujuan.X != startingPoint.X || tujuan.Y != startingPoint.Y);
chaincodes.Add(chainCode);
stringCodes.Add(ListIntConv(chainCode));
if (ispreprocessed)
result = Bombing(result, koords, Color.FromArgb(255,255,255), Color.FromArgb(0,0,0));
else
result = Bombing(result, koords, Color.FromArgb(0,0,0), Color.FromArgb(255,255,255));
return result;
}
private Bitmap BombingOLD(Bitmap image, List<System.Drawing.Point> koords, Color edge, Color bg)
{
Console.WriteLine("masuk bombing");
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
bool found = false;
for (int i = 0; i < image.Height; i++)
{
for (int j = 0; j < image.Width; j++)
{
foreach (System.Drawing.Point point in koords)
{
// detek edge
if ((j == point.X && i == point.Y))
{
found = true;
result.SetPixel(j, i, Color.FromArgb(bg.R, bg.G, bg.B));
}
}
if (!found && (result.GetPixel(j, i).R == edge.R && result.GetPixel(j, i).G == edge.G && result.GetPixel(j, i).B == edge.B))
{
// cek Y
int x1 = -1;
int x2 = -1;
foreach (System.Drawing.Point point in koords)
{
if (i == point.Y)
{
if (x1 == -1)
x1 = point.X;
else
x2 = point.X;
}
}
int xmax = Math.Max(x1, x2);
int xmin = Math.Min(x1, x2);
// cek X
int y1 = -1;
int y2 = -1;
foreach (System.Drawing.Point point in koords)
{
if (j == point.X)
{
if (y1 == -1)
y1 = point.Y;
else
y2 = point.Y;
}
}
int ymax = Math.Max(y1, y2);
int ymin = Math.Min(y1, y2);
// cek diantara
if (i < ymax && i > ymin && j < xmax && j > xmin)
result.SetPixel(j, i, Color.FromArgb(bg.R, bg.G, bg.B));
}
found = false;
}
}
return result;
}
private Bitmap Bombing(Bitmap image, List<System.Drawing.Point> koords, Color edge, Color bg)
{
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
bool found = false; for (int i = 0; i < image.Height; i++)
{
for (int j = 0; j < image.Width; j++)
{
foreach (System.Drawing.Point point in koords)
{ // detek edge
if ((j == point.X && i == point.Y)) { found = true; result.SetPixel(j, i, Color.FromArgb(bg.R, bg.G, bg.B)); }
}
if (!found && (result.GetPixel(j, i).R == edge.R && result.GetPixel(j, i).G == edge.G && result.GetPixel(j, i).B == edge.B))
{ // cek Y
int xmin = image.Width; int xmax = -1; foreach (System.Drawing.Point point in koords) { if (i == point.Y) { xmin = Math.Min(xmin, point.X); xmax = Math.Max(xmax, point.X); } }
// cek X
int ymin = image.Height; int ymax = -1; foreach (System.Drawing.Point point in koords) { if (j == point.X) { ymin = Math.Min(ymin, point.Y); ymax = Math.Max(ymax, point.Y); } }
// cek diantara
if (xmax != image.Width && xmin != -1 && ymax != image.Height && ymin != -1) if (i < ymax && i > ymin && j < xmax && j > xmin) result.SetPixel(j, i, Color.FromArgb(bg.R, bg.G, bg.B));
}
found = false;
}
}
return result;
}
private void SearchAdjacent(Bitmap result, ref Color[] adjacentColor, ref List<System.Drawing.Point> koords, ref System.Drawing.Point tujuan, ref List<int> chainCode, ref int arah, Color edge, Color bg)
{
while (adjacentColor[arah].R == bg.R && adjacentColor[arah].G == bg.G && adjacentColor[arah].B == bg.B)
{
if (arah == 7)
arah = 0;
else
arah++;
}
while (adjacentColor[arah].R == edge.R && adjacentColor[arah].G == edge.G && adjacentColor[arah].B == edge.B)
{
if (arah == 0)
arah = 7;
else
arah--;
}
if (arah == 7)
arah = 0;
else
arah++;
if (arah == 0)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X, tujuan.Y - 1);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(0);
}
}
else if (arah == 1)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X + 1, tujuan.Y - 1);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(1);
}
}
else if (arah == 2)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X + 1, tujuan.Y);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(2);
}
}
else if (arah == 3)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X + 1, tujuan.Y + 1);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(3);
}
}
else if (arah == 4)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X, tujuan.Y + 1);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(4);
}
}
else if (arah == 5)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X - 1, tujuan.Y + 1);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(5);
}
}
else if (arah == 6)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X - 1, tujuan.Y);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(6);
}
}
else if (arah == 7)
{
System.Drawing.Point next = new System.Drawing.Point(tujuan.X - 1, tujuan.Y - 1);
if (!koords.Contains(next))
{
koords.Add(next);
tujuan.X = next.X;
tujuan.Y = next.Y;
chainCode.Add(7);
}
}
adjacentColor[0] = result.GetPixel(tujuan.X, tujuan.Y - 1);
adjacentColor[1] = result.GetPixel(tujuan.X + 1, tujuan.Y - 1);
adjacentColor[2] = result.GetPixel(tujuan.X + 1, tujuan.Y);
adjacentColor[3] = result.GetPixel(tujuan.X + 1, tujuan.Y + 1);
adjacentColor[4] = result.GetPixel(tujuan.X, tujuan.Y + 1);
adjacentColor[5] = result.GetPixel(tujuan.X - 1, tujuan.Y + 1);
adjacentColor[6] = result.GetPixel(tujuan.X - 1, tujuan.Y);
adjacentColor[7] = result.GetPixel(tujuan.X - 1, tujuan.Y - 1);
}
private BitmapSource CreateBitmapSourceFromBitmap(Bitmap bitmap)
{
if (bitmap == null)
throw new ArgumentNullException("bitmap");
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
private double DotProduct(Bitmap image, double[,] matrix, int i, int j)
{
double result = (double)image.GetPixel(i - 1, j - 1).R * matrix[0, 0] +
(double)image.GetPixel(i - 1, j).R * matrix[0, 1] +
(double)image.GetPixel(i - 1, j + 1).R * matrix[0, 2] +
(double)image.GetPixel(i, j - 1).R * matrix[1, 0] +
(double)image.GetPixel(i, j).R * matrix[1, 1] +
(double)image.GetPixel(i, j + 1).R * matrix[1, 2] +
(double)image.GetPixel(i + 1, j - 1).R * matrix[2, 0] +
(double)image.GetPixel(i + 1, j).R * matrix[2, 1] +
(double)image.GetPixel(i + 1, j + 1).R * matrix[2, 2];
return result;
}
private double[,] Rotate(double[,] matrix)
{
double[,] result = (double[,])matrix.Clone();
double temp = result[0, 0];
result[0, 0] = result[0, 1];
result[0, 1] = result[0, 2];
result[0, 2] = result[1, 2];
result[1, 2] = result[2, 2];
result[2, 2] = result[2, 1];
result[2, 1] = result[2, 0];
result[2, 0] = result[1, 0];
result[1, 0] = temp;
return result;
}
private Bitmap OneDegree(Bitmap image, int mode)
{
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
Bitmap framed = AddFrame(result);
double[,] matrix;
switch (mode)
{
case 0:
matrix = new double[3, 3] { { -1, 0, 1 }, { -1, 0, 1 }, { -1, 0, 1 } };
break;
case 1:
matrix = new double[3, 3] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
break;
case 2:
matrix = new double[3, 3] { { -1, 0, 1 }, { -1.414, 0, 1.414 }, { -1, 0, 1 } };
break;
case 3:
matrix = new double[3, 3] { { 0, 0, -1 }, { 0, 1, 0 }, { 0, 0, 0 } };
break;
case 4:
matrix = new double[3, 3] { { 6, 0, -6 }, { 0, 0, 0 }, { -6, 0, 6 } };
break;
default:
matrix = new double[3, 3] { { -1, 0, 1 }, { -1, 0, 1 }, { -1, 0, 1 } };
break;
}
for (int i = 1; i < framed.Width - 1; i++)
{
for (int j = 1; j < framed.Height - 1; j++)
{
double north = DotProduct(framed, matrix, i, j);
matrix = Rotate(Rotate(matrix));
double east = DotProduct(framed, matrix, i, j);
int distance = (int)Distance(north, east);
distance = distance > 255 ? 255 : distance;
result.SetPixel(i - 1, j - 1, Color.FromArgb(distance, distance, distance));
}
}
return result;
}
private double Distance(double x, double y)
{
return Math.Pow(Math.Pow(x, 2) + Math.Pow(y, 2), 0.5);
}
private Bitmap TwoDegree(Bitmap image, int mode)
{
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
Bitmap framed = AddFrame(result);
double[,] matrix;
switch (mode)
{
case 0:
matrix = new double[3, 3] { { -1, 0, 1 }, { -1, 0, 1 }, { -1, 0, 1 } };
break;
case 1:
matrix = new double[3, 3] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
break;
case 2:
matrix = new double[3, 3] { { -3, -3, 5 }, { -3, 0, 5 }, { -3, -3, 5 } };
break;
default:
matrix = new double[3, 3] { { -1, 0, 1 }, { -1, 0, 1 }, { -1, 0, 1 } };
break;
}
for (int i = 1; i < framed.Width - 1; i++)
{
for (int j = 1; j < framed.Height - 1; j++)
{
double n = DotProduct(framed, matrix, i, j);
matrix = Rotate(matrix);
double ne = DotProduct(framed, matrix, i, j);
matrix = Rotate(matrix);
double e = DotProduct(framed, matrix, i, j);
matrix = Rotate(matrix);
double se = DotProduct(framed, matrix, i, j);
matrix = Rotate(matrix);
double s = DotProduct(framed, matrix, i, j);
matrix = Rotate(matrix);
double sw = DotProduct(framed, matrix, i, j);
matrix = Rotate(matrix);
double w = DotProduct(framed, matrix, i, j);
matrix = Rotate(matrix);
double nw = DotProduct(framed, matrix, i, j);
int distance = (int)Distance(n, Distance(ne, Distance(e, Distance(se, Distance(s, Distance(sw, Distance(w, nw)))))));
distance = distance > 255 ? 255 : distance;
result.SetPixel(i - 1, j - 1, Color.FromArgb(distance, distance, distance));
}
}
return result;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if (original != null)
{
if (comboBox1.Text.Equals("Contrast"))
{
processed = Contrast(processed);
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Grayscale"))
{
processed = Grayscale(processed);
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Sharpen"))
{
processed = Sharpen(processed);
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Binary Image"))
{
processed = Normalisasi(processed);
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("2 Differences"))
{
processed = EdgeDiff2(processed);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("4 Differences"))
{
processed = EdgeDiff4(processed);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Matrix 1 Degree"))
{
processed = Grayscale(processed);
if (comboBox2.Text.Equals("Prewitt"))
{
processed = OneDegree(processed, 0);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox2.Text.Equals("Sobel"))
{
processed = OneDegree(processed, 1);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox2.Text.Equals("Frei Chen"))
{
processed = OneDegree(processed, 2);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox2.Text.Equals("Robert"))
{
processed = OneDegree(processed, 3);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox2.Text.Equals("Kayalli"))
{
processed = OneDegree(processed, 4);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
}
else if (comboBox1.Text.Equals("Matrix 2 Degree"))
{
processed = Grayscale(processed);
if (comboBox3.Text.Equals("Prewitt"))
{
processed = TwoDegree(processed, 0);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox3.Text.Equals("Robinson"))
{
processed = TwoDegree(processed, 1);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox3.Text.Equals("Kirsch"))
{
processed = TwoDegree(processed, 2);
ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
}
else if (comboBox1.Text.Equals("Object Detection"))
{
if (ispreprocessed)
processed = ObjectDetection(processed, preprocessed);
else
processed = ObjectDetection(processed, unpreprocessed);
PrintListCodes();
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Zhang-Suen Thinning"))
{
processed = zhangsuen(processed);
//ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Face Count"))
{
processed = ScanSkintone(processed);
processed = ScanFace(processed);
//ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Morph"))
{
System.Drawing.Point A = new System.Drawing.Point(0, 0);
System.Drawing.Point B = new System.Drawing.Point(1, 0);
System.Drawing.Point C = new System.Drawing.Point(1, 2);
System.Drawing.Point D = new System.Drawing.Point(0, 1);
processed = RectangleMorph(processed, A, B, C, D);
//ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
else if (comboBox1.Text.Equals("Compress"))
{
processed = compress10(processed);
//ispreprocessed = true;
image2.Source = CreateBitmapSourceFromBitmap(processed);
}
}
}
private void PrintListCodes()
{
textBox1.Clear();
textBox1.AppendText("================= \n");
textBox1.AppendText("Jumlah objek terdeteksi = " + stringCodes.Count + "\n");
textBox1.AppendText("Daftar Chain Code \n");
int n = 1;
foreach (List<int> objek in chaincodes)
{
textBox1.AppendText("Objek #" + n + ": \n");
textBox1.AppendText(stringCodes[n-1] + " \n");
textBox1.AppendText("Hasil interpretasi = " + interpret(stringCodes[n - 1]) + " \n");
textBox1.AppendText("\n");
n++;
}
}
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void button3_Click(object sender, RoutedEventArgs e)
{
image2.Source = image1.Source;
processed = original;
ispreprocessed = false;
}
private int LevenshteinDistance(string s, string t) {
int n = s.Length;
int m = t.Length;
int[,] d = new int[n+1, m+1];
//step 1
if (n == 0)
return m;
if (m == 0)
return n;
//step 2
for (int i = 0; i < n; d[i, 0] = i++) {
}
for (int j = 0; j < m; d[0, m] = j++) {
}
//step 3
for (int i = 1; i <= n; i++) {
//step 4
for (int j = 1; j <= m; j++) {
//step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
//step 6
d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost);
}
}
//step 7
return d[n, m];
}
private String ListIntConv(List<int> a) {
String res = "";
foreach (int i in a) {
res += i.ToString();
}
return res;
}
private String interpret(String code) {
List<int> distances = new List<int>();
foreach (String s in codeBase) {
distances.Add(LevenshteinDistance(s, code));
Console.WriteLine("levenshtein = " + LevenshteinDistance(s, code));
}
int minima = distances[0];
int mindex = 0;
for (int i = 0; i < distances.Count; i++)
{
if (distances[i] < minima)
{ minima = distances[i]; mindex = i; }
}
Console.WriteLine("interpret index = " + mindex);
return labels[mindex];
}
private Bitmap ScanSkintone(Bitmap image) {
Console.WriteLine("Scanning Skintone");
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
//cari warna kulit
if (image.GetPixel(i, j).R >= 82 && image.GetPixel(i, j).R <= 152 &&
image.GetPixel(i, j).G >= 87 && image.GetPixel(i, j).G <= 157 &&
image.GetPixel(i, j).B >= 75 && image.GetPixel(i, j).B <= 145)
{
result.SetPixel(i, j, Color.FromArgb(255, 255, 255));
}
else
result.SetPixel(i, j, Color.FromArgb(0, 0, 0));
}
}
return result;
}
private Bitmap ScanFace(Bitmap image) {
Console.WriteLine("Scanning Face");
int c = 0;
int windowWidth = 50;
int windowHeight = 90;
int tempWindowW = windowWidth;
int tempWindowH = windowHeight;
Bitmap result = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
int i = 0;
int j = 0;
do
{
int whiteCount = 0;
List<int> FacePointX = new List<int>();
List<int> FacePointY = new List<int>();
List<int> NoneFaceX = new List<int>();
List<int> NoneFaceY = new List<int>();
//pendekin lebar window kalo melebihi ukuran gambar
if (i + tempWindowW > image.Width)
{
tempWindowW = tempWindowW - (tempWindowW + i - image.Width);
Console.WriteLine("window size changed: tempWindow(W) = " + tempWindowW);
}
//pendekin tinggi window kalo melebihi ukuran gambar
if (j + tempWindowH > image.Height)
{
tempWindowH = tempWindowH - (tempWindowH + j - image.Height);
Console.WriteLine("window size changed: tempWindow(H) = " + tempWindowH);
}
//hitung pixel putih dalam window
for (int a = i; a < i + tempWindowW; a++)
{
for (int b = j; b < j + tempWindowH; b++)
{
if (image.GetPixel(a, b).R == 255)
{
whiteCount++;
FacePointX.Add(a);
FacePointY.Add(b);
}
else {
NoneFaceX.Add(a);
NoneFaceY.Add(b);
}
}
}
Console.WriteLine("White count = " + whiteCount);
if (whiteCount > 1000)
{
c++;
Random rnd = new Random();
int colorR = rnd.Next(0, 255);
int colorG = rnd.Next(0, 255);
int colorB = rnd.Next(0, 255);
//warnain yang punya pixel kulit > treshold
for (int a = 0; a < FacePointX.Count; a++)
{
result.SetPixel(FacePointX[a], FacePointY[a], Color.FromArgb(colorR, colorG, colorB));
}
for (int a = 0; a < NoneFaceX.Count; a++)
{
result.SetPixel(NoneFaceX[a], NoneFaceY[a], Color.White);
}
}
else {
for (int a = 0; a < FacePointX.Count; a++)
{
result.SetPixel(FacePointX[a], FacePointY[a], Color.Black);
}
}
tempWindowW = windowWidth;
tempWindowH = windowHeight;
Console.WriteLine("Current location: (" + i + "," + j + ")");
if (i + windowWidth >= image.Width)
{
i = 0;
j = j + windowHeight;
Console.WriteLine("WIDTH EXCEEDED");
Console.WriteLine("Change location to: (" + i + "," + j + ")");
Console.WriteLine("");
Console.WriteLine("Windows Size = " + tempWindowW + " x " + tempWindowH);
Console.WriteLine("==============");
}
else
{
i = i + windowWidth;
Console.WriteLine("Change location to: (" + i + "," + j + ")");
Console.WriteLine("");
Console.WriteLine("Windows Size = " + tempWindowW + " x " + tempWindowH);
Console.WriteLine("xxxxxxxxxxxxxxx");
}
} while (i + windowWidth <= image.Width || j + windowHeight <= image.Height);
Console.WriteLine("Face Found:" + c);
return result;
}
private Bitmap Morph(Bitmap image, System.Drawing.Point tl, System.Drawing.Point bl, System.Drawing.Point tr, System.Drawing.Point br)
{
int topX = Math.Max(Math.Max(Math.Max(tl.X, bl.X), tr.X), br.X);
int topY = Math.Max(Math.Max(Math.Max(tl.Y, bl.Y), tr.Y), br.Y);
Bitmap res = new Bitmap(topX, topY);
Color[][] pixels = new Color[image.Width][];
//buat array yang diisi semua warna pada gambar
for (int i = 0; i < image.Width; i++) {
for (int j = 0; j < image.Height; j++) {
pixels[i][j] = image.GetPixel(i, j);
}
}
//cari skala tiap pixel di gambar awal
List<float> scaleIX = new List<float>(); //tiap pixel x di gambar awal
List<float> scaleIY = new List<float>(); //tiap pixel y di gambar awal
//isi scaleIX dan scale IY pake skala
for (int i = 0; i < image.Width; i++) {
scaleIX.Add(i / image.Width);
}
for (int j = 0; j < image.Height; j++) {
scaleIY.Add(j / image.Height);
}
//cari koordinat sisi-sisi trapesium via bresenham
List<System.Drawing.Point> TLBL = IEnumToList(GetPointsOnLine(tl.X, tl.Y, bl.X, bl.Y));
List<System.Drawing.Point> TLTR = IEnumToList(GetPointsOnLine(tl.X, tl.Y, tr.X, tr.Y));
List<System.Drawing.Point> BLBR = IEnumToList(GetPointsOnLine(bl.X, bl.Y, br.X, br.Y));
List<System.Drawing.Point> TRBR = IEnumToList(GetPointsOnLine(tr.X, tr.Y, br.X, br.Y));
//gabungin koordinat 4 sisi diatas kedalam satu list (biar gampang ntar)
List<System.Drawing.Point> koords = new List<System.Drawing.Point>();
foreach (System.Drawing.Point a in TLBL) {
koords.Add(a);
}
foreach (System.Drawing.Point a in TLTR)
{
koords.Add(a);
}
foreach (System.Drawing.Point a in BLBR)
{
koords.Add(a);
}
foreach (System.Drawing.Point a in TRBR)
{
koords.Add(a);
}
return res;
}
public static IEnumerable<System.Drawing.Point> GetPointsOnLine(int x0, int y0, int x1, int y1)
{
bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
if (steep)
{
int t;
t = x0; // swap x0 and y0
x0 = y0;
y0 = t;
t = x1; // swap x1 and y1
x1 = y1;
y1 = t;
}
if (x0 > x1)
{
int t;
t = x0; // swap x0 and x1
x0 = x1;
x1 = t;
t = y0; // swap y0 and y1
y0 = y1;
y1 = t;
}
int dx = x1 - x0;
int dy = Math.Abs(y1 - y0);
int error = dx / 2;
int ystep = (y0 < y1) ? 1 : -1;
int y = y0;
for (int x = x0; x <= x1; x++)
{
yield return new System.Drawing.Point((steep ? y : x), (steep ? x : y));
error = error - dy;
if (error < 0)
{
y += ystep;
error += dx;
}
}
yield break;
}
public static List<System.Drawing.Point> IEnumToList(IEnumerable<System.Drawing.Point> I){
List<System.Drawing.Point> res = I.ToList();
return res;
}
public static Bitmap Compress(Bitmap image) {
Bitmap res = image.Clone(new Rectangle(0, 0, image.Width, image.Height), image.PixelFormat);
return res;
}
public static Bitmap addFrame(Bitmap _b, Color _f)
{
Bitmap framedImage = new Bitmap(_b.Width + 2, _b.Height + 2);
for (int i = 0; i < framedImage.Width; i++)
{
for (int j = 0; j < framedImage.Height; j++)
{
framedImage.SetPixel(i, j, _f);
}
}
for (int i = 0; i < _b.Width; i++)
{
for (int j = 0; j < _b.Height; j++)
{
Color ct = _b.GetPixel(i, j);
framedImage.SetPixel(i + 1, j + 1, ct);
}
}
return framedImage;
}
private static Color latar = Color.FromArgb(0, 0, 0);
private static bool isLatar(XBitmap _b, int i, int j)
{
Color temp = _b.getPixel(i, j);
return XColor.isEqual(temp, latar);
}
private static bool isNotLatar(XBitmap _b, int i, int j)
{
return !isLatar(_b, i, j);
}
private static int getA(XBitmap image, int x, int y)
{
int count = 0;
//p2 p3
if (isLatar(image, x, y - 1) && isNotLatar(image, x + 1, y - 1)) count++;
//p3 p4
if (isLatar(image, x + 1, y - 1) && isNotLatar(image, x + 1, y)) count++;
//p4 p5
if (isLatar(image, x + 1, y) && isNotLatar(image, x + 1, y + 1)) count++;
//p5 p6
if (isLatar(image, x + 1, y + 1) && isNotLatar(image, x, y + 1)) count++;
//p6 p7
if (isLatar(image, x, y + 1) && isNotLatar(image, x - 1, y + 1)) count++;
//p7 p8
if (isLatar(image, x - 1, y + 1) && isNotLatar(image, x - 1, y)) count++;
//p8 p9
if (isLatar(image, x - 1, y) && isNotLatar(image, x - 1, y - 1)) count++;
//p9 p2
if (isLatar(image, x - 1, y - 1) && isNotLatar(image, x, y - 1)) count++;
return count;
}
private static int getB(XBitmap image, int x, int y, ref int p2, ref int p4, ref int p6, ref int p8)
{
int count = 0;
//p2
if (isNotLatar(image, x, y - 1)) { p2 = 1; count++; } else p2 = 0;
//p3
if (isNotLatar(image, x + 1, y - 1)) count++;
//p4
if (isNotLatar(image, x + 1, y)) { p4 = 1; count++; } else p4 = 0;
//p5
if (isNotLatar(image, x + 1, y + 1)) count++;
//p6
if (isNotLatar(image, x, y + 1)) { p6 = 1; count++; } else p6 = 0;
//p7
if (isNotLatar(image, x - 1, y + 1)) count++;
//p8
if (isNotLatar(image, x - 1, y)) { p8 = 1; count++; } else p8 = 0;
//p9
if (isNotLatar(image, x - 1, y - 1)) count++;
return count;
}
public static Bitmap zhangsuen(Bitmap _b)
{
Bitmap framedImage = addFrame(_b, latar);
XBitmap framedImage_xbmp = new XBitmap(framedImage);
List<System.Drawing.Point> pointsToChange = new List<System.Drawing.Point>();
int a, b; int p2 = 0; int p4 = 0; int p6 = 0; int p8 = 0;
bool notSkeleton = true;
while (notSkeleton)
{
notSkeleton = false;
for (int i = 1; i < _b.Height + 1; i++)
{
for (int j = 1; j < _b.Width + 1; j++)
{
if (isNotLatar(framedImage_xbmp, j, i))
{
a = getA(framedImage_xbmp, j, i);
b = getB(framedImage_xbmp, j, i, ref p2, ref p4, ref p6, ref p8);
if (2 <= b && b <= 6 && a == 1 && (p2 * p4 * p6 == 0) && (p4 * p6 * p8 == 0))
{
pointsToChange.Add(new System.Drawing.Point(j, i));
notSkeleton = true;
}
}
}
}
foreach (System.Drawing.Point point in pointsToChange)
{
framedImage_xbmp.setPixel(point.X, point.Y, latar);
}
pointsToChange.Clear();
for (int i = 1; i < _b.Height + 1; i++)
{
for (int j = 1; j < _b.Width + 1; j++)
{
if (isNotLatar(framedImage_xbmp, j, i))
{
a = getA(framedImage_xbmp, j, i);
b = getB(framedImage_xbmp, j, i, ref p2, ref p4, ref p6, ref p8);
if (2 <= b && b <= 6 && a == 1 && (p2 * p4 * p8 == 0) && (p2 * p6 * p8 == 0))
{
pointsToChange.Add(new System.Drawing.Point(j, i));
notSkeleton = true;
}
}
}
}
foreach (System.Drawing.Point point in pointsToChange)
{
framedImage_xbmp.setPixel(point.X, point.Y, latar);
}
pointsToChange.Clear();
}
return XImage.removeFrame(framedImage_xbmp.getBitmap());
}
public static Bitmap RectangleMorph(Bitmap _b, System.Drawing.Point _E, System.Drawing.Point _F, System.Drawing.Point _G, System.Drawing.Point _H)
{ // gradation diff
System.Drawing.Point E = new System.Drawing.Point(_b.Width * _E.X, _b.Height * _E.Y);
System.Drawing.Point F = new System.Drawing.Point(_b.Width * _F.X, _b.Height * _F.Y);
System.Drawing.Point G = new System.Drawing.Point(_b.Width * _G.X, _b.Height * _G.Y);
System.Drawing.Point H = new System.Drawing.Point(_b.Width * _H.X, _b.Height * _H.Y);
int res_w = Math.Max(F.X - E.X, G.X - H.X);
int res_h = Math.Max(H.Y - E.Y, G.Y - F.Y);
Bitmap result = new Bitmap(res_w, res_h);
XBitmap result_xbmp = new XBitmap(result);
for (int i = 0; i < result.Width; i++)
{
for (int j = 0; j < result.Height; j++)
{
int new_width = j * ((G.X - H.X) - (F.X - E.X)) / H.Y - E.Y + F.X - E.X;
int new_height = i * ((G.Y - F.Y) - (H.Y - E.Y)) / F.X - E.X + H.Y - E.Y;
int x1 = i * _b.Width / new_width;
int y1 = j * _b.Height / new_height;
Color px = (y1 >= _b.Height || x1 >= _b.Width || y1 < 0 || x1 < 0) ? Color.FromArgb(0, 0, 0) : _b.GetPixel(x1, y1);
result_xbmp.setPixel(i, j, px);
}
}
return (result_xbmp.getBitmap());
}
public static Bitmap compress50(Bitmap _b)
{
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
// Create an Encoder object based on the GUID
// for the Quality parameter category.
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
// Create an EncoderParameters object.
// An EncoderParameters object has an array of EncoderParameter
// objects. In this case, there is only one
// EncoderParameter object in the array.
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
try
{
using (Bitmap tempImage = new Bitmap(_b))
{
tempImage.Save(@"testing_images\tempFifty.jpg", jgpEncoder, myEncoderParameters);
}
}
catch (Exception e)
{
}
return _b;
}
public static Bitmap compress10(Bitmap _b)
{
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
// Create an Encoder object based on the GUID
// for the Quality parameter category.
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
// Create an EncoderParameters object.
// An EncoderParameters object has an array of EncoderParameter
// objects. In this case, there is only one
// EncoderParameter object in the array.
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 10L);
myEncoderParameters.Param[0] = myEncoderParameter;
try
{
using (Bitmap tempImage = new Bitmap(_b))
{
tempImage.Save(@"testing_images\tempTen.jpg", jgpEncoder, myEncoderParameters);
}
}
catch (Exception e)
{
}
return new Bitmap(@"testing_images\tempTen.jpg");
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models;
using SubSonic;
using ZrSoft;
using Core;
using System.Data;
using System.IO;
using Microsoft.Reporting.WebForms;
using System.Text;
namespace mvcProject.Areas.Sys.Controllers
{
public class DictionariesController : Controller
{
public string msg = "";
public int status = 1;
string LogStr = "";
ControllerHelper c = new ControllerHelper();
QueryPaged query = new QueryPaged();
[PowerFilter]
public ActionResult Index()
{
return View();
}
[HttpPost]
[LoginPower]
public JsonResult GetList(GridPager pager, string queryStr)
{
if (pager.rows == 0)
pager.rows = Core.Config.PageSize;
List<QueryModel> qList = c.getQList(queryStr);
query.pager = pager;
query.TableName = Sys_Dictionaries.Schema;
query.init();
GetQuery(qList);
int total = 0;
List<Sys_Dictionaries> list = query.Paged(ref total).ExecuteTypedList<Sys_Dictionaries>();
var json = new
{
total = total,
pager = query.pager,
rows = list.Select((r, i) => new
{
RowNumber = (i++) + (pager.page - 1) * pager.rows + 1,
Id = r.Id,
LimitLoginCount = r.LimitLoginCount,
LimitLoginTime = r.LimitLoginTime,
Ident = r.Ident == 0 ? "Ip限制" : "错误登录次数限制"
})
};
return Json(json);
}
[HttpPost]
public JsonResult GetListall()
{
SqlQuery sq = new Select().From<Sys_Dictionaries>();
List<Sys_Dictionaries> list = sq.ExecuteTypedList<Sys_Dictionaries>();
var json = new
{
total = list.Count,
rows = (from r in list
select new
{
Id = r.Id,
LimitLoginCount = r.LimitLoginCount,
LimitLoginTime = r.LimitLoginTime,
Ident = r.Ident
}
).ToArray()
};
return Json(json);
}
#region 拼接查询条件
//拼接查询条件
public void GetQuery(List<QueryModel> qList)
{
GetQuery(qList, null);
}
public void GetQuery(List<QueryModel> qList, string[] coulums)
{
if (c.GetQueryStr(qList, "searchtype") == "0")
{
//精确查询
query.IsEqualTo(qList, Sys_Dictionaries.Columns.Id);
}
else
{
//模糊查询
query.Like(qList, Sys_Dictionaries.Columns.Id);
}
query.IsEqualTo(qList, Sys_Dictionaries.Columns.LimitLoginCount);
query.IsEqualTo(qList, Sys_Dictionaries.Columns.LimitLoginTime);
query.IsEqualTo(qList, Sys_Dictionaries.Columns.Ident);
}
#endregion
#region Create
[PowerFilter]
public ActionResult Create()
{
return View();
}
[HttpPost]
[PowerFilter]
public JsonResult Create(Sys_Dictionaries model)
{
try
{
SqlQuery sq = new Select().From<Sys_Dictionaries>()
.Where(Sys_Dictionaries.Columns.Ident)
.IsEqualTo(model.Ident);
if (sq.GetRecordCount() > 0)
{
status = 0;
msg = Tip.InsertFail;
}
else
{
model.Id = Utils.GetNewDateID();
model.Save();
status = 1;
msg = Tip.InsertSucceed;
}
}
catch
{
status = 0;
msg = Tip.InsertFail;
}
GUI.InsertLog(" ", "新增", msg + "Id:" + model.Id + ",限制登录次数:" + model.LimitLoginCount + ",限制登录时长:" + model.LimitLoginTime + ",判断是否限制IP登录标识(0、同Ip限制1、错误次数):" + model.Ident + "");
return ControllerHelper.jsonresult(status, msg);
}
#endregion
#region Edit
[PowerFilter]
public ActionResult Edit(string id)
{
Sys_Dictionaries entity = new Sys_Dictionaries(id);
return View(entity);
}
[HttpPost]
[PowerFilter]
public JsonResult Edit(Sys_Dictionaries model)
{
try
{
Sys_Dictionaries entity = new Sys_Dictionaries(model.Id);
if (!string.IsNullOrEmpty(entity.Id))
{
LogStr = ""
+ "Id:" + model.Id
+ ",限制登录次数:" + model.LimitLoginCount
+ ",限制登录时长:" + model.LimitLoginTime
+ ",判断是否限制IP登录标识(0、同Ip限制1、错误次数):" + model.Ident
+ "";
entity.LimitLoginCount = model.LimitLoginCount;
entity.LimitLoginTime = model.LimitLoginTime;
entity.Ident = model.Ident;
entity.Save();
status = 1;
msg = Tip.EditSucceed;
}
else
{
status = 0;
msg = Tip.EditFail;
}
}
catch (Exception e)
{
status = 0;
msg = Tip.EditFail + Utils.NoHTML(e.Message);
}
GUI.InsertLog(" ", "编辑", msg + LogStr);
return ControllerHelper.jsonresult(status, msg);
}
#endregion
#region Delete
[HttpPost]
public JsonResult Delete(string id)
{
if (!string.IsNullOrWhiteSpace(id))
{
Sys_Dictionaries model = new Sys_Dictionaries(id);
try
{
//这里书写需要删除的逻辑代码
Sys_Dictionaries.Delete(id);
status = 1;
msg = Tip.DeleteSucceed;
}
catch (Exception e)
{
status = 0;
msg = Tip.DeleteFail + Utils.NoHTML(e.Message);
}
GUI.InsertLog(" ", "删除", msg + "Id:" + model.Id + ",限制登录次数:" + model.LimitLoginCount + ",限制登录时长:" + model.LimitLoginTime + ",判断是否限制IP登录标识(0、同Ip限制1、错误次数):" + model.Ident + "");
}
else
{
}
return ControllerHelper.jsonresult(status, msg);
}
#endregion
#region 导出到PDF EXCEL WORD
[PowerFilter]
public ActionResult Export(string type, string queryStr)
{
GridPager pager = new GridPager();
List<QueryModel> qList = c.getQList(queryStr);
query.pager = pager;
query.TableName = Sys_Dictionaries.Schema;
query.init();
GetQuery(qList);
List<Sys_Dictionaries> list = query.Paged().ExecuteTypedList<Sys_Dictionaries>();
LocalReport localReport = new LocalReport();
try
{
localReport.ReportPath = Server.MapPath("~/Report/Sys_Dictionaries.rdlc");
ReportDataSource reportDataSource = new ReportDataSource("DataSet", list);
localReport.DataSources.Add(reportDataSource);
if (type.ToLower() == "print")
{
//直接打印
ReportPrint.Run(localReport);
return View("/views/export/print.cshtml");
}
string reportType = type;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
"<OutPutFormat>" + type + "</OutPutFormat>" +
"<PageWidth>11in</PageWidth>" +
"<PageHeight>11in</PageHeight>" +
"<MarginTop>0.5in</MarginTop>" +
"<MarginLeft>1in</MarginLeft>" +
"<MarginRight>1in</MarginRight>" +
"<MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings
);
string ExportName = "Sys_Dictionaries";
GUI.InsertLog(" ", "导出", "导出[" + ExportName + "]成功![" + type.ToLower() + "]");
switch (type.ToLower())
{
case "pdf":
ExportName += ".pdf";
break;
case "image":
ExportName += ".png";
break;
case "excel":
ExportName += ".xls";
break;
case "word":
ExportName += ".doc";
break;
}
return File(renderedBytes, mimeType, ExportName);
}
catch (Exception ex)
{
Utils.WriteFile("D://", "222.txt", ex.Message);
return View("/views/export/error.cshtml");
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultiEdit.Model
{
public class EditorDataModel : PropertyChangedNotification
{
public ObservableCollection<ItemModel> Items
{
get { return GetValue(() => Items); }
set { SetValue(() => Items, value); }
}
public ItemModel CurrentItemOriginalValue
{
get { return GetValue(() => CurrentItemOriginalValue); }
set { SetValue(() => CurrentItemOriginalValue, value); }
}
public ItemModel CurrentItem
{
get { return GetValue(() => CurrentItem); }
set { SetValue(() => CurrentItem, value); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary.Model;
namespace ClassLibrary.ViewModels
{
public class PercursoModel
{
public int percursoID { get; set; }
public string Nome { get; set; }
public string Descricao { get; set; }
public List<int> listPois { get; set; }
public PercursoModel()
{
}
public PercursoModel(Percurso percurso)
{
this.percursoID = percurso.PercursoID;
this.Nome = percurso.Nome;
this.Descricao = percurso.Descricao;
this.listPois = preencheList(percurso.POIs);
}
public List<int> preencheList(ICollection<POI> listPoi)
{
this.listPois = new List<int>();
foreach (var poi in listPoi)
{
this.listPois.Add(poi.PoiID);
}
return listPois;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SdlDotNet.Core;
using SdlDotNet.Graphics;
using SdlDotNet.Graphics.Primitives;
using SdlDotNet.Input;
using System.Drawing;
using System.Windows;
using NAME_UNWN.Drawable;
using NAME_UNWN.Path;
namespace NAME_UNWN
{
class Program
{
public static int width = 1366;
public static int height = 768;
public static Surface videoScreen;
public static Direction direction;
public static bool[] directionKeys = {false, false, false, false};
public static List<Entity> entities;
public static List<Bullet> bullets;
public static List<Spray> sprays;
public static List<NormalPath> normalPath;
public static List<Explosive> explosives;
public static List<Entity> toKill;
public static Point mousePosition;
public static bool mouseClicked;
public static Random r = new Random();
public static Point offset = new Point();
static void Main(string[] args)
{
entities = new List<Entity>();
toKill = new List<Entity>();
sprays = new List<Spray>();
bullets = new List<Bullet>();
normalPath = new List<NormalPath>();
explosives = new List<Explosive>();
for(int i = 0; i < 100; i++)
{
entities.Add(new Entity((r.Next(0, width) / 32) * 32, (r.Next(0, height) / 32) * 32, Entity.entityType.Student));
}
direction = Direction.None;
videoScreen = Video.SetVideoMode(width, height, false, false, false, false, true);
Events.Tick += Update;
Events.Tick += displayDebugInfo;
Events.KeyboardDown += KeyDown;
Events.KeyboardUp += KeyUp;
Events.MouseMotion += MouseMotion;
Events.MouseButtonDown += MouseButtonDown;
Events.Quit += Quit;
Events.TargetFps = 144;
Mouse.ShowCursor = false;
setupTmpLevel();
Events.Run();
}
public static void MouseButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.Button == MouseButton.PrimaryButton)
{
mouseClicked = true;
}
if (e.Button == MouseButton.SecondaryButton)
{
normalPath.Add(new Point(mousePosition.X + offset.X, mousePosition.Y + offset.Y));
}
}
public static void MouseMotion(object sender, MouseMotionEventArgs e)
{
mousePosition = new Point(e.X, e.Y);
}
public static void Update(object sender, TickEventArgs e)
{
foreach(Entity kills in toKill)
{
entities.Remove(kills);
}
videoScreen.Fill(Color.DarkOliveGreen);
List<IDrawable> drawable = new List<IDrawable>();
drawable.AddRange(bullets);
drawable.AddRange(sprays);
drawable.AddRange(explosives);
drawable.AddRange(entities);
foreach (IDrawable entity in drawable)
{
entity.Update(directionKeys, entities, mousePosition, mouseClicked);
entity.Draw(videoScreen);
}
//Begin debug draw
Circle c = new Circle(mousePosition, 8);
c.Draw(videoScreen, Color.Red, true, false);
c.Draw(videoScreen, Color.FromArgb(32, 255, 0, 0), true, true);
mouseClicked = false;
foreach(Point p in normalPath)
{
c.Center = new Point(p.X - offset.X, p.Y - offset.Y);
c.Draw(videoScreen, Color.Blue, true, false);
c.Draw(videoScreen, Color.FromArgb(32, 128, 128, 0), true, true);
}
videoScreen.Update();
}
public static void Quit(object sender, QuitEventArgs e)
{
Events.QuitApplication();
}
public static void KeyDown(object sender, KeyboardEventArgs e)
{
if(e.Key == Key.LeftShift)
{
explosives.Add(new Explosive(mousePosition.X, mousePosition.Y, Explosive.explosiveType.bomb));
}
switch(e.Key)
{
case Key.W:
directionKeys[0] = true;
break;
case Key.A:
directionKeys[1] = true;
break;
case Key.S:
directionKeys[2] = true;
break;
case Key.D:
directionKeys[3] = true;
break;
}
}
public static void KeyUp(object sender, KeyboardEventArgs e)
{
switch (e.Key)
{
case Key.W:
directionKeys[0] = false;
break;
case Key.A:
directionKeys[1] = false;
break;
case Key.S:
directionKeys[2] = false;
break;
case Key.D:
directionKeys[3] = false;
break;
}
}
public static void displayDebugInfo(object sender, TickEventArgs e)
{
}
public enum Direction
{
Up,
Down,
Right,
Left,
None
}
public static void shotsFired(int x, int y, Entity shooter)
{
Point originOfShot = shooter.position;
Point DestinationOfShot = new Point(x,y);
foreach (Entity e in entities)
{
int dX = (e.position.X + 16)- x;
int dY = (e.position.Y + 16) - y;
if (dX * dX + dY * dY < (32 * 32) && e.type != Entity.entityType.Player)
{
e.health -= new Random().Next(25, 100);
}
}
}
public static void setupTmpLevel()
{
entities.Add(new Entity(0, 0, Entity.entityType.Player));
sprays.Add(new Spray(0, 0, Spray.sprayType.blood));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName="FafaTools/Audio/PitchVolumeAudio")]
public class PitchVolumeAudio : AudioEvent {
public RangedFloat volume;
[MinMaxRange(0,2)]
public RangedFloat pitch;
public override void Play(AudioSource source)
{
AudioClip toPlay = clips[Random.Range(0, clips.Length)];
source.outputAudioMixerGroup = audioMixerGroup;
source.volume = Random.Range(volume.minValue, volume.maxValue);
source.pitch = Random.Range(pitch.minValue, pitch.maxValue);
if (loop)
{
source.loop = loop;
source.clip = toPlay;
source.Play();
}
else
{
source.loop = false;
source.PlayOneShot(toPlay);
}
}
public void Stop()
{
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsightGroupTech
{
class FileRead
{
// ArrayList is required because the data in the text file can shift
public ArrayList coordValue()
{
string path = @"c:\Users/joona/source/repos/InsightGroup_Assign1/InsightGroupTech/coordtext.txt";
ArrayList arr = new ArrayList();
try
{
// just in case, no file or incorrect path exists
if (!File.Exists(path))
{
Console.WriteLine("File does not exist");
}
StreamReader objReader = new StreamReader(path);
string sLine = "";
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
{
arr.Add(sLine);
}
else
{
break;
}
}
objReader.Close();
}
catch (Exception e)
{
Console.WriteLine(e + ": The process failed.");
}
return arr;
}
}
}
|
using System;
namespace HelperLibrary.CustomExceptions
{
public class InvalidGradeException : Exception
{
public InvalidGradeException(){}
public InvalidGradeException(int grade)
: base(String.Format("Grade must be from 0 to 5: {0}", grade)) {}
}
} |
using Tookan.NET.Http;
namespace Tookan.NET.Authentication
{
class AnonymousAuthenticator : IAuthenticationHandler
{
public void Authenticate(IRequest request, Credentials credentials)
{
// Do nothing. Retain your anonymity.
}
}
}
|
using RC.Core.Interfaces;
using RC.Core.Silverlit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace RC.Core.Bluetooth
{
public sealed class Ferrari458Italia : SilverlitBluetoothDevice, ICar, ICarBlinkers, ICarBreakLights, ICarHeadlight
{
public Ferrari458Italia():base("Ferrari458Italia","{00001101-0000-1000-8000-00805F9B34FB}", 100)
{
this.Match = 0x40;
this.Trimmer = 8;
LightSequenceDelay = 1;
}
#region Properties
public float Speed { get; set; }
public float Steering { get; set; }
public bool LeftBlinkerOn { get; set; }
public bool RightBlinkerOn { get; set; }
public bool BreakLightOn { get; set; }
public bool HeadLightOn { get; set; }
public byte[] LightSequence { get; set; }
public int LightSequenceDelay { get; set; }
public new byte Trimmer
{
get { return base.Trimmer; }
set { base.Trimmer=value; }
}
#endregion
int lightSequenceCounter = 0;
int lightSequenceDelayCounter = 0;
protected override byte[] GetBytesToSend()
{
Lights = 0;
if (HeadLightOn)
{
Lights += (byte)LightEnum.Head;
}
if (BreakLightOn)
{
Lights += (byte)LightEnum.Break;
}
if (LeftBlinkerOn)
{
Lights += (byte)LightEnum.LeftBlinker;
}
if (RightBlinkerOn)
{
Lights += (byte)LightEnum.RightBlinker;
}
if (LightSequence != null && LightSequence.Length>0)
{
if (lightSequenceDelayCounter++ >= LightSequenceDelay)
{
lightSequenceDelayCounter = 0;
if (lightSequenceCounter >= LightSequence.Length)
lightSequenceCounter = 0;
Lights |= LightSequence[lightSequenceCounter++];
}
}
Pitch = (byte)Math.Floor(((Speed * -1) * 127) + 127);
Yaw = (byte)Math.Floor(((Steering*-1) * 127) + 127);
byte trimmerLightByte = (byte)(Trimmer | Lights << 4);
byte[] bytesProtocol = new byte[] { trimmerLightByte, Yaw, Pitch, Rotor, Match };
string protocolString = "r";
for (int i = 0; i < bytesProtocol.Length; i++)
{
int index = (bytesProtocol.Length - 1) - i;
protocolString += GetHexString(bytesProtocol[index]);
}
Debug.WriteLine(protocolString);
List<byte> bytelist = new List<byte>();
foreach (var c in protocolString)
{
bytelist.Add((byte)c);
}
return bytelist.ToArray();
}
}
}
|
using System;
using Xamarin.Forms;
namespace Dictionary
{
public class Start : TabbedPage
{
public Start()
{
var first = new Sasha();
first.Title = "Sasha";
var second = new Translate();
second.Title = "Переводчик";
Children.Add(first);
Children.Add(second);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Language.Analyzer;
namespace Language.Compiler
{
public class Optimizer
{
private readonly List<Triad> ir;
private readonly Operation[] replaceOps =
{
Operation.Add,
Operation.Sub,
Operation.Mul,
Operation.Div,
Operation.Mod,
Operation.Xor,
Operation.Or,
Operation.And,
Operation.Not,
Operation.Lshift,
Operation.Rshift,
Operation.Push,
Operation.Jz,
};
private readonly Operation[] splitOps =
{
Operation.Call,
Operation.Jmp,
Operation.Jz,
Operation.Proc,
};
public Optimizer(List<Triad> ir)
{
this.ir = ir;
}
public List<Triad> Optimize()
{
var splitted = SplitLinear();
return splitted.SelectMany(ConstSubstitution).ToList();
}
private List<List<(Triad, int)>> SplitLinear()
{
var res = new List<List<(Triad, int)>>();
var ll = new List<(Triad, int)>();
var dests = ir.Where(tr => tr.Operation == Operation.Jmp)
.Select(tr => (int) tr.Arg1)
.Union(ir.Where(tr => tr.Operation == Operation.Jz).Select(tr => (int) tr.Arg2));
for (var i = 0; i < ir.Count; i++)
{
var triad = ir[i];
ll.Add((triad, i));
if (splitOps.Contains(triad.Operation) || dests.Contains(i + 1))
{
res.Add(ll);
ll = new List<(Triad, int)>();
}
}
res.Add(ll);
return res;
}
private List<Triad> ConstSubstitution(List<(Triad, int)> code)
{
var constValues = new Dictionary<IResult, ConstResult>();
var res = new List<Triad>();
var halfOk = new Dictionary<int, int>();
for (var i = 0; i < code.Count; i++)
{
var triad = code[i].Item1;
if (triad.Operation == Operation.Assign)
{
if (constValues.ContainsKey(triad.Arg2))
{
triad.Arg2 = constValues[triad.Arg2];
}
if (triad.Arg2 is ConstResult)
{
constValues[triad.Arg1] = triad.Arg2;
}
}
if (triad.Operation == Operation.Cast)
{
var tr = constValues.TryGetValue(triad.Arg1, out ConstResult r) ? r :
triad.Arg1 is ConstResult cr ? cr : null;
if (tr != null)
{
dynamic val;
switch (triad.Arg2)
{
case SemType.Int:
val = (int) tr.Value;
break;
case SemType.LongLongInt:
val = (long) tr.Value;
break;
case SemType.Char:
val = (char) tr.Value;
break;
default:
throw new ArgumentOutOfRangeException(nameof(tr.Value));
}
constValues[TriadResult.Of(code[i].Item2, triad.Arg2)] = ConstResult.Of(val);
triad.Operation = Operation.Nop;
triad.Arg1 = triad.Arg2 = null;
}
}
if (replaceOps.Contains(triad.Operation))
{
if (triad.Arg1 != null && constValues.ContainsKey(triad.Arg1))
{
triad.Arg1 = constValues[triad.Arg1];
}
if (triad.Arg2 != null && triad.Arg2 is IResult && constValues.ContainsKey(triad.Arg2))
{
triad.Arg2 = constValues[triad.Arg2];
}
if (triad.Arg1 is ConstResult cr1)
{
if (triad.Arg2 == null || triad.Arg2 is ConstResult)
{
var val = EvalConst(triad.Operation, cr1, triad.Arg2 is ConstResult cr3 ? cr3.Value : null);
if (val != null)
{
constValues[TriadResult.Of(code[i].Item2, val.Type)] = val;
triad.Operation = Operation.Nop;
triad.Arg1 = triad.Arg2 = null;
}
}
}
if (triad.Arg1 is ConstResult || triad.Arg2 is ConstResult)
halfOk[code[i].Item2] = i;
if (triad.Arg1 is TriadResult tr &&
triad.Arg2 is ConstResult crr1 &&
halfOk.ContainsKey(tr.Index) &&
triad.Operation == res[halfOk[tr.Index]].Operation)
{
var tr2 = res[halfOk[tr.Index]];
if (tr2.Arg1 is ConstResult crr2)
{
triad.Arg1 = tr2.Arg2;
triad.Arg2 = ConstResult.Of(EvalConst(triad.Operation, crr1, crr2.Value));
tr2.Operation = Operation.Nop;
tr2.Arg1 = tr2.Arg2 = null;
}
if (tr2.Arg2 is ConstResult crr3)
{
triad.Arg1 = tr2.Arg1;
triad.Arg2 = ConstResult.Of(EvalConst(triad.Operation, crr1, crr3.Value));
tr2.Operation = Operation.Nop;
tr2.Arg1 = tr2.Arg2 = null;
}
}
if (triad.Arg2 is TriadResult trr &&
triad.Arg1 is ConstResult crr4 &&
halfOk.ContainsKey(trr.Index) &&
triad.Operation == res[halfOk[trr.Index]].Operation)
{
var tr2 = res[halfOk[trr.Index]];
if (tr2.Arg1 is ConstResult crr2)
{
triad.Arg2 = tr2.Arg2;
triad.Arg1 = ConstResult.Of(EvalConst(triad.Operation, crr4, crr2.Value));
tr2.Operation = Operation.Nop;
tr2.Arg1 = tr2.Arg2 = null;
}
if (tr2.Arg2 is ConstResult crr3)
{
triad.Arg2 = tr2.Arg1;
triad.Arg1 = ConstResult.Of(EvalConst(triad.Operation, crr4, crr3.Value));
tr2.Operation = Operation.Nop;
tr2.Arg1 = tr2.Arg2 = null;
}
}
}
res.Add(triad);
}
for (var i = 0; i < res.Count; i++)
{
var triad = res[i];
if (triad.Operation == Operation.Assign)
{
var j = i + 1;
while (j < res.Count && res[j].Operation == Operation.Nop)
{
++j;
}
if (j < res.Count && res[j].Operation == Operation.Assign && res[j].Arg1.Equals(triad.Arg1))
{
triad.Operation = Operation.Nop;
triad.Arg1 = triad.Arg2 = null;
}
}
}
return res;
}
private static dynamic EvalConst(Operation op, ConstResult cr1, dynamic v2)
{
ConstResult val = null;
switch (op)
{
case Operation.Add:
val = ConstResult.Of(cr1.Value + v2);
break;
case Operation.Sub:
val = ConstResult.Of(cr1.Value - v2);
break;
case Operation.Mul:
val = ConstResult.Of(cr1.Value * v2);
break;
case Operation.Div:
val = ConstResult.Of(cr1.Value / v2);
break;
case Operation.Mod:
val = ConstResult.Of(cr1.Value % v2);
break;
case Operation.And:
val = ConstResult.Of(cr1.Value & v2);
break;
case Operation.Or:
val = ConstResult.Of(cr1.Value | v2);
break;
case Operation.Xor:
val = ConstResult.Of(cr1.Value ^ v2);
break;
case Operation.Lshift:
val = ConstResult.Of(cr1.Value << v2);
break;
case Operation.Rshift:
val = ConstResult.Of(cr1.Value >> v2);
break;
case Operation.Not:
val = ConstResult.Of(~cr1.Value);
break;
case Operation.Push:
case Operation.Jz:
break;
default:
throw new ArgumentOutOfRangeException(nameof(op));
}
return val;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyEmitter : MonoBehaviour
{
public Transform enemies;
public float minDelay, maxDelay; // задержка между запусками
private float nextLaunchTime; // время следующего запуска
// Update is called once per frame
private void Update()
{
if (GameControllerScript.instance.isStarted == false)
{
return;
}
if (Time.time > nextLaunchTime)
{
float posY = 0;
float posX = Random.Range(-transform.localScale.x / 2, transform.localScale.x / 2); // задаем случайное положение врага по оси X
float posZ = transform.position.z;
Instantiate(enemies.transform.GetChild(0), new Vector3(posX, posY, posZ), Quaternion.Euler(0, 180,0)); // создаем врага
nextLaunchTime = Time.time + Random.Range(minDelay, maxDelay); // меняем время следующего появления врага
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Valve.VR.InteractionSystem
{
public class fixscript : MonoBehaviour
{
Throwable throwScript;
Animator anim;
GameObject spanar;
GameObject onHandSpanar;
AudioSource spanarSound;
// Start is called before the first frame update
void Start()
{
onHandSpanar = GameObject.Find("onHandSpanar");
spanar = GameObject.Find("spanar");
spanar.SetActive(false);
spanarSound = spanar.GetComponent<AudioSource>();
anim = spanar.GetComponent<Animator>();
throwScript = onHandSpanar.GetComponent<Throwable>();
}
// Destroy everything that enters the trigger
void OnTriggerEnter(Collider other)
{
if (this.enabled)
{
this.enabled = false;
//This will fire only the first time this object hits a trigger
if (other.tag == "spanar")
{
spanar.SetActive(true);
onHandSpanar.SetActive(false);
spanarSound.Play();
throwScript.attached = false;
throwScript.onDetachFromHand.Invoke(); //have to invoke this
anim.SetTrigger("isFixing");
Debug.Log("FIXED");
}
}
}
// Update is called once per frame
void Update()
{
}
}
} |
using System;
using System.Windows.Forms;
namespace Grimoire.UI
{
public partial class CommandEditorForm : Form
{
public string Input => txtCmd.Text;
public string Content { set => txtCmd.Text = value; }
private CommandEditorForm()
{
InitializeComponent();
txtCmd.Select();
}
private void txtCmd_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
btnOK.PerformClick();
break;
case Keys.Escape:
btnCancel.PerformClick();
break;
}
}
public static string Show(string content)
{
using (CommandEditorForm dialog = new CommandEditorForm {Content = content})
return dialog.ShowDialog() == DialogResult.OK ? dialog.Input : null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Idfy.Identification.Client;
using Idfy.Identification.Models;
using Newtonsoft.Json;
namespace IdentificationDemo.Controllers
{
public class HomeController : Controller
{
private Idfy.Identification.Client.IdentificationClient client = new IdentificationClient(
new Guid("YOUR_ACCOUNT_ID"),
"YOUR OAUTH CLIENT ID", "CLIENT SECRET", "identify",
IdentificationClient.Environment.TEST);
private const string baseUrl = "https://localhost:44334";
public async Task<ActionResult> Index()
{
var response = await client.Create(new CreateIdentificationRequest()
{
ExternalReference = Guid.NewGuid().ToString(),
ReturnUrls = new ReturnUrls()
{
Abort = baseUrl+Url.Action("Abort"),
Error = baseUrl+Url.Action("Error")+$"?statuscode=[0]",
Success = baseUrl+Url.Action("Success")+"?requestId=[1]",
},
iFrame = new iFrameSettings()
{
Domain = baseUrl.Replace("https://",""),
}
});
ViewBag.Url = response.Url;
ViewBag.RequestId = response.RequestId;
return View();
}
public ActionResult Abort()
{
ViewBag.Message = "Aborted";
return View();
}
public ActionResult Error(string statuscode)
{
return new ContentResult()
{
Content = statuscode,
ContentType = "text/plain",
};
}
public async Task<ActionResult> Success(string requestId)
{
var response = await client.GetResponse(requestId,true);
ViewBag.Json = Newtonsoft.Json.JsonConvert.SerializeObject(response,Formatting.Indented);
return View();
}
}
} |
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UdemyDotnetCourse.Dtos.Character;
using UdemyDotnetCourse.Dtos.Fight;
using UdemyDotnetCourse.Dtos.Skill;
using UdemyDotnetCourse.Dtos.Weapon;
using UdemyDotnetCourse.Models;
namespace UdemyDotnetCourse.AutoMapper
{
public class AutoMapperProfile: Profile
{
public AutoMapperProfile()
{
//Character
CreateMap<Character, GetCharacterDto>().ReverseMap();
CreateMap<Character, AddCharacterDto>().ReverseMap();
CreateMap<UpdateCharacterDto,Character>();
//Weapon
CreateMap<Weapon, GetWeaponDto>().ReverseMap();
CreateMap<AddWeaponDto, Weapon>();
CreateMap<UpdateWeaponDto, Weapon>();
//Skill
CreateMap<Skill, GetSkillDto>().ReverseMap();
//HighScore
CreateMap<Character, HighScoreDto>();
}
}
}
|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using NopSolutions.NopCommerce.BusinessLogic.Caching;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;
using NopSolutions.NopCommerce.DataAccess;
using NopSolutions.NopCommerce.DataAccess.Tax;
namespace NopSolutions.NopCommerce.BusinessLogic.Tax
{
/// <summary>
/// Tax provider manager
/// </summary>
public partial class TaxProviderManager
{
#region Constants
private const string TAXPROVIDERS_ALL_KEY = "Nop.taxprovider.all";
private const string TAXPROVIDERS_BY_ID_KEY = "Nop.taxprovider.id-{0}";
private const string TAXPROVIDERS_PATTERN_KEY = "Nop.taxprovider.";
#endregion
#region Utilities
private static TaxProviderCollection DBMapping(DBTaxProviderCollection dbCollection)
{
if (dbCollection == null)
return null;
TaxProviderCollection collection = new TaxProviderCollection();
foreach (DBTaxProvider dbItem in dbCollection)
{
TaxProvider item = DBMapping(dbItem);
collection.Add(item);
}
return collection;
}
private static TaxProvider DBMapping(DBTaxProvider dbItem)
{
if (dbItem == null)
return null;
TaxProvider item = new TaxProvider();
item.TaxProviderID = dbItem.TaxProviderID;
item.Name = dbItem.Name;
item.Description = dbItem.Description;
item.ConfigureTemplatePath = dbItem.ConfigureTemplatePath;
item.ClassName = dbItem.ClassName;
item.DisplayOrder = dbItem.DisplayOrder;
return item;
}
#endregion
#region Methods
/// <summary>
/// Deletes a tax provider
/// </summary>
/// <param name="TaxProviderID">Tax provider identifier</param>
public static void DeleteTaxProvider(int TaxProviderID)
{
DBProviderManager<DBTaxProviderProvider>.Provider.DeleteTaxProvider(TaxProviderID);
if (TaxProviderManager.CacheEnabled)
{
NopCache.RemoveByPattern(TAXPROVIDERS_PATTERN_KEY);
}
}
/// <summary>
/// Gets a tax provider
/// </summary>
/// <param name="TaxProviderID">Tax provider identifier</param>
/// <returns>Tax provider</returns>
public static TaxProvider GetTaxProviderByID(int TaxProviderID)
{
if (TaxProviderID == 0)
return null;
string key = string.Format(TAXPROVIDERS_BY_ID_KEY, TaxProviderID);
object obj2 = NopCache.Get(key);
if (TaxProviderManager.CacheEnabled && (obj2 != null))
{
return (TaxProvider)obj2;
}
DBTaxProvider dbItem = DBProviderManager<DBTaxProviderProvider>.Provider.GetTaxProviderByID(TaxProviderID);
TaxProvider taxProvider = DBMapping(dbItem);
if (TaxProviderManager.CacheEnabled)
{
NopCache.Max(key, taxProvider);
}
return taxProvider;
}
/// <summary>
/// Gets all tax providers
/// </summary>
/// <returns>Shipping rate computation method collection</returns>
public static TaxProviderCollection GetAllTaxProviders()
{
string key = string.Format(TAXPROVIDERS_ALL_KEY);
object obj2 = NopCache.Get(key);
if (TaxProviderManager.CacheEnabled && (obj2 != null))
{
return (TaxProviderCollection)obj2;
}
DBTaxProviderCollection dbCollection =DBProviderManager<DBTaxProviderProvider>.Provider.GetAllTaxProviders();
TaxProviderCollection taxProviderCollection = DBMapping(dbCollection);
if (TaxProviderManager.CacheEnabled)
{
NopCache.Max(key, taxProviderCollection);
}
return taxProviderCollection;
}
/// <summary>
/// Inserts a tax provider
/// </summary>
/// <param name="Name">The name</param>
/// <param name="Description">The description</param>
/// <param name="ConfigureTemplatePath">The configure template path</param>
/// <param name="ClassName">The class name</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Tax provider</returns>
public static TaxProvider InsertTaxProvider(string Name, string Description,
string ConfigureTemplatePath, string ClassName, int DisplayOrder)
{
DBTaxProvider dbItem = DBProviderManager<DBTaxProviderProvider>.Provider.InsertTaxProvider(Name, Description,
ConfigureTemplatePath, ClassName, DisplayOrder);
TaxProvider taxProvider = DBMapping(dbItem);
if (TaxProviderManager.CacheEnabled)
{
NopCache.RemoveByPattern(TAXPROVIDERS_PATTERN_KEY);
}
return taxProvider;
}
/// <summary>
/// Updates the tax provider
/// </summary>
/// <param name="TaxProviderID">The tax provider identifier</param>
/// <param name="Name">The name</param>
/// <param name="Description">The description</param>
/// <param name="ConfigureTemplatePath">The configure template path</param>
/// <param name="ClassName">The class name</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Tax provider</returns>
public static TaxProvider UpdateTaxProvider(int TaxProviderID, string Name, string Description,
string ConfigureTemplatePath, string ClassName, int DisplayOrder)
{
DBTaxProvider dbItem = DBProviderManager<DBTaxProviderProvider>.Provider.UpdateTaxProvider(TaxProviderID, Name,
Description, ConfigureTemplatePath, ClassName, DisplayOrder);
TaxProvider taxProvider = DBMapping(dbItem);
if (TaxProviderManager.CacheEnabled)
{
NopCache.RemoveByPattern(TAXPROVIDERS_PATTERN_KEY);
}
return taxProvider;
}
#endregion
#region Property
/// <summary>
/// Gets a value indicating whether cache is enabled
/// </summary>
public static bool CacheEnabled
{
get
{
return SettingManager.GetSettingValueBoolean("Cache.TaxProviderManager.CacheEnabled");
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioTestPlay : MonoBehaviour
{
public string Name;
public bool Test;
void Update()
{
if (Test)
{
AudioManager.Instance.Play(Name);
Test = false;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.