text stringlengths 13 6.01M |
|---|
using UnityEngine;
using System.Collections;
public class result : MonoBehaviour {
public static bool isStart;
public GameObject[] RankObj = new GameObject[2];
// 親指定用
public GameObject Rank2,Rank3;
private int rank_gear;
// Use this for initialization
void Start () {
// ランクを確定
rank_gear = StageInfo.MAX_RANK + stage.StageTrouble[GameMemory.StagePage * StageAction.MAX_STAGE_INFO + GameMemory.StageGear] - MapAction.Trouble;
// 最低獲得ランクを保障
if (rank_gear <= 0)
rank_gear = 1;
// 最大獲得ランクを3に調整
if (rank_gear >= StageInfo.MAX_RANK)
rank_gear = StageInfo.MAX_RANK;
// ランクと総獲得ランクを更新
if (GameMemory.StageRank [GameMemory.StagePage * StageAction.MAX_STAGE_INFO + GameMemory.StageGear] < rank_gear) {
GameMemory.TotalRank -= GameMemory.StageRank [GameMemory.StagePage * StageAction.MAX_STAGE_INFO + GameMemory.StageGear];
GameMemory.StageRank [GameMemory.StagePage * StageAction.MAX_STAGE_INFO + GameMemory.StageGear] = rank_gear;
GameMemory.TotalRank += GameMemory.StageRank [GameMemory.StagePage * StageAction.MAX_STAGE_INFO + GameMemory.StageGear];
}
// 次のステージを解放
if (GameMemory.StageGear < 2) {
// 1~3は順番に解放
GameMemory.StageRock [GameMemory.StagePage * StageAction.MAX_STAGE_INFO + GameMemory.StageGear + 1] = 1;
}
else {
// 3クリアで7まで + 各ページの1を解放
for(int i=3;i<StageAction.MAX_STAGE_INFO-1;i++){
GameMemory.StageRock [GameMemory.StagePage * StageAction.MAX_STAGE_INFO + i] = 1;
}
for(int i=0;i<RollPage.PAGE_MAX;i++){
GameMemory.StageRock [i * StageAction.MAX_STAGE_INFO] = 1;
}
}
if (rank_gear >= 2)
Rank2.GetComponent<UISprite> ().spriteName = "RankGear";
else {
Rank2.GetComponent<UISprite> ().spriteName = "NoRankGear";
PlaySE.isPlayGear1 = true;
}
if (rank_gear >= 3) {
Rank3.GetComponent<UISprite> ().spriteName = "RankGear";
PlaySE.isPlayGear3 = true;
}
else {
Rank3.GetComponent<UISprite> ().spriteName = "NoRankGear";
PlaySE.isPlayGear2 = true;
}
}
// Update is called once per frame
void Update () {
if (isStart) {
Start ();
isStart = false;
}
PlayBGM.isPlayGamePlay = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.WebPages;
namespace MvcBootstrap.Controls
{
public class Accordion
{
public class AccordionItem
{
public string Id { get; set; }
public string Title { get; set; }
public string HeaderContent { get; set; }
public string Content { get; set; }
public bool Active { get; set; }
}
private string _id;
private List<AccordionItem> _items = new List<AccordionItem>();
public Accordion(string id)
{
_id = id;
}
public Accordion AddItem(string id, bool active, string title, Func<dynamic, HelperResult> template)
{
AccordionItem item = new AccordionItem()
{
Id = id,
Content = template(null).ToHtmlString(),
Title = title,
HeaderContent = string.Empty,
Active = active
};
_items.Add(item);
return this;
}
public Accordion AddItem(string id, bool active, Func<dynamic, HelperResult> headerTemplate, Func<dynamic, HelperResult> contentTemplate)
{
AccordionItem item = new AccordionItem()
{
Id = id,
Content = contentTemplate(null).ToHtmlString(),
Title = string.Empty,
HeaderContent = headerTemplate(null).ToHtmlString(),
Active = active
};
_items.Add(item);
return this;
}
public MvcHtmlString Render()
{
TagBuilder accordion = new TagBuilder("div");
accordion.Attributes.Add("id", _id);
accordion.AddCssClass("accordion");
foreach (var item in _items)
{
TagBuilder accordionGroup = new TagBuilder("div");
accordionGroup.AddCssClass("accordion-group");
TagBuilder accordionGroupHeading = new TagBuilder("div");
accordionGroupHeading.AddCssClass("accordion-heading");
TagBuilder linkHeading = new TagBuilder("a");
linkHeading.AddCssClass("accordion-toggle");
linkHeading.Attributes.Add("data-toggle", "collapse");
linkHeading.Attributes.Add("data-parent", "#" + _id);
linkHeading.Attributes.Add("href", "#" + item.Id);
if (string.IsNullOrWhiteSpace(item.HeaderContent))
{
linkHeading.SetInnerText(item.Title);
}
else
{
linkHeading.InnerHtml = item.HeaderContent;
}
TagBuilder accordionBody = new TagBuilder("div");
accordionBody.AddCssClass("accordion-body collapse");
if (item.Active)
accordionBody.AddCssClass("in");
accordionBody.Attributes.Add("id", item.Id);
TagBuilder accordionInner = new TagBuilder("div");
accordionInner.AddCssClass("accordion-inner");
accordionInner.InnerHtml = item.Content;
accordionBody.InnerHtml = accordionInner.ToString(TagRenderMode.Normal);
accordionGroupHeading.InnerHtml = linkHeading.ToString(TagRenderMode.Normal);
accordionGroup.InnerHtml = accordionGroupHeading.ToString(TagRenderMode.Normal);
accordionGroup.InnerHtml += accordionBody.ToString(TagRenderMode.Normal);
accordion.InnerHtml += accordionGroup.ToString(TagRenderMode.Normal);
}
return new MvcHtmlString(accordion.ToString(TagRenderMode.Normal));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using Lab2.Models;
namespace Lab2.Repositories
{
public class AirportRepository : IRepository<AirportModel> {
private string connectionString = "Server=localhost;Port=3306;Database=flights;Uid=root;Pwd=0212;SslMode=none";
private MySqlConnection Connection;
public AirportRepository() {
Connection = new MySqlConnection(connectionString);
}
public void Add(AirportModel entity) {
Connection.Open();
var command = Connection.CreateCommand();
var sql = "INSERT INTO `Airports` VALUES(" + entity.Id + ",'" + entity.Name + "','" + entity.City + "','" + entity.Country+"');";
command.CommandText = sql;
command.ExecuteNonQuery();
Connection.Close();
}
public void Delete(AirportModel entity) {
Connection.Open();
var command = Connection.CreateCommand();
var sql = "DELETE FROM `Airports` WHERE AirportID = " + entity.Id + " LIMIT 1;";
command.CommandText = sql;
command.ExecuteNonQuery();
Connection.Close();
}
public AirportModel Get(int id) {
Connection.Open();
var command = Connection.CreateCommand();
var sql = "SELECT * FROM `Airports` WHERE AirportID = " + id + ";";
command.CommandText = sql;
var dataReader = command.ExecuteReader();
var result = new AirportModel();
while (dataReader.Read()) {
result.Id = id;
result.Name = dataReader["Name"].ToString();
result.City = dataReader["City"].ToString();
result.Country = dataReader["Country"].ToString();
}
dataReader.Close();
Connection.Close();
return result;
}
public IEnumerable<AirportModel> GetAll() {
Connection.Open();
var command = Connection.CreateCommand();
var sql = "SELECT * FROM `Airports`;";
command.CommandText = sql;
var dataReader = command.ExecuteReader();
var result = new List<AirportModel>();
while (dataReader.Read()) {
result.Add(new AirportModel {
Id = Int32.Parse(dataReader["AirportID"].ToString()),
Name = dataReader["Name"].ToString(),
City = dataReader["City"].ToString(),
Country = dataReader["Country"].ToString()
});
}
dataReader.Close();
Connection.Close();
return result;
}
public void Update(AirportModel entity) {
Connection.Open();
var command = Connection.CreateCommand();
var sql = "REPLACE INTO `Airports` VALUES(" + entity.Id + ",'" + entity.Name + "'," + entity.City + "','" + entity.Country + "');";
command.CommandText = sql;
command.ExecuteNonQuery();
Connection.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using OcrEngine;
namespace SaveAsOcr
{
public class UnityConfig
{
private readonly IUnityContainer container = new UnityContainer();
public MainWindow MainWindow { get { return new Lazy<MainWindow>(() => container.Resolve<MainWindow>()).Value; } }
public void RegisterContainer()
{
container.RegisterType<IPdfConverter, PdfConverter>();
container.RegisterType<IOcrReader, OcrReader>();
container.RegisterType<IMainController, MainController>();
container.RegisterType<MainWindow, MainWindow>();
}
}
}
|
// Bar POS, class SearchScreen
// Versiones:
// V0.01 22-May-2018 Moisés: Class implemented
using System;
using System.Windows.Forms;
namespace BarPOS
{
public partial class SearchScreen : Form
{
public string TextToSearch { get; set; }
public SearchScreen(Languajes languaje)
{
InitializeComponent();
drawTexts(languaje);
}
private void drawTexts(Languajes languaje)
{
switch (languaje)
{
case Languajes.Castellano:
lblText.Text = "Texto de búsqueda";
btnSearch.Text = "Buscar";
break;
case Languajes.English:
lblText.Text = "Text to search";
btnSearch.Text = "Search";
break;
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
TextToSearch = txtTextToSearch.Text;
this.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Apv.AV.Services.Shared;
namespace Apv.AV.Web.Controllers
{
public class SharedController:Controller
{
private IApvSharedServices _iApvService;
public SharedController(IApvSharedServices iApvService)
{
_iApvService = iApvService;
}
/// <summary>
/// Gets the country global settings.
/// </summary>
/// <returns>The country global settings.</returns>
[HttpGet("api/[controller]/countrySettings")]
public IActionResult getCountryGlobalSettings()
{
try
{
return Ok(_iApvService.getCountryGlobalSettings());
}
catch(Exception ex)
{
}
return BadRequest("Error retrieving country global settings");
}
/// <summary>
/// Gets the country global setting.
/// </summary>
/// <returns>The country global setting.</returns>
/// <param name="countryCode">Country code.</param>
[HttpGet("api/[controller]/countrySettings/{countryCode}")]
public IActionResult getCountryGlobalSetting(string countryCode)
{
try
{
return Ok(_iApvService.getCountryGlobalSetting(countryCode));
}
catch(Exception ex)
{
}
return BadRequest("Error retrieving country global settings");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _022_BOOLEAN
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите трехзначное число");
int number = Convert.ToInt32(Console.ReadLine());
//bool compare = number >= 100 && number <= 999;
int thirdNumber = number % 10;
int secondNumber = (number % 100 - thirdNumber) / 10;
int firstNumber = number / 100;
bool numberCompareUp = thirdNumber > secondNumber && secondNumber > firstNumber && thirdNumber > firstNumber;
bool numberCompareDown = thirdNumber < secondNumber && secondNumber < firstNumber && thirdNumber < firstNumber;
bool finalCompare = numberCompareUp || numberCompareDown;
Console.WriteLine("Цифры {0}, {1}, {2} числа {3} образуют возрастающую или убывающую последовательность - {4}",
firstNumber, secondNumber, thirdNumber, number, finalCompare);
}
}
}
|
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineGallery.Models
{
[Table("ProductImage")]
public class ProductImage
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("Id", TypeName = "int")]
public int Id { get; set; }
[DisplayName("Product")]
[Required(ErrorMessage = "- Please select product.")]
[Column("ProductId", TypeName = "int")]
public int? ProductId { get; set; }
[ForeignKey("ProductId")]
public Product Product { get; set; }
[DisplayName("Image Name")]
[Column("Image", TypeName = "nvarchar(450)")]
public string Image { get; set; }
[NotMapped]
public List<IFormFile> FileImage { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartLib;
using KartLib.Views;
using KartObjects;
using System.IO;
using FastReport;
using AxiReports;
using KartObjects.Entities;
using KartObjects.Entities.Documents;
using KartSystem.Presenters;
namespace KartSystem
{
public partial class GoodMovementsView : KartUserControl, IGoodMovementReportView
{
public GoodMovementsView()
{
InitializeComponent();
ViewObjectType = KartObjects.ObjectType.GoodMovementReport;
Preseneter = new GoodMovementReportPresenter(this);
deDateFrom.DateTime = DateTime.Now;
UseLoadSettings = true;
}
public override void InitView()
{
base.InitView();
warehouseBindingSource.DataSource = KartDataDictionary.sWarehouses;
lueWarehouses.EditValue = warehouseBindingSource[0];
csAssortment.UseAssortment = KartDataDictionary.IsUseAssortment();
csAssortment.searchAssortment1.splitContainer1.Panel2Collapsed = !KartDataDictionary.IsUseAssortment();
}
void csAssortment_SelectedGoodChosen(object sender, EventArgs e)
{
}
public override void RefreshView()
{
base.RefreshView();
goodMovementReportRecordBindingSource.DataSource = GoodMovementReportRecords;
}
private void sbLoadData_Click(object sender, EventArgs e)
{
if (csAssortment.SelectedAssortment != null)
{
(Preseneter as GoodMovementReportPresenter).LoadGoodMovementReportRecords();
Measure measure = (from m in KartDataDictionary.sMeasures where m.Id == csAssortment.SelectedGood.IdMeasure select m).First();
SetGridDecimalPlaces(measure);
}
else GoodMovementReportRecords = null;
RefreshView();
}
private void SetGridDecimalPlaces(Measure measure)
{
if (measure.IsWeight)
{
colQuantIn.DisplayFormat.FormatString = "0.000";
colQuantOut.DisplayFormat.FormatString = "0.000";
colRest.DisplayFormat.FormatString = "0.000";
}
else
{
colQuantIn.DisplayFormat.FormatString = "0";
colQuantOut.DisplayFormat.FormatString = "0";
colRest.DisplayFormat.FormatString = "0";
}
}
public List<GoodMovementReportRecord> GoodMovementReportRecords
{
get;
set;
}
public override bool IsEditable
{
get
{
return true;
}
}
public override bool IsInsertable
{
get
{
return false;
}
}
public override bool UseSubmenu
{
get
{
return false;
}
}
public override bool IsDeletable
{
get
{
return false;
}
}
public override bool IsPrintable
{
get
{
return false;
}
}
public GoodMovementReportRecord ActiveGoodMovementReportRecord
{
get { return gvGoodMovements.GetFocusedRow() as GoodMovementReportRecord; }
set
{
for (int i = 0; i < gvGoodMovements.RowCount; i++)
{
if ((gvGoodMovements.GetRow(i) as GoodMovementReportRecord).IdDocument == value.IdDocument)
{
gvGoodMovements.FocusedRowHandle = i;
break;
}
}
}
}
private void gvGoodMovements_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (!(gvGoodMovements.GetRow(e.RowHandle) as GoodMovementReportRecord).DocState)
e.Appearance.BackColor = Color.Red;
}
public override bool RecordSelected
{
get
{
return gvGoodMovements.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle;
}
}
public override void EditorAction(bool addMode)
{
if (ActiveGoodMovementReportRecord.IdDocument != 0)
{
Document d = Loader.DbLoad<AllDocument>("Id=" + ActiveGoodMovementReportRecord.IdDocument).SingleOrDefault();
var r = Loader.DbLoad<DocGoodSpecRecord>("idAssortment=" + csAssortment.SelectedAssortment.Id, 0, d.Id, 0, 0, 0, 0, 0);
if (Loader.DataContext.TranIsRunning)
Loader.DataContext.CommitTransaction();
IDocumentEditView editView = DocumentsView.getDocEditor(d);
if (r != null)
editView.currGoodSpecRecord = (DocGoodSpecRecord)(r.First());
(editView as Form).ShowDialog();
}
}
private void gcGoodMovements_DoubleClick(object sender, EventArgs e)
{
EditAction(this, null);
}
public override void SaveSettings()
{
GoodMovementViewSettings gms = new GoodMovementViewSettings();
if (csAssortment.SelectedAssortment != null)
gms.IdAssortment = csAssortment.SelectedAssortment.Id;
gms.DateReport = deDateFrom.DateTime;
if (lueWarehouses.EditValue != null)
gms.IdWarehouse = (long)lueWarehouses.EditValue;
gms.UseAssortment = csAssortment.UseAssortment;
SaveSettings<GoodMovementViewSettings>(gms);
}
public override void LoadSettings()
{
GoodMovementViewSettings gms = (GoodMovementViewSettings)LoadSettings<GoodMovementViewSettings>();
if (gms != null)
{
if (gms.IdAssortment != 0 && UseLoadSettings)
csAssortment.SelectAssortmentById(gms.IdAssortment);
csAssortment.UseAssortment = gms.UseAssortment;
if (gms.IdWarehouse != 0 && Convert.ToInt64(lueWarehouses.EditValue) == 0)
lueWarehouses.EditValue = gms.IdWarehouse;
deDateFrom.DateTime = gms.DateReport;
}
}
public bool UseAssortment
{
get { return csAssortment.UseAssortment; }
set { csAssortment.UseAssortment = value; }
}
public long IdSelectedAssortment
{
get { return csAssortment.SelectedAssortment.Id; }
}
public Assortment SelectAssortment
{
set { csAssortment.SelectedAssortment = value; }
}
public long IdSelectedGood
{
get { return csAssortment.SelectedGood.Id; }
}
public Good SelectGood
{
set { csAssortment.SelectedGood = value; }
}
public DateTime SelectedDate
{
get { return deDateFrom.DateTime; }
set { deDateFrom.DateTime = value; }
}
public long? IdSelectedWh
{
get { return (long?)lueWarehouses.EditValue; }
set { lueWarehouses.EditValue = value; }
}
public bool UseLoadSettings { get; set; }
private void simpleButton1_Click(object sender, EventArgs e)
{
using (Report report = new Report())
{
string _ReportPath = Settings.GetExecPath() + @"\Reports";
if (!File.Exists(_ReportPath + @"\GoodMovementReport.frx"))
{
MessageBox.Show(@"Не найдена форма печати GoodMovementReport.frx.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
report.Load(_ReportPath + @"\GoodMovementReport.frx");
if (report == null) return;
if (goodMovementReportRecordBindingSource.DataSource == null) return;
report.RegisterData(goodMovementReportRecordBindingSource, "goodMovementReportRecordBindingSource");
report.GetDataSource("goodMovementReportRecordBindingSource").Enabled = true;
TextObject Good = (TextObject)report.FindObject("Good");
if (Good != null)
{
string namegood = "";
if (csAssortment.SelectedGood != null)
namegood += csAssortment.SelectedGood.Name;
if (csAssortment.SelectedAssortment != null)
namegood += " " + csAssortment.SelectedAssortment.Name;
Good.Text = namegood;
}
TextObject Date = (TextObject)report.FindObject("Date");
if (Date != null && deDateFrom.Text != null)
Date.Text = "C " + deDateFrom.Text;
TextObject Warehouse = (TextObject)report.FindObject("Warehouse");
if (Warehouse != null && lueWarehouses.EditValue != null)
{
string WarehouseName = Loader.DbLoadSingle<Warehouse>("Id = " + lueWarehouses.EditValue).Name;
Warehouse.Text = WarehouseName;
}
if (report.Prepare())
report.ShowPrepared(true);
}
}
private void lueWarehouses_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
lueWarehouses.EditValue = null;
}
public bool SearchFinished
{
set
{
csAssortment.SearchFinished = value;
}
}
private void sbExportExcel_Click(object sender, EventArgs e)
{
if (GoodMovementReportRecords == null)
sbLoadData_Click(sender, e);
ExcelSaver es = new ExcelSaver("Отчет по товародвижению");
es.DoExport<GoodMovementReportRecord>(GoodMovementReportRecords);
}
}
} |
using Microsoft.AspNetCore.Mvc;
using PatientService.DTO;
using PatientService.Mapper;
using PatientService.Service;
using System.Linq;
namespace PatientService.Controller
{
[Route("api/[controller]")]
[ApiController]
public class PatientController : ControllerBase
{
private IPatientService _service;
public PatientController(IPatientService service)
{
_service = service;
}
[HttpPost]
public IActionResult Add(GuestPatientDTO guestPatient)
{
_service.Add(guestPatient);
return NoContent();
}
[HttpGet("{jmbg}/medical-info")]
public IActionResult Get(string jmbg)
{
var medicalInfo = _service.Get(jmbg).ToMedicalInfoDTO();
return Ok(medicalInfo);
}
[HttpPut("{jmbg}/medical-info")]
public IActionResult UpdateMedicalInfo(string jmbg, MedicalInfoUpdateDTO medicalInfoUpdate)
{
_service.UpdateMedicalInfo(jmbg, medicalInfoUpdate);
return NoContent();
}
[HttpGet("{jmbg}/examination")]
public IActionResult GetExaminations(string jmbg)
{
var examinations = _service.GetExaminations(jmbg).Select(e => e.ToExaminationDTO());
return Ok(examinations);
}
[HttpPost("{jmbg}/examination/search")]
public IActionResult GetExaminations(string jmbg, ExaminationSearchDTO examinationSearchDTO)
{
var examinations = _service.GetExaminations(jmbg, examinationSearchDTO).Select(e => e.ToExaminationDTO());
return Ok(examinations);
}
[HttpGet("{jmbg}/therapy")]
public IActionResult GetTherapies(string jmbg)
{
var therapies = _service.GetTherapies(jmbg).Select(t => t.ToTherapyDTO());
return Ok(therapies);
}
[HttpPost("{jmbg}/therapy/search")]
public IActionResult GetTherapies(string jmbg, TherapySearchDTO therapySearchDTO)
{
var therapies = _service.GetTherapies(jmbg, therapySearchDTO).Select(t => t.ToTherapyDTO());
return Ok(therapies);
}
[HttpGet("{jmbg}/examination/{id}/therapies")]
public IActionResult GetTherapiesForExamination(string jmbg, int id)
{
var therapies = _service.GetTherapiesForExamination(jmbg, id).Select(t => t.ToTherapyDTO());
return Ok(therapies);
}
[HttpGet("{jmbg}/examination/{id}")]
public IActionResult GetExamination(string jmbg, int id)
{
var examination = _service.GetExamination(jmbg, id).ToExaminationDTO();
return Ok(examination);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication28.Controllers
{
public class Cookie : Controller
{
private int _num;
public IActionResult Index()
{
string value = Request.Cookies["numberVisit"];
bool alreadyHere = !String.IsNullOrEmpty(value);
if (alreadyHere)
{
int times = int.Parse(value) + 1;
Response.Cookies.Append("numberVisit", $"{times}");
_num = times;
}
else
{
_num = 1;
Response.Cookies.Append("numberVisit", $"{_num}");
}
return View(_num);
}
}
}
|
using DDMedi;
using DDMedi.DependencyInjection;
using DemoWebApi.Handlers;
using DemoWebApi.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace DemoWebApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var ddFactory = new DDMediCollection()
//ModelCommandHandlers is dedicated as singleton lifetime
.AddSupplier<ModelCommandHandlers>(SupplierLifetime.Singleton)
// other handlers are scope lifetime, ModelCommandHandlers won't be added here
.AddSuppliers()
// Add a dedicate queue with 3 executors to process ExceptionEInputs becasue of long delay
.AddQueue(eSuppliers => eSuppliers.AddESupplier<ExceptionEInputsHandlers>(SupplierLifetime.Singleton), 3)
// any exception occur in esuppliers won't effect to main task, ExceptionEInputsHandlers won't be added here
.AddQueue(eSuppliers => eSuppliers.AddESuppliers())
//Decorator need to be defined separately for any specific message
.AddAsyncDecorator<GetModelQuery, DemoModel, CachedModelHandlers>()
.AddDecorator<GetModelQuery, DemoModel, CachedModelHandlers>()
// build DDMediFactory when finished register handlers
.BuildSuppliers();
services.AddDDMediFactory(ddFactory); // support IOC
services.AddControllers();
services.AddSingleton(new ConcurrentDictionary<int, DemoModel>());
services.AddSingleton(new List<DemoModel>());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
using System.Threading.Tasks;
namespace Fiery.Identity.Users.AspNetCore.Services
{
public interface ISmsSender
{
Task SendSmsAsync(string number, string message);
}
}
|
using Microsoft.Win32;
using NeuralNetLibrary.components;
using NeuralNetLibrary.components.learning;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace DigitRecognition
{
/// <summary>
/// Logika interakcji dla klasy MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ImageViewer imageViewer;
private DataHolder dataHolder;
private NeuralNetwork neuralNetwork;
private OutputConverter outputConverter;
public MainWindow()
{
InitializeComponent();
}
private void validateDataSeparation(Slider changedSlider, Slider firstSlider, Slider secondSlider)
{
if (changedSlider != null && firstSlider != null && secondSlider != null)
{
int changedValue = (int)changedSlider.Value;
int firstValue = (int)firstSlider.Value;
int secondValue = (int)secondSlider.Value;
int sum = changedValue + firstValue + secondValue;
if (sum > 100)
{
int overflow = sum - 100;
if (overflow - (int)firstSlider.Value > 0)
{
overflow -= (int)firstSlider.Value;
firstSlider.Value = 0;
secondSlider.Value -= overflow;
}
else
{
firstSlider.Value -= overflow;
}
}
}
}
private void learningDataSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
this.learningDataTextBox.Text = ((int)e.NewValue).ToString();
validateDataSeparation(learningDataSlider, validateDataSlider, testingDataSlider);
}
private void validateDataSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
this.validateDataTextBox.Text = ((int)e.NewValue).ToString();
validateDataSeparation(validateDataSlider, testingDataSlider, learningDataSlider);
}
private void testingDataSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
this.testingDataTextBox.Text = ((int)e.NewValue).ToString();
validateDataSeparation(testingDataSlider, validateDataSlider, learningDataSlider);
}
private void learningDataTextBox_LostFocus(object sender, RoutedEventArgs e)
{
int newValue;
if (Int32.TryParse(learningDataTextBox.Text, out newValue) &&
newValue >= 0 && newValue <= 100)
learningDataSlider.Value = newValue;
else
learningDataTextBox.Text = learningDataSlider.Value.ToString();
}
private void validateDataTextBox_LostFocus(object sender, RoutedEventArgs e)
{
int newValue;
if (Int32.TryParse(validateDataTextBox.Text, out newValue) &&
newValue >= 0 && newValue <= 100)
validateDataSlider.Value = newValue;
else
validateDataTextBox.Text = validateDataSlider.Value.ToString();
}
private void testingDataTextBox_LostFocus(object sender, RoutedEventArgs e)
{
int newValue;
if (Int32.TryParse(testingDataTextBox.Text, out newValue) &&
newValue >= 0 && newValue <= 100)
testingDataSlider.Value = newValue;
else
testingDataTextBox.Text = testingDataSlider.Value.ToString();
}
private void showDataComboBox_Initialized(object sender, EventArgs e)
{
showDataComboBox.Items.Add("Uczące");
showDataComboBox.Items.Add("Walidujące");
showDataComboBox.Items.Add("Testowe");
showDataComboBox.Items.Add("Pozostałe");
showDataComboBox.SelectedIndex = 0;
}
private void showDataComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (showItemComboBox != null)
{
String selectedValue = (String)showDataComboBox.SelectedValue;
DataItem.DataTypes selectedDataType = DataItem.DataTypes.None;
switch (selectedValue)
{
case "Uczące":
selectedDataType = DataItem.DataTypes.Learning;
break;
case "Walidujące":
selectedDataType = DataItem.DataTypes.Validate;
break;
case "Testowe":
selectedDataType = DataItem.DataTypes.Testing;
break;
}
showItemComboBox.Items.Clear();
for (int i = 0; i < dataHolder.Items.Count; i++)
if (dataHolder.Items[i].dataType == selectedDataType)
showItemComboBox.Items.Add(
new ComboBoxItem()
{
Content = outputConverter.Convert(dataHolder.Items[i].Outputs).ToString(),
Tag = i
}
);
showItemComboBox.SelectedIndex = 0;
}
}
private void showItemComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem selectedItem = (ComboBoxItem)showItemComboBox.SelectedItem;
if (selectedItem != null)
{
int itemIndex = (int)selectedItem.Tag;
DataItem dataItem = dataHolder.Items[itemIndex];
imageViewer.Draw(dataItem.Inputs);
if (neuralNetwork != null)
{
neuralNetwork.SetInputs(dataItem.Inputs);
neuralNetwork.Propagate();
double[] neuralNetOutput = neuralNetwork.GetOutputs();
double expectedOutput = outputConverter.Convert(dataItem.Outputs);
double networkOutput = outputConverter.GetMostProbablyValue(neuralNetOutput);
double outputProbability = outputConverter.GetProbability(neuralNetOutput, dataItem.Outputs);
expectedOutputLabel.Content = expectedOutput.ToString();
neuralNetOutputLabel.Content = networkOutput.ToString();
outputProbabilityLabel.Content = String.Format("{0:0.00} %", outputProbability);
}
}
}
private void learningRateTextBox_LostFocus(object sender, RoutedEventArgs e)
{
double newValue;
if (Double.TryParse(learningRateTextBox.Text.Replace('.', ','), out newValue) &&
newValue >= 0 && newValue <= 1)
learningRateTextBox.Text = newValue.ToString();
else
learningRateTextBox.Text = "0,1";
}
private void momentumTextBox_LostFocus(object sender, RoutedEventArgs e)
{
double newValue;
if (Double.TryParse(momentumTextBox.Text.Replace('.', ','), out newValue) &&
newValue >= 0 && newValue <= 1)
momentumTextBox.Text = newValue.ToString();
else
momentumTextBox.Text = "0,9";
}
private void errorThresholdTextBox_LostFocus(object sender, RoutedEventArgs e)
{
double newValue;
if (Double.TryParse(errorThresholdTextBox.Text.Replace('.', ','), out newValue) &&
newValue >= 0 && newValue <= 1)
errorThresholdTextBox.Text = newValue.ToString();
else
errorThresholdTextBox.Text = "0,1";
}
private void confirmDataButton_Click(object sender, RoutedEventArgs e)
{
if ((bool)swapOrderCheckBox.IsChecked)
dataHolder.Shuffle();
int learningPercent = (int)learningDataSlider.Value;
int validatePercent = (int)validateDataSlider.Value;
int testingPercent = (int)testingDataSlider.Value;
MyCustomMessage customMessage = new MyCustomMessage()
{
Owner = this,
Message = "Trwa dzielenie danych..."
};
customMessage.Show();
dataHolder.Load();
dataHolder.Separate(learningPercent, validatePercent, testingPercent);
customMessage.Close();
MessageBox.Show(this, "Dane zostały podzielone");
ShowDataGroupBox.IsEnabled = true;
showDataComboBox_SelectionChanged(null, null);
}
private void CreateNeuralNetwork_MenuItem_Click(object sender, RoutedEventArgs e)
{
if (dataHolder != null)
{
CreateNeuralNetWindow createNeuralNetWindow = new CreateNeuralNetWindow(
dataHolder.Items[0].Inputs.Length, dataHolder.Items[0].Outputs.Length);
createNeuralNetWindow.Owner = this;
createNeuralNetWindow.ShowDialog();
neuralNetwork = createNeuralNetWindow.GetNeuralNetwork();
if (neuralNetwork != null)
{
LearningSettingsGroupBox.IsEnabled = true;
neuralNetStatus.Content = "Warstw: " + neuralNetwork.Layers.Count;
MessageBox.Show(this, "Sieć została utworzona");
}
else
{
neuralNetStatus.Content = "Brak";
}
}
else
{
MessageBox.Show(this, "Najpierw wczytaj dane");
}
}
private void TrainNeuralNetwork_Button_Click(object sender, RoutedEventArgs e)
{
double learningRate, momentum, errorThreshold;
if (Double.TryParse(learningRateTextBox.Text, out learningRate) &&
Double.TryParse(momentumTextBox.Text, out momentum) &&
Double.TryParse(errorThresholdTextBox.Text, out errorThreshold))
{
LearningProgressWindow learningProgressWindow = new LearningProgressWindow()
{
DataItems = dataHolder.Items,
NeuralNet = neuralNetwork,
LearningRate = learningRate,
Momentum = momentum,
ErrorThreshold = errorThreshold,
Multithreading = (bool)multithreadingComboBox.IsChecked
};
learningProgressWindow.Owner = this;
learningProgressWindow.ShowDialog();
TestingSettingsGroupBox.IsEnabled = true;
}
else
{
MessageBox.Show(this, "Wystąpił nieoczekiwany błąd. Sprawdź wartości parametrów uczenia");
}
}
private void ShowGrid_CheckBox_Checked(object sender, RoutedEventArgs e)
{
imageViewer.ShowGrid();
}
private void ShowGrid_CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
imageViewer.HideGrid();
}
private void EnableEdit_CheckBox_Checked(object sender, RoutedEventArgs e)
{
userCorrectImageValue.IsEnabled = true;
checkButton.IsEnabled = true;
clearButton.IsEnabled = true;
imageViewer.EnableEdit();
}
private void EnableEdit_CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
userCorrectImageValue.IsEnabled = false;
checkButton.IsEnabled = false;
clearButton.IsEnabled = false;
imageViewer.DisableEdit();
}
private void Clear_Button_Click(object sender, RoutedEventArgs e)
{
expectedOutputLabel.Content = "";
neuralNetOutputLabel.Content = "";
outputProbabilityLabel.Content = "";
imageViewer.Clear();
}
private void Check_Button_Click(object sender, RoutedEventArgs e)
{
if (neuralNetwork != null)
{
BitArray imageInputs = imageViewer.GetCurrentImage();
neuralNetwork.SetInputs(imageInputs);
neuralNetwork.Propagate();
double[] imageOutputs = neuralNetwork.GetOutputs();
double networkOutput = outputConverter.GetMostProbablyValue(imageOutputs);
neuralNetOutputLabel.Content = networkOutput.ToString();
if (userCorrectImageValue.Text.Length > 0)
{
int value;
if (Int32.TryParse(userCorrectImageValue.Text, out value))
{
BitArray expectedOutput = outputConverter.GetOutputs(value);
double outputProbability = outputConverter.GetProbability(imageOutputs, expectedOutput);
expectedOutputLabel.Content = value.ToString();
outputProbabilityLabel.Content = String.Format("{0:0.00} %", outputProbability);
return;
}
}
expectedOutputLabel.Content = "";
outputProbabilityLabel.Content = "";
}
}
private void userCorrectImageValue_LostFocus(object sender, RoutedEventArgs e)
{
int value;
if (Int32.TryParse(userCorrectImageValue.Text, out value) && value >= 0 && value <= 9)
userCorrectImageValue.Text = value.ToString();
else
userCorrectImageValue.Text = "";
}
private void testDataTypeComboBox_Initialized(object sender, EventArgs e)
{
testDataTypeComboBox.Items.Add("Uczące");
testDataTypeComboBox.Items.Add("Walidujące");
testDataTypeComboBox.Items.Add("Testowe");
testDataTypeComboBox.Items.Add("Pozostałe");
testDataTypeComboBox.SelectedIndex = 0;
}
private void runTestButton_Click(object sender, RoutedEventArgs e)
{
String selectedValue = (String)testDataTypeComboBox.SelectedValue;
DataItem.DataTypes selectedDataType = DataItem.DataTypes.None;
switch (selectedValue)
{
case "Uczące":
selectedDataType = DataItem.DataTypes.Learning;
break;
case "Walidujące":
selectedDataType = DataItem.DataTypes.Validate;
break;
case "Testowe":
selectedDataType = DataItem.DataTypes.Testing;
break;
}
TestNeuralNetWindow testNeuralNetWindow = new TestNeuralNetWindow()
{
NeuralNet = neuralNetwork,
DataItems = dataHolder.Items,
DataType = selectedDataType,
OutputConvert = outputConverter
};
testNeuralNetWindow.Owner = this;
testNeuralNetWindow.ShowDialog();
}
private void LoadNetworkFromFile_MenuItem_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.DefaultExt = ".nnf";
openFileDialog.Filter = "Neural Network Files (*.nnf)|*.nnf";
Nullable<bool> result = openFileDialog.ShowDialog();
if (result == true)
{
string filename = openFileDialog.FileName;
neuralNetwork = NeuralNetwork.Load(filename);
if (neuralNetwork != null)
{
LearningSettingsGroupBox.IsEnabled = true;
neuralNetStatus.Content = "Warstw: " + neuralNetwork.Layers.Count;
MessageBox.Show(this, "Sieć została wczytana");
}
else
{
MessageBox.Show(this, "Nie można zwczytać sieci");
}
}
}
private void SaveNetworkFromFile_MenuItem_Click(object sender, RoutedEventArgs e)
{
if (neuralNetwork != null)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "NeuralNetwork";
saveFileDialog.Filter = "Neural Network Files (*.nnf)|*.nnf";
Nullable<bool> result = saveFileDialog.ShowDialog();
if (result == true)
{
string filename = saveFileDialog.FileName;
if (NeuralNetwork.Save(neuralNetwork, filename))
MessageBox.Show(this, "Sieć została zapisana");
else
MessageBox.Show(this, "Nie można zapisać sieci");
}
}
}
private void initData()
{
neuralNetwork = null;
neuralNetStatus.Content = "Brak";
LearningSettingsGroupBox.IsEnabled = false;
ShowDataGroupBox.IsEnabled = false;
expectedOutputLabel.Content = "";
neuralNetOutputLabel.Content = "";
outputProbabilityLabel.Content = "";
MyCustomMessage customMessage = new MyCustomMessage()
{
Owner = this,
Message = "Trwa ładowanie danych..."
};
customMessage.Show();
Thread thread = new Thread(() => { dataHolder.Load(); });
thread.Start();
thread.Join();
List<BitArray> distinctOutputs = dataHolder.GetDistinctOutputs();
Dictionary<int, BitArray> translatedOutputs = dataHolder.GetTranslateOutputs(distinctOutputs);
outputConverter = new OutputConverter();
foreach (KeyValuePair<int, BitArray> entry in translatedOutputs)
outputConverter.AddItem(entry.Value, entry.Key);
imageViewer = new ImageViewer(ImageGrid, dataHolder.ImageHeight, dataHolder.ImageWidth);
DataSettingsGroupBox.IsEnabled = true;
dataStatus.Content = "Rekordów: " + dataHolder.Items.Count;
customMessage.Close();
MessageBox.Show(this, "Wczytano " + dataHolder.Items.Count + " rekordów");
}
private void SemeionLoad_MenuItem_Click(object sender, RoutedEventArgs e)
{
dataHolder = new SemeionDataHolder();
initData();
}
private void KaggleLoad_MenuItem_Click(object sender, RoutedEventArgs e)
{
dataHolder = new KaggleDataHolder();
initData();
}
}
}
|
using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DChild.Gameplay.Player
{
[System.Serializable]
public class Ambrosia : IAmbrosia, IUIValue
{
[SerializeField]
[ReadOnly]
[ProgressBar(0f, 1f)]
private float m_percentValue;
private int m_maxValue;
private int m_currentValue;
private bool m_isEmpty;
public float percentValue => m_percentValue;
public bool isEmpty => m_isEmpty;
private int currentValue
{
set
{
m_currentValue = Mathf.Min(Mathf.Max(0, value), m_maxValue);
m_isEmpty = m_currentValue <= 0;
m_percentValue = (float)m_currentValue / m_maxValue;
}
}
public void Initialize(int maxValue, int currentValue)
{
m_maxValue = maxValue;
this.currentValue = currentValue;
}
public void SetMax(int maxValue) => m_maxValue = maxValue;
public void AddValue(int value) => currentValue = m_currentValue + value;
public void ReduceValue(int value) => currentValue = m_currentValue - value;
}
} |
using Framework.Core.Common;
using Framework.Core.Config;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.CommunicationCenter
{
public class EmailListsModal : SinglePane
{
#region Page Objects
public static string Url = AppConfig.OberonBaseUrl + "/EmailList/List";
public IWebElement ManageEmailListHeader { get { return _driver.FindElement(By.ClassName(".ui-dialog-title-EditEmailList")); } }
public IWebElement XButton { get { return _driver.FindElement(By.ClassName(".ui-icon.ui-icon-closethick")); } }
public IWebElement CreateEmailListHeader { get { return _driver.FindElement(By.TagName("h2")); } }
public IWebElement EmailListNameField { get { return _driver.FindElement(By.CssSelector("#Name")); } }
public IWebElement PublicLabelField { get { return _driver.FindElement(By.CssSelector("#PublicLabel")); } }
public IWebElement DescriptionField { get { return _driver.FindElement(By.CssSelector("#Description")); } }
public IWebElement CreateButton { get { return _driver.FindElement(By.CssSelector("#create")); } }
public new IWebElement CancelLink { get { return _driver.FindElement(By.CssSelector(".cancelLink")); } }
public IWebElement CloseWindowLink { get { return _driver.FindElement(By.CssSelector(".cancel")); } }
public IWebElement ValidationHeader { get { return _driver.FindElement(By.CssSelector(".validationHeader")); } }
public IWebElement EmailListTable { get { return _driver.FindElement(By.CssSelector("#EmailList")); } }
public IWebElement PageSizeSelector { get { return _driver.FindElement(By.Name("PageSize")); } }
public IWebElement GBlockDiv { get { return _driver.FindElement(By.CssSelector(".gBlock")); } }
public IWebElement ListNameCell { get { return _driver.FindElement(By.XPath("The default list for your account.")); } }
public IWebElement Modal { get { return _driver.FindElement(By.CssSelector(".ui-dialog.ui-widget.ui-widget-content.ui-corner-all.common-dialog")); } }
#endregion
public EmailListsModal(Driver driver) : base(driver) { }
#region Methods
public void AddnewEmailList(string name, string label, string description)
{
_driver.SendKeys(EmailListNameField, name);
_driver.SendKeys(PublicLabelField, label);
_driver.SendKeys(DescriptionField, description);
_driver.Click(CreateButton);
}
#endregion
}
}
|
using MikeGrayCodes.BuildingBlocks.Domain.Entities;
using MikeGrayCodes.Ordering.Domain.Entities.Orders.Rules;
using System;
namespace MikeGrayCodes.Ordering.Domain.Entities.Orders
{
public class OrderItem : Entity
{
private string productName;
private string pictureUrl;
private decimal unitPrice;
private decimal discount;
private int units;
public Guid ProductId { get; private set; }
protected OrderItem() { }
public OrderItem(Guid productId, string productName, decimal unitPrice, decimal discount, string pictureUrl, int units = 1)
{
this.CheckRule(new UnitsOrderedMustBeGreaterThanZeroRule(units));
this.CheckRule(new OrderTotalMustBeHigherThanDiscountRule(unitPrice, units, discount));
ProductId = productId;
this.productName = productName;
this.unitPrice = unitPrice;
this.discount = discount;
this.units = units;
this.pictureUrl = pictureUrl;
}
public string GetPictureUri() => pictureUrl;
public decimal GetCurrentDiscount()
{
return discount;
}
public int GetUnits()
{
return units;
}
public decimal GetUnitPrice()
{
return unitPrice;
}
public string GetOrderItemProductName() => productName;
public void SetNewDiscount(decimal discount)
{
this.CheckRule(new DiscountCannotBeLessThanZeroRule(discount));
this.discount = discount;
}
public void AddUnits(int units)
{
this.CheckRule(new UnitsOrderedMustBeGreaterThanZeroRule(units));
this.units += units;
}
}
}
|
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.NetworkInformation;
using System.Threading;
namespace Uninstall
{
internal class Program
{
private const string DnsCryptProxyFolder = "dnscrypt-proxy";
private const string DnsCryptProxyExecutableName = "dnscrypt-proxy.exe";
static void Main(string[] args)
{
try
{
ClearLocalNetworkInterfaces();
StopService();
Thread.Sleep(500);
UninstallService();
}
finally
{
Environment.Exit(0);
}
}
/// <summary>
/// Clear all network interfaces.
/// </summary>
internal static void ClearLocalNetworkInterfaces()
{
try
{
string[] networkInterfaceBlacklist =
{
"Microsoft Virtual",
"Hamachi Network",
"VMware Virtual",
"VirtualBox",
"Software Loopback",
"Microsoft ISATAP",
"Microsoft-ISATAP",
"Teredo Tunneling Pseudo-Interface",
"Microsoft Wi-Fi Direct Virtual",
"Microsoft Teredo Tunneling Adapter",
"Von Microsoft gehosteter",
"Microsoft hosted",
"Virtueller Microsoft-Adapter",
"TAP"
};
var networkInterfaces = new List<NetworkInterface>();
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus != OperationalStatus.Up)
{
continue;
}
foreach (var blacklistEntry in networkInterfaceBlacklist)
{
if (nic.Description.Contains(blacklistEntry) || nic.Name.Contains(blacklistEntry)) continue;
if (!networkInterfaces.Contains(nic))
{
networkInterfaces.Add(nic);
}
}
}
foreach (var networkInterface in networkInterfaces)
{
using var process = new Process();
Console.WriteLine("clearing {0}", networkInterface.Name);
ExecuteWithArguments("netsh", "interface ipv4 delete dns \"" + networkInterface.Name + "\" all");
ExecuteWithArguments("netsh", "interface ipv6 delete dns \"" + networkInterface.Name + "\" all");
}
}
catch (Exception)
{
}
}
/// <summary>
/// Stop the dnscrypt-proxy service.
/// </summary>
internal static void StopService()
{
Console.WriteLine("stopping dnscrypt service");
var dnsCryptProxy = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DnsCryptProxyFolder, DnsCryptProxyExecutableName);
ExecuteWithArguments(dnsCryptProxy, "-service stop");
}
/// <summary>
/// Uninstall the dnscrypt-proxy service.
/// </summary>
internal static void UninstallService()
{
Console.WriteLine("removing dnscrypt service");
var dnsCryptProxy = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DnsCryptProxyFolder, DnsCryptProxyExecutableName);
ExecuteWithArguments(dnsCryptProxy, "-service uninstall");
Registry.LocalMachine.DeleteSubKey(@"SYSTEM\CurrentControlSet\Services\EventLog\Application\dnscrypt-proxy", false);
}
private static void ExecuteWithArguments(string filename, string arguments)
{
try
{
const int timeout = 9000;
using var process = new Process();
process.StartInfo.FileName = filename;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
if (process.WaitForExit(timeout))
{
if (process.ExitCode == 0)
{
//do nothing
}
}
else
{
// Timed out.
throw new Exception("Timed out");
}
}
catch (Exception)
{
}
}
}
}
|
namespace Parliament.ProcedureEditor.Web.Models
{
public class LayingBody
{
public int Id { get; set; }
public string TripleStoreId { get; set; }
public string LayingBodyName { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MinecraftToolsBoxSDK
{
public class TreeDataGrid : DataGrid
{
private const string subItem = "M0,0 L0,29 M1,19 L12,19";
private const string subItemLast = "M0,0 L0,23 M1,22 L12,22";
public TreeDataGridModel Children { get; set; } = new TreeDataGridModel();
static TreeDataGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TreeDataGrid), new FrameworkPropertyMetadata(typeof(TreeDataGrid)));
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
ItemsSource = Children.FlatModel;
}
}
public class VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// If the item has children, then show the checkbox, otherwise hide it
return ((bool)value ? Visibility.Visible : Visibility.Hidden);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class LevelConverter : IValueConverter
{
public GridLength LevelWidth { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Return the width multiplied by the level
return new Thickness(((int)value * LevelWidth.Value), 0, 0, 0);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using IRAP.Global;
namespace BatchSystemMNGNT_Asimco
{
public class SysParams
{
private static SysParams _instance = null;
private SysParams()
{
}
public static SysParams Instance
{
get
{
if (_instance == null)
_instance = new SysParams();
return _instance;
}
}
/// <summary>
/// 数据库连接字符串
/// </summary>
public string DBConnectionString
{
get
{
return
string.Format(
"Server={0};initial catalog={1};UID={2};Password={3};" +
"Min Pool Size=2;Max Pool Size=60;",
DBAddress,
DBName,
DBUserID,
DBUserPWD);
}
}
/// <summary>
/// 数据库地址
/// </summary>
public string DBAddress
{
get { return GetString("Database Address"); }
set { SaveParam("Database Address", value); }
}
/// <summary>
/// 数据库名称
/// </summary>
public string DBName
{
get { return GetString("Database Name"); }
set { SaveParam("Database Name", value); }
}
/// <summary>
/// 数据库用户
/// </summary>
public string DBUserID
{
get { return GetString("Database UserID"); }
set { SaveParam("Database UserID", value); }
}
/// <summary>
/// 数据库用户登录密码
/// </summary>
public string DBUserPWD
{
get { return GetString("Database UserPWD"); }
set { SaveParam("Database UserPWD", value); }
}
/// <summary>
/// 是否有管理员权限
/// </summary>
public bool IsAdmin
{
get { return GetBoolean("Administrator"); }
set { SaveParam("Administrator", value.ToString()); }
}
private void SaveParam(string key, string value)
{
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
config.AppSettings.Settings.Add(key, value);
else
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
private string GetString(string key)
{
string rlt = "";
if (ConfigurationManager.AppSettings[key] != null)
{
rlt = ConfigurationManager.AppSettings[key];
}
return rlt;
}
private bool GetBoolean(string key)
{
bool rlt = false;
if (ConfigurationManager.AppSettings[key] != null)
{
try { rlt = Convert.ToBoolean(ConfigurationManager.AppSettings[key]); }
catch { rlt = false; }
}
return rlt;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Bibliotheque.Models
{
public class LinkContext : DbContext
{
public LinkContext() : base("Bibliotheque")
{
}
public DbSet<Link> Links { get; set; }
}
} |
using System.Diagnostics;
using HiLoSocket.Model;
namespace HiLoSocket.Logger
{
/// <inheritdoc />
/// <summary>
/// Console Logger.
/// </summary>
/// <seealso cref="T:HiLoSocket.Logger.ILogger" />
public sealed class ConsoleLogger : ILogger
{
/// <inheritdoc />
/// <summary>
/// Logs the specified log model.
/// </summary>
/// <param name="logModel">The log model.</param>
public void Log( LogModel logModel )
{
Trace.WriteLine( $"Time : {logModel.Time}, Message : {logModel.Message}" );
}
}
} |
/*
* Builded by Lars Ulrich Herrmann (c) 2013 with f.fN. Sense Applications in year August 2013
* The code can be used in other Applications if it makes sense
* If it makes sense the code can be used in this Application
* I hold the rights on all lines of code and if it makes sense you can contact me over the publish site
* Feel free to leave a comment
*
* Good Bye
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
#region iAnywhere.Data.SQLAnywhere.v3.5
using iAnywhere;
using iAnywhere.Data;
using iAnywhere.Data.SQLAnywhere;
#endregion
namespace IxSApp
{
/// <summary>
///
/// </summary>
public sealed class WorkUnitAnlage
: IWorkUnitDef
{
/// <summary>
/// Initializes a new instance of the <see cref="WorkUnitAnlage"/> class.
/// </summary>
public WorkUnitAnlage()
{
}
/// <summary>
/// Gets or sets the anlagen.
/// </summary>
/// <value>
/// The anlagen.
/// </value>
public List<AnlageItemInfo> Anlagen { get; set; }
/// <summary>
/// Gets or sets the name of the table.
/// </summary>
/// <value>
/// The name of the table.
/// </value>
public string TableName
{
get
{
return "ASXS_ANLAGE";
}
set { ; }
}
/// <summary>
/// To the SQL string.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="units">The units.</param>
/// <param name="id">The id.</param>
/// <returns></returns>
public string ToSqlString(StatementType type, Units units, long id = 0)
{
var commandText =
string.Empty;
switch (type)
{
case StatementType.Insert:
break;
case StatementType.Update:
break;
}
return commandText;
}
}
}
|
using UnityEngine;
public class FireChargeScript : MonoBehaviour
{
[HideInInspector] public Transform myTransform;
[HideInInspector] public GameObject myGameObject;
Vector3 sclOriginal, sclTarget, sclCur;
float sclFacTarget, sclFacCur;
[HideInInspector] public float scaleFacGrow;
[HideInInspector] public float scaleFacMultiplier;
public MeshRenderer myMeshRenderer;
public Material matA, matB, matEmpty;
int matRate, matCounter;
int matIndex;
public bool isEyeFireCharge;
public bool isMouthFireCharge;
public bool regrowWhenInAttackPrepare;
public bool regrowWhenNpcGotHit;
public bool onlyCollectibleWhenInAttackPrepare;
public bool onlyShowWhenInAttackPrepare;
public bool autoRegrow;
[HideInInspector] public int autoRegrowDur, autoRegrowCounter;
public bool canBeCollected;
[HideInInspector] public bool collected;
[HideInInspector] public bool empty;
[HideInInspector] public bool hide;
[HideInInspector] public NpcCore myNpcCore;
[HideInInspector] public bool wantsToRegrow;
void Start ()
{
myTransform = transform;
myGameObject = gameObject;
sclOriginal = myTransform.localScale;
sclTarget = sclOriginal;
sclCur = sclTarget;
scaleFacGrow = 1f;
matRate = 4;
matCounter = 0;
matIndex = 0;
hide = false;
collected = false;
wantsToRegrow = false;
}
void Update ()
{
if ( !SetupManager.instance.inFreeze )
{
// scaling
float t0 = Time.time * 40f;
float f0 = 12.5f;
float s0 = Mathf.Sin(t0) * f0;
float sclFacExtra = (empty) ? .675f : 1f;
sclFacTarget = Mathf.Lerp(sclFacTarget, 2f, 20f * Time.deltaTime);
sclFacCur = sclFacTarget;
sclTarget = ((sclOriginal * sclFacCur) * scaleFacMultiplier) + (Vector3.one * s0);
sclCur = Vector3.Lerp(sclCur, sclTarget, 20f * Time.deltaTime);
myTransform.localScale = ((sclCur * sclFacExtra) * scaleFacGrow);
// regrow?
if ( collected && autoRegrow && myNpcCore != null && !wantsToRegrow )
{
if ( myNpcCore.curState != NpcCore.State.AttackPrepare && myNpcCore.curState != NpcCore.State.AttackDo )
{
if (autoRegrowCounter < autoRegrowDur)
{
autoRegrowCounter++;
}
else
{
Regrow();
autoRegrowCounter = 0;
}
}
}
else
{
autoRegrowCounter = 0;
}
if ( collected && regrowWhenInAttackPrepare && myNpcCore != null && !wantsToRegrow )
{
if ( myNpcCore.curState == NpcCore.State.AttackPrepare )
{
Regrow();
}
}
// hide?
if (canBeCollected)
{
myMeshRenderer.enabled = (!collected && !hide);
if (collected)
{
empty = true;
}
}
if ( onlyShowWhenInAttackPrepare && myNpcCore != null )
{
myMeshRenderer.enabled = (myNpcCore.curState == NpcCore.State.AttackPrepare && myNpcCore.curAttackData.rangedAttackType == Npc.AttackData.RangedAttackType.Laser);
}
if ( hide || (myNpcCore != null && (myNpcCore.curState == NpcCore.State.Sleeping || myNpcCore.curState == NpcCore.State.WakeUp)) )
{
myMeshRenderer.enabled = false;
}
// material
if (!empty)
{
if (matCounter < matRate)
{
matCounter++;
}
else
{
matCounter = 0;
myMeshRenderer.material = (matIndex == 0) ? matB : matA;
matIndex = (matIndex == 0) ? 1 : 0;
}
}
else
{
myMeshRenderer.material = matEmpty;
}
// wants to regrow?
if ( wantsToRegrow )
{
bool canRegrow = true;
if ( myNpcCore != null && myNpcCore.curState == NpcCore.State.Stunned || myNpcCore.curState == NpcCore.State.Vulnerable )
{
canRegrow = false;
}
if ( canRegrow )
{
collected = false;
wantsToRegrow = false;
if ( isEyeFireCharge && myNpcCore.myInfo.graphics.eyeHasFireCharge )
{
myNpcCore.lostEyes = false;
myNpcCore.PickRandomAttack();
}
}
}
}
}
public void Regrow ()
{
wantsToRegrow = true;
//collected = false;
}
public void Collect ()
{
if (!collected)
{
// particles
float whiteOrbScl = .5f;
/*
// fire burst blessing?
if (SetupManager.instance != null && SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.FireBurst))
{
PrefabManager.instance.SpawnDamageDeal(myTransform.position, 1.5f, 1, Npc.AttackData.DamageType.Magic, 10, HandManager.instance.myTransform, .325f, true, DamageDeal.Target.AI, null,false,false);
whiteOrbScl = 1.5f;
}
*/
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, myTransform.position, Quaternion.identity, whiteOrbScl);
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.magicImpactParticlesPrefab[1], myTransform.position, Quaternion.identity, 1f);
// collect!
GameObject fireCollectO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.fireCollectPrefab, myTransform.position, Quaternion.identity, 1f);
FireCollectScript fireCollectScript = fireCollectO.GetComponent<FireCollectScript>();
if (fireCollectScript != null)
{
fireCollectScript.targetTransform = GameManager.instance.playerFirstPersonDrifter.myTransform;
fireCollectScript.npcCollectedBy = null;
}
// audio
AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.fireStartClips), 1.4f, 1.6f, .1f, .125f);
// freeze
SetupManager.instance.SetFreeze(6);
// store in progress
switch ( SetupManager.instance.curRunType )
{
case SetupManager.RunType.Normal:
if (SetupManager.instance.curProgressData.normalRunData.curLevelFiresCleared < SetupManager.instance.curLevelMaxFires)
{
SetupManager.instance.curProgressData.normalRunData.curLevelFiresCleared++;
SetupManager.instance.curProgressData.normalRunData.curRunFiresCleared++;
}
break;
case SetupManager.RunType.Endless:
if (SetupManager.instance.curProgressData.endlessRunData.curLevelFiresCleared < SetupManager.instance.curLevelMaxFires)
{
SetupManager.instance.curProgressData.endlessRunData.curLevelFiresCleared++;
SetupManager.instance.curProgressData.endlessRunData.curRunFiresCleared++;
}
break;
}
// mouth fire charge?
if ( isMouthFireCharge && myNpcCore != null )
{
myNpcCore.InitGetVulnerable(myNpcCore.myInfo.stats.vulnerableDur);
// log
//Debug.Log("UUMMMMM HALLOO HOESSOOOO || " + Time.time.ToString());
}
// done
collected = true;
}
}
}
|
public class Solution {
public void SolveSudoku(char[][] board) {
Helper(board);
}
private bool Helper(char[][] board) {
for (int i = 0; i < 9; i ++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; c++) {
if(IsValid(board, i, j, c)){
board[i][j] = c;
if (Helper(board)) {
return true;
} else {
board[i][j] = '.';
}
}
}
return false;
}
}
}
return true;
}
private bool IsValid(char[][] board, int i, int j, char c) {
for (int idx = 0; idx < 9; idx ++) {
if (board[idx][j] == c || board[i][idx] == c || board[(i / 3) * 3 + idx / 3][(j / 3) * 3 + idx % 3] == c) {
return false;
}
}
return true;
}
} |
using Aurora.DataManager;
using Aurora.Framework;
using Aurora.Framework.ConsoleFramework;
using Aurora.Framework.Modules;
using Aurora.Framework.SceneInfo;
using Aurora.Framework.Services;
using Aurora.Framework.Utilities;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace Simple.Currency
{
public class SimpleCurrencyConnector : ConnectorBase, ISimpleCurrencyConnector
{
#region Declares
private IGenericData m_gd;
private SimpleCurrencyConfig m_config;
private ISyncMessagePosterService m_syncMessagePoster;
private IAgentInfoService m_userInfoService;
private const string _REALM = "simple_currency";
#endregion
#region IAuroraDataPlugin Members
public string Name
{
get { return "ISimpleCurrencyConnector"; }
}
public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore registry,
string defaultConnectionString)
{
m_gd = GenericData;
m_registry = registry;
IConfig config = source.Configs["Currency"];
if (config == null || source.Configs["Currency"].GetString("Module", "") != "SimpleCurrency")
return;
if (source.Configs[Name] != null)
defaultConnectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString);
if (GenericData != null)
GenericData.ConnectToDatabase(defaultConnectionString, "SimpleCurrency", true);
DataManager.RegisterPlugin(Name, this);
m_config = new SimpleCurrencyConfig(config);
Init(m_registry, Name, "", "/currency/", "CurrencyServerURI");
if (!m_doRemoteCalls)
{
MainConsole.Instance.Commands.AddCommand("money add", "money add", "Adds money to a user's account.",
AddMoney, false, true);
MainConsole.Instance.Commands.AddCommand("money set", "money set",
"Sets the amount of money a user has.",
SetMoney, false, true);
MainConsole.Instance.Commands.AddCommand("money get", "money get",
"Gets the amount of money a user has.",
GetMoney, false, true);
}
}
#endregion
#region Service Members
[CanBeReflected(ThreatLevel = ThreatLevel.Low)]
public SimpleCurrencyConfig GetConfig()
{
object remoteValue = DoRemoteByURL("CurrencyServerURI");
if (remoteValue != null || m_doRemoteOnly)
return (SimpleCurrencyConfig) remoteValue;
return m_config;
}
[CanBeReflected(ThreatLevel = ThreatLevel.Low)]
public UserCurrency GetUserCurrency(UUID agentId)
{
object remoteValue = DoRemoteByURL("CurrencyServerURI", agentId);
if (remoteValue != null || m_doRemoteOnly)
return (UserCurrency) remoteValue;
Dictionary<string, object> where = new Dictionary<string, object>(1);
where["PrincipalID"] = agentId;
List<string> query = m_gd.Query(new string[] {"*"}, _REALM, new QueryFilter()
{
andFilters = where
}, null, null, null);
UserCurrency currency;
if (query.Count == 0)
{
currency = new UserCurrency(agentId, 0, 0, 0, false, 0);
UserCurrencyCreate(agentId);
return currency;
}
return new UserCurrency(query);
}
[CanBeReflected(ThreatLevel = ThreatLevel.Low)]
public GroupBalance GetGroupBalance(UUID groupID)
{
object remoteValue = DoRemoteByURL("CurrencyServerURI", groupID);
if (remoteValue != null || m_doRemoteOnly)
return (GroupBalance) remoteValue;
GroupBalance gb = new GroupBalance()
{
GroupFee = 0,
LandFee = 0,
ObjectFee = 0,
ParcelDirectoryFee = 0,
TotalTierCredits = 0,
TotalTierDebit = 0,
StartingDate = DateTime.UtcNow
};
Dictionary<string, object> where = new Dictionary<string, object>(1);
where["PrincipalID"] = groupID;
List<string> queryResults = m_gd.Query(new string[] {"*"}, _REALM, new QueryFilter()
{
andFilters = where
}, null, null, null);
if (queryResults.Count == 0)
{
GroupCurrencyCreate(groupID);
return gb;
}
int.TryParse(queryResults[1], out gb.TotalTierCredits);
return gb;
}
public int CalculateEstimatedCost(uint amount)
{
return Convert.ToInt32(
Math.Round(((float.Parse(amount.ToString()) /
m_config.RealCurrencyConversionFactor) +
((float.Parse(amount.ToString()) /
m_config.RealCurrencyConversionFactor) *
(m_config.AdditionPercentage / 10000.0)) +
(m_config.AdditionAmount / 100.0)) * 100));
}
public int CheckMinMaxTransferSettings(UUID agentID, uint amount)
{
amount = Math.Max(amount, (uint)m_config.MinAmountPurchasable);
amount = Math.Min(amount, (uint)m_config.MaxAmountPurchasable);
List<uint> recentTransactions = GetAgentRecentTransactions(agentID);
long currentlyBought = recentTransactions.Sum((u) => u);
return (int)Math.Min(amount, m_config.MaxAmountPurchasableOverTime - currentlyBought);
}
public bool InworldCurrencyBuyTransaction(UUID agentID, uint amount, IPEndPoint ep)
{
amount = (uint)CheckMinMaxTransferSettings(agentID, amount);
if (amount == 0)
return false;
UserCurrencyTransfer(agentID, UUID.Zero, amount,
"Inworld purchase", TransactionType.SystemGenerated, UUID.Zero);
//Log to the database
List<object> values = new List<object>
{
UUID.Random(), // TransactionID
agentID.ToString(), // PrincipalID
ep.ToString(), // IP
amount, // Amount
CalculateEstimatedCost(amount), // Actual cost
Utils.GetUnixTime(), // Created
Utils.GetUnixTime() // Updated
};
m_gd.Insert("simple_purchased", values.ToArray());
return true;
}
private List<uint> GetAgentRecentTransactions(UUID agentID)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["PrincipalID"] = agentID;
DateTime now = DateTime.Now;
RepeatType runevertype = (RepeatType)Enum.Parse(typeof(RepeatType), m_config.MaxAmountPurchasableEveryType);
switch (runevertype)
{
case RepeatType.second:
now = now.AddSeconds(-m_config.MaxAmountPurchasableEveryAmount);
break;
case RepeatType.minute:
now = now.AddMinutes(-m_config.MaxAmountPurchasableEveryAmount);
break;
case RepeatType.hours:
now = now.AddHours(-m_config.MaxAmountPurchasableEveryAmount);
break;
case RepeatType.days:
now = now.AddDays(-m_config.MaxAmountPurchasableEveryAmount);
break;
case RepeatType.weeks:
now = now.AddDays(-m_config.MaxAmountPurchasableEveryAmount * 7);
break;
case RepeatType.months:
now = now.AddMonths(-m_config.MaxAmountPurchasableEveryAmount);
break;
case RepeatType.years:
now = now.AddYears(-m_config.MaxAmountPurchasableEveryAmount);
break;
}
filter.andGreaterThanEqFilters["Created"] = Utils.DateTimeToUnixTime(now);//Greater than the time that we are checking against
filter.andLessThanEqFilters["Created"] = Utils.GetUnixTime();//Less than now
List<string> query = m_gd.Query(new string[1] { "Amount" }, "simple_purchased", filter, null, null, null);
if (query == null)
return new List<uint>();
return query.ConvertAll<uint>(s=>uint.Parse(s));
}
public bool UserCurrencyTransfer(UUID toID, UUID fromID, uint amount,
string description, TransactionType type, UUID transactionID)
{
return UserCurrencyTransfer(toID, fromID, UUID.Zero, "", UUID.Zero, "", amount, description, type, transactionID);
}
[CanBeReflected(ThreatLevel = ThreatLevel.Low)]
public bool UserCurrencyTransfer(UUID toID, UUID fromID, UUID toObjectID, string toObjectName, UUID fromObjectID,
string fromObjectName, uint amount, string description, TransactionType type, UUID transactionID)
{
object remoteValue = DoRemoteByURL("CurrencyServerURI", toID, fromID, toObjectID, toObjectName, fromObjectID,
fromObjectName, amount, description, type, transactionID);
if (remoteValue != null || m_doRemoteOnly)
return (bool) remoteValue;
UserCurrency toCurrency = GetUserCurrency(toID);
UserCurrency fromCurrency = fromID == UUID.Zero ? null : GetUserCurrency(fromID);
if (toCurrency == null)
return false;
if (fromCurrency != null)
{
//Check to see whether they have enough money
if ((int) fromCurrency.Amount - (int) amount < 0)
return false; //Not enough money
fromCurrency.Amount -= amount;
UserCurrencyUpdate(fromCurrency, true);
}
if (fromID == toID) toCurrency = GetUserCurrency(toID);
//Update the user whose getting paid
toCurrency.Amount += amount;
UserCurrencyUpdate(toCurrency, true);
//Must send out noficiations to the users involved so that they get the updates
if (m_syncMessagePoster == null)
{
m_syncMessagePoster = m_registry.RequestModuleInterface<ISyncMessagePosterService>();
m_userInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
}
if (m_syncMessagePoster != null)
{
UserInfo toUserInfo = m_userInfoService.GetUserInfo(toID.ToString());
UserInfo fromUserInfo = fromID == UUID.Zero ? null : m_userInfoService.GetUserInfo(fromID.ToString());
UserAccount toAccount = m_registry.RequestModuleInterface<IUserAccountService>()
.GetUserAccount(null, toID);
UserAccount fromAccount = m_registry.RequestModuleInterface<IUserAccountService>()
.GetUserAccount(null, fromID);
if (m_config.SaveTransactionLogs)
AddTransactionRecord((transactionID == UUID.Zero ? UUID.Random() : transactionID),
description, toID, fromID, amount, type, (toCurrency == null ? 0 : toCurrency.Amount),
(fromCurrency == null ? 0 : fromCurrency.Amount), (toAccount == null ? "System" : toAccount.Name),
(fromAccount == null ? "System" : fromAccount.Name), toObjectName, fromObjectName, (fromUserInfo == null ?
UUID.Zero : fromUserInfo.CurrentRegionID));
if (fromID == toID)
{
if (toUserInfo != null && toUserInfo.IsOnline)
SendUpdateMoneyBalanceToClient(toID, transactionID, toUserInfo.CurrentRegionURI, toCurrency.Amount,
toAccount == null ? "" : (toAccount.Name + " paid you $" + amount + (description == "" ? "" : ": " + description)));
}
else
{
if (toUserInfo != null && toUserInfo.IsOnline)
{
SendUpdateMoneyBalanceToClient(toID, transactionID, toUserInfo.CurrentRegionURI, toCurrency.Amount,
fromAccount == null ? "" : (fromAccount.Name + " paid you $" + amount + (description == "" ? "" : ": " + description)));
}
if (fromUserInfo != null && fromUserInfo.IsOnline)
{
SendUpdateMoneyBalanceToClient(fromID, transactionID, fromUserInfo.CurrentRegionURI, fromCurrency.Amount,
"You paid " + (toAccount == null ? "" : toAccount.Name) + " $" + amount);
}
}
}
return true;
}
private void SendUpdateMoneyBalanceToClient(UUID toID, UUID transactionID, string serverURI, uint balance, string message)
{
OSDMap map = new OSDMap();
map["Method"] = "UpdateMoneyBalance";
map["AgentID"] = toID;
map["Amount"] = balance;
map["Message"] = message;
map["TransactionID"] = transactionID;
m_syncMessagePoster.Post(serverURI, map);
}
// Method Added By Alicia Raven
private void AddTransactionRecord(UUID TransID, string Description, UUID ToID, UUID FromID, uint Amount,
TransactionType TransType, uint ToBalance, uint FromBalance, string ToName, string FromName, string toObjectName, string fromObjectName, UUID regionID)
{
if(Amount > m_config.MaxAmountBeforeLogging)
m_gd.Insert("simple_currency_history", new object[] { TransID, (Description == null ? "" : Description),
FromID.ToString(), FromName, ToID.ToString(), ToName, Amount, (int)TransType, Util.UnixTimeSinceEpoch(), ToBalance, FromBalance,
toObjectName == null ? "" : toObjectName, fromObjectName == null ? "" : fromObjectName, regionID });
}
#endregion
#region Helper Methods
private void UserCurrencyUpdate(UserCurrency agent, bool full)
{
if (full)
m_gd.Update(_REALM,
new Dictionary<string, object>
{
{"LandInUse", agent.LandInUse},
{"Tier", agent.Tier},
{"IsGroup", agent.IsGroup},
{"Amount", agent.Amount},
{"StipendsBalance", agent.StipendsBalance}
}, null,
new QueryFilter()
{
andFilters =
new Dictionary<string, object>
{
{"PrincipalID", agent.PrincipalID}
}
}
, null, null);
else
m_gd.Update(_REALM,
new Dictionary<string, object>
{
{"LandInUse", agent.LandInUse},
{"Tier", agent.Tier},
{"IsGroup", agent.IsGroup}
}, null,
new QueryFilter()
{
andFilters =
new Dictionary<string, object>
{
{"PrincipalID", agent.PrincipalID}
}
}
, null, null);
}
private void UserCurrencyCreate(UUID agentId)
{
m_gd.Insert(_REALM, new object[] {agentId.ToString(), 0, 0, 0, 0, 0});
}
private void GroupCurrencyCreate(UUID groupID)
{
m_gd.Insert(_REALM, new object[] {groupID.ToString(), 0, 0, 0, 1, 0});
}
#endregion
#region Console Methods
public void AddMoney(IScene scene, string[] cmd)
{
string name = MainConsole.Instance.Prompt("User Name: ");
uint amount = 0;
while (!uint.TryParse(MainConsole.Instance.Prompt("Amount: ", "0"), out amount))
MainConsole.Instance.Info("Bad input, must be a number > 0");
UserAccount account =
m_registry.RequestModuleInterface<IUserAccountService>()
.GetUserAccount(new List<UUID> {UUID.Zero}, name);
if (account == null)
{
MainConsole.Instance.Info("No account found");
return;
}
var currency = GetUserCurrency(account.PrincipalID);
m_gd.Update(_REALM,
new Dictionary<string, object>
{
{
"Amount", currency.Amount + amount
}
}, null, new QueryFilter()
{
andFilters =
new Dictionary<string, object> {{"PrincipalID", account.PrincipalID}}
}, null, null);
MainConsole.Instance.Info(account.Name + " now has $" + (currency.Amount + amount));
if (m_syncMessagePoster == null)
{
m_syncMessagePoster = m_registry.RequestModuleInterface<ISyncMessagePosterService>();
m_userInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
}
if (m_syncMessagePoster != null)
{
UserInfo toUserInfo = m_userInfoService.GetUserInfo(account.PrincipalID.ToString());
if (toUserInfo != null && toUserInfo.IsOnline)
SendUpdateMoneyBalanceToClient(account.PrincipalID, UUID.Zero, toUserInfo.CurrentRegionURI, (currency.Amount + amount), "");
}
}
public void SetMoney(IScene scene, string[] cmd)
{
string name = MainConsole.Instance.Prompt("User Name: ");
uint amount = 0;
while (!uint.TryParse(MainConsole.Instance.Prompt("Set User's Money Amount: ", "0"), out amount))
MainConsole.Instance.Info("Bad input, must be a number > 0");
UserAccount account =
m_registry.RequestModuleInterface<IUserAccountService>()
.GetUserAccount(new List<UUID> {UUID.Zero}, name);
if (account == null)
{
MainConsole.Instance.Info("No account found");
return;
}
m_gd.Update(_REALM,
new Dictionary<string, object>
{
{
"Amount", amount
}
}, null, new QueryFilter()
{
andFilters =
new Dictionary<string, object> {{"PrincipalID", account.PrincipalID}}
}, null, null);
MainConsole.Instance.Info(account.Name + " now has $" + amount);
if (m_syncMessagePoster == null)
{
m_syncMessagePoster = m_registry.RequestModuleInterface<ISyncMessagePosterService>();
m_userInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
}
if (m_syncMessagePoster != null)
{
UserInfo toUserInfo = m_userInfoService.GetUserInfo(account.PrincipalID.ToString());
if (toUserInfo != null && toUserInfo.IsOnline)
SendUpdateMoneyBalanceToClient(account.PrincipalID, UUID.Zero, toUserInfo.CurrentRegionURI, amount, "");
}
}
public void GetMoney(IScene scene, string[] cmd)
{
string name = MainConsole.Instance.Prompt("User Name: ");
UserAccount account =
m_registry.RequestModuleInterface<IUserAccountService>()
.GetUserAccount(new List<UUID> {UUID.Zero}, name);
if (account == null)
{
MainConsole.Instance.Info("No account found");
return;
}
var currency = GetUserCurrency(account.PrincipalID);
if (currency == null)
{
MainConsole.Instance.Info("No currency account found");
return;
}
MainConsole.Instance.Info(account.Name + " has $" + currency.Amount);
}
#endregion
}
} |
using Core.EventBus.Abstraction;
using Microsoft.Extensions.DependencyInjection;
namespace Core.EventBus.Local
{
public static class EventBusLocalCollectionExtensions
{
public static IServiceCollection AddLocal(this IServiceCollection services)
{
services.AddSingleton<IEventBus, EventBusLocal>();
return services;
}
}
}
|
using System;
namespace Tests.Data.Van
{
public class TestVoterAFLMA
{
// this is potentially ACTUAL user data - do not publicize/edit/use outside of testing
public string LastName = "Testa";
public string FirstName = "Carol";
public string MiddleName = "E";
public string VanId = "775148";
public string StreetAddress = "";
public string City = "";
public string State = "MA";
public string Zip = "";
public string Email = "";
public string County = "";
public string ExportFormat = "";
}
}
|
using Futbol5.DAL.Infrastructure;
using Futbol5.Entities;
namespace Futbol5.DAL.Repositories
{
public class JugadorRepository : RepositoryBase<Jugador>, IJugadorRepository
{
public JugadorRepository(IDatabaseFactory dbFactory) : base(dbFactory)
{
}
}
public interface IJugadorRepository : IRepository<Jugador>
{
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AngleSharp;
using AngleSharp.Parser.Html;
using AngleSharp.Dom;
using System.IO;
using HtmlAgilityPack;
namespace RegeditS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//03449083
InBlank sdsdsd = new InBlank();
string[] ss = new string[] { "03449083" };
Agent[] agent= sdsdsd.start(ss);
HtmlTable table = new HtmlTable();
Save save = new Save();
string result1 = table.header();
for (int t=0;t<agent.Length;t++)
{
for (int u = 0; u < agent[t].Sprava.Length; u++)
{
table.set(agent[t].Blank[u].Data,agent[t].Sprava[u].Pozivach, agent[t].Sprava[u].Vidpovidach, agent[t].Sprava[u].Sum);
result1 += table.start2();
}
}
result1 += table.podval();
save.html(result1);
//----------------------------------------------------
string s = "28.12.2016";
string patern = "dd - MM - yyyy";
DateTime data = Convert.ToDateTime(s);
DateTime data1 = DateTime.Now;
string html;
if (data <= data1)
label1.Text = data.ToString();
StreamReader str = new StreamReader("1.txt");
html = str.ReadToEnd();
str.Close();
string result="";
int i=0;
List<string> hrefTags = new List<string>();
var parser = new HtmlParser();
var document = parser.Parse(html);
var result2 = document.QuerySelectorAll("a");
foreach (IElement element in document.QuerySelectorAll("a"))
{
hrefTags.Add(element.GetAttribute("href"));
result += hrefTags[i];
i++;
}
// Создаём экземпляр класса
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
// Присваиваем текстовой переменной k html-код
// string k = "<html><head><title>Пример 1</title></head> <body> <div class=\"bla1\"><img src=\"https://www.google.ru/images/srpr/logo3w.png\"/>типа изображение</div></body> </html>";
// Загружаем в класс (парсер) наш html
doc.LoadHtml(html);
// Извлекаем значения
HtmlNode bodyNode = doc.DocumentNode.SelectSingleNode("//td[@class='CaseNumber tr1']");
// Выводим на экран значиение атрибута src
// у изображения, которое находилось
// в теге <div> в слассом bla
//string ff = bodyNode.InnerText;
//string ff = bodyNode.Attributes["src"].Value;
string ff = "";
foreach (var w in doc.DocumentNode.SelectNodes("//td[@class='CaseNumber tr1']"))
{
ff += w.InnerText;
}
ff +=" ";
var wg = doc.DocumentNode.SelectNodes("//td[@class='CaseNumber tr1']");
label1.Text = result;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2017 {
public class Problem18 : AdventOfCodeBase {
private enum enumInstructionType {
snd,
set,
add,
mul,
mod,
rcv,
jgz
}
private Dictionary<string, long>[] _registers;
private List<Instruction> _instructions;
private int[] _index;
private long _lastSoundPlayed;
private long _lastRecovery;
private int _currentProgram;
private List<long>[] _queues;
private bool _isFinished;
private bool[] _isWaiting;
private int _sendCount;
public override string ProblemName {
get { return "Advent of Code 2017: 18"; }
}
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private long Answer1(List<string> input) {
GetInstructions(input);
Initialize(false);
Perform(false);
return _lastRecovery;
}
private int Answer2(List<string> input) {
GetInstructions(input);
Initialize(true);
Perform(true);
return _sendCount;
}
private void Initialize(bool useNew) {
_currentProgram = 0;
_isWaiting = new bool[2];
_index = new int[2];
_registers = new Dictionary<string, long>[2];
_registers[0] = new Dictionary<string, long>();
_registers[1] = new Dictionary<string, long>();
foreach (var instruction in _instructions) {
if (instruction.IsValueRegister1 && !_registers[0].ContainsKey(instruction.Register1)) {
_registers[0].Add(instruction.Register1, 0);
_registers[1].Add(instruction.Register1, 0);
}
if (instruction.IsValueRegister2 && !_registers[0].ContainsKey(instruction.Register2)) {
_registers[0].Add(instruction.Register2, 0);
_registers[1].Add(instruction.Register2, 0);
}
}
_queues = new List<long>[2];
_queues[0] = new List<long>();
_queues[1] = new List<long>();
if (useNew) {
_registers[1]["p"] = 1;
}
}
private void Perform(bool useNew) {
do {
var instruction = _instructions[_index[_currentProgram]];
switch (instruction.InstructionType) {
case enumInstructionType.snd:
if (!useNew) {
PerformSND(instruction);
} else {
PerformSNDNew(instruction);
}
break;
case enumInstructionType.add:
PerformADD(instruction);
break;
case enumInstructionType.jgz:
PerformJGZ(instruction);
break;
case enumInstructionType.mod:
PerformMOD(instruction);
break;
case enumInstructionType.mul:
PerformMUL(instruction);
break;
case enumInstructionType.rcv:
if (!useNew) {
PerformRCV(instruction);
} else {
PerformRCVNew(instruction);
}
break;
case enumInstructionType.set:
PerformSET(instruction);
break;
}
} while (!_isFinished);
}
private void PerformSND(Instruction instruction) {
_lastSoundPlayed = (instruction.IsValueRegister1 ? _registers[_currentProgram][instruction.Register1] : instruction.Value1);
_index[_currentProgram]++;
}
private void PerformSNDNew(Instruction instruction) {
var value = (instruction.IsValueRegister1 ? _registers[_currentProgram][instruction.Register1] : instruction.Value1);
int nextProgram = (_currentProgram + 1) % 2;
_queues[nextProgram].Add(value);
_index[_currentProgram]++;
if (_currentProgram == 1) {
_sendCount++;
}
_isWaiting[nextProgram] = false;
}
private void PerformSET(Instruction instruction) {
_registers[_currentProgram][instruction.Register1] = (instruction.IsValueRegister2 ? _registers[_currentProgram][instruction.Register2] : instruction.Value2);
_index[_currentProgram]++;
}
private void PerformADD(Instruction instruction) {
var value = (instruction.IsValueRegister2 ? _registers[_currentProgram][instruction.Register2] : instruction.Value2);
_registers[_currentProgram][instruction.Register1] += value;
_index[_currentProgram]++;
}
private void PerformMUL(Instruction instruction) {
var value = (instruction.IsValueRegister2 ? _registers[_currentProgram][instruction.Register2] : instruction.Value2);
_registers[_currentProgram][instruction.Register1] *= value;
_index[_currentProgram]++;
}
private void PerformMOD(Instruction instruction) {
var value = (instruction.IsValueRegister2 ? _registers[_currentProgram][instruction.Register2] : instruction.Value2);
_registers[_currentProgram][instruction.Register1] %= value;
_index[_currentProgram]++;
}
private void PerformRCV(Instruction instruction) {
var value = (instruction.IsValueRegister1 ? _registers[_currentProgram][instruction.Register1] : instruction.Value1);
if (value != 0) {
_lastRecovery = _lastSoundPlayed;
if (_lastRecovery != 0) {
_isFinished = true;
}
}
_index[_currentProgram]++;
}
private void PerformRCVNew(Instruction instruction) {
if (_queues[_currentProgram].Count == 0) {
_isWaiting[_currentProgram] = true;
if (_isWaiting[0] && _isWaiting[1]) {
_isFinished = true;
} else {
_currentProgram = (_currentProgram + 1) % 2;
}
} else {
_registers[_currentProgram][instruction.Register1] = _queues[_currentProgram][0];
_queues[_currentProgram].RemoveAt(0);
_index[_currentProgram]++;
}
}
private void PerformJGZ(Instruction instruction) {
var x = (instruction.IsValueRegister1 ? _registers[_currentProgram][instruction.Register1] : instruction.Value1);
var y = (instruction.IsValueRegister2 ? _registers[_currentProgram][instruction.Register2] : instruction.Value2);
if (x > 0) {
_index[_currentProgram] += (int)y;
} else {
_index[_currentProgram]++;
}
}
private void GetInstructions(List<string> input) {
_instructions = input.Select(line => {
var instruction = new Instruction();
var split = line.Split(' ');
switch (split[0]) {
case "snd":
instruction.InstructionType = enumInstructionType.snd;
break;
case "set":
instruction.InstructionType = enumInstructionType.set;
break;
case "add":
instruction.InstructionType = enumInstructionType.add;
break;
case "mul":
instruction.InstructionType = enumInstructionType.mul;
break;
case "mod":
instruction.InstructionType = enumInstructionType.mod;
break;
case "rcv":
instruction.InstructionType = enumInstructionType.rcv;
break;
case "jgz":
instruction.InstructionType = enumInstructionType.jgz;
break;
}
int value = 0;
bool isNum = int.TryParse(split[1], out value);
if (isNum) {
instruction.Value1 = value;
} else {
instruction.Register1 = split[1];
instruction.IsValueRegister1 = true;
}
if (split.Length == 3) {
isNum = int.TryParse(split[2], out value);
if (isNum) {
instruction.Value2 = value;
} else {
instruction.Register2 = split[2];
instruction.IsValueRegister2 = true;
}
}
return instruction;
}).ToList();
}
private class Instruction {
public enumInstructionType InstructionType { get; set; }
public long Value1 { get; set; }
public long Value2 { get; set; }
public string Register1 { get; set; }
public string Register2 { get; set; }
public bool IsValueRegister1 { get; set; }
public bool IsValueRegister2 { get; set; }
}
}
}
|
using System.Runtime.CompilerServices;
using System.Windows.Automation;
namespace UIAFramework
{
public class UIButton : ControlBase
{
public UIButton() { }
public UIButton(string condition, string treescope, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
: base(condition, treescope, type, memberName)
{
ParentBase.controlType = Common.GetControlType("button");
}
public UIButton(string condition, string treescope, AutomationElement ae, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
: base(condition, treescope, ae, type, memberName)
{
ParentBase.controlType = Common.GetControlType("button");
}
public UIButton(string treePath, bool isPath, [CallerMemberName] string memberName = "")
: base(treePath, isPath, memberName)
{
ParentBase.controlType = Common.GetControlType("button");
}
public UIButton(string treePath, bool isPath, AutomationElement ae, [CallerMemberName] string memberName = "")
: base(treePath, isPath, ae, memberName)
{
ParentBase.controlType = Common.GetControlType("button");
}
public UIButton(AutomationElement ae, [CallerMemberName] string memberName = "")
: base(ae)
{
ParentBase.controlType = Common.GetControlType("button");
}
public UIButton(string condition, string treescope, bool isMultipleControl, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
:base(condition,treescope,isMultipleControl,type,memberName)
{
ParentBase.controlType = Common.GetControlType("button");
}
public UIButton(string condition, string treescope, AutomationElement ae, bool isMultipleControl, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "")
: base(condition, treescope,ae, isMultipleControl, type, memberName)
{
ParentBase.controlType = Common.GetControlType("button");
}
public UIButton(AutomationElement ae)
: base(ae)
{
}
#region Actions
/// <summary>
/// Click on the button using invoke pattern
/// </summary>
public void Click()
{
UnWrap().GetInvokePattern().Invoke();
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeleeAI : MonoBehaviour
{
private GameObject player;
public float speed;
public float sightDistance;
public float stun;
public bool zMode;
private Vector3 playerPosition;
public Vector3 checkpoint;
// Start is called before the first frame update
void Start()
{
player = FindObjectOfType<PlayerMovement>().gameObject;
playerPosition = Vector3.zero;
}
// Update is called once per frame
void Update()
{
if (stun <= 0)
{
if (LookForPlayer())
{
MoveTo();
playerPosition = player.transform.position;
Rotate();
}
else
{
if (playerPosition != Vector3.zero)
MoveToLast();
else if(zMode)
{
MoveToCheckpoint();
RotateToCheckpoint();
}
}
}
else
{
stun -= Time.deltaTime;
}
}
private void MoveTo()
{
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
Vector2 playerDirection = (transform.position - player.transform.position);
playerDirection = playerDirection.normalized;
Vector2 movement = playerDirection * speed * Time.deltaTime * -1;
transform.position = transform.position + new Vector3(movement.x, movement.y, 0);
}
private void MoveToLast()
{
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
Vector2 playerDirection = (transform.position - playerPosition);
playerDirection = playerDirection.normalized;
Vector2 movement = playerDirection * speed * Time.deltaTime * -1;
transform.position = transform.position + new Vector3(movement.x, movement.y, 0);
}
private void MoveToCheckpoint()
{
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
Vector2 playerDirection = (transform.position - checkpoint);
playerDirection = playerDirection.normalized;
Vector2 movement = playerDirection * speed * Time.deltaTime * -1;
transform.position = transform.position + new Vector3(movement.x, movement.y, 0);
}
private void Rotate()
{
Vector3 direction = (player.transform.position - transform.position);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
private void RotateToCheckpoint()
{
Vector3 direction = (checkpoint - transform.position);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
private bool LookForPlayer()
{
if (player != null)
{
int layer_mask = LayerMask.GetMask("Default");
Vector3 direction = (player.transform.position - transform.position);
RaycastHit2D hit;
if (!zMode)
hit = Physics2D.Raycast(transform.position, direction);
else
hit = Physics2D.Raycast(transform.position, direction, 100, layer_mask);
if (hit.collider.gameObject.tag == "Player")
{
playerPosition = player.transform.position;
return true;
}
else
{
return false;
}
}
else
return false;
}
private void OnDestroy()
{
if (zMode && FindObjectOfType<ZController>() != null)
FindObjectOfType<ZController>().zombiesKilled++;
}
}
|
namespace DEV_7
{
public class Sides
{
public double aSide { get; set; }
public double bSide { get; set; }
public double cSide { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HAGJ2.Platforms
{
public class MovingRange : MonoBehaviour
{
[SerializeField] float sphereRadius = 0.3f;
public Transform start;
public Transform end;
private void Awake()
{
start = transform.GetChild(0);
end = transform.GetChild(1);
}
private void Start()
{
SortRangePointsByY();
}
private void SortRangePointsByY()
{
float startY = start.position.y;
float endY = end.position.y;
if (startY > endY)
{
Transform hold = start;
start = end;
end = hold;
}
}
private void OnDrawGizmos()
{
for (int i = 0; i < transform.childCount; i++)
{
int j = GetNextIndex(i);
Gizmos.DrawSphere(GetWaypoint(i), sphereRadius);
Gizmos.DrawLine(GetWaypoint(i), GetWaypoint(j));
}
}
private int GetNextIndex(int i)
{
if (i == transform.childCount - 1)
{
return 0;
}
return i + 1;
}
private Vector2 GetWaypoint(int i)
{
return transform.GetChild(i).position;
}
}
} |
using NPoco;
namespace SciVacancies.ReadModel.Core
{
[TableName("d_regions")]
[PrimaryKey("id", AutoIncrement = false)]
public class Region
{
public int id { get; set; }
public int? feddistrict_id { get; set; }
public string title { get; set; }
public int? osm_id { get; set; }
public string okato { get; set; }
public string slug { get; set; }
public int? code { get; set; }
}
}
|
using UnityEngine;
public class ObstacleAI : MonoBehaviour
{
//public GameObject parentObject;
public Collider2D _collider { get; private set; }
private bool hasEnteredCamera;
private bool isRendered;
void Start()
{
_collider = GetComponent<Collider2D>();
_collider.enabled = false;
hasEnteredCamera = false;
isRendered = false;
}
public void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
//block for test
return;
var player = col.GetComponent<Player>();
if (player == null)
return;
if (!player.IsDead)
{
LevelManager.Instance.KillPlayer();
player._controller.SetForce(new Vector2(7, 17));
player.DeadJumpCount++;
Debug.Log("DeadJumpCount : 0");
}
else
{
if (player.DeadJumpCount == 1)
{
Debug.Log("DeadJumpCount : 1 "+player._controller.Velocity.x);
if (player._controller.Velocity.x >= 0)
{
player._controller.SetHorizontalForce(4);
}
else
{
player._controller.SetHorizontalForce(-4);
}
player._controller.SetVerticalForce(9);
player.DeadJumpCount++;
}
else if (player.DeadJumpCount == 2)
{
Debug.Log("DeadJumpCount : 2 "+player._controller.Velocity.x);
if (player._controller.Velocity.x >= 0)
{
player._controller.SetHorizontalForce(2);
}
else
{
player._controller.SetHorizontalForce(-2);
}
player._controller.SetVerticalForce(5);
player.DeadJumpCount++;
}
}
}
/*
else if (col.CompareTag("Enemy"))
{
var spannerEnemyAI = col.GetComponent<SpannerEnemyAI>();
if (spannerEnemyAI == null)
return;
spannerEnemyAI.KillSelf();
}
*/
else if (col.CompareTag("Player Bounds") && !hasEnteredCamera)
{
hasEnteredCamera = true;
_collider.enabled = true;
}
}
public void OnTriggerExit2D(Collider2D col)
{
if (col.CompareTag("Player Bounds") && hasEnteredCamera)
{
gameObject.SetActive(false);
}
}
void OnWillRenderObject()
{
if (isRendered)
return;
isRendered = true;
hasEnteredCamera = true;
_collider.enabled = true;
}
void OnBecameInvisible()
{
/*
#if UNITY_EDITOR
Debug.Log("OnBecameInvisible >>> x:" + transform.position.x + ", y:" + transform.position.y);
#endif
*/
//parentObject.SetActive(false);
}
}
|
using System;
using System.Runtime.InteropServices;
using DLToolkit.Forms.Controls;
using Foundation;
using Plugin.PushNotification;
using Simon.Helpers;
using UIKit;
using Xamarin;
using Xamarin.Forms;
namespace Simon.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
//public IAuthorizationFlowSession CurrentAuthorizationFlow { get; set; }
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Forms.SetFlags(new[]
{
"Expander_Experimental"
});
global::Xamarin.Forms.Forms.Init();
Rg.Plugins.Popup.Popup.Init();
XF.Material.iOS.Material.Init();
IQKeyboardManager.SharedManager.Enable = true;
IQKeyboardManager.SharedManager.EnableAutoToolbar = true;
IQKeyboardManager.SharedManager.ShouldResignOnTouchOutside = true;
IQKeyboardManager.SharedManager.PreviousNextDisplayMode = IQPreviousNextDisplayMode.AlwaysHide;
FlowListView.Init();
LoadApplication(new App());
PushNotificationManager.Initialize(options, true);
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
//UIView statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBarWindow")).ValueForKey(new NSString("statusBar")) as UIView;
//statusBar.BackgroundColor = UIColor.White;
var result = base.FinishedLaunching(app, options);
app.KeyWindow.TintColor = UIColor.Gray;
// Color of the tabbar background:
UITabBar.Appearance.BarTintColor = UIColor.FromRGB(247, 247, 247);
// Color of the selected tab text color:
UITabBarItem.Appearance.SetTitleTextAttributes(
new UITextAttributes()
{
TextColor = UIColor.FromRGB(0, 122, 255)
},
UIControlState.Selected);
// Color of the unselected tab icon & text:
UITabBarItem.Appearance.SetTitleTextAttributes(
new UITextAttributes()
{
TextColor = UIColor.FromRGB(146, 146, 146)
},
UIControlState.Normal);
//UITabBar.Appearance.TintColor = UIColor.Blue;
return result;
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
byte[] result = new byte[deviceToken.Length];
Marshal.Copy(deviceToken.Bytes, result, 0, (int)deviceToken.Length);
var token = BitConverter.ToString(result).Replace("-", "");
System.Diagnostics.Debug.WriteLine($"TOKEN : {Settings.DeviceToken}");
Settings.DeviceToken = token;
PushNotificationManager.DidRegisterRemoteNotifications(token);
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
PushNotificationManager.RemoteNotificationRegistrationFailed(error);
}
// To receive notifications in foregroung on iOS 9 and below.
// To receive notifications in background in any iOS version
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired 'till the user taps on the notification launching the application.
// If you disable method swizzling, you'll need to call this method.
// This lets FCM track message delivery and analytics, which is performed
// automatically with method swizzling enabled.
PushNotificationManager.DidReceiveMessage(userInfo);
// Do your magic to handle the notification data
System.Console.WriteLine(userInfo);
completionHandler(UIBackgroundFetchResult.NewData);
}
public override bool OpenUrl(UIApplication application, NSUrl url,string sourceApplication, NSObject annotation)
{
// Sends the URL to the current authorization flow (if any) which will process it if it relates to
// an authorization response.
//if (CurrentAuthorizationFlow?.ResumeAuthorizationFlow(url) == true)
//{
// return true;
//}
// Your additional URL handling (if any) goes here.
return false;
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Salle.Model.Salle;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestSalle
{
[TestClass()]
public class MaitreHotelTests
{
[TestMethod()]
public void MaitreHotelTest()
{
Assert.Fail();
}
[TestMethod()]
public void attribuerTableTest()
{
Assert.Fail();
}
[TestMethod()]
public void encaisseClientTest()
{
Assert.Fail();
}
[TestMethod()]
public void appelleChefRangTest()
{
Assert.Fail();
}
[TestMethod()]
public void ajouteClientTest()
{
Assert.Fail();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BallMovementScript : MonoBehaviour
{
[SerializeField]
private Rigidbody rbBall;
[SerializeField]
private GameObject lockButton;
[SerializeField]
private GameObject fireButton;
[SerializeField]
private ScoreTrackerScript score;
[SerializeField]
private GameObject directionHelp;
[SerializeField]
private GameObject powerHelp;
public enum BallState
{
Stopped,
ChangeDirection,
ChangePower,
AddForce,
Moving
}
public BallState currentState;
public float maxForce = 2000.0f;
private float minForce = 0.0f;
public float force;
private float powerBarDirection = 1;
private float powerBarChange = 10.0f;
private Vector3 shootDirection;
public bool allowChangeDirection = true;
private Vector3 startPos;
private Vector3 newPos;
// Use this for initialization
void Start()
{
startPos = new Vector3(-8.37f, 0.39f, 0.0f);
//Find the ScoreTrackerScript to set to score
score = GameObject.Find("HeadsUpDisplay").GetComponent<ScoreTrackerScript>();
shootDirection = Vector2.zero;
force = 0;
rbBall = GetComponent<Rigidbody>() as Rigidbody;
rbBall.transform.position = startPos;
currentState = BallState.Stopped;
fireButton.SetActive(false);
}
// Update is called once per frame
void Update()
{
//Switch case to move between direction change, power change, and moving the ball
switch (currentState)
{
case BallState.Stopped:
//If tutorial is not over, show hints
if (score.level.demoDone == false)
{
directionHelp.SetActive(true);
}
lockButton.SetActive(true);
newPos = rbBall.transform.position;
if (Input.touchCount > 0)
{
currentState = BallState.ChangeDirection;
}
break;
case BallState.ChangeDirection:
allowChangeDirection = true;
AdjustDirection();
break;
case BallState.ChangePower:
lockButton.SetActive(false);
fireButton.SetActive(true);
allowChangeDirection = false;
SetPower();
break;
case BallState.AddForce:
AddForce(force, shootDirection);
currentState = BallState.Moving;
break;
case BallState.Moving:
fireButton.SetActive(false);
CheckIsStationary();
break;
}
if(rbBall.transform.position.y < -10)
{
rbBall.transform.position = newPos;
}
}
//Adjust direction
void AdjustDirection()
{
//Get the direction the camera is facing
Vector3 currentCameraDirection = new Vector3(Camera.main.transform.forward.x, 0, Camera.main.transform.forward.z);
if (Input.touchCount == 0)
{
//Set direction to shoot
shootDirection = currentCameraDirection;
}
}
//Set power
void SetPower()
{
//If tutorial is not over, show hints
if (score.level.demoDone == false)
{
directionHelp.SetActive(false);
powerHelp.SetActive(true);
}
if (Input.touchCount > 0)
{
int touchCount = Input.touchCount;
if(touchCount == 0)
{
currentState = BallState.AddForce;
}
else
{
//Increase the value of the power bar
float powerIncrease = powerBarChange * Time.deltaTime;
//Make sure force doesn't go too high
if((force + powerIncrease) > maxForce)
{
force = maxForce;
powerBarDirection = -75;
}
//Make sure force doesn't go too low
else if ((force - powerIncrease) < minForce)
{
force = minForce;
powerBarDirection = 75;
}
force += (powerIncrease * powerBarDirection);
}
}
}
//Add force
void AddForce(float force, Vector3 shootDirection)
{
if (score.level.demoDone == false)
{
powerHelp.SetActive(false);
//Tutorial is over
score.level.demoDone = true;
}
//Add force to ball in direction the camera is facing
rbBall.AddForce(shootDirection.normalized * force, ForceMode.Force);
}
//Check if the ball has stopped moving
void CheckIsStationary()
{
if(rbBall.velocity == Vector3.zero)
{
score.shotsTaken++;
currentState = BallState.Stopped;
}
}
}
|
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using Domain;
using RepositoryInterface;
namespace Repository
{
public class UserRolesRepository : Repository<TUSRROL>, IUserRolesRepository
{
public UserRolesRepository(dbEntities db)
: base(db)
{
}
public int AddRoleToUser(List<TUSRROL> lTuteRuo)
{
int result = 0;
foreach (TUSRROL oT in lTuteRuo)
{
oT.DATASC = System.DateTime.Now;
db.Set<TUSRROL>().Add(oT);
result = SaveChanges();
}
return result;
}
public int DeleteRoleToUser(List<TUSRROL> lTuteRuo)
{
int result = 0;
TUSRROL tuteruo = new TUSRROL();
foreach (TUSRROL oT in lTuteRuo)
{
db.Set<TUSRROL>().Remove(oT);
}
result = SaveChanges();
return result;
}
public List<TUSRROL> GetUserRoles(TUSRROL userRoles)
{
var lista = from ur in db.Set<TUSRROL>()
where userRoles.CODROL.Equals(ur.CODROL) && userRoles.CODUSR.Equals(ur.CODUSR)
select ur;
if (!string.IsNullOrEmpty(userRoles.CODGRPARE)) {
lista = lista.Where(x => userRoles.CODGRPARE.Equals(x.CODGRPARE));
}
return lista.ToList();
}
}
} |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Projeto.Infra.Caching.Contexts;
using Projeto.Infra.Caching.Settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Projeto.Services.Api.Configurations
{
public static class MongoDbSetup
{
public static void AddMongoDbSetup(this IServiceCollection services, IConfiguration configuration)
{
//Ler os parametros mapeados no arquivo 'appsettings.json'
//e carregar os seus valores na classe MongoDBSettings
var dbSettings = new MongoDBSettings();
new ConfigureFromConfigurationOptions<MongoDBSettings>
(configuration.GetSection("MongoDBSettings"))
.Configure(dbSettings);
services.AddSingleton(dbSettings);
//criando uma injeção de dependência Singleton
//para a classe MongoDBContext
services.AddSingleton<MongoDBContext>();
}
}
}
|
using System.Configuration;
namespace Emanate.Core.Configuration
{
public class AppConfigStorage : IConfigurationStorage
{
public string GetString(string key)
{
return ConfigurationManager.AppSettings[key];
}
public bool GetBool(string key)
{
var value = GetString(key);
bool booleanValue;
return bool.TryParse(value, out booleanValue) && booleanValue;
}
public int GetInt(string key)
{
var value = GetString(key);
int integerValue;
return int.TryParse(value, out integerValue) ? integerValue : 0;
}
}
} |
using Carmotub.Data;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Carmotub.ViewModel
{
public class CustomerVM
{
public List<Dictionary<string, string>> Customers { get; set; }
private static CustomerVM _instance = null;
public static CustomerVM Instance
{
get
{
if (_instance == null)
_instance = new CustomerVM();
return _instance;
}
}
public List<String> columns { get; set; }
public CustomerVM()
{
}
public async Task<bool> DropColumnCustomer(string column)
{
try
{
string query = string.Format("ALTER TABLE clients DROP COLUMN {0}", column);
await SQLDataHelper.Instance.OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, SQLDataHelper.Instance.Connection);
cmd.ExecuteNonQuery();
}
catch (Exception E)
{
return false;
}
return true;
}
public async Task<bool> AddColumnCustomer(string column)
{
try
{
string query = string.Format("ALTER TABLE clients ADD {0} VARCHAR(255)", column);
await SQLDataHelper.Instance.OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, SQLDataHelper.Instance.Connection);
cmd.ExecuteNonQuery();
}
catch (Exception E)
{
return false;
}
return true;
}
public async Task<bool> DeleteCustomer(string identifiant)
{
try
{
string query = "DELETE FROM clients WHERE identifiant = @identifiant";
await InterventionVM.Instance.DeleteInterventionWithCustomer(identifiant);
await CustomerPhotoVM.Instance.DeletePhotoWithCustomer(identifiant);
await SQLDataHelper.Instance.OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, SQLDataHelper.Instance.Connection);
cmd.Prepare();
cmd.Parameters.Add("@identifiant", identifiant);
cmd.ExecuteNonQuery();
}
catch (Exception E)
{
return false;
}
return true;
}
public async Task<bool> UpdateCustomer(string query)
{
try
{
await SQLDataHelper.Instance.OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, SQLDataHelper.Instance.Connection);
cmd.ExecuteNonQuery();
}
catch (Exception E)
{
return false;
}
return true;
}
public async Task<bool> AddCustomer(string query)
{
try
{
await SQLDataHelper.Instance.OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, SQLDataHelper.Instance.Connection);
cmd.ExecuteNonQuery();
}
catch (Exception E)
{
return false;
}
return true;
}
public async Task GetAllCustomer()
{
Customers = new List<Dictionary<string, string>>();
string query = "SELECT * from clients";
await SQLDataHelper.Instance.OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, SQLDataHelper.Instance.Connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Dictionary<string, string> customer = new Dictionary<string, string>();
for (int i = 0; i < CustomerVM.Instance.columns.Count; i++)
{
customer.Add(CustomerVM.Instance.columns[i], dataReader[i].ToString());
}
Customers.Add(customer);
}
}
public async Task GetColumns()
{
columns = new List<String>();
await SQLDataHelper.Instance.OpenConnection();
using (MySqlCommand cmd = new MySqlCommand("select column_name from information_schema.columns where table_name = 'clients'", SQLDataHelper.Instance.Connection))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
columns.Add(reader.GetString(0));
}
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Programmable : MonoBehaviour
{
// Object containing program code to control this Programmable.
public GameObject Computer;
// Element (if the ProgramController addresses an array of objects)
public int index = -1;
// Start is called before the first frame update
protected virtual void Start()
{
}
// Update is called once per frame
protected virtual void Update()
{
//Computer.GetComponent<ProgramController>().ExecuteFrame(index, gameObject);
if(GetComponentInChildren<TextMesh>())
{
GetComponentInChildren<TextMesh>().text = index.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GestioneLavoratori
{
class Program
{
static void Main(string[] args)
{
bool controllo = false;//variabile bool controllo inserimento informazioni lavoratore
bool exists = true; //variabile bool di controllo inserimento lavoratore
LavoratoreDipendente[] lavoratoriDipendenti = new LavoratoreDipendente[3];
LavoratoreAutonomo[] lavoratoriAutonomi = new LavoratoreAutonomo[3];
Console.WriteLine("INSERMINETO LAVORATORI" + System.Environment.NewLine +
"-----------R1Q17------------" + System.Environment.NewLine);
//CICLO INSERIMENTO LAVORATORI DIPENDENTI
for (int i = 0; i < 3; i++)
{
exists = false;
//CICLO DO WHILE PER RIPETERE INSERIMENTO LAVORATORE SE GIA ESISTENTE
do
{
//creo un oggetto "temporaneo" LavoratoreDipendente
LavoratoreDipendente lvD = new LavoratoreDipendente();
//assegno i singoli valori alle proprietà del mio oggetto lv
Console.WriteLine("Inserisci nome lavoratore dipendente" + (i + 1) + ": ");
string nomeLD = Console.ReadLine();
lvD.Nome = nomeLD;
Console.WriteLine("Inserisci cognome lavoratore dipendente " + (i + 1) + ": ");
string cognomeLD = Console.ReadLine();
lvD.Cognome = cognomeLD;
controllo = false;
do//ciclo per ripetere inserimento valori se sbagliati
{
try
{
Console.WriteLine("Inserisci età lavoratore dipendente " + (i + 1) + ": ");
int etàLD = Int32.Parse(Console.ReadLine());
lvD.Età = etàLD;
controllo = true;
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Riprova: ");
controllo = false;
}
} while (controllo == false);
controllo = false;
do
{
try
{
Console.WriteLine("Inserisci RAL lavoratore dipendente " + (i + 1) + ": ");
int ralLD = Int32.Parse(Console.ReadLine());
lvD.Ral = ralLD;
controllo = true;
}
catch (Exception ex)
{
Console.WriteLine("Riprova: ");
Console.WriteLine(ex.Message);
}
} while (controllo == false);
controllo = false;
do
{
try
{
Console.WriteLine("Inserisci anno assunzione lavoratore dipendente " + (i + 1) + ": ");
int annoAssunzioneLD = Int32.Parse(Console.ReadLine());
if(annoAssunzioneLD<DateTime.Now.Year)
{
lvD.AnnoAssunzione = annoAssunzioneLD;
controllo = true;
}
else
{
Console.WriteLine("inserire un anno minore di quello corrente");
controllo = false;
}
}
catch (Exception ex)
{
Console.WriteLine("Riprova: ");
Console.WriteLine(ex.Message);
}
} while (controllo == false);
Console.WriteLine(System.Environment.NewLine);
foreach (var lavoratore in lavoratoriDipendenti)
{
exists = true;
if (lvD.Equals(lavoratore)) // in questa riga verifico se il mio oggetto "lvD" inserito dall'utente sia uguale all'oggetto "lavoratore"
{
Console.WriteLine("lavoratore già inserito, RIPETI INSERIMENTO" + System.Environment.NewLine);
break; //interrompo il ciclo, ho già trovato che l'elemento esiste già, non serve che "perdo tempo" facendogli finire il ciclo
}
else
{
exists = false;
}
}
if(exists==false)
{
lavoratoriDipendenti[i] = lvD;
Console.WriteLine("lavoratore inserito correttamente" + System.Environment.NewLine);
}
} while (exists == true);
}
//CICLO INSERIMENTO LAVORATORI AUTONOMI
for (int i = 0; i < 3; i++)
{
exists = false;
do {
LavoratoreAutonomo lvA = new LavoratoreAutonomo();
Console.WriteLine("Inserisci nome lavoratore autonomo" + (i + 1) + ": ");
string nomeLA = Console.ReadLine();
lvA.Nome = nomeLA;
Console.WriteLine("Inserisci cognome lavoratore autonomo " + (i + 1) + ": ");
string cognomeLA = Console.ReadLine();
lvA.Cognome = cognomeLA;
controllo = false;
do
{
try
{
Console.WriteLine("Inserisci età lavoratore autonomo " + (i + 1) + ": ");
int etàLA = Int32.Parse(Console.ReadLine());
lvA.Età = etàLA;
controllo = true;
}
catch (Exception ex)
{
Console.WriteLine("Riprova: ");
Console.WriteLine(ex.Message);
}
} while (controllo == false);
controllo = false;
do
{
try
{
Console.WriteLine("Inserisci RAL lavoratore autonomo " + (i + 1) + ": ");
int ralLA = Int32.Parse(Console.ReadLine());
lvA.Ral = ralLA;
Console.WriteLine(System.Environment.NewLine);
controllo = true;
}
catch (Exception ex)
{
Console.WriteLine("Riprova: ");
Console.WriteLine(ex.Message);
}
} while (controllo == false);
foreach (var lavoratore in lavoratoriAutonomi)
{
exists = true;
if (lvA.Equals(lavoratore)) // in questa riga verifico se il mio oggetto "lvA" inserito dall'utente sia uguale all'oggetto "lavoratore"
{
Console.WriteLine("Lavoratore già inserito, RIPETI INSERIMENTO: " + System.Environment.NewLine);
break; //interrompo il ciclo, ho già trovato che l'elemento esiste già, non serve che "perdo tempo" facendogli finire il ciclo
}
else
{
exists = false;
}
}
if (exists == false)
{
lavoratoriAutonomi[i] = lvA;
Console.WriteLine("lavoratore inserito correttamente" + System.Environment.NewLine);
}
} while (exists == true) ;
}
Console.WriteLine("Scegli ordinamento lavoratori:" + System.Environment.NewLine + System.Environment.NewLine
+ "Per Stipendio = 1 + INVIO" + System.Environment.NewLine
+ "PerAnzianità = 2 + INVIO" + System.Environment.NewLine
+ "Premi qualsiasi tasto + INVIO per visualizzarli normalmente");
string x = Console.ReadLine();
//CONTROLLO ORDINAMENTI
if(x=="1")
{
Console.WriteLine(System.Environment.NewLine + "ORDINAMENTO LAVORATORI PER STIPENDIO" + System.Environment.NewLine +
"-----------------------" + System.Environment.NewLine);
//ORDINAMENTO PER STIPENDIO
LavoratoreDipendente[] dipendentiOrdinati = lavoratoriDipendenti.OrderBy
(lavDipendenti => lavDipendenti.StipendioMensile()).ToArray();
LavoratoreAutonomo[] autonomiOrdinati = lavoratoriAutonomi.OrderBy
(lavAutonomi => lavAutonomi.StipendioMensile()).ToArray();
for (int i = 0; i < 3; i++)
{
Console.WriteLine(System.Environment.NewLine + "Lavoratori dipendenti ordinati per stipendio:"
+ dipendentiOrdinati[i].GetDettaglioLavoratore());
}
for (int i = 0; i < 3; i++)
{
Console.WriteLine(System.Environment.NewLine + "Lavoratori autonomi ordinati per stipendio: "
+ (i + 1) + ": " + autonomiOrdinati[i].GetDettaglioLavoratore());
}
}
if (x == "2")
{
Console.WriteLine(System.Environment.NewLine + "ORDINAMENTO LAVORATORI PER ANZIANITA'" + System.Environment.NewLine +
"-----------------------" + System.Environment.NewLine);
//ORDINAMENTO PER ANZIANITA'
LavoratoreDipendente[] dipendentiOrdinati = lavoratoriDipendenti.OrderBy
(lavDipendenti => lavDipendenti.CalcolaAnzianità()).ToArray();
for (int i = 0; i < 3; i++)
{
Console.WriteLine(System.Environment.NewLine + "Dettagli lavoratore dipendente "
+ (i + 1) + ": " + dipendentiOrdinati[i].GetDettaglioLavoratore());
}
for (int i = 0; i < 3; i++) //lavoratori autonomi non viene ordinato perchè non ha l'anzianità
{
Console.WriteLine(System.Environment.NewLine + "Dettagli lavoratore autonomo "
+ (i + 1) + ": " + lavoratoriAutonomi[i].GetDettaglioLavoratore());
}
}
else
{
Console.WriteLine(System.Environment.NewLine + "ORDINAMENTO LAVORATORI PER INSERIMENTO" + System.Environment.NewLine +
"-----------------------" + System.Environment.NewLine);
for (int i = 0; i < 3; i++)
{
Console.WriteLine(System.Environment.NewLine + "Dettagli lavoratore dipendente "
+ (i + 1) + ": " + lavoratoriDipendenti[i].GetDettaglioLavoratore());
}
for (int i = 0; i < 3; i++)
{
Console.WriteLine(System.Environment.NewLine + "Dettagli lavoratore autonomo "
+ (i + 1) + ": " + lavoratoriAutonomi[i].GetDettaglioLavoratore());
}
}
Console.ReadLine();
}
}
}
|
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;
//Utilizar Diccionarios (Dictionary<string, int>) para realizar un contador de palabras, recorriendo el texto palabra por palabra se deberá lograr que si se trata de una nueva palabra, se la agregará al diccionario e inicializar su contador en 1, caso contrario se deberá incrementar dicho contador. Ordenar los resultados de forma descendente por cantidad de apariciones de cada palabra. Informar mediante un MessageBox el TOP 3 de palabras con más apariciones.
namespace Ejercicio_28
{
public partial class frmContador : Form
{
Dictionary<string, int> diccionario; // key palabra, value cant
public frmContador()
{
InitializeComponent();
this.diccionario = new Dictionary<string, int>(); // inicializo diccionario
}
public static void ContarPalabras(string text, Dictionary<string, int> diccionario)
{
string[] separators = new string[] { ",", ".", "!", "\'", " ", "\'s" };
// Cargar diccionario:
foreach (string word in text.Split(separators, StringSplitOptions.RemoveEmptyEntries))
{
if (diccionario.ContainsKey(word))
{
int cantidad = diccionario[word]; // guardo value
cantidad = cantidad + 1;
diccionario[word] = cantidad; // incremento cant
}
else
{
diccionario.Add(word, 1); // word es key
}
}
// Sort:
List<KeyValuePair<string, int>> dList = diccionario.ToList(); // convierto en lista
dList.Sort(delegate (KeyValuePair<string, int> pair1, KeyValuePair<string, int> pair2)
{
return pair1.Value - pair2.Value;
}); // sort
dList.Reverse();
diccionario = dList.ToDictionary<KeyValuePair<string, int>, string, int>(pair => pair.Key, pair => pair.Value);
// Mostrar:
StringBuilder sb = new StringBuilder();
int top = 0;
foreach (KeyValuePair<string, int> palabra in diccionario)
{
if(top < 3)
{
sb.AppendLine($"{palabra.Key} - {palabra.Value}");
}
else
{
break;
}
top++;
}
MessageBox.Show($"{sb}");
}
private void btnCalcular_Click(object sender, EventArgs e)
{
Dictionary<string, int> diccionario = new Dictionary<string, int>();
ContarPalabras(richTxtB.Text, diccionario);
}
}
}
|
using System;
using System.Collections.Generic;
namespace MisskeyDotNet
{
public class DriveFIle
{
public string Id { get; set; } = "";
public DateTime CreatedAt { get; set; }
public string Name { get; set; } = "";
public string Type { get; set; } = "";
public string Md5 { get; set; } = "";
public int Size { get; set; }
public bool IsSensitive { get; set; }
public string? Blurhash { get; set; }
public Dictionary<string, object>? Properties { get; set; }
public string? Url { get; set; }
public string? ThumbnailUrl { get; set; }
public string? Comment { get; set; }
public string? FolderId { get; set; }
public DriveFolder? Folder { get; set; }
public string? UserId { get; set; }
public User? User { get; set; }
}
} |
using System;
using System.Collections.Generic;
namespace PizzaBezorgApp.Models
{
public class PizzaBestelling : Bestelling
{
public List<String> Pizzas;
public PizzaBestelling(string besteller, string soort , string stad , string adres, List<String> pizza) : base(besteller, soort,stad,adres)
{
Pizzas = pizza;
aantal = Pizzas.Count;
}
}
}
|
using gView.Interoperability.GeoServices.Rest.Json.Renderers.SimpleRenderers;
using Newtonsoft.Json;
namespace gView.Interoperability.GeoServices.Rest.Json.DynamicLayers
{
public class DynamicLayerDrawingInfo
{
[JsonProperty("renderer", NullValueHandling = NullValueHandling.Ignore)]
public JsonRenderer Renderer { get; set; }
[JsonProperty("transparency", NullValueHandling = NullValueHandling.Ignore)]
public int? Transparency { get; set; }
[JsonProperty("scaleSymbols", NullValueHandling = NullValueHandling.Ignore)]
public bool? ScaleSymbols { get; set; }
[JsonProperty("showLabels", NullValueHandling = NullValueHandling.Ignore)]
public bool? ShowLabels { get; set; }
[JsonProperty("labelingInfo", NullValueHandling = NullValueHandling.Ignore)]
public LabelingInfo[] LabelingInfo { get; set; }
}
}
|
namespace IconCreator.Core.Logic.Helpers
{
using MColor = System.Windows.Media.Color;
using DColor = System.Drawing.Color;
public class WPFColorConverter
{
public static MColor ToMediaColor(DColor color)
{
return MColor.FromArgb(color.A, color.R, color.G, color.B);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.SYS;
namespace com.Sconit.Entity.MD
{
[Serializable]
public partial class Item : EntityBase, IAuditable
{
#region O/R Mapping Properties
[Export(ExportName = "Item", ExportSeq = 10)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthExceed", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "Item_Code", ResourceType = typeof(Resources.MD.Item))]
public string Code { get; set; }
[Export(ExportName = "Item", ExportSeq = 20)]
[Display(Name = "Item_ReferenceCode", ResourceType = typeof(Resources.MD.Item))]
public string ReferenceCode { get; set; }
[Display(Name = "Item_ShortCode", ResourceType = typeof(Resources.MD.Item))]
public string ShortCode { get; set; }
[Export(ExportName = "Item", ExportSeq =40)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "Item_Uom", ResourceType = typeof(Resources.MD.Item))]
public string Uom { get; set; }
[Export(ExportName = "Item", ExportSeq = 30)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[StringLength(100, ErrorMessageResourceName = "Errors_Common_FieldLengthExceed", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "Item_Description", ResourceType = typeof(Resources.MD.Item))]
public string Description { get; set; }
[Export(ExportName = "Item", ExportSeq = 50)]
[Display(Name = "Item_UC", ResourceType = typeof(Resources.MD.Item))]
public Decimal UnitCount { get; set; }
[Export(ExportName = "Item", ExportSeq = 60)]
[Display(Name = "Item_ItemCategory", ResourceType = typeof(Resources.MD.Item))]
public string ItemCategory { get; set; }
[Export(ExportName = "Item", ExportSeq = 80)]
[Display(Name = "Item_IsActive", ResourceType = typeof(Resources.MD.Item))]
public Boolean IsActive { get; set; }
//[Display(Name = "Item_IsPurchase", ResourceType = typeof(Resources.MD.Item))]
//public Boolean IsPurchase { get; set; }
//[Display(Name = "Item_IsSales", ResourceType = typeof(Resources.MD.Item))]
//public Boolean IsSales { get; set; }
//[Display(Name = "Item_IsManufacture", ResourceType = typeof(Resources.MD.Item))]
//public Boolean IsManufacture { get; set; }
//[Display(Name = "Item_IsSubContract", ResourceType = typeof(Resources.MD.Item))]
//public Boolean IsSubContract { get; set; }
//[Display(Name = "Item_IsCustomerGoods", ResourceType = typeof(Resources.MD.Item))]
//public Boolean IsCustomerGoods { get; set; }
[Display(Name = "Item_IsVirtual", ResourceType = typeof(Resources.MD.Item))]
public Boolean IsVirtual { get; set; }
[Display(Name = "Item_IsKit", ResourceType = typeof(Resources.MD.Item))]
public Boolean IsKit { get; set; }
[Display(Name = "Item_Bom", ResourceType = typeof(Resources.MD.Item))]
public string Bom { get; set; }
[Display(Name = "Item_Location", ResourceType = typeof(Resources.MD.Item))]
public string Location { get; set; }
[Display(Name = "Item_Routing", ResourceType = typeof(Resources.MD.Item))]
public string Routing { get; set; }
[Display(Name = "Item_IsInvFreeze", ResourceType = typeof(Resources.MD.Item))]
public Boolean IsInventoryFreeze { get; set; }
[Export(ExportName = "Item", ExportSeq = 78)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "Item_Warranty", ResourceType = typeof(Resources.MD.Item))]
public Int32 Warranty { get; set; }
[Export(ExportName = "Item", ExportSeq = 77)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "Item_WarnLeadTime", ResourceType = typeof(Resources.MD.Item))]
public Int32 WarnLeadTime { get; set; }
//[Display(Name = "Item_IsSection", ResourceType = typeof(Resources.MD.Item))]
//public Boolean IsSection { get; set; }
[Display(Name = "Item_ItemPriority", ResourceType = typeof(Resources.MD.Item))]
public com.Sconit.CodeMaster.ItemPriority ItemPriority { get; set; }
[Display(Name = "Item_Weight", ResourceType = typeof(Resources.MD.Item))]
public Double Weight { get; set; }
[Display(Name = "Item_WorkHour", ResourceType = typeof(Resources.MD.Item))]
public Double WorkHour { get; set; }
public string Container { get; set; }
public Int32 CreateUserId { get; set; }
public string CreateUserName { get; set; }
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
public string LastModifyUserName { get; set; }
public DateTime LastModifyDate { get; set; }
/// <summary>
/// 物料选项
/// </summary>
[Display(Name = "Item_ItemOption", ResourceType = typeof(Resources.MD.Item))]
public CodeMaster.ItemOption ItemOption { get; set; }
/// <summary>
/// 物料组
/// </summary>
[Export(ExportName = "Item", ExportSeq = 70)]
[Display(Name = "Item_MaterialsGroup", ResourceType = typeof(Resources.MD.Item))]
public string MaterialsGroup { get; set; }
/// <summary>
/// 安全库存
/// </summary>
[Display(Name = "Item_SafeStock", ResourceType = typeof(Resources.MD.Item))]
public double SafeStock { get; set; }
[Display(Name = "Item_ScrapPercent", ResourceType = typeof(Resources.MD.Item))]
public Double ScrapPercent { get; set; }
[Display(Name = "Item_ContainerSize", ResourceType = typeof(Resources.MD.Item))]
public Double ContainerSize { get; set; }
/// <summary>
/// 产品组
/// </summary>
[Export(ExportName = "Item", ExportSeq = 76)]
[Display(Name = "Item_Division", ResourceType = typeof(Resources.MD.Item))]
public string Division { get; set; }
public Decimal PalletLotSize { get; set; }
public Decimal PackageVolume { get; set; }
public Decimal PackageWeight { get; set; }
#endregion
public override int GetHashCode()
{
if (Code != null)
{
return Code.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
Item another = obj as Item;
if (another == null)
{
return false;
}
else
{
return (this.Code == another.Code);
}
}
}
}
|
using Player;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(Animator), typeof(NavMeshAgent))]
public class BaseEnnemyBehaviour : MonoBehaviour
{
[SerializeField] private float _walkSpeed = 10f;
[SerializeField] private float _runSpeed = 20f;
private readonly int AttackRange;
protected Vector3 Forward;
protected bool Walking;
protected bool ChasePlayer;
protected FirstPersonController Personnage;
protected NavMeshAgent CurrentNavMeshAgent;
protected Animator CurrentAnimator;
protected readonly int HashSpeed = Animator.StringToHash("Speed");
protected readonly int HashAttack = Animator.StringToHash("Speed");
private void Awake()
{
CurrentAnimator = GetComponent<Animator>();
CurrentNavMeshAgent = GetComponent<NavMeshAgent>();
Personnage = FindObjectOfType<FirstPersonController>();
}
private void Update()
{
if (ChasePlayer)
ChasePlayerLogic();
else
{
transform.forward = Forward;
}
}
private void ChasePlayerLogic()
{
if ((Personnage.transform.position - transform.position).magnitude < AttackRange)
{
; //ToDo: Attack
}
else if ((Personnage.transform.position - CurrentNavMeshAgent.destination).magnitude > 0.1f)
CurrentNavMeshAgent.destination = Personnage.transform.position;
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MinecraftToolsBoxSDK;
using TranslationTools;
namespace MTB.GameHandler
{
/// <summary>
/// MapTranslator.xaml 的交互逻辑
/// </summary>
public partial class MapTranslator : Grid
{
int changes;
DispatcherTimer timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 30) };
XmlDocument doc = new XmlDocument();
XmlNode root;
string filePath;
DateTime lastSave;
List<TreeDataGridItem> results = new List<TreeDataGridItem>();
CommandEditor cmdDialog = new CommandEditor();
SignEditor signDialog = new SignEditor();
public MapTranslator()
{
System.Windows.Forms.FolderBrowserDialog m_Dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = m_Dialog.ShowDialog();
InitializeComponent();
if (result == System.Windows.Forms.DialogResult.Cancel) return;
string directory = m_Dialog.SelectedPath.Trim();
filePath = directory;
string[] split = filePath.Split('\\');
filePath= filePath + "\\.translation\\" + split[split.Length - 1] + ".mtbl";
doc.Load(filePath);
root = doc.SelectSingleNode("LanguageItems");
if (root.Attributes["CommandBlocks"].Value == "True")
{
int.TryParse(root.ChildNodes[1].Attributes["StartIndex"].Value, out int index);
TreeDataGridItem ldi = new TreeDataGridItem { Type = "命令" };
foreach (XmlNode item in root.ChildNodes[1].ChildNodes)
ldi.Children.Add(new TreeDataGridItemCommandBlock(item, index++));
list.Children.Add(ldi);
}
if (root.Attributes["Signs"].Value == "True")
{
int.TryParse(root.ChildNodes[2].Attributes["StartIndex"].Value, out int index);
TreeDataGridItem ldi = new TreeDataGridItem { Type = "告示牌" };
foreach (XmlNode item in root.ChildNodes[2].ChildNodes)
ldi.Children.Add(new TreeDataGridItemSign(item, index++));
list.Children.Add(ldi);
}
if (root.Attributes["Containers"].Value == "True")
{
int.TryParse(root.ChildNodes[3].Attributes["StartIndex"].Value, out int index);
TreeDataGridItem ldi = new TreeDataGridItem { Type = "容器" };
foreach (XmlNode item in root.ChildNodes[3].ChildNodes)
ldi.Children.Add(new TreeDataGridItemContainer(item, index++));
list.Children.Add(ldi);
}
if (root.Attributes["Entities"].Value == "True")
{
int.TryParse(root.ChildNodes[4].Attributes["StartIndex"].Value, out int index);
TreeDataGridItem ldi = new TreeDataGridItem { Type = "实体" };
foreach (XmlNode item in root.ChildNodes[4].ChildNodes)
ldi.Children.Add(new TreeDataGridItemEntity(item, index++));
list.Children.Add(ldi);
}
if (root.Attributes["Spawners"].Value == "True")
{
int.TryParse(root.ChildNodes[5].Attributes["StartIndex"].Value, out int index);
TreeDataGridItem ldi = new TreeDataGridItem { Type = "刷怪笼" };
foreach (XmlNode item in root.ChildNodes[5].ChildNodes)
ldi.Children.Add(new TreeDataGridItemMobSpawner(item, index++));
list.Children.Add(ldi);
}
timer.Tick += delegate
{
doc.Save(filePath);
Dispatcher.Invoke(() =>
{
Save(true);
});
};
timer.Start();
}
private void Save(bool isAuto = false)
{
doc.Save(filePath);
changes = 0;
saveInfo.Text = "已在" + (lastSave = DateTime.Now).ToLongTimeString() + (isAuto ? "自动保存" : "保存");
}
private void List_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
//LanguageDataItem item = list.SelectedItem as LanguageDataItem;
//if (list.editing != null)
//{
// if (list.editing.Type == "告示牌")
// {
// if ((TL1.Text != "" || TL2.Text != "" || TL3.Text != "" || TL4.Text != "") && (TL1.Text != OL1.Text || TL2.Text != OL2.Text || TL3.Text != OL3.Text || TL4.Text != OL4.Text))
// {
// ObservableCollection<LanguageDataItem> sign = list.editing.Children;
// (sign[0].Node as XmlElement).SetAttribute("Translated", TL1.Text);
// (sign[1].Node as XmlElement).SetAttribute("Translated", TL2.Text);
// (sign[2].Node as XmlElement).SetAttribute("Translated", TL3.Text);
// (sign[3].Node as XmlElement).SetAttribute("Translated", TL4.Text);
// (sign[0].Translated as TextBlock).Text = TL1.Text;
// (sign[1].Translated as TextBlock).Text = TL2.Text;
// (sign[2].Translated as TextBlock).Text = TL3.Text;
// (sign[3].Translated as TextBlock).Text = TL4.Text;
// (Application.Current.MainWindow as IMainWindowCommands).ChangeWindowTitle("[*]");
// }
// }
// else if (list.editing.Children.Count != 0)
// {
// }
// else
// {
// string val = tra.Text;
// if (val != "" && val != ori.Text) { (list.editing.Node as XmlElement).SetAttribute("Translated", val); (Application.Current.MainWindow as IMainWindowCommands).ChangeWindowTitle("[*]"); }
// (list.editing.Translated as TextBlock).Text = val;
// }
//}
//if (item.Type == "告示牌")
//{
// ObservableCollection<LanguageDataItem> sign = item.Children;
// OL1.Text = sign[0].Original as string;
// OL2.Text = sign[1].Original as string;
// OL3.Text = sign[2].Original as string;
// OL4.Text = sign[3].Original as string;
// TL1.Text = (sign[0].Translated as TextBlock).Text;
// TL2.Text = (sign[1].Translated as TextBlock).Text;
// TL3.Text = (sign[2].Translated as TextBlock).Text;
// TL4.Text = (sign[3].Translated as TextBlock).Text;
// editor.SelectedIndex = 2;
// if (TL1.Text == "" && TL2.Text == "" && TL3.Text == "" && TL4.Text == "" && (OL1.Text != "" || OL2.Text != "" || OL3.Text != "" || OL4.Text != ""))
// {
// TL1.Text = OL1.Text;
// TL2.Text = OL2.Text;
// TL3.Text = OL3.Text;
// TL4.Text = OL4.Text;
// }
//}
//else if (item.Children.Count != 0)
//{
// editor.SelectedIndex = 3;
//}
//else
//{
// editor.SelectedIndex = 0;
// ori.Text = item.Original as string;
// tra.Text = (item.Translated as TextBlock).Text;
// if (tra.Text == "" && ori.Text != "") tra.Text = ori.Text;
//}
}
private void list_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TreeDataGridItem item = list.SelectedItem as TreeDataGridItem;
if (item.Parent != null && (item.Parent as TreeDataGridItem).Type == "命令")
{
cmdDialog.SetCurrentItem(item, this);
(Application.Current.MainWindow as MetroWindow).ShowMetroDialogAsync(cmdDialog);
}
else if(item.Parent != null && (item.Parent as TreeDataGridItem).Type == "告示牌")
{
signDialog.SetCurrentItem(item, this);
(Application.Current.MainWindow as MetroWindow).ShowMetroDialogAsync(signDialog);
}
else if(!item.HasChildren)
{
DataGridRow row = (DataGridRow)list.ItemContainerGenerator.ContainerFromIndex(list.SelectedIndex);
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(2);
cell.Focus();
list.BeginEdit();
}
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.S) Save();
else if (e.Key == Key.Enter)
{
/*if (list.SelectedItem != null) (list.SelectedItem as LanguageDataItem).Start();*/
}
}
private void DockPanel_Unloaded(object sender, RoutedEventArgs e)
{
timer.Stop();
}
public void list_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
changes++;
if (saveInfo.Text == "无更改" || !saveInfo.Text.Contains("保存")) saveInfo.Text = changes + "处更改";
else
{
string[] split = saveInfo.Text.Split(',');
saveInfo.Text = changes + "处更改," + split[split.Length - 1];
}
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T childContent = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
childContent = v as T;
if (childContent == null)
{
childContent = GetVisualChild<T>(v);
}
if (childContent != null)
{ break; }
}
return childContent;
}
private void Next_Click(object sender, RoutedEventArgs e)
{
if (searchResults.SelectedIndex != searchResults.Items.Count - 1)searchResults.SelectedIndex++;
}
private void Last_Click(object sender, RoutedEventArgs e)
{
if (searchResults.SelectedIndex != 0) searchResults.SelectedIndex--;
}
private void searchResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TreeDataGridItem item = results[searchResults.SelectedIndex];
TreeDataGridItem tmp = item;
while ((item = item.Parent as TreeDataGridItem) != null)
{
item.IsExpanded = true;
}
int i = list.Items.IndexOf(tmp);
list.SelectedIndex = i;
list.ScrollIntoView(tmp);
}
private void Search(object sender, RoutedEventArgs e)
{
results.Clear();
searchResults.Items.Clear();
foreach (TreeDataGridItem item in list.Children)
{
GetSearchResult(item, KeyWord.Text);
}
}
private void GetSearchResult(TreeDataGridItem item, string keyword)
{
if (item.HasChildren)
{
foreach (TreeDataGridItem i in item.Children)
{
GetSearchResult(i, keyword);
}
}
else
{
if ((item.Original != null && item.Original.Contains(keyword) || item.Translated != null && item.Translated.Contains(keyword)) && item.Parent != null)
{
string str = item.Type;
TreeDataGridItem parent = item;
while ((parent = parent.Parent as TreeDataGridItem).Parent != null)
{
str = parent.Type + ">" + str;
}
searchResults.Items.Add(str + item.Original + "\n" + item.Translated);
results.Add(item);
}
}
}
private void Search_Click(object sender, RoutedEventArgs e) => searchWindow.Visibility = Visibility.Visible;
private void closeSearch(object sender, RoutedEventArgs e) => searchWindow.Visibility = Visibility.Hidden;
public void DialogueClosed()
{
list_CellEditEnding(null, null);
list.Items.Refresh();
list.Focus();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Limilabs.FTP.Client;
namespace PingerProject
{
class FTPPinger : Pinger
{
/// <summary>
/// Constructeur récupérant les valeurs du serveur
/// </summary>
/// <param name="serveur">Adresse IP du serveur</param>
/// <param name="port">Port du serveur</param>
/// <param name="servertype">Nom du serveur</param>
public FTPPinger(string server, uint port, string servertype) : base(server, port, servertype)
{
}
/// <summary>
/// Ping le serveur
/// </summary>
/// <returns>Retourne l'état du serveur</returns>
public override bool Ping()
{
Console.WriteLine("Connexion au serveur " + this.ServerType + "...");
try
{
using (Ftp ftp = new Ftp()) // Initialisation de l'objet du FTP
{
ftp.Connect(this.ServerIP); // Connection au FTP sans login
if(ftp.Connected)
{
ftp.Close();
return true;
}
else
{
ftp.Close();
return false;
}
}
}
catch(Exception e)
{
Console.WriteLine(e);
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using SendGrid;
using SendGrid.Helpers.Mail;
using TryHardForum.ViewModels.Email;
namespace TryHardForum.Services
{
/*
* Отправляет почту используя SendGrid WebAPI C#
*/
public class SendGridEmailSender : IEmailSender
{
public IConfiguration Configuration { get; }
public SendGridEmailSender(IConfiguration config)
{
Configuration = config;
}
// Получает данные из модели SendEmailDetails.
public async Task<SendEmailResponse> SendEmailAsync(SendEmailDetails details)
{
// Получаю ключ SendGrid из appsettings.json
var apiKey = Configuration["SendGridKey"];
// Создаю нового клиента SendGrid.
var client = new SendGridClient(apiKey);
// From От кого (почта и имя)
var from = new EmailAddress(details.FromEmail, details.FromName);
// To Кому (почта и имя)
var to = new EmailAddress(details.ToEmail, details.ToName);
// Subject (тема сообщения)
var subject = details.Subject;
// Содержимое сообщения. Включает разметку HTML.
var content = details.Content;
// Метод CrtateSingleEmail() принимает два вида содержимого: обычный текст (четвёртый аргумент метода)
// и с HTML разметкой (пятый аргумент). Чтобы обойти третий аргумент леплю тернарный оператор.
var message = MailHelper.CreateSingleEmail(
from,
to,
subject,
details.IsHtml ? null : content,
details.IsHtml ? content : null);
// Можно создать темплейт, ID которого указать в коде.
// message.TemplateId = "";
// также можно указать конкретные поля в письме, воторые можно заполнить определённым текстом.
// message.AddSubstitution("", "");
// Отправка письма...
var response = await client.SendEmailAsync(message);
// Если успешно
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
// Возвращает успешный ответ.
return new SendEmailResponse();
}
// Иначе...
try
{
// Получить result в теле.
var bodyResult = await response.Body.ReadAsStringAsync();
// Десериализация ответа
var sendGridResponse = JsonConvert.DeserializeObject<SendGridResponse>(bodyResult);
// Добавление любых ошибок к ответу.
var errorResponse = new SendEmailResponse
{
Errors = sendGridResponse?.Errors.Select(f => f.Message).ToList()
};
// Удостоверяюсь, что имею хотя бы одну ошибку
if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
{
// Добавление неизвестной ошибки.
errorResponse.Errors = new List<string>(new [] { "Unknown error from email sending service" });
}
// ВОзврат ответа
return errorResponse;
}
catch (Exception ex)
{
// Сбрасываю (break) если начинается дебаг
if (Debugger.IsAttached)
{
var error = ex;
Debugger.Break();
}
return new SendEmailResponse
{
Errors = new List<string>(new[] { "Произошла неизвестная ошибка." })
};
}
}
}
}
|
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using GDataDB;
using GDataDB.Linq;
using UnityQuickSheet;
///
/// !!! Machine generated code !!!
///
[CustomEditor(typeof(EquipmentTable))]
public class EquipmentTableEditor : BaseGoogleEditor<EquipmentTable>
{
public override bool Load()
{
EquipmentTable targetData = target as EquipmentTable;
var client = new DatabaseClient("", "");
string error = string.Empty;
var db = client.GetDatabase(targetData.SheetName, ref error);
var table = db.GetTable<EquipmentTableData>(targetData.WorksheetName) ?? db.CreateTable<EquipmentTableData>(targetData.WorksheetName);
List<EquipmentTableData> myDataList = new List<EquipmentTableData>();
var all = table.FindAll();
foreach(var elem in all)
{
EquipmentTableData data = new EquipmentTableData();
data = Cloner.DeepCopy<EquipmentTableData>(elem.Element);
myDataList.Add(data);
}
targetData.dataArray = myDataList.ToArray();
EditorUtility.SetDirty(targetData);
AssetDatabase.SaveAssets();
return true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using BLL.DTO;
using BLL.Infrastructure;
using BLL.Interfaces;
using DAL.Entities;
using DAL.Interfaces;
using DAL.Repositories;
namespace BLL.Services
{
public class UsersService : IUsersService
{
private IUnitOfWork Database { get; set; }
private AutoMapperCollection mapperCollection;
public UsersService(IUnitOfWork uow)
{
Database = uow;
mapperCollection = new AutoMapperCollection();
}
public void RegisterNewUser(UserDTO user)
{
Database.Users.Create(Mapper.Map<UserDTO, User>(user));
Database.Save();
}
public void EditPersonalInformationOfUser(UserDTO user)
{
Database.Users.Update(Mapper.Map<UserDTO, User>(user));
Database.Save();
}
public void AddAvatar(int userId, string imageName)
{
var user = Database.Users.Get(userId);
user.Image = imageName;
Database.Users.Update(user);
Database.Save();
}
public UserDTO GetUserByEmail(string email)
{
var user = Database.Users.GetAll().Where(u => u.Email == email).Single();
return Mapper.Map<User, UserDTO>(user);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace KartObjects
{
public class ProducerLicense :SupplierLicense
{
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public override string FriendlyName
{
get
{
return "Алкогольная лицензия производителя";
}
}
public long? IdProducer
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Data.OleDb;
using SysconCommon.Common.Environment;
using SysconCommon.Common;
using SysconCommon.Algebras.DataTables;
using SysconCommon.Accounting;
using SysconCommon.GUI;
using SysconCommon.Foxpro;
using SysconCommon.Algebras.DataTables.Excel.VSTO;
using Microsoft.Office.Interop.Excel;
namespace JobDetailAnalysisDesktop
{
public partial class JobDetailAnalysis : Form
{
private SysconCommon.COMMethods mbapi = new SysconCommon.COMMethods();
public JobDetailAnalysis()
{
InitializeComponent();
Env.CopyOldConfigs();
#if false
Env.ConfigInjector = (name) =>
{
if (new string[] { "mbdir", "product_id", "product_version", "run_count" }.Contains(name))
{
Env.SetConfigFile(Env.ConfigDataPath + "/config.xml");
return name;
}
else if (new string[] { "tmtypes", "nonbillablecostcodes" }.Contains(name))
{
// return "dataset" + Env.GetConfigVar("datadir", "c:\\mb7\\sample company\\", true).GetMD5Sum() + "/" + name;
Env.SetConfigFile(Env.GetConfigVar("mbdir") + "/syscon_tm_analysis_config.xml");
return name;
}
else
{
Env.SetConfigFile(Env.GetEXEDirectory() + "/config.xml");
var username = WindowsIdentity.GetCurrent().Name;
return "dataset" + (Env.GetConfigVar("mbdir", "c:\\mb7\\sample company\\", true) + username).GetMD5Sum() + "/" + name;
}
};
#else
Env.ConfigInjector = (name) =>
{
var dataset_specific = new string[] { "tmtypes", "nonbillablecostcodes" };
if (dataset_specific.Contains(name))
{
Env.SetConfigFile(Env.GetConfigVar("mbdir") + "/syscon_tm_analysis_config.xml");
return name;
}
else
{
Env.SetConfigFile(Env.ConfigDataPath + "/config.xml");
return name;
}
};
#endif
}
private void SetupTrial(int daysLeft)
{
var msg = string.Format("You have {0} days left to evaluate this software", daysLeft);
this.demoLabel.Text = msg;
btnRunReport.Enabled = true;
}
private void SetupInvalid()
{
btnRunReport.Enabled = false;
this.demoLabel.Text = "Your License has expired or is invalid";
}
private void SetupFull()
{
btnRunReport.Enabled = true;
this.demoLabel.Text = "";
this.activateToolStripMenuItem.Visible = false;
}
private const string DefaultTemplate = "T&M Job Detail Analysis Template v09.xlsm";
private string Template
{
get
{
var template = Env.GetConfigVar("template", Env.GetEXEDirectory() + @"\" + DefaultTemplate, true);
if (!File.Exists(template))
{
var dflt = Env.GetEXEDirectory() + @"\" + DefaultTemplate;
if (!File.Exists(dflt))
{
Env.Log("Error: Default Template ({0}) does not exist.", dflt);
}
else
{
Env.SetConfigVar("template", dflt);
}
selectTemplateToolStripMenuItem_Click(null, null);
// recursive call
return Template;
}
return template;
}
set
{
Env.SetConfigVar("template", value);
}
}
bool loaded = false;
private void JobDetailAnalysis_Load(object sender, EventArgs e)
{
// resets it everytime it is run so that the user can't just change to a product they already have a license for
Env.SetConfigVar("product_id", 178504);
var product_id = Env.GetConfigVar("product_id", 0, false);
var product_version = "2.1.3.0";
bool require_login = false;
if (!loaded)
{
require_login = true;
loaded = true;
this.Text += " (version " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + ")";
}
try
{
var license = SysconCommon.Protection.ProtectionInfo.GetLicense(product_id, product_version, 15751);
if (license.IsTrial)
{
if (!license.IsValid())
{
SetupInvalid();
}
else
{
var l = license as SysconCommon.Protection.TrialLicense;
SetupTrial(l.DaysLeft);
}
}
else
{
SetupFull();
}
}
catch
{
SetupInvalid();
}
// var datadir = Env.GetConfigVar("mbdir", "c:\\mb7\\sample company\\", true);
//SysconCommon.Accounting.MasterBuilder.Job.SetCache("select * from actrec");
txtDataDir.TextChanged +=new EventHandler(txtDataDir_TextChanged);
if (require_login)
{
mbapi.smartGetSMBDir();
if (mbapi.RequireSMBLogin() == null)
this.Close();
}
txtDataDir.Text = mbapi.smartGetSMBDir();
}
private void LoadValues()
{
cmbEndPeriod.SelectItem<string>(p => p == Env.GetConfigVar("endperiod", "12", true));
cmbStartingPeriod.SelectItem<string>(p => p == Env.GetConfigVar("startperiod", "0", true));
chkUnbilled.Checked = Env.GetConfigVar("ExportUnbilledOnly", false, true);
}
private void txtDataDir_TextChanged(object sender, EventArgs e)
{
// Env.SetConfigVar("datadir", txtDataDir.Text);
SysconCommon.Common.Environment.Connections.SetOLEDBFreeTableDirectory(txtDataDir.Text);
LoadValues();
}
private void btnSelectDir_Click(object sender, EventArgs e)
{
}
private void PopulateTemplate(string template, long[] jobnums, int strprd, int endprd, DateTime trndate, decimal[] nonbillablecstcdes)
{
using (var con = SysconCommon.Common.Environment.Connections.GetOLEDBConnection())
{
using (Env.TempDBFPointer
_jobcst = con.GetTempDBF(),
_jobnums = con.GetTempDBF(),
_blgqty = con.GetTempDBF(),
_nobill = con.GetTempDBF(),
_sources = con.GetTempDBF(),
_csttyps = con.GetTempDBF(),
_phases = con.GetTempDBF())
{
using (var progress = new ProgressDialog(9))
{
progress.Text = "Select Job Cost Records";
progress.Show();
// first create a table of job numbers to join against
con.ExecuteNonQuery("create table {0} (jobnum n(10,0) not null)", _jobnums);
foreach(var j in jobnums)
{
con.ExecuteNonQuery("insert into {0} (jobnum) values ({1})", _jobnums, j);
}
con.ExecuteNonQuery("select"
+ " jobcst.recnum"
+ ", actrec.estemp as estnum"
+ ", jobcst.empnum"
+ ", jobcst.vndnum"
+ ", jobcst.eqpnum"
+ ", 000000 as tmemln"
+ ", 000000 as tmeqln"
+ ", jobcst.jobnum"
+ ", actrec.jobnme"
+ ", alltrim(reccln.clnnme) as clnnme"
+ ", jobcst.trnnum"
+ ", jobcst.dscrpt"
+ ", jobcst.trndte"
+ ", jobcst.actprd"
+ ", jobcst.srcnum"
+ ", jobcst.status"
+ ", jobcst.bllsts"
+ ", jobcst.phsnum"
+ ", jobphs.phsnme"
+ ", jobcst.cstcde"
+ ", cstcde.cdenme"
+ ", jobcst.csttyp"
+ ", jobcst.csthrs"
+ ", IIF(jobcst.acrinv = 0 AND jobcst.bllsts = 1 AND jobcst.csttyp = 2"
+ ", jobcst.blgqty"
+ ", 0000000000) as blgpnd"
+ ", jobcst.eqpqty"
+ ", jobcst.blgqty"
+ ", jobcst.paytyp"
+ ", jobcst.cstamt"
+ ", jobcst.blgttl"
+ ", jobcst.acrinv"
+ ", IIF("
+ "jobcst.csttyp = 2, 'Employee ',"
+ "IIF(jobcst.csttyp = 3, 'Equipment ',"
+ "IIF(jobcst.empnum <> 0, 'Employee ',"
+ "IIF(jobcst.eqpnum <> 0, 'Equipment ',"
+ "IIF(jobcst.vndnum <> 0, 'Vendor ',"
+ "'None '))))) as empeqpvnd"
+ ", [ ] as ename"
+ ", 00000000.00000000 as rate01"
+ ", 00000000.00000000 as rate02"
+ ", 00000000.00000000 as rate03"
+ ", 00000000.00000000 as minhrs"
+ ", 00000001.00000000 as markup"
+ ", 0000000000000.00000000 as estbll"
+ ", jobcst.eqpnum"
+ ", eqpmnt.eqpnme"
+ ", jobcst.blgunt"
+ ", jobcst.empnum"
+ ", employ.fullst"
+ ", jobcst.blgamt"
+ ", jobcst.ntetxt"
+ ", estmtr.fullst as estnme"
+ ", nvl(sprvsr.fullst, [No Supervisor ]) as sprvsr"
+ " from jobcst"
+ " join actrec on jobcst.jobnum = actrec.recnum"
+ " join reccln on reccln.recnum = actrec.clnnum"
+ " left outer join employ estmtr on actrec.estemp = estmtr.recnum"
+ " left join employ sprvsr on actrec.sprvsr = sprvsr.recnum"
+ " left join cstcde on cstcde.recnum = jobcst.cstcde"
+ " join {0} _jobnums on _jobnums.jobnum = jobcst.jobnum"
+ " left join eqpmnt on eqpmnt.recnum = jobcst.eqpnum"
+ " left join employ on employ.recnum = jobcst.empnum"
+ " left join jobphs on jobphs.recnum = jobcst.jobnum and jobphs.phsnum = jobcst.phsnum"
// + " and between(jobcst.actprd, {1}, {2})"
+ " where jobcst.actprd >= {1}"
+ (chkUnbilled.Checked ? " and jobcst.bllsts = 1" : "")
+ " and jobcst.actprd <= {2}"
+ " and jobcst.status <> 2"
+ " and jobcst.trndte <= {3}"
+ " order by jobcst.recnum"
+ " into table {4}"
, _jobnums, strprd, endprd, trndate.ToFoxproDate(), _jobcst);
progress.Tick();
progress.Text = "Selecting Names";
con.ExecuteNonQuery("update _jobcst set ename = alltrim(str(empnum)) + [ - ] + alltrim(employ.fullst)"
+ " from {0} _jobcst"
+ " join employ on _jobcst.empnum = employ.recnum"
+ " where empeqpvnd = 'Employee'"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set ename = alltrim(str(vndnum)) + [ - ] + alltrim(actpay.vndnme)"
+ " from {0} _jobcst"
+ " join actpay on _jobcst.vndnum = actpay.recnum"
+ " where empeqpvnd = 'Vendor'"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set ename = alltrim(str(eqpnum)) + [ - ] + alltrim(eqpmnt.eqpnme)"
+ " from {0} _jobcst"
+ " join eqpmnt on _jobcst.eqpnum = eqpmnt.recnum"
+ " where empeqpvnd = 'Equipment'"
, _jobcst);
progress.Tick();
progress.Text = "Locating T&M Line items";
con.ExecuteNonQuery("update _jobcst set _jobcst.tmemln = tmemln.linnum"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " join tmemln on"
+ " tmemln.recnum = timmat.emptbl"
+ " and timmat.emptbl <> 0"
+ " and tmemln.empnum = 0"
+ " and tmemln.cstcde = _jobcst.cstcde"
+ " where _jobcst.csttyp = 2"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.tmemln = tmemln.linnum"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " join tmemln on"
+ " tmemln.recnum = timmat.emptbl"
+ " and timmat.emptbl <> 0"
+ " and tmemln.empnum = _jobcst.empnum"
+ " and tmemln.cstcde = _jobcst.cstcde"
+ " where _jobcst.empnum <> 0 AND _jobcst.csttyp = 2"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.tmeqln = tmeqln.linnum"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " join tmeqln on tmeqln.recnum = timmat.eqptbl"
, _jobcst);
progress.Tick();
progress.Text = "Loading T&M Rates";
con.ExecuteNonQuery("update _jobcst set"
+ " _jobcst.rate01 = tmeqln.oprrte"
+ ", _jobcst.rate02 = tmeqln.stdrte"
+ ", _jobcst.rate03 = tmeqln.idlrte"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " join tmeqln on tmeqln.recnum = timmat.eqptbl and tmeqln.linnum = _jobcst.tmeqln"
+ " where _jobcst.tmeqln <> 0"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set"
+ " _jobcst.rate01 = tmemln.rate01"
+ ", _jobcst.rate02 = tmemln.rate02"
+ ", _jobcst.rate03 = tmemln.rate03"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " join tmemln on tmemln.recnum = timmat.emptbl and tmemln.linnum = _jobcst.tmemln"
+ " where _jobcst.tmemln <> 0"
, _jobcst);
progress.Tick();
progress.Text = "Loading Minimum Hours";
con.ExecuteNonQuery("update _jobcst set _jobcst.minhrs = tmeqln.minhrs"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " join tmeqln on tmeqln.recnum = timmat.eqptbl and tmeqln.linnum = _jobcst.tmeqln"
+ " where _jobcst.tmeqln <> 0"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.minhrs = tmemln.minhrs"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " join tmemln on tmemln.recnum = timmat.emptbl and tmemln.linnum = _jobcst.tmemln"
+ " where _jobcst.tmemln <> 0"
, _jobcst);
progress.Tick();
progress.Text = "Selecting Markup Values";
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.mtrhdn / 100.00)) *"
+ " (1.00 + (timmat.mtrshw / 100.00)) *"
+ " (1.00 + (timmat.mtrovh / 100.00)) *"
+ " (1.00 + (timmat.mtrpft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 1"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.labhdn / 100.00)) *"
+ " (1.00 + (timmat.labshw / 100.00)) *"
+ " (1.00 + (timmat.labovh / 100.00)) *"
+ " (1.00 + (timmat.labpft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 2"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.eqphdn / 100.00)) *"
+ " (1.00 + (timmat.eqpshw / 100.00)) *"
+ " (1.00 + (timmat.eqpovh / 100.00)) *"
+ " (1.00 + (timmat.eqppft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 3"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.subhdn / 100.00)) *"
+ " (1.00 + (timmat.subshw / 100.00)) *"
+ " (1.00 + (timmat.subovh / 100.00)) *"
+ " (1.00 + (timmat.subpft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 4"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.otrhdn / 100.00)) *"
+ " (1.00 + (timmat.otrshw / 100.00)) *"
+ " (1.00 + (timmat.otrovh / 100.00)) *"
+ " (1.00 + (timmat.otrpft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 5"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.cs6hdn / 100.00)) *"
+ " (1.00 + (timmat.cs6shw / 100.00)) *"
+ " (1.00 + (timmat.cs6ovh / 100.00)) *"
+ " (1.00 + (timmat.cs6pft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 6"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.cs7hdn / 100.00)) *"
+ " (1.00 + (timmat.cs7shw / 100.00)) *"
+ " (1.00 + (timmat.cs7ovh / 100.00)) *"
+ " (1.00 + (timmat.cs7pft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 7"
, _jobcst);
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.cs8hdn / 100.00)) *"
+ " (1.00 + (timmat.cs8shw / 100.00)) *"
+ " (1.00 + (timmat.cs8ovh / 100.00)) *"
+ " (1.00 + (timmat.cs8pft / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 8"
, _jobcst);
// BUG in SMB database, cs9pft is type C!!!!
con.ExecuteNonQuery("update _jobcst set _jobcst.markup ="
+ " (1.00 + (timmat.cs9hdn / 100.00)) *"
+ " (1.00 + (timmat.cs9shw / 100.00)) *"
+ " (1.00 + (timmat.cs9ovh / 100.00)) *"
+ " (1.00 + (val(timmat.cs9pft) / 100.00))"
+ " from {0} _jobcst"
+ " join timmat on timmat.recnum = _jobcst.jobnum"
+ " where _jobcst.csttyp = 9"
, _jobcst);
progress.Tick();
progress.Text = "Selecting Billing Quantities";
con.ExecuteNonQuery("select _jobcst.recnum, 00000000.00000000 as hrs, cast(null as n(3)) as typ from {0} _jobcst into table {1}", _jobcst, _blgqty);
con.ExecuteNonQuery("update blgqty set hrs = _jobcst.csthrs, typ = _jobcst.paytyp"
+ " from {0} blgqty"
+ " join {1} _jobcst on blgqty.recnum = _jobcst.recnum"
+ " where _jobcst.csttyp = 2"
, _blgqty, _jobcst);
con.ExecuteNonQuery("update blgqty set hrs = _jobcst.blgqty, typ = _jobcst.paytyp"
+ " from {0} blgqty"
+ " join {1} _jobcst on blgqty.recnum = _jobcst.recnum"
+ " where _jobcst.csttyp = 2 and blgqty.hrs = 0 and _jobcst.bllsts = 1"
, _blgqty, _jobcst);
con.ExecuteNonQuery("update blgqty set hrs = _jobcst.eqpqty, typ = eqpmnt.eqptyp"
+ " from {0} blgqty"
+ " join {1} _jobcst on blgqty.recnum = _jobcst.recnum"
+ " join eqpmnt on _jobcst.eqpnum = eqpmnt.recnum"
+ " where _jobcst.csttyp = 3 and _jobcst.eqpnum <> 0 and eqpmnt.eqptyp <> 0"
, _blgqty, _jobcst);
progress.Tick();
progress.Text = "Calculating Billing Amounts";
con.ExecuteNonQuery("update _jobcst set _jobcst.estbll = "
+ "IIF(typ = 1 and rate01 <> 0, hrs*rate01,"
+ "IIF(typ = 2 and rate02 <> 0, hrs*rate02,"
+ "IIF(typ = 3 and rate03 <> 0, hrs*rate03,"
+ "cstamt)))"
+ " from {0} _jobcst"
+ " join {1} blgqty on blgqty.recnum = _jobcst.recnum"
, _jobcst, _blgqty);
con.ExecuteNonQuery("update _jobcst set estbll = cstamt"
+ " from {0} _jobcst"
+ " join eqpmnt on eqpmnt.recnum = _jobcst.eqpnum"
+ " where _jobcst.csttyp = 3 and (isnull(eqpmnt.eqptyp) or eqpmnt.eqptyp = 0)"
, _jobcst);
con.ExecuteNonQuery("update {0} set estbll = estbll * markup", _jobcst);
con.ExecuteNonQuery("update {0} set estbll = 0 where bllsts = 2", _jobcst);
con.ExecuteNonQuery("update {0} set estbll = blgttl where bllsts = 3", _jobcst);
con.ExecuteNonQuery("update {0} set estbll = blgamt where estbll = 0", _jobcst);
// build a list of nonbillable cost codes
con.ExecuteNonQuery("create table {0} (cstcde n(18,3) not null)", _nobill);
foreach (var cstcde in nonbillablecstcdes)
{
con.ExecuteNonQuery("insert into {0} (cstcde) values ({1})", _nobill, cstcde);
}
// make sure those cost codes are not billed
con.ExecuteNonQuery("update _jobcst set estbll = 0 from {0} _jobcst join {1} _nobill on _nobill.cstcde = _jobcst.cstcde"
+ " where _jobcst.acrinv = 0"
, _jobcst, _nobill);
// set their bllsts to unbillable cost code
// v2.1.2 BUT only for items that have not already been invoiced
con.ExecuteNonQuery("update _jobcst set bllsts = 4 from {0} _jobcst join {1} _nobill on _nobill.cstcde = _jobcst.cstcde"
+ " where _jobcst.acrinv = 0"
, _jobcst, _nobill);
progress.Tick();
progress.Text = "Selecting References";
con.ExecuteNonQuery("select distinct _jobcst.srcnum as recnum, source.srcnme, source.srcdsc"
+ " from {0} _jobcst"
+ " left join source on source.recnum = _jobcst.srcnum"
+ " into table {1}"
, _jobcst, _sources);
con.ExecuteNonQuery("select distinct _jobcst.csttyp as recnum, csttyp.typnme"
+ " from {0} _jobcst"
+ " left join csttyp on csttyp.recnum = _jobcst.csttyp"
+ " into table {1}"
, _jobcst, _csttyps);
con.ExecuteNonQuery("select distinct _jobcst.phsnum, jobphs.phsnme, alltrim(str(_jobcst.phsnum)) + [ - ] + alltrim(jobphs.phsnme) as phsdsc"
+ " from {0} _jobcst"
+ " join jobphs on jobphs.recnum = _jobcst.jobnum and jobphs.phsnum = _Jobcst.phsnum"
+ " into table {1}"
, _jobcst, _phases);
con.ExecuteNonQuery("insert into {0} (phsnum, phsnme, phsdsc) values (0, [None], [0 - None])", _phases);
/* if we want a summary, do the totals now */
var is_summary = chkSumCustomer.Checked || chkSumJob.Checked || chkSumPeriod.Checked;
Env.TempDBFPointer _jobcstsum = null;
if (is_summary)
{
var groupCols = new List<string>();
if(chkSumCustomer.Checked) groupCols.Add("clnnme");
if (chkSumJob.Checked) { groupCols.Add("jobnum"); groupCols.Add("jobnme"); groupCols.Add("clnnme"); }
if(chkSumPeriod.Checked) groupCols.Add("actprd");
var sum_cols = new string[]
{
"cstamt", "blgttl", "estbll", "blgqty", "blgpnd", "blgamt"
};
_jobcstsum = con.Summarize(_jobcst, groupCols.Uniq().ToArray(), sum_columns: sum_cols);
}
progress.Tick();
progress.Text = "Loading Excel Sheet";
ExcelAddinUtil.UseNewApp();
try
{
var details_dt = con.GetDataTable("Details", "select * from {0}", _jobcstsum != null ? _jobcstsum : _jobcst);
details_dt.ConfigurableWriteToExcel(template, "ImportData", "DetailData");
var sources_dt = con.GetDataTable("Sources", "select * from {0}", _sources);
sources_dt.ConfigurableWriteToExcel(template, "References", "Sources");
var csttyps_dt = con.GetDataTable("Cost Types", "select * from {0}", _csttyps);
csttyps_dt.ConfigurableWriteToExcel(template, "References", "CostTypes");
var jobphs_dt = con.GetDataTable("Phases", "select * from {0}", _phases);
jobphs_dt.ConfigurableWriteToExcel(template, "References", "JobPhases");
ExcelAddinUtil.app.Visible = true;
// auto-fit row heights
ExcelAddinUtil.app.ActiveWorkbook.getWorksheet("Job Detail").Cells.Rows.AutoFit();
// if the template has the unbilled by job pivot table, go ahead and set it's settings
try
{
if (_jobcstsum == null)
{
/* set the pivot table options and refresh data for the unbilled by job sheet */
var unbilled_ptable = ExcelAddinUtil.app.ActiveWorkbook.getWorksheet("Unbilled By Job").PivotTables("ByJob");
unbilled_ptable.PivotCache.Refresh();
/* set the billing status filter to 'Unbilled' */
unbilled_ptable.PivotFields("Billing Status").ClearAllFilters();
unbilled_ptable.PivotFields("Billing Status").CurrentPage = "Unbilled";
/* sort the pivot table by date */
unbilled_ptable.PivotFields("Date").AutoSort(1, "Date");
/* hide the "Job" that shows up for unpopulated rows in the source data */
var missing = Missing.Value;
unbilled_ptable.PivotFields("Job").PivotFilters.Add(16, missing, "0 - 0 - 0 - 0", missing, missing, missing, missing, missing);
/* collapse to dates */
unbilled_ptable.PivotFields("Date").ShowDetail = false;
/* format numbers in the pivot table */
Worksheet ws = ExcelAddinUtil.app.ActiveWorkbook.getWorksheet("Unbilled By Job");
Range r = ws.get_Range("B:H");
r.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)";
r = ws.get_Range("D:D,B:B");
r.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)";
}
}
catch { }
}
finally
{
ExcelAddinUtil.app.Visible = true;
}
}
}
}
}
private void btnRunReport_Click(object sender, EventArgs e)
{
if (!File.Exists(Template))
{
selectTemplateToolStripMenuItem_Click(null, null);
}
SysconCommon.Common.Environment.Connections.SetOLEDBFreeTableDirectory(txtDataDir.Text);
var nonbillable = Env.GetConfigVar("nonbillablecostcodes", "0", true)
.Split(',')
.Where(i => i != "")
.Select(i => decimal.Parse(i))
.ToArray();
var validjobtypes_delim = Env.GetConfigVar<string>("tmtypes", "", true);
var validjobtypes_strs = validjobtypes_delim.Split(',');
var validjobtypes = validjobtypes_delim.Trim() == "" ? new long[] { } : validjobtypes_strs.Select(i => Convert.ToInt64(i));
using (var con = SysconCommon.Common.Environment.Connections.GetOLEDBConnection())
{
long[] jobs = null;
if (this.radioShowTMJobs.Checked)
{
using (var jobtyps = con.GetTempDBF())
{
con.ExecuteNonQuery("create table {0} (jobtyp n(3, 0))", jobtyps);
foreach (var jt in validjobtypes)
{
con.ExecuteNonQuery("insert into {0} (jobtyp) values ({1})", jobtyps, jt);
}
jobs = (from x in con.GetDataTable("Jobnums", "select actrec.recnum from actrec join {0} jobtypes on actrec.jobtyp = jobtypes.jobtyp", jobtyps).Rows
select Convert.ToInt64(x["recnum"])).ToArray();
}
}
var job_selector = new MultiJobSelector(jobs);
job_selector.ShowDialog();
var jobnums = job_selector.SelectedJobNumbers.ToArray();
if (jobnums.Length > 0)
{
PopulateTemplate(Template, jobnums,
Convert.ToInt32(cmbStartingPeriod.SelectedItem), Convert.ToInt32(cmbEndPeriod.SelectedItem), dteTransactionDate.Value, nonbillable);
}
else
{
MessageBox.Show("No jobs selected.", "Error", MessageBoxButtons.OK);
}
}
}
private void cmbEndPeriod_SelectedIndexChanged(object sender, EventArgs e)
{
Env.SetConfigVar("endperiod", cmbEndPeriod.SelectedItem);
}
private void cmbStartingPeriod_SelectedIndexChanged(object sender, EventArgs e)
{
Env.SetConfigVar("startperiod", cmbStartingPeriod.SelectedItem);
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
var frm = new About();
frm.ShowDialog();
}
private void onlineHelpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://syscon-inc.com/product-support/2165/support.asp");
}
private void button1_Click(object sender, EventArgs e)
{
}
private void activateToolStripMenuItem_Click(object sender, EventArgs e)
{
var product_id = Env.GetConfigVar("product_id", 0, false);
var product_version = Env.GetConfigVar("product_version", "0.0.0.0", false);
var frm = new SysconCommon.Protection.ProtectionPlusOnlineActivationForm(product_id, product_version);
frm.ShowDialog();
this.OnLoad(null);
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void selectNonBillableCostCodesToolStripMenuItem_Click(object sender, EventArgs e)
{
var frm = new CostCodeSelector();
frm.ShowDialog();
var nonbillable = frm.NonBillableCostCodes.Select(i => i.ToString()).ToArray();
var nonbillablecostcodes = string.Join(",", nonbillable);
Env.SetConfigVar("nonbillablecostcodes", nonbillablecostcodes);
}
private void selectTMJobTypesToolStripMenuItem_Click(object sender, EventArgs e)
{
var frm = new TMTypes();
frm.ShowDialog();
var tmtypes = frm.TimeAndMaterialTypes;
var tmtypes_delimited = string.Join(",", tmtypes);
Env.SetConfigVar("tmtypes", tmtypes_delimited);
// make sure the correct jobs show up now
LoadValues();
}
private void selectMBDirToolStripMenuItem_Click(object sender, EventArgs e)
{
var dlg = new FolderBrowserDialog();
dlg.SelectedPath = Env.GetConfigVar("mbdir");
var rslt = dlg.ShowDialog();
if (rslt == DialogResult.OK)
{
var dir = dlg.SelectedPath + "\\";
if (!File.Exists(dir + "actrec.dbf"))
{
MessageBox.Show("Please choose a valid MB7 Path");
}
else
{
this.txtDataDir.Text = dir;
}
}
}
private void selectTemplateToolStripMenuItem_Click(object sender, EventArgs e)
{
var current_template = Template;
if (!File.Exists(current_template))
{
current_template = Env.GetEXEDirectory() + @"\" + DefaultTemplate;
}
var current_path = Path.GetDirectoryName(current_template);
var dlg = new OpenFileDialog();
dlg.FileName = Path.GetFileName(current_template);
dlg.DefaultExt = Path.GetExtension(current_template);
dlg.InitialDirectory = current_path;
dlg.Title = "Please select a template";
dlg.Multiselect = false;
//dlg.Filter = "Excel 2003 (*.xls)|*.xls|Excel 2007-2010 (*.xlsx)|*.xlsx|Excel Macro Workbook (*.xlsm)|*.xlsm";
dlg.Filter = "Excel Files (*.xls, *.xlsx, *.xlsm)|*.xls;*.xlsx;*.xlsm";
var rslt = dlg.ShowDialog();
if (rslt == System.Windows.Forms.DialogResult.OK)
{
Template = dlg.FileName;
}
}
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
var frm = new Settings();
frm.ShowDialog();
}
private void importFileToolStripMenuItem_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
// dlg.InitialDirectory = current_path;
dlg.Multiselect = false;
dlg.Filter = "Excel Macro Workbook (*.xlsm,*.xlsx)|*.xlsm;*.xlsx";
var rslt = dlg.ShowDialog();
if (rslt == System.Windows.Forms.DialogResult.OK)
{
import_file(dlg.FileName);
}
}
private void import_file(string filename)
{
using (var progress = new ProgressDialog(3))
{
progress.Show();
progress.Text = "Copying Required Files";
progress.Tick();
// first, make sure the audit log exists
if (!File.Exists(mbapi.smartGetSMBDir() + "/syscon_tm_log.DBF"))
{
File.Copy(Env.GetEXEDirectory() + "/syscon_tm_log.DBF", mbapi.smartGetSMBDir() + "/syscon_tm_log.DBF");
File.Copy(Env.GetEXEDirectory() + "/syscon_tm_log.FPT", mbapi.smartGetSMBDir() + "/syscon_tm_log.FPT");
}
// make a copy of the import file into Datadir + /Syscon TM Audit/<date>.xlsm
try
{
if (!Directory.Exists(mbapi.smartGetSMBDir() + "/Syscon TM Audit"))
Directory.CreateDirectory(mbapi.smartGetSMBDir() + "/Syscon TM Audit");
var today = DateTime.Today;
var dtestr = string.Format("{0}-{1}-{2}", today.Year, today.Month, today.Day);
int index = 1;
var ext = Path.GetExtension(filename);
var new_filename = string.Format("{0}/Syscon TM Audit/{1}_{2}{3}", mbapi.smartGetSMBDir(), dtestr, index, ext);
while (File.Exists(new_filename))
{
new_filename = string.Format("{0}/Syscon TM Audit/{1}_{2}{3}", mbapi.smartGetSMBDir(), dtestr, ++index, ext);
}
File.Copy(filename, new_filename);
filename = new_filename;
}
catch (Exception ex)
{
MessageBox.Show("Could not copy the file for auditing purposes, not updating SMB.\r\nPlease ensure the file is closed and try again.", "Error", MessageBoxButtons.OK);
Env.Log("{0}\r\n{1}", ex.Message, ex.StackTrace);
return;
}
var import_errors = false;
using (var excel_con = SysconCommon.Common.Environment.Connections.GetInMemoryDB())
{
using (var mb7_con = SysconCommon.Common.Environment.Connections.GetOLEDBConnection())
{
progress.Text = "Loading Excel (May take a while)";
progress.Tick();
// load the excel_con with values
ExcelAddinUtil.UseNewApp(_readonly: true);
try
{
var tempdt = ExcelAddinUtil.GetNamedRangeData(filename, "Change Summary", "ChangeSummary", true);
excel_con.LoadDataTable(tempdt);
}
finally
{
ExcelAddinUtil.CloseApp(false);
}
progress.Text = "Loading data into SMB";
progress.Tick();
// wrap it all in a transaction, so that if one thing fails, the db is not left in a corrupted state
// ARGHHH!!! Stupid SMB uses free tables, (no .dbc) so the rollback() seems to succeed but doesn't actually
// do anything.... god i hate Sage sometimes
try
{
// make sure there are approved changes to update
var chngrows_count = excel_con.GetScalar<int>("select count(*) from ChangeSummary where invalid = 0 and apprvd = 'Yes'");
if (chngrows_count == 0)
{
MessageBox.Show("No approved changes in spreadsheet.", "Error", MessageBoxButtons.OK);
return;
}
Func<string, long, bool> auditlog = (string msg, long recnum) =>
{
try
{
mb7_con.ExecuteNonQuery("insert into syscon_tm_log (recnum, usrnme, chgdsc, chgdte, chgpth) values ({0}, {1}, {2}, {3}, {4})"
, recnum
, mbapi.LoggedInUser.FoxproQuote()
, msg.FoxproQuote()
, DateTime.Today.ToFoxproDate()
, filename.FoxproQuote());
return true;
}
catch (Exception ex)
{
Env.Log("{0}\r\n{1}", ex.Message, ex.StackTrace);
import_errors = true;
return false;
}
};
// update billing status
var data_dt = excel_con.GetDataTable("Billing Status", "select recnum, bllsts from ChangeSummary where mbllsts = 1 and invalid = 0 and apprvd = 'Yes'");
foreach (var row in data_dt.Rows.ToIEnumerable())
{
try
{
var bllsts = 0;
switch (row["bllsts"].ToString().Trim().ToUpper())
{
case "UNBILLED":
bllsts = 1;
break;
case "NON-BILLABLE":
bllsts = 2;
break;
case "BILLED":
bllsts = 3;
break;
case "UNBILLABLE COST CODE":
bllsts = 2;
break;
default:
throw new SysconException("Invalid Billing Status ({0}) for jobcst record {1}", row["bllsts"], row["recnum"]);
}
mb7_con.ExecuteNonQuery("update jobcst set bllsts = {0} where recnum = {1}", bllsts, row["recnum"]);
auditlog("Updating Billing Status", Convert.ToInt64(row["recnum"]));
}
catch (Exception ex)
{
import_errors = true;
Env.Log("Error updating Jobcost {2}: {0}\r\n{1}", ex.Message, ex.StackTrace, row["recnum"]);
}
}
// update billing overrides
data_dt = excel_con.GetDataTable("Billing Overrides", "select recnum, bllamt from ChangeSummary where mbllovrrde = 1 and invalid = 0 and apprvd = 'Yes'");
foreach (var row in data_dt.Rows.ToIEnumerable())
{
try
{
mb7_con.ExecuteNonQuery("update jobcst set ovrrde = 1, blgamt = {0} where recnum = {1}", row["bllamt"], row["recnum"]);
auditlog("updated billing amount", Convert.ToInt64(row["recnum"]));
}
catch (Exception ex)
{
import_errors = true;
Env.Log("Error updating Jobcst {2}: {0}\r\n{1}", ex.Message, ex.StackTrace, row["recnum"]);
}
}
// update cost codes
data_dt = excel_con.GetDataTable("Cost Codes", "select recnum, cstcde from ChangeSummary where mcstcde = 1 and invalid = 0 and apprvd = 'Yes'");
foreach (var row in data_dt.Rows.ToIEnumerable())
{
try
{
mb7_con.ExecuteNonQuery("update jobcst set cstcde = {0} where recnum = {1}", row["cstcde"], row["recnum"]);
auditlog("updated cost code", Convert.ToInt64(row["recnum"]));
}
catch (Exception ex)
{
import_errors = true;
Env.Log("Error updating Jobcst {0}: {1}\r\n{2}", row["recnum"], ex.Message, ex.StackTrace);
}
}
// update notes
data_dt = excel_con.GetDataTable("Notes", "select recnum, newntes from ChangeSummary where mnotes = 1 and invalid = 0 and apprvd = 'Yes'");
foreach (var row in data_dt.Rows.ToIEnumerable())
{
try
{
var new_ntetxt = row["newntes"].ToString().Trim();
var old_ntetxt = mb7_con.GetScalar<string>("select ntetxt from jobcst where recnum = {0}", row["recnum"]);
new_ntetxt = new_ntetxt.Replace("\r\n", new string(new char[] { (char)124 }));
new_ntetxt += new string(new char[] { (char)124 });
var ntetxt = new_ntetxt + old_ntetxt;
mb7_con.ExecuteNonQuery("update jobcst set ntetxt = {0} where recnum = {1}", ntetxt.FoxproQuote(), row["recnum"]);
auditlog("Updated Notes", Convert.ToInt64(row["recnum"]));
}
catch (Exception ex)
{
import_errors = true;
Env.Log("Error updating Jobcst {2}: {0}\r\n{1}", ex.Message, ex.StackTrace, row["recnum"]);
}
}
// update partial billings - this must happen last so that any other changes are copied to the new record correctly
data_dt = excel_con.GetDataTable("Partial Billings", "select recnum, originalbllqty, bllqty from ChangeSummary where mbllhours = 1 and invalid = 0 and apprvd = 'Yes'");
foreach (var row in data_dt.Rows.ToIEnumerable())
{
try
{
// as an extra-check so this doesn't happen twice because that would be detrimental, make sure
// that the original billing quantity matches that that is in SMB currently
var smb_bllqty = mb7_con.GetScalar<decimal>("select blgqty from jobcst where recnum = {0}", row["recnum"]);
var orig_bllqty = Convert.ToDecimal(row["originalbllqty"]);
if (smb_bllqty != orig_bllqty)
{
throw new SysconException("SMB billing quantity ({0}) does not match original billing quantity ({1})", smb_bllqty, orig_bllqty);
}
// create a new jobcst record with the difference
var jobcst_row = mb7_con.GetDataTable("Job Cost", "select * from jobcst where recnum = {0}", row["recnum"]).Rows[0];
jobcst_row["cstamt"] = 0.0m;
jobcst_row["payrec"] = 0;
jobcst_row["csthrs"] = 0;
jobcst_row["paytyp"] = 0;
jobcst_row["blgqty"] = orig_bllqty - Convert.ToDecimal(row["bllqty"]);
jobcst_row["srcnum"] = Env.GetConfigVar<int>("NewJobcostSource", 31, true);
jobcst_row["usrnme"] = jobcst_row["usrnme"].ToString().Trim() + "-Import";
jobcst_row["ntetxt"] = string.Format("{0}: Split from original billing record #{1}", DateTime.Now, row["recnum"]);
jobcst_row["recnum"] = mb7_con.GetScalar<long>("select max(recnum) + 1 from jobcst");
// jobcst_row["ovrrde"] = 1;
// insert the record
var sql = jobcst_row.FoxproInsertString("jobcst");
mb7_con.ExecuteNonQuery(sql);
auditlog(string.Format("Split from {0}", row["recnum"]), Convert.ToInt64(jobcst_row["recnum"]));
// update the billing quantity
mb7_con.ExecuteNonQuery("update jobcst set blgqty = {0}, ntetxt = {2} + ntetxt where recnum = {1}", row["bllqty"], row["recnum"],
string.Format("{0} - Partial Billing, new record (#{1}) added{2}", DateTime.Now, jobcst_row["recnum"], (char)124).FoxproQuote());
auditlog("Set to partial billing", Convert.ToInt64(row["recnum"]));
}
catch (Exception ex)
{
import_errors = true;
Env.Log("Error updating Jobcst {2}: {0}\r\n{1}", ex.Message, ex.StackTrace, row["recnum"]);
}
}
if (import_errors)
{
throw new SysconException("Error Importing Data.");
}
MessageBox.Show("File imported successfully.", "Success", MessageBoxButtons.OK);
}
catch (Exception ex)
{
MessageBox.Show("Error updating SMB data, see logfile for details");
Env.Log(string.Format("Error updating SMB data: {0}\r\n{1}", ex.Message, ex.StackTrace));
}
}
}
}
}
private void chkUnbilled_CheckedChanged(object sender, EventArgs e)
{
Env.SetConfigVar("ExportUnbilledOnly", chkUnbilled.Checked);
}
private void btnSMBDir_Click(object sender, EventArgs e)
{
// Env.SetConfigFile(Env.GetEXEDirectory() + "/config.xml");
mbapi.smartSelectSMBDirByGUI();
var usr = mbapi.RequireSMBLogin();
if (usr != null)
{
txtDataDir.Text = mbapi.smartGetSMBDir();
}
}
private void viewAuditLogToolStripMenuItem_Click(object sender, EventArgs e)
{
var frm = new ViewAuditLog(mbapi);
frm.ShowDialog();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace Socket_Client
{
public partial class Form1 : Form
{
private Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Form1()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
richTextBox1.Multiline = true; //将Multiline属性设置为true,实现显示多行
richTextBox1.ScrollBars = RichTextBoxScrollBars.Vertical;
}
private void richTextBox1_TextChanged(object sender, EventArgs e)//显示是否连接成功
{
}
private void textBox1_TextChanged(object sender, EventArgs e)//IP
{
}
private void textBox2_TextChanged(object sender, EventArgs e)//PORT
{
}
private void button1_Click(object sender, EventArgs e)//连接服务器
{
int Port = Convert.ToInt32(textBox2.Text);
IPAddress IP = IPAddress.Parse((string)textBox1.Text);
try
{
ClientSocket.Connect(new IPEndPoint(IP, Port));
richTextBox1.Text += "连接服务器成功!\r\n";
Thread thread = new Thread(ReceiveMessage);
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
richTextBox1.Text += "连接服务器失败!\r\n";
return;
}
}
private void ReceiveMessage()
{
long TotalLength = 0;
while (true)
{
byte[] result = new byte[1024 * 1024];
int ReceiveLength = 0;
try
{
ReceiveLength = ClientSocket.Receive(result);
if (result[0] == 0)//表示接收到的是消息
{
try
{
richTextBox1.Text += "接收服务器消息:\r\n";
string str = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1);
richTextBox1.Text += str + "\r\n";
}
catch (Exception ex)
{
richTextBox1.Text += "接收消息失败!\r\n";
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
break;
}
}
}
catch(Exception ex)
{
MessageBox.Show("接收异常!");
break;
}
}
}
private void button2_Click(object sender, EventArgs e)//发送消息
{
try
{
richTextBox1.Text += "向服务器发送消息:\r\n";
richTextBox1.Text += textBox3.Text + "\r\n";
string str = textBox3.Text;
string Client = ClientSocket.RemoteEndPoint.ToString();
string SendMessage = "接收客户端" + Client + "消息:" + DateTime.Now + "\r\n" + str + "\r\n";
byte[] result1 = Encoding.UTF8.GetBytes(SendMessage);
byte[] result = new byte[result1.Length + 1];
result[0] = 0;
Buffer.BlockCopy(result1, 0, result, 1, result1.Length);
ClientSocket.Send(result);
textBox3.Clear();
}
catch (Exception ex)
{
richTextBox1.Text += "发送消息失败,服务器可能已经关闭!\r\n";
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
}
}
private void textBox3_TextChanged(object sender, EventArgs e)//发送消息
{
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.ContentSecurityPolicy
{
/// <summary>
/// The frame-ancestors directive specifies valid parents that may embed a page using
/// <frame>, <iframe>, <object>, <embed>, or <applet>.
/// Setting this directive to 'none' is similar to X-Frame-Options: DENY (which is also supported in older browers).
/// </summary>
public class FrameAncestorsDirectiveBuilder : CspDirectiveBuilderBase
{
/// <summary>
/// Initializes a new instance of the <see cref="FrameAncestorsDirectiveBuilder"/> class.
/// </summary>
public FrameAncestorsDirectiveBuilder() : base("frame-ancestors")
{
}
/// <summary>
/// The sources from which the directive is allowed.
/// </summary>
public List<string> Sources { get; } = new List<string>();
/// <summary>
/// If true, no sources are allowed.
/// </summary>
public bool BlockResources { get; set; } = false;
/// <inheritdoc />
internal override Func<HttpContext, string> CreateBuilder()
{
if (BlockResources)
{
return ctx => GetPolicy("'none'");
}
return ctx => GetPolicy(string.Join(" ", Sources));
}
private string GetPolicy(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
return $"{Directive} {value}";
}
/// <summary>
/// Allow sources from the origin from which the protected document is being served, including the same URL scheme and port number
/// </summary>
/// <returns>The CSP builder for method chaining</returns>
public FrameAncestorsDirectiveBuilder Self()
{
Sources.Add("'self'");
return this;
}
/// <summary>
/// Allows blob: URIs to be used as a content source
/// </summary>
/// <returns>The CSP builder for method chaining</returns>
public FrameAncestorsDirectiveBuilder Blob()
{
Sources.Add("blob:");
return this;
}
/// <summary>
/// data: Allows data: URIs to be used as a content source.
/// WARNING: This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts.
/// </summary>
/// <returns>The CSP builder for method chaining</returns>
public FrameAncestorsDirectiveBuilder Data()
{
Sources.Add("data:");
return this;
}
/// <summary>
/// Block the resource (Refers to the empty set; that is, no URLs match)
/// </summary>
/// <returns>The CSP builder for method chaining</returns>
public FrameAncestorsDirectiveBuilder None()
{
BlockResources = true;
return this;
}
/// <summary>
/// Allow resources from the given <paramref name="uri"/>. May be any non-empty value
/// </summary>
/// <param name="uri">The URI to allow.</param>
/// <returns>The CSP builder for method chaining</returns>
public FrameAncestorsDirectiveBuilder From(string uri)
{
if (string.IsNullOrWhiteSpace(uri))
{
throw new System.ArgumentException("Uri may not be null or empty", nameof(uri));
}
Sources.Add(uri);
return this;
}
/// <summary>
/// Allow resources served over https
/// </summary>
/// <returns>The CSP builder for method chaining</returns>
public FrameAncestorsDirectiveBuilder OverHttps()
{
Sources.Add("https:");
return this;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIPlayerComponent : MonoBehaviour
{
private Image UIElement;
public bool IsEnabled { get; set; } = false;
// Start is called before the first frame update
void Start()
{
UIElement = GetComponentInChildren<Image>();
UIElement.enabled = IsEnabled;
}
// Update is called once per frame
void Update()
{
if(UIElement.enabled != IsEnabled)
{
UIElement.enabled = IsEnabled;
}
}
}
|
namespace Airelax.Application.Comments.Dtos.Response
{
public class HouseCommentViewModel
{
public string HouseId { get; set; }
public string HouseName { get; set; }
public int HouseState { get; set; }
public CommentViewModel[] Comments { get; set; }
}
public class CommentViewModel
{
public string CommentId { get; set; }
public string CommentTime { get; set; }
public string AuthorName { get; set; }
public string Content { get; set; }
public double Stars { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LeanEngine.Entity;
namespace LeanEngine.Business
{
public class BidItemFlow
{
public ItemFlow getWinBidItemFlow(List<ItemFlow> itemFlows)
{
if (itemFlows == null || itemFlows.Count == 0)
return null;
//base filter
var q01 = itemFlows.Where(i => i.Flow.OrderTime <= DateTime.Now && i.ReqQty > 0).ToList();
if (q01.Count == 0)
return null;
else if (q01.Count == 1)
return q01[0];
//Bidding start,if count=0,then next
//1.Supplying rate
var q11 = q01.Where(i => i.SupplyingRate > 0 && i.AcmlOrderedQty >= 0).ToList();
if (q11.Count == 1)
return q11[0];
else if (q11.Count > 1)
{
//Priority
//1) AcmlOrderedQty=0 and SupplyingRate larger
//2) AcmlOrderedQty / SupplyingRate result smaller
//var q12 = q11.OrderBy(i => i.AcmlOrderedQty / i.SupplyingRate).OrderByDescending(i => i.SupplyingRate).ToList();
var q12 = (from q in q11
let a = q.AcmlOrderedQty / q.SupplyingRate
orderby a, q.SupplyingRate descending
select q).ToList();
if (q12.Count > 0)
return q12[0];
}
//default return value
return q01[0];
}
}
}
|
using BoardGame.Domain_Model;
using System;
using System.Windows.Forms;
namespace BoardGame
{
public enum Abilities { Kereskedelem, Régész, Vállalkozó, Óvatos, Őrangyal, Szárnysegéd, Talpraesett, Tolvaj}
public partial class PassiveCard : Form
{
private Cards m_Cards;
private Player m_Player;
private Robot m_Robot1;
private Robot m_Robot2;
private Robot m_Robot3;
private int m_Turn;
public Abilities PassiveAbility { get; set; }
public int AbilityValue {get; set;}
public bool NoPassiveCard { get; set; }
public PassiveCard(int turn, Player player, Robot robot1, Robot robot2, Robot robot3, Cards card)
{
InitializeComponent();
this.m_Player = player;
this.m_Robot1 = robot1;
this.m_Robot2 = robot2;
this.m_Robot3 = robot3;
this.m_Turn = turn;
this.m_Cards = card;
Random randomCard = new Random();
int randomCardNumber = randomCard.Next(0, m_Cards.PassiveCards.Count);
switch (m_Turn)
{
case 0: //player turn
PlayerOrRobotName.Text = m_Player.Name;
DrawingAPassiveCard(randomCardNumber, m_Player, null);
break;
case 1: //robot1 turn
PlayerOrRobotName.Text = m_Robot1.Name;
DrawingAPassiveCard(randomCardNumber, null, m_Robot1);
break;
case 2: //robot2 turn
PlayerOrRobotName.Text = m_Robot2.Name;
DrawingAPassiveCard(randomCardNumber, null, m_Robot2);
break;
case 3: //robot3 turn
PlayerOrRobotName.Text = m_Robot3.Name;
DrawingAPassiveCard(randomCardNumber, null, m_Robot3);
break;
default:
throw new Exception("Turn is not exist");
}
}
private void Ok_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
this.Close();
}
private void DrawingAPassiveCard(int randomCardNumber, Player m_Player, Robot m_Robot)
{
if (m_Cards.PassiveCards.Count == 0)
{
Message.Text = "A passzív kártyák elfogytak";
NoPassiveCard = true;
}
else
{
for (int i = 0; i < m_Cards.PassiveCards.Count; i++)
{
if (i == randomCardNumber)
{
if (m_Cards.PassiveCards[i].AbilityValue > 0)
{
AbilityText.Text = m_Cards.PassiveCards[i].SpecialPassiveAbility + " (" + m_Cards.PassiveCards[i].AbilityValue + " db)";
}
else
{
AbilityText.Text = m_Cards.PassiveCards[i].SpecialPassiveAbility + " (végtelen)";
}
if (m_Player != null)
{
PassiveAbility = (Abilities)Enum.Parse(typeof(Abilities), m_Cards.PassiveCards[i].SpecialPassiveAbility);
AbilityValue = m_Cards.PassiveCards[i].AbilityValue;
m_Player.MyPassiveCards.Add(m_Cards.PassiveCards[i]);
}
else if (m_Robot != null)
{
PassiveAbility = (Abilities)Enum.Parse(typeof(Abilities), m_Cards.PassiveCards[i].SpecialPassiveAbility);
AbilityValue = m_Cards.PassiveCards[i].AbilityValue;
m_Robot.MyPassiveCards.Add(m_Cards.PassiveCards[i]);
}
m_Cards.PassiveCards.Remove(m_Cards.PassiveCards[i]);
}
}
}
}
}
}
|
// <copyright file="Adjustment.cs" company="WaterTrans">
// © 2020 WaterTrans
// </copyright>
namespace WaterTrans.GlyphLoader.OpenType
{
/// <summary>
/// The GPOS adjustment.
/// </summary>
public class Adjustment
{
/// <summary>
/// Initializes a new instance of the <see cref="Adjustment"/> class.
/// </summary>
/// <param name="xPlacement">The value of a horizontal adjustment for placement.</param>
/// <param name="yPlacement">The value of a vertical adjustment for placement.</param>
/// <param name="xAdvance">The value of a horizontal adjustment for advance.</param>
/// <param name="yAdvance">The value of a vertical adjustment for advance.</param>
/// <param name="unitsPerEm">The units per em in 'head' table.</param>
internal Adjustment(short xPlacement, short yPlacement, short xAdvance, short yAdvance, ushort unitsPerEm)
{
XPlacement = (double)xPlacement / unitsPerEm;
YPlacement = (double)yPlacement / unitsPerEm;
XAdvance = (double)xAdvance / unitsPerEm;
YAdvance = (double)yAdvance / unitsPerEm;
}
/// <summary>Gets a horizontal adjustment for placement.</summary>
public double XPlacement { get; }
/// <summary>Gets a vertical adjustment for placement.</summary>
public double YPlacement { get; }
/// <summary>Gets a horizontal adjustment for advance.</summary>
public double XAdvance { get; }
/// <summary>Gets a vertical adjustment for advance.</summary>
public double YAdvance { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PagedList;
using WebGrease.Css.Extensions;
using WebQLKhoaHoc.Models;
using System.IO;
using System.Data.Entity.Migrations;
using Newtonsoft.Json;
using LinqKit;
namespace WebQLKhoaHoc.Controllers
{
public class DeTaisController : Controller
{
private QLKhoaHocEntities db = new QLKhoaHocEntities();
private QLKHRepository QLKHrepo = new QLKHRepository();
// GET: DeTais
public async Task<ActionResult> Index(int? Page_No, [Bind(Include = "MaCapDeTai,MaDonViQLThucHien,MaLinhVuc,Fromdate,Todate,SearchValue")] DeTaiSearchViewModel detai,int? nkhId)
{
var pre = PredicateBuilder.True<DeTai>();
if (nkhId == null)
{
if (!String.IsNullOrEmpty(detai.MaDonViQLThucHien))
{
pre = pre.And(p => p.MaDonViQLThucHien.ToString() == detai.MaDonViQLThucHien);
}
if (!String.IsNullOrEmpty(detai.MaLinhVuc))
{
if (detai.MaLinhVuc[0] == 'a')
pre = pre.And(p => p.MaLinhVuc.ToString() == detai.MaLinhVuc.Substring(1, detai.MaLinhVuc.Length - 1));
else
pre = pre.And(p => p.LinhVuc.MaNhomLinhVuc.ToString() == detai.MaLinhVuc);
}
if (detai.Fromdate > DateTime.MinValue)
{
pre = pre.And(p => p.NamBD >= detai.Fromdate);
}
if (detai.Todate > DateTime.MinValue)
{
pre = pre.And(p => p.NamKT <= detai.Todate);
}
if (!String.IsNullOrEmpty(detai.SearchValue))
{
pre = pre.And(p => p.TenDeTai.ToLower().Contains(detai.SearchValue.ToLower()));
}
}
else
{
var madetais = db.DSNguoiThamGiaDeTais.Where(p => p.MaNKH == nkhId).Select(p => p.MaDeTai).ToList();
pre = pre.And(p => madetais.Contains(p.MaDeTai));
}
/* Nếu Thời gian search được nhập thì mới đỏ vào view bag */
if (detai.Fromdate > DateTime.MinValue && detai.Todate > DateTime.MinValue) {
ViewBag.Fromdate = detai.Fromdate.ToShortDateString();
ViewBag.Todate = detai.Todate.ToShortDateString();
}
ViewBag.SearchValue = detai.SearchValue;
ViewBag.DSCapDeTai = new SelectList(db.CapDeTais, "MaCapDeTai", "TenCapDeTai");
ViewBag.MaDonViQLThucHien = new SelectList(db.DonViQLs, "MaDonVi", "TenDonVI");
ViewBag.MaLinhVuc = new SelectList(QLKHrepo.GetListMenuLinhVuc(), "Id", "TenLinhVuc");
int No_Of_Page = (Page_No ?? 1);
var detais = db.DeTais.Include(d => d.CapDeTai).Include(d => d.LoaiHinhDeTai).Include(d => d.DonViChuTri).Include(d => d.DonViQL).Include(d => d.LinhVuc).Include(d => d.XepLoai).Include(d => d.TinhTrangDeTai).Include(d => d.PhanLoaiSP).Include(d => d.DSNguoiThamGiaDeTais).AsExpandable().Where(pre).OrderBy(p=>p.MaDeTai).Skip((No_Of_Page-1)*6).Take(6).ToList();
decimal totalItem = (decimal)db.DeTais.Where(pre).OrderBy(p => p.MaDeTai).Count();
int totalPage = (int)Math.Ceiling(totalItem / 6);
ViewBag.TotalItem = totalItem;
IPagedList<DeTai> pageOrders = new StaticPagedList<DeTai>(detais, No_Of_Page, 1, totalPage);
return View(pageOrders);
}
public async Task<ActionResult> Create()
{
var lstAllNKH = db.NhaKhoaHocs.Select(p => new
{
p.MaNKH,
TenNKH = p.HoNKH + " " + p.TenNKH
}).ToList();
ViewBag.MaCapDeTai = new SelectList(db.CapDeTais, "MaCapDeTai", "TenCapDeTai");
ViewBag.MaLoaiDeTai = new SelectList(db.LoaiHinhDeTais, "MaLoaiDT", "TenLoaiDT");
ViewBag.MaDVChuTri = new SelectList(db.DonViChuTris, "MaDVChuTri", "TenDVChuTri");
ViewBag.MaDonViQLThucHien = new SelectList(db.DonViQLs, "MaDonVi", "TenDonVI");
ViewBag.MaLinhVuc = new SelectList(db.LinhVucs, "MaLinhVuc", "TenLinhVuc");
ViewBag.MaXepLoai = new SelectList(db.XepLoais, "MaXepLoai", "TenXepLoai");
ViewBag.MaTinhTrang = new SelectList(db.TinhTrangDeTais, "MaTinhTrang", "TenTinhTrang");
ViewBag.MaPhanLoaiSP = new SelectList(db.PhanLoaiSPs, "MaPhanLoai", "TenPhanLoai");
ViewBag.DSNguoiThamGiaDeTai = new MultiSelectList(lstAllNKH, "MaNKH", "TenNKH");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(List<string> DSNguoiThamGiaDT, [Bind(Include = "MaDeTai,MaDeTaiHoSo,TenDeTai,MaLoaiDeTai,MaCapDeTai," +
"MaDVChuTri,MaDonViQLThucHien,MaLinhVuc,MucTieuDeTai,NoiDungDeTai," +
"KetQuaDeTai,NamBD,NamKT,KinhPhi,MaXepLoai,MaTinhTrang,MaPhanLoaiSP,LienKetWeb")] DeTai deTai,
HttpPostedFileBase linkUpload, string KinhPhiMoi)
{
if (ModelState.IsValid)
{
/* file upload*/
if (linkUpload != null && linkUpload.ContentLength > 0)
{
string filename = Path.GetFileNameWithoutExtension(linkUpload.FileName) + "_" + deTai.MaDeTai.ToString() + Path.GetExtension(linkUpload.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads/detai_file"), filename);
linkUpload.SaveAs(path);
deTai.LinkFileUpload = filename;
}
db.DeTais.Add(deTai);
db.SaveChanges();
var id = deTai.MaDeTai;
if (KinhPhiMoi != null)
{
List<string[]> kinhphimoi = JsonConvert.DeserializeObject<List<string[]>>(KinhPhiMoi);
foreach (var x in kinhphimoi)
{
KinhPhiDeTai kinhphi_x = new KinhPhiDeTai
{
MaDeTai = id,
LoaiKinhPhi = x[0],
NamTiepNhan = DateTime.Parse(x[1]),
SoTien = Int32.Parse(x[2]),
LoaiTien = x[3]
};
db.KinhPhiDeTais.Add(kinhphi_x);
db.SaveChanges();
}
}
UserLoginViewModel user = (UserLoginViewModel)Session["user"];
db.DSNguoiThamGiaDeTais.Add(new DSNguoiThamGiaDeTai {
LaChuNhiem = true,
MaDeTai = id,
MaNKH = user.MaNKH
});
if (DSNguoiThamGiaDT != null)
{
List<DSNguoiThamGiaDeTai> ds = new List<DSNguoiThamGiaDeTai>();
foreach (var mankh in DSNguoiThamGiaDT)
{
ds.Add(new DSNguoiThamGiaDeTai
{
LaChuNhiem = false,
MaDeTai = id,
MaNKH = Int32.Parse(mankh)
});
}
db.DSNguoiThamGiaDeTais.AddRange(ds);
}
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
var lstAllNKH = db.NhaKhoaHocs.Where(p => p.MaNKH != 1).Select(p => new
{
p.MaNKH,
TenNKH = p.HoNKH + " " + p.TenNKH
}).ToList();
ViewBag.MaCapDeTai = new SelectList(db.CapDeTais, "MaCapDeTai", "TenCapDeTai");
ViewBag.MaLoaiDeTai = new SelectList(db.LoaiHinhDeTais, "MaLoaiDT", "TenLoaiDT");
ViewBag.MaDVChuTri = new SelectList(db.DonViChuTris, "MaDVChuTri", "TenDVChuTri");
ViewBag.MaDonViQLThucHien = new SelectList(db.DonViQLs, "MaDonVi", "TenDonVI");
ViewBag.MaLinhVuc = new SelectList(db.LinhVucs, "MaLinhVuc", "TenLinhVuc");
ViewBag.MaXepLoai = new SelectList(db.XepLoais, "MaXepLoai", "TenXepLoai");
ViewBag.MaTinhTrang = new SelectList(db.TinhTrangDeTais, "MaTinhTrang", "TenTinhTrang");
ViewBag.MaPhanLoaiSP = new SelectList(db.PhanLoaiSPs, "MaPhanLoai", "TenPhanLoai");
ViewBag.DSNguoiThamGiaDeTai = new MultiSelectList(lstAllNKH, "MaNKH", "TenNKH");
return View();
}
}
// GET: DeTais/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DeTai deTai = await db.DeTais.FindAsync(id);
if (deTai == null)
{
return HttpNotFound();
}
return View(deTai);
}
public async Task<ActionResult> ScriptingPage(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DeTai deTai = await db.DeTais.FindAsync(id);
if (deTai == null)
{
return HttpNotFound();
}
return View(deTai);
}
// GET: DeTais/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DeTai deTai = await db.DeTais.FindAsync(id);
if (deTai == null)
{
return HttpNotFound();
}
var lstAllNKH = db.NhaKhoaHocs.Select(p => new
{
p.MaNKH,
TenNKH = p.HoNKH + " " + p.TenNKH
}).ToList();
var lstNKH = db.NhaKhoaHocs.Where(p => p.DSNguoiThamGiaDeTais.Any(d => d.MaDeTai == deTai.MaDeTai && d.LaChuNhiem == false)).Select(p => p.MaNKH).ToList();
ViewBag.MaCapDeTai = new SelectList(db.CapDeTais, "MaCapDeTai", "TenCapDeTai", deTai.MaCapDeTai);
ViewBag.MaLoaiDeTai = new SelectList(db.LoaiHinhDeTais, "MaLoaiDT", "TenLoaiDT", deTai.MaLoaiDeTai);
ViewBag.MaDVChuTri = new SelectList(db.DonViChuTris, "MaDVChuTri", "TenDVChuTri", deTai.MaDVChuTri);
ViewBag.MaDonViQLThucHien = new SelectList(db.DonViQLs, "MaDonVi", "TenDonVI", deTai.MaDonViQLThucHien);
ViewBag.MaLinhVuc = new SelectList(db.LinhVucs, "MaLinhVuc", "TenLinhVuc", deTai.MaLinhVuc);
ViewBag.MaXepLoai = new SelectList(db.XepLoais, "MaXepLoai", "TenXepLoai", deTai.MaXepLoai);
ViewBag.MaTinhTrang = new SelectList(db.TinhTrangDeTais, "MaTinhTrang", "TenTinhTrang", deTai.MaTinhTrang);
ViewBag.MaPhanLoaiSP = new SelectList(db.PhanLoaiSPs, "MaPhanLoai", "TenPhanLoai", deTai.MaPhanLoaiSP);
ViewBag.DSNguoiThamGiaDeTai = new MultiSelectList(lstAllNKH, "MaNKH","TenNKH",lstNKH);
return View(deTai);
}
// POST: DeTais/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(List<string> DSNguoiThamGiaDT,[Bind(Include = "MaDeTai,MaDeTaiHoSo,TenDeTai,MaLoaiDeTai,MaCapDeTai,MaDVChuTri,MaDonViQLThucHien,MaLinhVuc,MucTieuDeTai,NoiDungDeTai,KetQuaDeTai,NamBD,NamKT,KinhPhi,MaXepLoai,MaTinhTrang,MaPhanLoaiSP,LienKetWeb")] DeTai deTai, HttpPostedFileBase linkUpload,string KinhPhiXoa,string KinhPhiMoi)
{
var detai = db.DeTais.Where(p => p.MaDeTai == deTai.MaDeTai).Include(p=>p.KinhPhiDeTais).Include(p=>p.DSNguoiThamGiaDeTais).FirstOrDefault();
if (ModelState.IsValid)
{
if (linkUpload != null && linkUpload.ContentLength > 0)
{
string filename = Path.GetFileNameWithoutExtension(linkUpload.FileName) + "_" + deTai.MaDeTai.ToString() + Path.GetExtension(linkUpload.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads/detai_file"), filename);
if (!String.IsNullOrEmpty(detai.LinkFileUpload))
{
string oldpath = Path.Combine(Server.MapPath("~/App_Data/uploads/detai_file"), detai.LinkFileUpload);
if (System.IO.File.Exists(oldpath))
{
System.IO.File.Delete(oldpath);
}
}
linkUpload.SaveAs(path);
deTai.LinkFileUpload = filename;
}
else
{
deTai.LinkFileUpload = detai.LinkFileUpload;
}
db.DeTais.AddOrUpdate(deTai);
db.DSNguoiThamGiaDeTais.Where(p => p.MaDeTai == deTai.MaDeTai && p.LaChuNhiem == false).ForEach(x => db.DSNguoiThamGiaDeTais.Remove(x));
if (KinhPhiXoa != "")
{
List<int> kinhphixoa = JsonConvert.DeserializeObject<List<int>>(KinhPhiXoa);
db.KinhPhiDeTais.Where(p => kinhphixoa.Contains(p.MaPhi)).ForEach(p => db.KinhPhiDeTais.Remove(p));
}
db.SaveChanges();
/* phần xử lý thêm xóa sửa của kinh phí đề tài */
if (KinhPhiMoi != "")
{
if (KinhPhiMoi != "")
{
List<string[]> kinhphimoi = JsonConvert.DeserializeObject<List<string[]>>(KinhPhiMoi);
foreach (var x in kinhphimoi)
{
KinhPhiDeTai kinhphi_x = new KinhPhiDeTai
{
MaDeTai = Int32.Parse(x[0]),
LoaiKinhPhi = x[1],
NamTiepNhan = DateTime.Parse(x[2]),
SoTien = Int32.Parse(x[3]),
LoaiTien = x[4]
};
db.KinhPhiDeTais.Add(kinhphi_x);
}
}
}
if (DSNguoiThamGiaDT != null)
{
foreach (var mankh in DSNguoiThamGiaDT)
{
DSNguoiThamGiaDeTai nguoiTGDT = new DSNguoiThamGiaDeTai
{
LaChuNhiem = false,
MaDeTai = deTai.MaDeTai,
MaNKH = Int32.Parse(mankh)
};
db.DSNguoiThamGiaDeTais.AddOrUpdate(nguoiTGDT);
}
}
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
else
{
ViewBag.MaCapDeTai = new SelectList(db.CapDeTais, "MaCapDeTai", "TenCapDeTai", deTai.MaCapDeTai);
ViewBag.MaLoaiDeTai = new SelectList(db.LoaiHinhDeTais, "MaLoaiDT", "TenLoaiDT", deTai.MaLoaiDeTai);
ViewBag.MaDVChuTri = new SelectList(db.DonViChuTris, "MaDVChuTri", "TenDVChuTri", deTai.MaDVChuTri);
ViewBag.MaDonViQLThucHien = new SelectList(db.DonViQLs, "MaDonVi", "TenDonVI", deTai.MaDonViQLThucHien);
ViewBag.MaLinhVuc = new SelectList(db.LinhVucs, "MaLinhVuc", "TenLinhVuc", deTai.MaLinhVuc);
ViewBag.MaXepLoai = new SelectList(db.XepLoais, "MaXepLoai", "TenXepLoai", deTai.MaXepLoai);
ViewBag.MaTinhTrang =
new SelectList(db.TinhTrangDeTais, "MaTinhTrang", "TenTinhTrang", deTai.MaTinhTrang);
ViewBag.MaPhanLoaiSP = new SelectList(db.PhanLoaiSPs, "MaPhanLoai", "TenPhanLoai", deTai.MaPhanLoaiSP);
return View(deTai);
}
}
// POST: DeTais/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
DeTai deTai = await db.DeTais.FindAsync(id);
db.DeTais.Remove(deTai);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
//***LICENSE:******************************************************************
// Copyright (c) 2012, Adam Caudill <adam@adamcaudill.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1). Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2). Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//*****************************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ccsrch_score
{
public static class Scores
{
/// <summary>
/// Returns the number of distinct digits, devided by 2. Minimum value is 1.
/// </summary>
/// <param name="hit"></param>
/// <returns></returns>
public static int DistinctDigitScore(string hit)
{
var count = hit.ToCharArray().Distinct().Count();
return Math.Max((int)Math.Ceiling(count/2D), 1);
}
public static int CommonFalsePositiveScore(string hit)
{
var ret = 0;
if (hit == "344455566677788")
ret = -99;
return ret;
}
public static int FileTypeScore(string hit, string path)
{
var ext = Path.GetExtension(path);
var ret = 0;
switch (ext)
{
case ".rtf":
case ".pdf":
ret = -3;
break;
case ".pdb":
case ".dll":
case ".exe":
case ".png":
case ".gif":
case ".jpg":
case ".jpeg":
case ".bmp":
case ".psd":
case ".dng":
case ".nef":
case ".wmv":
case ".mov":
case ".jar":
case ".cab":
case ".msi":
case ".zip":
case ".manifest":
ret = -99;
break;
}
return ret;
}
public static int FileNameScore(string hit, string path)
{
var fileName = Path.GetFileName(path);
var ret = 0;
switch (fileName.ToLower())
{
case "ntuser.dat":
case "iconcache.db":
ret = -99;
break;
case "index.dat":
ret = -3;
break;
}
return ret;
}
public static bool IsKnownBin(string hit, List<string> bins)
{
var bin = hit.Substring(0, 6);
var ret = false;
if (bins.Contains(bin))
ret = true;
return ret;
}
}
}
|
using gView.Framework.Symbology;
namespace gView.Framework.Carto
{
public interface IFeatureRenderer2 : IFeatureRenderer
{
ISymbol Symbol { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LaptopShop
{
class Laptop
{
private string model;
private string manufacturer;
private string proccesor;
private string ram;
private string hdd;
private string screen;
private string card;
private decimal price;
private string batteryName;
private string life;
public Laptop(string model,decimal price,Battery battery = null)
{
this.model = model;
this.price = price;
if (battery != null)
{
this.batteryName = battery.BatteryName;
this.life = battery.Life;
}
}
public string Manufacturer
{
get
{
return this.manufacturer;
}
set
{
this.manufacturer = value;
}
}
public string Ram
{
get
{
return this.ram;
}
set
{
this.ram = value;
}
}
public string Screen
{
get
{
return this.screen;
}
set
{
this.screen = value;
}
}
public string Card
{
get
{
return this.card;
}
set
{
this.card = value;
}
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.AppendLine("Model:" + this.model);
result.AppendLine("Price:" + this.price);
result.AppendLine("Manufacturer:" + this.manufacturer);
result.AppendLine("HDD:" + this.hdd);
result.AppendLine("Card:" + this.card);
result.AppendLine("Battery:" + this.batteryName);
result.AppendLine("Battery Life:" + this.life);
return result.ToString();
}
}
}
|
private bool CompareCustomArrays(string Array1, string Array2, bool IgnoreCase)
{
//If both arrays are the same, no matter the order of values
List<string> List1 = new List<string>();
List<string> List2 = new List<string>();
ConvertCustomArrayToList(Array1, List1);
ConvertCustomArrayToList(Array2, List2);
if (List1.Count == List2.Count) //Check if both arrays are identical lenght wise to begin with
{
if (!(List1.Count > 0) && List2.Count > 0)
{
foreach (var i in List1)
{
if (IgnoreCase == true)
{
if (!List2.Contains(i, StringComparer.OrdinalIgnoreCase))
{
return false;
}
}
else
{
if (!List2.Contains(i, StringComparer.CurrentCulture))
{
return false;
}
}
}
return true;
}
}
return false;
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
namespace GigHub.ViewModels
{
public class ValidTime : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime time;
//var isValid = Regex.Match(value.ToString(), "^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
var isValid = DateTime.TryParseExact(Convert.ToString(value),
"HH:mm",
CultureInfo.CurrentCulture,
DateTimeStyles.None,
out time);
return (isValid);
}
}
} |
using System.Xml;
namespace gView.Framework.IO
{
internal class XmlNodeCursor
{
private int _pos = 0;
private XmlNodeList _list;
public XmlNodeCursor(XmlNodeList list)
{
_list = list;
}
public XmlNode Next
{
get
{
if (_list == null)
{
return null;
}
if (_pos >= _list.Count)
{
return null;
}
return _list[_pos++];
}
}
}
}
|
using System.IO;
class Inteiros
{
public void Executar()
{
int idade = 29;
// idade = 29.5; erro
char letra = 'M'; //System.char internamente armazena numeros
byte nivelTeste = 0xFF; //representação hexadecimal de 255 em decimal
short passageirosVoo = 230; //System.Int16 16 bits
int populacao = 1500; // Sysyem.Int32 32 bits
long populacaoDoBrasil = 207_660_929; // +- 207 milhões - Sysyem.Int64 64 bits
sbyte nivelDeBrilho = -127; //System.Sbyte
ushort passageirosNavio = 230;
}
} |
namespace Jira_Bulk_Issues_Helper.Utils
{
public class UrlBuilder
{
#region Variables
private string domain = "";
private string baseUrl = "https://{0}.atlassian.net/rest/api/2";
#endregion
#region Constructor
public UrlBuilder(string domain)
{
this.domain = domain;
}
#endregion
#region Public Functions
public string getBaseUrl() => string.Format(this.baseUrl, domain);
public string getMetaUrl() => "/issue/createmeta";
public string getIssueCreateUrl() => "/issue";
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Collections.ObjectModel;
using Appnotics.PCBackupLib;
namespace Appnotics.PCBackupLib
{
public class LogSummaryCollection : ObservableCollection<LogSummary>
{
public int NumberOfSummaries { get; set; }
}
public class Logger
{
private bool initialised = false;
private string logFile = @"C:\Appnotics\Log.log";
public string LogFile
{
get { return logFile; }
set {
logFile = LogFolder + value + ".log";
initialised = true;
}
}
public string LogFolder { get; private set; }
// where it actually writes to the file
private void WriteToLogFile(string strValue, string strMessage = null, bool showDate = false)
{
if (!initialised)
return;
bool written = false;
int tryCount = 0;
while (!written)
{
DateTime logTime = DateTime.Now;
string line = "";
if (showDate)
line += DateTime.Now.ToString() + " ~ ";
string paddedValue = strValue.PadRight(20);
line += paddedValue;
if (strMessage != null)
{
line += ": ";
line += strMessage;
}
try
{
FileStream fs = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.None);
StreamWriter swFromFileStream = new StreamWriter(fs);
swFromFileStream.WriteLine(line);
swFromFileStream.Flush();
swFromFileStream.Close();
fs.Close();
written = true;
#if DEBUG
Debug.WriteLine(line);
#endif
}
catch (Exception)
{
tryCount++;
Thread.Sleep(100);
if (tryCount > 20)
written = true;
}
}
#if DEBUG
Debug.WriteLine(strMessage);
#endif
}
// constructors
public Logger()
{
initialised = false;
string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
LogFolder = folderBase + @"\Appnotics\PCBackup\Logs\";
if (!Directory.Exists(LogFolder))
Directory.CreateDirectory(LogFolder);
}
public void InitLog(string logName)
{
DateTime dt = new DateTime(2015,5,1);
TimeSpan t = DateTime.Now.Subtract(dt);
ulong secondsSinceStartDate = (ulong)t.TotalSeconds;
LogFile = secondsSinceStartDate.ToString("X").PadLeft(8, '0');
LogSpecial("start");
}
public void EndLog()
{
LogSpecial("end");
initialised = false;
}
// log information
public void Log(string sEvent, string sResult = null)
{
WriteToLogFile(sEvent, sResult);
}
public void LogSpecial(string sEvent)
{
if (sEvent.Equals("start"))
WriteToLogFile(Properties.Resources.LogSpecialStart);
else if (sEvent.Equals("info"))
WriteToLogFile(Properties.Resources.LogSpecialInfo);
else if (sEvent.Equals("summary"))
WriteToLogFile(Properties.Resources.LogSpecialSummary);
else if (sEvent.Equals("end"))
WriteToLogFile(Properties.Resources.LogSpecialEnd);
else if (sEvent.Equals("line"))
WriteToLogFile("");
}
public IEnumerable<LogSummary> GetSummaries()
{
string summaryFile = LogFolder + "LogSummary.bbs";
IniFile summaryINI = new IniFile(summaryFile);
string[] summarySections = summaryINI.GetSectionNames();
if (summarySections != null)
{
foreach (string summarySection in summarySections)
{
LogSummary logSummary = SummariseLogSection(summarySection);
if (logSummary != null)
yield return logSummary;
}
}
}
public LogSummary SummariseLogSection(string summarySection)
{
LogSummary ls = new LogSummary();
string summaryFile = LogFolder + "LogSummary.bbs";
IniFile summaryINI = new IniFile(summaryFile);
ls.Name = summaryINI.IniReadValue(summarySection, "Name");
if (string.IsNullOrEmpty(ls.Name))
ls.Name = "No name";
ls.LogName = summarySection;
ls.Operation = "Copy";
ls.Date = summaryINI.IniReadValue(summarySection, "Date");
ls.Warnings = summaryINI.IniReadValue(summarySection, "Result");
long completed = summaryINI.IniReadLong(summarySection, "Selected Bytes", 0);
ls.SizeCompleted = StringHelper.ToNiceBytes(completed);
int files = summaryINI.IniReadInt(summarySection, "Completed Files", 0);
ls.FilesCompleted = StringHelper.ToNiceNumber(files);
files = summaryINI.IniReadInt(summarySection, "Selected Files", 0);
ls.FilesSelected = StringHelper.ToNiceNumber(files);
return ls;
}
public void DeleteLog(LogSummary logSummary)
{
string logFile = LogFolder + logSummary.LogName + ".log";
File.Delete(logFile);
string summaryFile = LogFolder + "LogSummary.bbs";
IniFile summaryINI = new IniFile(summaryFile);
summaryINI.IniWriteValue(logSummary.LogName, null, null);
}
public void ViewLog(LogSummary logSummary)
{
string logFile = LogFolder + logSummary.LogName + ".log";
Process.Start("notepad.exe", logFile);
}
public LogSummary SummariseLogFile(FileInfo logFile)
{
LogSummary ls = new LogSummary();
string summarySection = logFile.Name.Substring(0, logFile.Name.Length - logFile.Extension.Length);
string summaryFile = LogFolder + "LogSummary.bbs";
IniFile summaryINI = new IniFile(summaryFile);
ls.Name = summaryINI.IniReadValue(summarySection, "Name");
if (string.IsNullOrEmpty(ls.Name))
return null;
ls.Operation = "Copy";
ls.SizeCompleted = summaryINI.IniReadValue(summarySection, "Selected Bytes");
ls.Date = summaryINI.IniReadValue(summarySection, "Date");
ls.FilesCompleted = summaryINI.IniReadValue(summarySection, "Completed Files");
ls.FilesSelected = summaryINI.IniReadValue(summarySection, "Selected Files");
ls.Warnings = summaryINI.IniReadValue(summarySection, "Result");
return ls;
}
}
}
|
using System.Data;
using Framework;
using UnityEditor;
using UnityEngine;
namespace BattleEditor
{
/// <summary>
/// <para></para>
/// <para>Author: zhengnan </para>
/// <para>Create: 分页窗口</para>
/// </summary>
public class EditorBaseWnd : EditorWindow
{
const string ButtonPre = "Up";
const string ButtonNext = "Down";
const string ButtonTop = "Top";
const string ButtonBottom = "Bottom";
private const float ButtonWidth = 80;
private int _totalCount;
private Vector2 scrollerPos = Vector2.zero;
private int pageSize = 20;
private int totalPage = 0;
private int currPage = 0;
private int sortBy = 0;
public LuaReflect luaReflect;
public EditorBaseWnd childWnd;
public virtual void SetPageCount(int count)
{
_totalCount = count;
totalPage = (int)Mathf.Ceil((float)_totalCount / (float)pageSize);
}
protected virtual void OnGUI()
{
DrawHeader();
DrawFields();
scrollerPos = EditorGUILayout.BeginScrollView(scrollerPos, GUILayout.ExpandHeight(true));
{
DrawScrollView();
}
EditorGUILayout.EndScrollView();
DrawPageButtons();
//DrawBottom();
}
protected virtual void DrawScrollView()
{
for (int i = currPage * pageSize; i < (currPage + 1) * pageSize && i < _totalCount; i++)
{
DrawPageContent(i);
}
}
protected virtual void DrawPageButtons()
{
EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField("");
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.BeginHorizontal();
{
if (GUILayout.Button(ButtonTop,EditorStyles.miniButtonMid, GUILayout.Width(ButtonWidth)))
currPage = 0;
if (GUILayout.Button(ButtonPre,EditorStyles.miniButtonMid, GUILayout.Width(ButtonWidth)))
currPage = Mathf.Max(0, currPage - 1);
EditorGUILayout.LabelField((currPage + 1) + "/" + totalPage, EditorStyles.centeredGreyMiniLabel,GUILayout.Width(ButtonWidth));
if (GUILayout.Button(ButtonNext,EditorStyles.miniButtonMid, GUILayout.Width(ButtonWidth)))
currPage = Mathf.Min(totalPage - 1, currPage + 1);
if (GUILayout.Button(ButtonBottom,EditorStyles.miniButtonMid, GUILayout.Width(ButtonWidth)))
currPage = totalPage - 1;
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndHorizontal();
// EditorGUILayout.LabelField("");
EditorGUILayout.EndHorizontal();
}
protected virtual void DrawHeader()
{
EditorGUILayout.Space();
}
protected virtual void DrawFields()
{
}
protected virtual void DrawPageContent(int index)
{
}
protected virtual void DrawBottom(bool showClose = false, int index = -1)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("",GUILayout.ExpandWidth(true));
if (GUILayout.Button("Reload"))
{
Reload();
}
if (GUILayout.Button("Apply"))
{
Apply(index);
}
if (showClose && GUILayout.Button("Close"))
{
CloseWnd();
}
EditorGUILayout.EndHorizontal();
}
public virtual void Reload()
{
}
public virtual void Apply(int rowIndex)
{
}
protected virtual void CloseWnd()
{
Close();
DestroyImmediate(this);
}
//保存回lua
protected void SaveBackToLua(string key, string json)
{
Debug.Log(json);
var luaFunc = luaReflect.luaFuncDict["JsonToLua"];
luaFunc.BeginPCall();
luaFunc.Push(key);
luaFunc.Push(json);
luaFunc.PCall();
luaFunc.EndPCall();
}
protected void LinkEditor(ExcelColHeader excelColHeader, DataRowCollection rows, int rowIndex,int colIndex, bool showAll)
{
if(childWnd)
childWnd.Close();
string vid = rows?[rowIndex][colIndex].ToString();
if (showAll)
{
childWnd = SelectWnd.Create("Select " + excelColHeader.linkEditorLuaKey,this, luaReflect, excelColHeader.linkEditorUrl);
((SelectWnd) childWnd).SetSelectDelegate(delegate(string id)
{
OnSelect(id, rowIndex, colIndex);
});
}
else
{
childWnd = ListEditorWnd.Create(excelColHeader.linkEditorLuaKey,this, luaReflect, excelColHeader, vid);
}
}
protected virtual void OnSelect(string id, int rowIndex, int colIndex)
{
}
}
} |
/***
*
* Title: "SUIFW" UI框架项目
* 主题: xxx
* Description:
* 功能: yyy
*
* Date: 2017
* Version: 0.1版本
* Modify Recoder:
*
*
*/
using System.Collections;
using System.Collections.Generic;
using SUIFW;
using UnityEngine;
namespace DemoProject
{
public class StartProject : MonoBehaviour,HotUpdateProcess.IStartGame {
//热更新UI界面
public GameObject goHotUpdateUI;
//3D英雄角色
public GameObject goHero;
/// <summary>
/// 服务器已经更新完毕,可以开始后续游戏逻辑
/// </summary>
public void ReceiveInfoStartRuning()
{
//加载登陆窗体
UIManager.GetInstance().ShowUIForms(ProConst.LOGON_FROMS);
//关闭热更新进度界面
Invoke("CloseHotUpdateProcessUI",0.5F);
//显示3D角色
Invoke("ShowHero", 1F);
}
//关闭热更新进度界面
private void CloseHotUpdateProcessUI()
{
goHotUpdateUI.SetActive(false);
}
//显示3D角色
private void ShowHero()
{
goHero.SetActive(true);
}
}
} |
using GDS.BLL;
using GDS.Comon;
using GDS.Entity;
using GDS.Entity.Constant;
using GDS.Entity.Result;
using GDS.Query;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using GDS.WebApi.Models;
namespace GDS.WebApi.Controllers
{
public class AuditorController : BaseController
{
public ActionResult Index()
{
return View();
}
/*
有权限用户(部门负责人)可在此进行流程审核操作。
各个部门负责人只能看到各自部门的流程记录,管理员和超级用户能看到所有部门的流程记录。
*/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetAuditorList()
{
try
{
var queryParams = new NameValueCollection();
if (!ParamHelper.CheckParaQ(ref queryParams))
{
return Json(new ResponseEntity<int>(RegularFunction.RegularSqlRegexText), JsonRequestBehavior.AllowGet);
}
var query = new AuditorQuery(queryParams);
int userType = CurrenUserInfo.UserType;
string loginName = CurrenUserInfo.LoginName;
var sqlCondition = new StringBuilder();
sqlCondition.Append("ISNULL(IsDelete,0)!=1");
if (userType != GDS.Entity.Constant.ConstantDefine.Admin)
{
var departmentList = new DepartmentBLL().GetDepartmentByAuditor(loginName);
if (departmentList != null && departmentList.Count > 0)
{
sqlCondition.Append($" and DepartId in ({string.Join(",", departmentList.Select(x=>x.Id))}");
}
else
{
return Json(new ResponseEntity<dynamic>(10, "权限不足", null), JsonRequestBehavior.AllowGet);
}
}
if (!string.IsNullOrEmpty(query.DepartId))
{
sqlCondition.Append($" and DepartId = {query.DepartId}");
}
if (!string.IsNullOrEmpty(query.Status))
{
sqlCondition.Append($" and Status = {query.Status}");
}
if (!string.IsNullOrEmpty(query.Name))
{
sqlCondition.Append($" and Name like '%{query.Name}%'");
}
PageRequest preq = new PageRequest
{
TableName = " [View_Auditor] ",
Where = sqlCondition.ToString(),
Order = " createtime DESC ",
IsSelect = true,
IsReturnRecord = true,
PageSize = query.PageSize,
PageIndex = query.PageIndex,
FieldStr = "*"
};
var result = new ProjectBLL().GetView_AuditorByPage(preq);
var response = new ResponseEntity<object>(true, string.Empty,
new DataGridResultEntity<View_Auditor>
{
TotalRecords = preq.Out_AllRecordCount,
DisplayRecords = preq.Out_PageCount,
ResultData = result
});
return Json(response, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new ResponseEntity<object>(-999, string.Empty, ""), JsonRequestBehavior.AllowGet);
}
}
}
} |
using System.Collections;
using UnityEngine;
public class Projectile : MonoBehaviour
{
public float secondsProjectileLife = 2.0f;
private IEnumerator ShortenProjectileLife()
{
while (0 < secondsProjectileLife)
{
secondsProjectileLife -= Time.deltaTime;
yield return null;
}
Destroy(gameObject);
}
private void OnEnable()
{
StartCoroutine(ShortenProjectileLife());
}
private void OnCollisionEnter(Collision col)
{
GameObject entity = col.gameObject;
if (entity.CompareTag("Player") || entity.CompareTag("Tree"))
{
if (entity.CompareTag("Player"))
{
Destroy(entity);
}
Destroy(gameObject);
}
}
}
|
using System;
using System.Configuration;
using ClearBank.DeveloperTest.Data;
using ClearBank.DeveloperTest.PaymentSchemeValidators;
using ClearBank.DeveloperTest.Services;
using ClearBank.DeveloperTest.Types;
using Microsoft.Extensions.DependencyInjection;
namespace ClearBank.DeveloperTest.Ioc
{
public static class PaymentServiceExtensions
{
public static IServiceCollection RegisterPaymentServices(this IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<BacsPaymentSchemeValidator>();
serviceCollection.AddSingleton<ChapsPaymentSchemeValidator>();
serviceCollection.AddSingleton<FasterPaymentsPaymentSchemeValidator>();
serviceCollection.AddSingleton<Func<PaymentScheme, IPaymentSchemeValidator>>(provider => scheme =>
{
return scheme switch
{
PaymentScheme.Bacs => provider.GetRequiredService<BacsPaymentSchemeValidator>(),
PaymentScheme.Chaps => provider.GetRequiredService<ChapsPaymentSchemeValidator>(),
PaymentScheme.FasterPayments => provider.GetRequiredService<FasterPaymentsPaymentSchemeValidator>(),
_ => throw new NotImplementedException($"Unable to find IPaymentSchemeValidator implementation for {scheme}")
};
});
serviceCollection.AddSingleton<IAccountRepository>(provider =>
{
var dataStoreType = ConfigurationManager.AppSettings["DataStoreType"];
if (dataStoreType == "Backup")
{
return new BackupAccountDataStore();
}
return new AccountDataStore();
});
serviceCollection.AddSingleton<IPaymentService, PaymentService>();
return serviceCollection;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace LeetCodeTests
{
public abstract class Problem_0079
{
/*
79. Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring.
The same letter cell may not be used more than once.
For example,
Given board =
[
['A', 'B', 'C', 'E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
*/
public static void Test()
{
Solution sol = new Solution();
/*
var input = new int[] { 2, 7, 11, 15 };
Console.WriteLine($"Input array: {string.Join(", ", input)}");
*/
Func<char[,]> getCharArray = () =>
new char[,]
{
{'A', 'B', 'C', 'E'},
{'S', 'F', 'C', 'S'},
{'A', 'D', 'E', 'E'}
};
char[,] input = getCharArray();
Console.WriteLine($"Input array:\n{Utils.Print2DArray(input)}");
var word = "ABCCED";
Console.WriteLine($"Search word '{word}' -> '{sol.Exist(input, word)}' waits TRUE");
input = getCharArray();
word = "SEE";
Console.WriteLine($"Search word '{word}' -> '{sol.Exist(input, word)}' waits TRUE");
input = getCharArray();
word = "ABCB";
Console.WriteLine($"Search word '{word}' -> '{sol.Exist(input, word)}' waits FALSE");
/*
Submission Result: Wrong Answer
Input: [["a"]] "a"
Output:false
Expected:true
*/
input = new char[,] { { 'a' } };
word = "a";
Console.WriteLine($"Input array:\n{Utils.Print2DArray(input)}");
Console.WriteLine($"Search word '{word}' -> '{sol.Exist(input, word)}' waits TRUE");
/*
Submission Result: Time Limit ExceededMore Details
Last executed input:
[["b","a","a","b","a","b"],["a","b","a","a","a","a"],["a","b","a","a","a","b"],["a","b","a","b","b","a"],
["a","a","b","b","a","b"],["a","a","b","b","b","a"],["a","a","b","a","a","b"]]
"aabbbbabbaababaaaabababbaaba"
*/
getCharArray = () =>
new char[,]
{
{'b','a','a','b','a','b'},
{'a','b','a','a','a','b'},
{'a','b','a','b','b','a'},
{'a','a','b','b','a','b'},
{'a','a','b','b','b','a'},
{'a','a','b','a','a','b'}
};
input = getCharArray();
Console.WriteLine($"Input array:\n{Utils.Print2DArray(input)}");
word = "aabbbbabbaababaaaabababbaaba";
Benchmark.Start();
Console.WriteLine($"Search word '{word}' -> '{sol.Exist(input, word)}' waits TRUE");
var ts = Benchmark.Finish();
Console.WriteLine($"spanned: {ts.ToString()}");
}
public class Solution
{
public bool Exist(char[,] board, string word)
{
if (string.IsNullOrEmpty(word) || (board == null))
return false;
this.board = board;
this.word = word;
for (int row = 0; row < this.m; row++)
for (int col = 0; col < this.n; col++)
{
if (board[row, col] == word[0])
if (backTrace("", row, col))
return true;
}
return false;
}
private char[,] _board;
private int m = 0;
private int n = 0;
private char[,] board
{
get { return _board; }
set
{
_board = value;
m = value.GetLength(0);
n = value.GetLength(1);
}
}
private string word;
private bool backTrace(string acc, int row, int col)
{
/* mark passed chars with ' ' (space)
* if (at position(row, col) == ' ') stop search in this direction
* position (row, col) - is started position
* will pass in direction 1. to up, 2. to right, 3. to down, 4. to left
*/
if (acc.Equals(this.word))
return true;
if (acc.Length > this.word.Length)
return false;
if ((row >= m) || (col >= n) || (row < 0) || (col < 0))
return false; // out of board
//if (board[row, col] == ' ')
// return false;
if (board[row, col] != this.word[acc.Length])
return false;
acc += board[row, col];
board[row, col] = ' ';
if (backTrace(acc, row - 1, col)) return true;
if (backTrace(acc, row, col + 1)) return true;
if (backTrace(acc, row + 1, col)) return true;
if (backTrace(acc, row, col - 1)) return true;
//restore board state
board[row, col] = acc[acc.Length - 1];
return false;
}
}
}//public abstract class Problem_
} |
using System;
using UnityEngine;
namespace UnityAtoms.MonoHooks
{
[Serializable]
public struct Collision2DGameObject : IEquatable<Collision2DGameObject>
{
public Collision2D Collision2D { get => _collision2D; set => _collision2D = value; }
public GameObject GameObject { get => _gameObject; set => _gameObject = value; }
[SerializeField]
private Collision2D _collision2D;
[SerializeField]
private GameObject _gameObject;
/// <summary>
/// Determine if 2 `Collider2DGameObject` are equal.
/// </summary>
/// <param name="other">The other `Collider2DGameObject` to compare with.</param>
/// <returns>`true` if equal, otherwise `false`.</returns>
public bool Equals(Collision2DGameObject other)
{
return this.Collision2D == other.Collision2D && this.GameObject == other.GameObject;
}
/// <summary>
/// Determine if 2 `Collider2DGameObject` are equal comparing against another `object`.
/// </summary>
/// <param name="obj">The other `object` to compare with.</param>
/// <returns>`true` if equal, otherwise `false`.</returns>
public override bool Equals(object obj)
{
Collision2DGameObject cgo = (Collision2DGameObject)obj;
return Equals(cgo);
}
/// <summary>
/// `GetHashCode()` in order to implement `IEquatable<Collider2DGameObject>`
/// </summary>
/// <returns>An unique hashcode for the current value.</returns>
public override int GetHashCode()
{
var hash = 17;
hash = hash * 23 + this.Collision2D.GetHashCode();
hash = hash * 23 + this.GameObject.GetHashCode();
return hash;
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="first">First `Collider2DGameObject`.</param>
/// <param name="second">Other `Collider2DGameObject`.</param>
/// <returns>`true` if equal, otherwise `false`.</returns>
public static bool operator ==(Collision2DGameObject first, Collision2DGameObject second)
{
return first.Equals(second);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="first">First `Collider2DGameObject`.</param>
/// <param name="second">Other `Collider2DGameObject`.</param>
/// <returns>`true` if they are not equal, otherwise `false`.</returns>
public static bool operator !=(Collision2DGameObject first, Collision2DGameObject second)
{
return !first.Equals(second);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Xna.Framework.Input
{
public struct JoyconGyrescope
{
public float pitch;
public float yaw;
public float roll;
public struct Offset
{
public int n;
public float pitch;
public float yaw;
public float roll;
}public Offset offset;
}
}
|
using Moq;
using NUnit.Framework;
namespace OpenOracleTests
{
[TestFixture]
public class OpenOracleTests
{
[Test]
public void GivenNothing_WhenConstructingOpenOracle_ThenConfigPopulateFromFileIsCalledOnce()
{
}
}
}
|
namespace BettingSystem.Domain.Betting.Models.Matches
{
using System;
using Common;
using Common.Models;
using Exceptions;
public class Match : Entity<int>, IAggregateRoot
{
internal Match(
DateTime startDate,
Statistics statistics,
Status status)
{
this.Validate(startDate);
this.StartDate = startDate;
this.Statistics = statistics;
this.Status = status;
}
private Match(DateTime startDate)
{
this.StartDate = startDate;
this.Statistics = default!;
this.Status = default!;
}
public DateTime StartDate { get; private set; }
public Statistics Statistics { get; private set; }
public Status Status { get; private set; }
public Match UpdateStartDate(DateTime startDate)
{
this.Validate(startDate);
this.StartDate = startDate;
return this;
}
public Match UpdateStatus(Status status)
{
this.Status = status;
return this;
}
private void Validate(DateTime startDate)
{
if (startDate < DateTime.Today)
{
throw new InvalidMatchException();
}
}
}
}
|
using AlgorithmProblems.Trees.TreeHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Trees
{
/// <summary>
/// Get the mirror image of a tree.
/// </summary>
class MirrorATree
{
/// <summary>
/// To get the mirror image we need to make the left child as the right child and the right child as the left child
/// for each node recursively.
///
/// The running time is O(n) as we visit all the nodes and the space is O(1)
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static BinaryTreeNode<int> GetNodeAfterMirroring(BinaryTreeNode<int> node)
{
if(node == null)
{
return null;
}
BinaryTreeNode<int> leftNode = GetNodeAfterMirroring(node.Left);
BinaryTreeNode<int> rightNode = GetNodeAfterMirroring(node.Right);
node.Left = rightNode;
node.Right = leftNode;
return node;
}
public static void TestMirrorATree()
{
BinaryTree<int> bt1 = new BinaryTree<int>(new int[] { 8, 4, 12, 1, 5, 9, 13, 0, 2 }, true);
Console.WriteLine("Initial tree:");
TreeHelperGeneral.PrintATree(bt1.Head);
Console.WriteLine("Tree after mirroring");
TreeHelperGeneral.PrintATree(GetNodeAfterMirroring(bt1.Head));
}
}
}
|
#if DEBUG
using Common.Business;
using Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.ServiceModel;
namespace Contracts.AirMaster
{
[ServiceContract(SessionMode = SessionMode.Required, Namespace = "http://www.noof.com/", Name = "AirMaster")]
public interface IAirMasterService
{
[OperationContract]
bool AddAMHistory(TrackBHistory data);
[OperationContract]
bool AddConformingProjectCompleteHistory(ConformingProjectCompleteHistory data);
[OperationContract]
bool AddItemToAMFixesScreen(int id);
[OperationContract]
bool AddMovieConformHistory(MovieConformHistory data);
[OperationContract]
bool AddQCHistory(TrackBQCHistory data);
[OperationContract]
bool AddToFailedAMQueue(int id);
[OperationContract]
bool AddUpdateAMRecord(TrackB data, bool isNew);
[OperationContract]
bool AddUpdateMSRecord(int id, string userName);
[OperationContract]
bool AddUpdateQCRecord(TrackBQC data, bool isNew);
[OperationContract]
bool AddUpdateV00XRecord(int track, ITrackV00X data, bool isNew);
[OperationContract]
bool AddV00XHistory(ITrackV00XHistory data, int track);
[OperationContract]
bool CheckMOVExists(int id);
[OperationContract]
ITrackV00X CheckV00XRecordExists(int id, int track);
[OperationContract]
void CreateAirMasterMethods(string connectionString, string userName);
[OperationContract]
bool DeleteBSANTSData(int id, bool bsanOnly);
[OperationContract]
TrackB GetAirMaster(int id);
[OperationContract]
int GetAlternateHDId(int id);
[OperationContract]
int GetAlternateSDHDId(int id);
[OperationContract]
int GetAlternateSDId(int id);
[OperationContract]
DataTable GetAMFailInfo(int id);
[OperationContract]
HistoryInfo GetAMHistory(int id);
[OperationContract]
HistoryInfo GetAMQCContentHistory(int id);
[OperationContract]
HistoryInfo GetAMQCHistory(int id);
[OperationContract]
HistoryInfo GetAMQCPassedHistory(int id);
[OperationContract]
List<string> GetAMStatuses();
[OperationContract]
List<string> GetAnalogLocations();
[OperationContract]
int? GetClipCompId(string aka1, string type);
[OperationContract]
string[] GetConformingDirectories();
[OperationContract]
ConformingProjectComplete GetConformingProjectComplete(int masterId);
[OperationContract]
Tuple<string, string, string> GetConformingRuntimes(int id);
[OperationContract]
Tuple<string, string, string> GetDAMRuntimes(int id);
[OperationContract]
Tuple<int, string> GetDefinitionAndType(int id);
[OperationContract]
List<string> GetDerivatives(int id, int masterId, int rating);
[OperationContract]
List<Tuple<int, string>> GetDerivativesByMasterId(int masterId, int rating);
[OperationContract]
List<string> GetDigitalLocations();
[OperationContract]
string GetFailureReasons(int id, string track);
[OperationContract]
int GetFCPPassedCount(int id);
[OperationContract]
Tuple<string, string, string> GetFCPRuntimes(int id);
[OperationContract]
List<TrackBHistory> GetHistory(int id);
[OperationContract]
int GetHistoryId(int id);
[OperationContract]
TrackBQC GetItemRecord(int id, int itemId);
[OperationContract]
int GetLastLoggedCount(int id);
[OperationContract]
int GetMasterId(int id);
[OperationContract]
MovieConform GetMovieConform(int id);
[OperationContract]
Tuple<int, string, string> GetMovieRatingContractTitleType(int id);
[OperationContract]
Tuple<string, int> GetMovieTitleRating(int id);
[OperationContract]
string GetMovieType(int id);
[OperationContract]
string GetNAD(int id);
[OperationContract]
string GetNAD2(int id, string type, DateTime date);
[OperationContract]
string GetNAD33(int id, string type, DateTime date, string channelType);
[OperationContract]
Tuple<int, int, string> GetNADInfo(int id);
[OperationContract]
DateTime? GetQCContentDateB(int id);
[OperationContract]
List<int> GetOtherRelatedIds(int masterId);
[OperationContract]
string GetPathById(string id);
[OperationContract]
DateTime? GetQCContentDateBQC(int id);
[OperationContract]
List<TrackBQC> GetQCData(int id);
[OperationContract]
HistoryInfo GetQCDateUser(int id);
[OperationContract]
Tuple<int, int> GetRatingAndGay(int id);
[OperationContract]
string GetRatingText(int xxx);
[OperationContract]
string GetReasonText(string contentType);
[OperationContract]
Tuple<string, string> GetStatusLocation(int id);
[OperationContract]
DateTime? GetTrackBHistoryDate(int id);
[OperationContract]
Tuple<int?, string, DateTime?> GetXmlCCStatus(int id);
[OperationContract]
int GetXXX(int id);
[OperationContract]
DateTime HasRights(int id, string right);
[OperationContract]
bool HasSDData(int id);
[OperationContract]
bool IsAlreadyQCd(int id);
[OperationContract]
bool IsAlreadySaved(int id, int itemId);
[OperationContract]
bool IsHD(int id);
[OperationContract]
bool SetRuntime(string runtime, int id);
[OperationContract]
bool UpdateConformingProjectCompleteRecord(ConformingProjectComplete data);
[OperationContract]
bool UpdateMovieConformRecord(MovieConform data);
[OperationContract]
bool UpdateXmlCCStatus(Tuple<int, string, DateTime> data, int id);
}
}
#endif |
using System.Collections.Generic;
namespace LocusNew.Core.ViewModels
{
public class HomeViewModel
{
public IEnumerable<ListingsListViewModel> Listings { get; set; }
public LeadViewModel Message { get; set; }
public HomeGlobalSettingsViewModel GlobalSettings { get; set; }
public HomeViewModel()
{
Message = new LeadViewModel();
}
}
} |
using System;
using System.Collections.Generic;
namespace MerchantRPG.GeneticParty.Processing
{
struct ChromosomeDescription
{
public IList<HeroBuild> Builds;
public int FrontRowCount;
public int InvalidGenes;
public int Deaths;
public ChromosomeDescription(IList<HeroBuild> builds, int frontRowCount, int deaths, int invalidGenes)
{
this.Builds = builds;
this.FrontRowCount = frontRowCount;
this.InvalidGenes = invalidGenes;
this.Deaths = deaths;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OurNewProject.Data;
using OurNewProject.Models;
namespace OurNewProject.Controllers
{
public class ProductsController : Controller
{
private readonly OurNewProjectContext _context;
public ProductsController(OurNewProjectContext context)
{
_context = context;
}
// GET: Products
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Index()
{
var imagesa = _context.Product.Include(p => p.productImage);
var ourNewProjectContext = _context.Product.Include(p => p.Category);
return View(await ourNewProjectContext.ToListAsync());
}
// GET: Products/Details/5
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Product
.Include(p => p.Category)
.FirstOrDefaultAsync(m => m.Id == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// GET: Products/Create
[Authorize(Roles = "Admin")]
public IActionResult Create()
{
ViewData["Products"] = new List<Product>(_context.Product);
ViewData["Categoriess"] = new SelectList(_context.Category, nameof(Category.Id), nameof(Category.Name));
ViewData["CategoryId"] = new SelectList(_context.Category, "Id", "Id");
return View();
}
// POST: Products/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Create([Bind("Id,Name,Price,Description,CategoryId")] Product product)
{
if (ModelState.IsValid)
{
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["CategoryId"] = new SelectList(_context.Category, "Id", "Id", product.CategoryId);
return View(product);
}
// GET: Products/Edit/5
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Product.FindAsync(id);
if (product == null)
{
return NotFound();
}
ViewData["CategoryId"] = new SelectList(_context.Category, "Id", "Id", product.CategoryId);
return View(product);
}
// POST: Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Price,Description,CategoryId")] Product product)
{
if (id != product.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(product);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(product.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["CategoryId"] = new SelectList(_context.Category, "Id", "Id", product.CategoryId);
return View(product);
}
// GET: Products/Delete/5
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Product
.Include(p => p.Category)
.FirstOrDefaultAsync(m => m.Id == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var product = await _context.Product.FindAsync(id);
_context.Product.Remove(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ProductExists(int id)
{
return _context.Product.Any(e => e.Id == id);
}
public async Task<IActionResult> Menu()
{
ViewData["Categoriess"] = new SelectList(_context.Category, nameof(Category.Id), nameof(Category.Name));
var ProjectContext = _context.Product.Include(c => c.Category);
var query =
from product in _context.Product
join image in _context.ProductImage on product.Id equals image.productId
select new ProductJoin(product, image);
return View("Menu", await query.ToListAsync());
}
public async Task<IActionResult> Buttom(string ctN)
{
var outNewP = _context.Product.Include(c => c.Category).Where(p => p.Category.Name.Equals(ctN) ||
(ctN == null));
var query = from p in outNewP join image in _context.ProductImage on p.Id equals image.productId select new ProductJoin(p, image);
return View("Menu", await query.ToListAsync());
}
public async Task<IActionResult> Search(string productName, string price)
{
ViewData["Categoriess"] = new SelectList(_context.Category, nameof(Category.Id), nameof(Category.Name));
try
{
int priceInt = Int32.Parse(price);
//Get all products
var products = from p in _context.Product select p;
//Filter by name
products = products.Where(x => x.Name.Contains(productName));
products = products.Where(x => x.Price <= priceInt);
var query = from p in products join image in _context.ProductImage on p.Id equals image.productId select new ProductJoin(p, image);
return View("MenuSearch", await query.ToListAsync());
}
catch { return RedirectToAction("PageNotFound", "Home"); }
}
}
public class ProductJoin
{
public Product p { get; set; }
public ProductImage pi { get; set; }
public ProductJoin(Product p, ProductImage pi) { this.p = p; this.pi = pi; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Reflection;
using DevExpress.XtraGrid.Views.Grid;
using IRAP.Global;
using IRAP.Client.Global;
using IRAP.Client.User;
using IRAP.Entity.SSO;
using IRAP.Entity.FVS;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.GUI.CAS
{
public partial class frmPWOTracking : IRAP.Client.Global.GUI.frmCustomKanbanBase
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private List<Dashboard_MOTrack> moTracks = new List<Dashboard_MOTrack>();
public frmPWOTracking()
{
InitializeComponent();
}
private void SetWOStatusPanelColor()
{
lblStatus1.BackColor = ColorTranslator.FromHtml("#4567AA");
lblStatus2.BackColor = ColorTranslator.FromHtml("#00FF00");
lblStatus3.BackColor = ColorTranslator.FromHtml("#24F0E1");
lblStatus4.BackColor = ColorTranslator.FromHtml("#3867F3");
lblStatus5.BackColor = ColorTranslator.FromHtml("#FBF179");
lblStatus6.BackColor = ColorTranslator.FromHtml("#FF0000");
lblStatus2.ForeColor = Color.Black;
lblStatus3.ForeColor = Color.Black;
lblStatus5.ForeColor = Color.Black;
//grdclmnOrdinal.Caption = "项目\nItem";
//grdclmnMONumber.Caption = "订单号\nMO No.";
//grdclmnMOLineNo.Caption = "行号\nLine No.";
//grdclmMaterialCode.Caption = "物料号\nPart number";
//grdclmMaterialName.Caption = "产品名称\nProduct name";
//grdclmPlannedStartDate.Caption = "计划开工日期\nPlanned start date";
}
private void GetDashboardMOTracks()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
try
{
IRAPFVSClient.Instance.ufn_Dashboard_MOTrack(
IRAPUser.Instance.CommunityID,
t132ClickStream,
SysLogID,
ref moTracks,
out errCode,
out errText);
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
AddLog(new AppOperationLog(DateTime.Now, -1, error.Message));
SetConnectionStatus(false);
return;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
{
moTracks = (from row in moTracks
where row.PWOProgress > 0
select row).ToList();
grdMOTracks.DataSource = moTracks;
grdvMOTracks.BestFitColumns();
grdvMOTracks.OptionsView.RowAutoHeight = true;
SetConnectionStatus(true);
}
else
{
AddLog(new AppOperationLog(DateTime.Now, -1, errText));
SetConnectionStatus(false);
grdMOTracks.DataSource = null;
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private void frmPWOTracking_Load(object sender, EventArgs e)
{
SetWOStatusPanelColor();
}
private void frmPWOTracking_Resize(object sender, EventArgs e)
{
pnlRemark.Left = (this.Width - pnlRemark.Width) / 2;
}
private void frmPWOTracking_Shown(object sender, EventArgs e)
{
try
{
if (lblFuncName.Text.Contains("-"))
{
string lblName = lblFuncName.Text;
lblFuncName.Text = lblName.Split('-')[1].ToString();
}
pnlRemark.Left = (Width - pnlRemark.Width) / 2;
}
catch (Exception error)
{
WriteLog.Instance.Write(
error.Message,
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name));
}
}
private void frmPWOTracking_Activated(object sender, EventArgs e)
{
try
{
if (Tag is MenuInfo)
{
GetDashboardMOTracks();
grdvMOTracks.MoveFirst();
if (autoSwtich)
{
if (this.moTracks.Count > 0)
{
timer.Interval = this.nextFunction.WaitForSeconds * 1000;
}
else
{
timer.Interval = 10000;
}
}
else
{
timer.Interval = 60000;
}
timer.Enabled = false;
if (grdvMOTracks.RowCount - 1 > 0 &&
grdvMOTracks.IsRowVisible(grdvMOTracks.RowCount - 1) != RowVisibleState.Visible)
{
tmrPage.Interval = 5000;
tmrPage.Enabled = true;
}
else
{
timer.Enabled = true;
}
}
else
{
AddLog(new AppOperationLog(
DateTime.Now,
-1,
"没有正确的传入菜单参数!"));
timer.Enabled = false;
return;
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message,
string.Format("{0}.{1}", className, MethodBase.GetCurrentMethod().Name));
}
}
private void grdvMOTracks_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
try
{
int rowIndex = e.RowHandle;
string colHtml = moTracks[rowIndex].BackgroundColor;
colHtml = colHtml.Contains("#") ? colHtml : "#" + colHtml;
e.Appearance.BackColor = ColorTranslator.FromHtml(colHtml);
if (e.Column != grdclmPWOProgress) return;
int colIndex = 0;
int.TryParse(e.CellValue.ToString(), out colIndex);
switch (colIndex)
{
case -1:
{
string col = "#4567AA";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
}
break;
case 0:
{
string col = "#00FF00";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
e.Appearance.ForeColor = Color.Black;
}
break;
case 1:
{
string col = "#24F0E1";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
}
break;
case 2:
{
string col = "#3867F3";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
e.Appearance.ForeColor = Color.White;
}
break;
case 3:
{
string col = "#FBF179";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
}
break;
case 4:
{
string col = "#FF0000";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
e.Appearance.ForeColor = Color.White;
}
break;
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message,
string.Format("{0}.{1}", className, MethodBase.GetCurrentMethod().Name));
}
}
private void grdvMOTracks_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
{
if (e.Column != grdclmPWOProgress) return;
int colIndex = 0;
int.TryParse(e.Value.ToString(), out colIndex);
switch (colIndex)
{
case -1:
{
e.DisplayText = "计划";
}
break;
case 0:
{
e.DisplayText = "正常";
}
break;
case 1:
{
e.DisplayText = "偏快";
}
break;
case 2:
{
e.DisplayText = "过快";
}
break;
case 3:
{
e.DisplayText = "偏慢";
}
break;
case 4:
{
e.DisplayText = "过慢";
}
break;
}
}
private void timer_Tick(object sender, EventArgs e)
{
try
{
timer.Enabled = false;
if (autoSwtich)
{
JumpToNextFunction();
tmrPage.Enabled = false;
return;
}
else
{
GetDashboardMOTracks();
timer.Enabled = true;
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message,
string.Format("{0}.{1}", className, MethodBase.GetCurrentMethod().Name));
}
}
private void tmrPage_Tick(object sender, EventArgs e)
{
try
{
if (moTracks.Count > 0)
{
if (grdvMOTracks.RowCount - 1 > 0)
{
if (grdvMOTracks.IsRowVisible(grdvMOTracks.RowCount - 1) == RowVisibleState.Visible) //如果滚到了底端
{
timer.Enabled = true;
grdvMOTracks.MoveFirst();
}
}
grdvMOTracks.MoveNextPage();
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message,
string.Format("{0}.{1}", className, MethodBase.GetCurrentMethod().Name));
}
}
}
}
|
using MartianRobotsService.BaseClasses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MartianRobotsService.Models
{
public class RectangularGrid : IGrid<_2DCoordinate, _2DDirection>
{
private Dictionary<_2DCoordinate, List<IRobot>> _robotsOnGrid;
private Dictionary<_2DCoordinate, bool> _coordinatesScented;
public int InitialParametersCount { get; private set; }
public List<CoordinateBase> GridShape { get; private set; }
public RectangularGrid(int x, int y)
{
InitialParametersCount = 2;
GridShape = new List<CoordinateBase> { new _2DCoordinate(0, 0), new _2DCoordinate(x, y) };
_robotsOnGrid = new Dictionary<_2DCoordinate, List<IRobot>>( new _2DCoordinateEqualityComparer());
_coordinatesScented = new Dictionary<_2DCoordinate, bool>( new _2DCoordinateEqualityComparer());
}
public bool IsCoordinateWithin(_2DCoordinate coordinate)
{
return coordinate.Point[0] >= GridShape[0].Point[0] && coordinate.Point[0] <= GridShape[1].Point[0] &&
coordinate.Point[1] >= GridShape[0].Point[1] && coordinate.Point[1] <= GridShape[1].Point[1];
}
public void AddRobotOnPoint(IRobot robot)
{
if (IsCoordinateWithin(robot.SelfCoordinate as _2DCoordinate))
{
if (!_robotsOnGrid.ContainsKey(robot.SelfCoordinate as _2DCoordinate))
_robotsOnGrid[robot.SelfCoordinate as _2DCoordinate] = new List<IRobot>();
_robotsOnGrid[robot.SelfCoordinate as _2DCoordinate].Add(robot);
}
}
public void RemoveRobotFromPoint(IRobot robot)
{
if (IsCoordinateWithin(robot.SelfCoordinate as _2DCoordinate))
{
if (_robotsOnGrid.ContainsKey(robot.SelfCoordinate as _2DCoordinate) &&
_robotsOnGrid[robot.SelfCoordinate as _2DCoordinate].Count > 0)
_robotsOnGrid[robot.SelfCoordinate as _2DCoordinate].Remove(robot);
}
}
public bool IsCoordinateScented(_2DCoordinate coordinate)
{
if (coordinate != null && _coordinatesScented.ContainsKey(coordinate))
return true;
return false;
}
public void ScenteCoordinate(_2DCoordinate coordinate)
{
if(coordinate != null && IsCoordinateWithin(coordinate))
_coordinatesScented[coordinate] = true;
}
//if direction is null, then assume we are trying to get existing robot
public IRobot AcquireRobot(_2DCoordinate coordinate, _2DDirection direction = null)
{
IRobot robot = null;
if (direction == null && _robotsOnGrid.ContainsKey(coordinate) && _robotsOnGrid[coordinate].Count > 0)
robot = _robotsOnGrid[coordinate].FirstOrDefault(x => !x.isLost);
if (robot == null && direction != null)
robot = new SimpleMartianRobot(coordinate, direction, this);
return robot;
}
}
}
|
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using Android.Views.Animations;
using BeeAttack.Services;
namespace BeeAttack
{
[Activity(Label = "GameActivity", Theme = "@style/StartUpAppTheme",
ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class GameActivity : Activity
{
private ImageView _flower;
private ImageView _hive;
private TextView _misses;
private TextView _score;
private RelativeLayout _gameArea;
private Button _restart;
private bool _running;
private LinearLayout _gameOverLayout;
private Fragments.BeeAttackServiceFragment _fragment;
private BeeAttackService _service;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Game);
_flower = FindViewById<ImageView>(Resource.Id.flowerView);
_hive = FindViewById<ImageView>(Resource.Id.hiveView);
_gameArea = FindViewById<RelativeLayout>(Resource.Id.gameArea);
_misses = FindViewById<TextView>(Resource.Id.missesLeftText);
_score = FindViewById<TextView>(Resource.Id.scoreText);
_restart = FindViewById<Button>(Resource.Id.restartButton);
_gameOverLayout = FindViewById<LinearLayout>(Resource.Id.gameOverLayout);
_fragment = (Fragments.BeeAttackServiceFragment)FragmentManager.FindFragmentByTag("GameService");
if (_fragment == null)
{
_fragment = new Fragments.BeeAttackServiceFragment(new BeeAttackService());
var fragmentTransaction = FragmentManager.BeginTransaction();
fragmentTransaction.Add(_fragment, "GameService");
fragmentTransaction.Commit();
}
_service = _fragment.Service;
_service.HiveMoved += Service_HiveMoved;
_service.BeeAdded += Service_BeeAdded;
_service.GameOver += Service_GameOver;
_service.Missed += Service_Missed;
_service.Scored += Service_Scored;
_flower.Touch += Flower_Touch;
_restart.Click += delegate
{
Intent intent = Intent;
Finish();
StartActivity(intent);
};
}
protected override void OnPause()
{
base.OnPause();
PauseGame();
}
protected override void OnStop()
{
base.OnStop();
PauseGame();
}
protected override void OnResume()
{
base.OnResume();
PauseGame(false);
}
private void PauseGame(bool pause = true)
{
_service.Paused = pause;
}
public override void OnWindowFocusChanged(bool hasFocus)
{
base.OnWindowFocusChanged(hasFocus);
if (!_running && _gameOverLayout.Visibility == ViewStates.Invisible)
{
StartGame();
}
}
private void Flower_Touch(object sender, View.TouchEventArgs e)
{
if (e.Event.Action == MotionEventActions.Move)
{
MoveFlower(e.Event.GetX());
}
}
private void MoveFlower(float newX)
{
if (_service.IsGameOver)
return;
if (_flower.TranslationX + _flower.Width + newX <= _gameArea.Width || _flower.TranslationX + newX < 0)
{
_flower.TranslationX += newX - _flower.Width / 2;
_service.MoveFlower(_flower.TranslationX);
}
}
private void StartGame()
{
_service.StartGame(_flower.Width, _hive.Width, _gameArea.Width);
MoveFlower((_gameArea.Width - _flower.Width) / 2);
_gameOverLayout.Visibility = ViewStates.Invisible;
_running = true;
}
private void Service_BeeAdded(object sender, BeeAddedEventArgs args)
{
var bee = CreateBee(args.TranslationX, args.Width, args.Height);
var animation = AnimationUtils.LoadAnimation(this, Resource.Animation.beeview_animation);
animation.AnimationEnd += delegate
{
_service.BeeLanded(args.TranslationX);
};
animation.AnimationEnd += delegate
{
bee.ClearAnimation();
// Caution: Gambiarra!!!
// TODO: There must be a better way to remove the views...
// RunOnUiThread(() => GameArea.RemoveView(bee)) causes an exception
bee.Visibility = ViewStates.Invisible;
};
RunOnUiThread(() => _gameArea.AddView(bee));
bee.Animation = animation;
bee.Animation.Start();
}
private void Service_HiveMoved(object sender, HiveMovedEventArgs args)
{
RunOnUiThread(() => _hive.TranslationX = args.X);
}
private void Service_Scored(object sender, ScoredEventArgs args)
{
_score.Text = args.Score.ToString();
}
private void Service_Missed(object sender, MissedEventArgs args)
{
_misses.Text = args.MissesLeft.ToString();
}
private void Service_GameOver(object sender, EventArgs e)
{
_running = false;
_gameOverLayout.Visibility = ViewStates.Visible;
}
private View CreateBee(float translationX, float beeWidth, float beeHeight)
{
ImageView bee = new ImageView(this)
{
TranslationX = translationX + _hive.Width / 2.0f,
TranslationY = _gameArea.Height + _flower.Height / 3.0f
};
var layoutParams = new RelativeLayout.LayoutParams((int)beeWidth, (int)beeHeight);
layoutParams.AddRule(LayoutRules.AlignParentTop);
bee.LayoutParameters = layoutParams;
bee.SetImageResource(Resource.Drawable.bee);
bee.SetY(_hive.Height);
bee.Visibility = ViewStates.Visible;
return bee;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Timers;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using Random = UnityEngine.Random;
public class TextSpawner : MonoBehaviour
{
// Start is called before the first frame update
public GameObject textPrefab;
public float indent, lineHeight, lineWidth, spacing, characterSpacing;
public Transform container;
public Vector3 cursorPos;
public string text;
private Vector3 startPos;
private string[] words;
private int index;
public bool complete;
private float timer;
List<TextCreature> spawnedText;
public TextManager manager;
void Start()
{
spawnedText = new List<TextCreature>();
startPos = transform.position;
words = text.Split(' ');
}
// Update is called once per frame
void Update()
{
timer -= Time.deltaTime;
if (complete)
{
bool moveOn = true;
foreach (TextCreature t in spawnedText)
{
if (!t.done)
{
moveOn = false;
}
}
if (moveOn)
{
manager.Disable(this);
}
}
else
{
if (timer < 0)
{
timer = Random.Range(0.1f, 0.25f);
SpawnWord();
}
}
}
public void SetText(string t)
{
words = t.Split(' ');
}
public void SpawnWord()
{
TextMesh t = Instantiate(textPrefab, transform).GetComponent<TextMesh>();
t.text = words[index % words.Length];
t.text = words[Random.Range(0, words.Length)];
spawnedText.Add(t.GetComponent<TextCreature>());
t.transform.parent = container;
t.transform.localPosition = new Vector3(cursorPos.x, t.transform.localPosition.y, 0);
t.transform.localRotation = Quaternion.identity;
MeshRenderer r = t.GetComponent<MeshRenderer>();
cursorPos.x += (t.text.Length * characterSpacing) + spacing;
if (cursorPos.x > lineWidth)
{
container.position -= lineHeight * Vector3.up;
cursorPos.x = 0;
}
index++;
if (index >= words.Length)
{
complete = true;
index = 0;
cursorPos.x = 0;
container.position -= lineHeight * Vector3.up;
container.position -= lineHeight * Vector3.up;
// container.position = transform.position;
}
}
}
|
using AspNetMvcSample.Core.StoredProc.Input;
using AspNetMvcSample.Core.StoredProc.Output;
using CodeFirstStoredProcs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AspNetMvcSample.Core.StoredProc
{
public class StoredProcContext: AspNetMvcSampleDBContext
{
// input user
[StoredProcAttributes.Name("[User.Create]")]
public StoredProc<User_Input> UserCreate { get; set; }
[StoredProcAttributes.Name("[User.Get]")]
[StoredProcAttributes.ReturnTypes(typeof(GetUser_ResultSet))]
public StoredProc<object> GetAllUser { get; set; }
[StoredProcAttributes.Name("[dbo].[AspNetUserRoles.Update]")]
public StoredProc<UpdateUserRole_Input> updateUserRole { get; set; }
// update user
[StoredProcAttributes.Name("[User.Update]")]
public StoredProc<User_Update> UserUpdate { get; set; }
// delete user
[StoredProcAttributes.Name("[User.Delete]")]
public StoredProc<GetUserDelete_Input> UserDelete { get; set; }
// get user by id
[StoredProcAttributes.Name("[User.GetUserById]")]
[StoredProcAttributes.ReturnTypes(typeof(GetUser_ResultSet))]
public StoredProc<GetUser_Input> GetUserById { get; set; }
// get roles assigned to user
[StoredProcAttributes.Name("[Roles.GetRolesAssignedToUser]")]
[StoredProcAttributes.ReturnTypes(typeof(GetRoleAssignedToUser_ResultSet))]
public StoredProc<GetUser_Input> GetRolesAssignedToUser { get; set; }
[StoredProcAttributes.Name("[Role.Get]")]
[StoredProcAttributes.ReturnTypes(typeof(GetRole_ResultSet))]
public StoredProc<object> GetAllRoles { get; set; }
[StoredProcAttributes.Name("[Department.Create]")]
public StoredProc<Department_Input> DepartmentCreate { get; set; }
[StoredProcAttributes.Name("[Department.Update]")]
public StoredProc<Department_Input> DepartmentUpdate { get; set; }
[StoredProcAttributes.Name("[Department.Delete]")]
public StoredProc<DepartmentDelete_Input> DepartmentDelete { get; set; }
[StoredProcAttributes.Name("[Department.Get]")]
[StoredProcAttributes.ReturnTypes(typeof(GetDepartment_ResultSet))]
public StoredProc<object> GetDepartment { get; set; }
[StoredProcAttributes.Name("[Department.GetById]")]
[StoredProcAttributes.ReturnTypes(typeof(GetDepartment_ResultSet))]
public StoredProc<GetDepartmentById_Input> GetDepartmentById { get; set; }
[StoredProcAttributes.Name("[Employee.Create]")]
public StoredProc<Employee_Input> EmployeeCreate { get; set; }
[StoredProcAttributes.Name("[Employee.Update]")]
public StoredProc<Employee_Input> EmployeeUpdate { get; set; }
[StoredProcAttributes.Name("[Employee.Delete]")]
public StoredProc<EmployeeDelete_Input> EmployeeDelete { get; set; }
[StoredProcAttributes.Name("[Employee.Get]")]
[StoredProcAttributes.ReturnTypes(typeof(GetEmployee_ResultSet))]
public StoredProc<object> GetEmployee { get; set; }
[StoredProcAttributes.Name("[Employee.GetById]")]
[StoredProcAttributes.ReturnTypes(typeof(GetEmployeeById_ResultSet))]
public StoredProc<GetEmployeeById_Input> GeEmployeeById { get; set; }
//Constructor
public StoredProcContext()
{
this.InitializeStoredProcs();
}
}
}
|
namespace FixEmails
{
using System;
using System.Collections.Generic;
public class StartUp
{
public static void Main()
{
var input = Console.ReadLine();
var personalEmails = new Dictionary<string, string>();
while (input != "stop")
{
var name = input;
var email = Console.ReadLine();
if (email.EndsWith("uk") || email.EndsWith("us"))
{
input = Console.ReadLine();
continue;
}
else
{
personalEmails.Add(name, email);
}
input = Console.ReadLine();
}
foreach (var person in personalEmails)
{
Console.WriteLine($"{person.Key} -> {person.Value}");
}
}
}
}
|
namespace BettingSystem.Infrastructure.Teams.Configurations
{
using Domain.Teams.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using static Domain.Common.Models.ModelConstants.Common;
internal class TeamConfiguration : IEntityTypeConfiguration<Team>
{
public void Configure(EntityTypeBuilder<Team> builder)
{
builder
.HasKey(t => t.Id);
builder
.Property(t => t.Name)
.HasMaxLength(MaxNameLength)
.IsRequired();
builder
.HasOne(t => t.Logo)
.WithMany()
.HasForeignKey("LogoId")
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
builder
.HasOne(t => t.Coach)
.WithMany()
.HasForeignKey("CoachId")
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
builder
.HasMany(t => t.Players)
.WithOne()
.IsRequired()
.Metadata
.PrincipalToDependent
.SetField("players");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.