text stringlengths 13 6.01M |
|---|
using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
namespace JDE_Integration_HDL
{
public class Common
{
private DataTable dtInputData = new DataTable();
private DataTable dtPersonData = new DataTable();
private DataTable dtLookupData = new DataTable();
private string InputFilePath = string.Empty;
private string DATFilePath = ConfigurationManager.AppSettings["DATFile"].ToString();
private string LogFilePath = ConfigurationManager.AppSettings["LogFilePath"].ToString();
public void GeneratingDATFiles(string InputFile)
{
InputFilePath = InputFile;
dtInputData = ImportDataIntoDataTable(InputFile, "|", 0);
CreatingDATFiles();
}
private DataTable ImportDataIntoDataTable(
string FilePath,
string Delimiter,
int iHeaderLine)
{
DataTable dataTable = new DataTable();
try
{
string[] strArray1 = File.ReadAllLines(FilePath);
string[] strArray2 = strArray1[iHeaderLine].Split(Delimiter.ToCharArray());
int length = strArray2.GetLength(0);
for (int index = 0; index < length; ++index)
dataTable.Columns.Add(strArray2[index].ToLower(), typeof(string));
for (int index1 = iHeaderLine + 1; index1 < strArray1.GetLength(0); ++index1)
{
if (strArray1[index1] != "")
{
string[] strArray3 = strArray1[index1].Split(Delimiter.ToCharArray());
DataRow row = dataTable.NewRow();
for (int index2 = 0; index2 < length; ++index2)
row[index2] = (object)strArray3[index2];
dataTable.Rows.Add(row);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return dataTable;
}
public void CreatingDATFiles()
{
RemoveOldFiles(DATFilePath);
Generate_Location_Details(DATFilePath, "Location", InputFilePath);
}
public string GenerateDetails(string DetailsFor, string InputFilePath)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("METADATA|Location|FLEX:PER_LOCATIONS_DF|yardiCode(PER_LOCATIONS_DF=Global Data Elements)|LocationCode|SetCode|EffectiveStartDate|EffectiveEndDate|ActiveStatus|LocationName|Description|AddressLine1|AddressLine2");
stringBuilder.AppendLine("|AddressLine3|AddressLine4|TownOrCity|Region1|Region2|Region3|Country|PostalCode");
stringBuilder.Append("METADATA|LocationLegislative|FLEX:PER_LOCATION_LEG_EFF|EFF_CATEGORY_CODE|LleInformationCategory|LocationCode|SequenceNumber|SetCode|EffectiveStartDate|EffectiveEndDate");
stringBuilder.Append("|_MWS_REPORTING_INCLUDE(PER_LOCATION_LEG_EFF=HRX_US_MWS_INFORMATION)|_HR_REPORTING_LOCATION(PER_LOCATION_LEG_EFF=HRX_US_LOC_EEO_VETS_INF)");
stringBuilder.AppendLine("|_HR_REPORTING_PROXY_Display(PER_LOCATION_LEG_EFF=HRX_US_LOC_EEO_VETS_INF)|_DUNS_NUMBER(PER_LOCATION_LEG_EFF=HRX_US_REPORTING_INFORMATION)|_NAICS_NUMBER(PER_LOCATION_LEG_EFF=HRX_US_REPORTING_INFORMATION)");
foreach (DataRow row in (InternalDataCollectionBase)dtInputData.Rows)
{
stringBuilder.Append("MERGE|Location|");
stringBuilder.Append("Global Data Elements|");
if (row["LOCATION_NAME"].ToString().IndexOf('(') != -1)
stringBuilder.Append(row["LOCATION_NAME"].ToString().Split('(').GetValue(1).ToString().Replace(")", "").ToString() + "|");
else
stringBuilder.Append("|");
stringBuilder.Append(row["LOCATION_ID"].ToString() + "|");
stringBuilder.Append("COMMON|");
stringBuilder.Append(row["EFFECTIVE_START_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.Append(row["EFFECTIVE_END_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.Append(row["ACTIVE_STATUS"].ToString() + "|");
stringBuilder.Append(row["LOCATION_NAME"].ToString() + "|");
stringBuilder.Append(row["DESCRIPTION"].ToString() + "|");
stringBuilder.Append(row["ADDRESS_LINE_1"].ToString() + "|");
stringBuilder.Append(row["ADDRESS_LINE_2"].ToString() + "|");
stringBuilder.Append(row["ADDRESS_LINE_3"].ToString() + "|");
stringBuilder.Append(row["ADDRESS_LINE_4"].ToString() + "|");
stringBuilder.Append(row["TOWN_OR_CITY"].ToString() + "|");
stringBuilder.Append(row["REGION_1"].ToString() + "|");
stringBuilder.Append(row["REGION_2"].ToString() + "|");
stringBuilder.Append(row["REGION_3"].ToString() + "|");
stringBuilder.Append(row["COUNTRY"].ToString() + "|");
stringBuilder.AppendLine(row["POSTAL_CODE"].ToString());
stringBuilder = GenerateLocationLegislative(stringBuilder, row);
}
return stringBuilder.ToString();
}
public StringBuilder GenerateLocationLegislative(StringBuilder stringBuilder, DataRow row)
{
stringBuilder.Append("MERGE|LocationLegislative|HRX_US_MWS_INFORMATION|HCM_LOC_LEG|HRX_US_MWS_INFORMATION|");
stringBuilder.Append(row["LOCATION_ID"].ToString() + "|");
stringBuilder.Append("1|COMMON|");
stringBuilder.Append(row["EFFECTIVE_START_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.Append(row["EFFECTIVE_END_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.AppendLine("Y||||");
stringBuilder.Append("MERGE|LocationLegislative|HRX_US_LOC_EEO_VETS_INF|HCM_LOC_LEG|HRX_US_LOC_EEO_VETS_INF|");
stringBuilder.Append(row["LOCATION_ID"].ToString() + "|");
stringBuilder.Append("1|COMMON|");
stringBuilder.Append(row["EFFECTIVE_START_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.Append(row["EFFECTIVE_END_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.Append("|N|");
stringBuilder.Append(row["DIVISION"].ToString() + "|");
stringBuilder.AppendLine("|");
stringBuilder.Append("MERGE|LocationLegislative|HRX_US_REPORTING_INFORMATION|HCM_LOC_LEG|HRX_US_REPORTING_INFORMATION|");
stringBuilder.Append(row["LOCATION_ID"].ToString() + "|");
stringBuilder.Append("1|COMMON|");
stringBuilder.Append(row["EFFECTIVE_START_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.Append(row["EFFECTIVE_END_DATE"].ToString().Replace("-", "/") + "|");
stringBuilder.Append("|||");
stringBuilder.Append(row["DUNS Number"].ToString() + "|");
stringBuilder.AppendLine(row["NAICS Number"].ToString());
return stringBuilder;
}
public void Generate_Location_Details(
string FilePath,
string DATFileName,
string InputFilePath)
{
Directory.CreateDirectory(FilePath);
FileStream fileStream = new FileStream(FilePath + "Location.dat", FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter streamWriter = new StreamWriter((Stream)fileStream);
streamWriter.Write(GenerateDetails(DATFileName, InputFilePath));
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
public void RemoveOldFiles(string strFilePath)
{
foreach (FileInfo file in new DirectoryInfo(strFilePath).GetFiles())
{
if (File.Exists(strFilePath + (object)file))
File.Delete(strFilePath + (object)file);
}
}
public string ArchiveOldFiles()
{
StringBuilder stringBuilder = new StringBuilder();
try
{
string path = ConfigurationManager.AppSettings["ArchiveInputFile"] + "\\Archive_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
foreach (string file in Directory.GetFiles(ConfigurationManager.AppSettings["InputFile"]))
{
string str = file.Split('\\').GetValue(file.Split('\\').Length - 1).ToString();
File.Move(file, path + "\\" + str);
stringBuilder.Append("File has been successfully moved");
}
}
catch (Exception ex)
{
stringBuilder.Append(ex.Message.ToString());
}
return stringBuilder.ToString();
}
public void GeneratingLOGFile(string Message)
{
using (FileStream fileStream = new FileStream(LogFilePath + "DSIntegrationLogFile" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmssfff") + ".txt", FileMode.OpenOrCreate))
{
using (StreamWriter streamWriter = new StreamWriter((Stream)fileStream))
{
streamWriter.BaseStream.Seek(0L, SeekOrigin.End);
streamWriter.Write(Message);
streamWriter.WriteLine();
streamWriter.Flush();
}
}
}
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
namespace Zitadel.Spa.Dev.Controller
{
[Route("unauthed")]
public class UnauthorizedApi : ControllerBase
{
[HttpGet]
public object UnAuthedGet()
=> new { Ping = "Pong", Timestamp = DateTime.Now };
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Trees
{
/// <summary>
/// Get the different paths in a tree which sums up to the given value
/// </summary>
class TreePathSumsToValue
{
/// <summary>
/// Recursively get each path and keep the current sum that need to be matched and the path.
/// if the path is not found backtrack by removing the path.
///
/// The running time of the operation is O(n) since we have to visit all the elements once.
/// The space complexity will be O(depth of tree) ie O(n) for a non balanced tree.
/// </summary>
/// <param name="currentNode"></param>
/// <param name="sum"></param>
/// <param name="path"></param>
public void PrintPathWithSumToValue(BinaryTreeNode<int> currentNode, int sum, List<BinaryTreeNode<int>> path)
{
if (currentNode == null)
{
// error condition
return;
}
sum -= currentNode.Data;
path.Add(currentNode);
if (sum == 0 && currentNode.Left == null && currentNode.Right == null)
{
// print path
PrintPath(path);
}
PrintPathWithSumToValue(currentNode.Left, sum, path);
PrintPathWithSumToValue(currentNode.Right, sum, path);
path.Remove(currentNode);
}
/// <summary>
/// Prints the path of the tree
/// </summary>
/// <param name="path"></param>
private void PrintPath(List<BinaryTreeNode<int>> path)
{
if(path != null)
{
foreach(BinaryTreeNode<int> node in path)
{
Console.Write("{0} -> ", node.Data);
}
Console.WriteLine();
}
}
#region TestArea
public static void TestTreePathSumsToValue()
{
// create tree with 2 paths that sum to 6
BinaryTreeNode<int> root = new BinaryTreeNode<int>(1);
BinaryTreeNode<int> rootLeft = new BinaryTreeNode<int>(2);
BinaryTreeNode<int> rootRight = new BinaryTreeNode<int>(6);
root.Left = rootLeft;
root.Right = rootRight;
BinaryTreeNode<int> n1Left = new BinaryTreeNode<int>(3);
rootLeft.Left = n1Left;
BinaryTreeNode<int> n1Right = new BinaryTreeNode<int>(13);
rootLeft.Right = n1Right;
BinaryTreeNode<int> n2Right = new BinaryTreeNode<int>(-1);
rootRight.Right = n2Right;
TreePathSumsToValue tp = new TreePathSumsToValue();
tp.PrintPathWithSumToValue(root, 6, new List<BinaryTreeNode<int>>());
}
#endregion
}
}
|
namespace GatewayEDI.Logging.Factories
{
/// <summary> Factory to log to the console. </summary>
public class ConsoleLogFactory : NamedLogFactoryBase<ConsoleLog>
{
/// <summary> Creates a named log. </summary>
/// <param name="name"> Name of the log to create. </param>
/// <returns> A ConsoleLog with the specified name. </returns>
protected override ConsoleLog CreateLog(string name)
{
return new ConsoleLog(name);
}
}
} |
using AutoMapper;
using LocusNew.Core.AdminViewModels;
using LocusNew.Core.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using PagedList;
using System.IO;
using LocusNew.Core;
namespace LocusNew.Areas.Admin.Controllers
{
[Authorize]
public class ListingsManagerController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public ListingsManagerController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public ActionResult Index(string sortOrder, string listingNumber, string agent, int? page, int? cityPartId = 0, int? propertyType = 0, int? adType = 0, int? beds = 0, int? floor = -1, decimal? minPrice = 0, decimal? maxPrice = 0)
{
int pageSize = 8;
int pageNumber = (page ?? 1);
var model = new AdminSearchListingsViewModel()
{
ListingsList = Mapper.Map<IEnumerable<AdminListingsListViewModel>>(
_unitOfWork.Listings.SearchListings(sortOrder, null, listingNumber, agent, true, false, false, cityPartId, propertyType, adType, beds, floor, minPrice, maxPrice))
.ToPagedList(pageNumber, pageSize),
SearchForm = new AdminSearchFormViewModel()
{
PropertyTypes = _unitOfWork.PropertyTypes.GetPropertyTypes().AsEnumerable(),
AdTypes = _unitOfWork.AdTypes.GetAdTypes(),
CityParts = _unitOfWork.CityParts.GetCityParts(),
selectedListingNumber = listingNumber,
Agents = _unitOfWork.Users.GetActiveAgents(),
AdTypeId = (int)adType,
CityPartId = cityPartId,
AgentId = agent,
selectedBeds = beds,
selectedFloor = floor,
selectedListingType = propertyType,
selectedMaxPrice = maxPrice,
selectedMinPrice = minPrice,
selectedSaleLease = adType,
selectedSortOrder = sortOrder
}
};
ViewData["ResultNumber"] = model.ListingsList.TotalItemCount;
return View(model);
}
public ActionResult InactiveListings(string sortOrder, string listingNumber, string agent, int? page, int? cityPartId = 0, int? propertyType = 0, int? adType = 0, int? beds = 0, int? floor = -1, decimal? minPrice = 0, decimal? maxPrice = 0)
{
int pageSize = 8;
int pageNumber = (page ?? 1);
var model = new AdminSearchListingsViewModel()
{
ListingsList = Mapper.Map<IEnumerable<AdminListingsListViewModel>>(
_unitOfWork.Listings.SearchListings(sortOrder, null, listingNumber, agent, false, false, false, cityPartId, propertyType, adType, beds, floor, minPrice, maxPrice))
.ToPagedList(pageNumber, pageSize),
SearchForm = new AdminSearchFormViewModel()
{
PropertyTypes = _unitOfWork.PropertyTypes.GetPropertyTypes().AsEnumerable(),
AdTypes = _unitOfWork.AdTypes.GetAdTypes(),
CityParts = _unitOfWork.CityParts.GetCityParts(),
selectedListingNumber = listingNumber,
Agents = _unitOfWork.Users.GetActiveAgents(),
AdTypeId = (int)adType,
CityPartId = cityPartId,
AgentId = agent,
selectedBeds = beds,
selectedFloor = floor,
selectedListingType = propertyType,
selectedMaxPrice = maxPrice,
selectedMinPrice = minPrice,
selectedSaleLease = adType,
selectedSortOrder = sortOrder
}
};
ViewData["ResultNumber"] = model.ListingsList.TotalItemCount;
return View(model);
}
public ActionResult SoldListings(string sortOrder, string listingNumber, string agent, int? page, int? cityPartId = 0, int? propertyType = 0, int? adType = 0, int? beds = 0, int? floor = -1, decimal? minPrice = 0, decimal? maxPrice = 0)
{
int pageSize = 8;
int pageNumber = (page ?? 1);
var model = new AdminSearchListingsViewModel()
{
ListingsList = Mapper.Map<IEnumerable<AdminListingsListViewModel>>(
_unitOfWork.Listings.SearchListings(sortOrder, null, listingNumber, agent, true, true, false, cityPartId, propertyType, adType, beds, floor, minPrice, maxPrice))
.ToPagedList(pageNumber, pageSize),
SearchForm = new AdminSearchFormViewModel()
{
PropertyTypes = _unitOfWork.PropertyTypes.GetPropertyTypes().AsEnumerable(),
AdTypes = _unitOfWork.AdTypes.GetAdTypes(),
CityParts = _unitOfWork.CityParts.GetCityParts(),
selectedListingNumber = listingNumber,
Agents = _unitOfWork.Users.GetActiveAgents(),
AdTypeId = (int)adType,
CityPartId = cityPartId,
AgentId = agent,
selectedBeds = beds,
selectedFloor = floor,
selectedListingType = propertyType,
selectedMaxPrice = maxPrice,
selectedMinPrice = minPrice,
selectedSaleLease = adType,
selectedSortOrder = sortOrder
}
};
ViewData["ResultNumber"] = model.ListingsList.TotalItemCount;
return View(model);
}
public ActionResult ReservedListings(string sortOrder, string listingNumber, string agent, int? page, int? cityPartId = 0, int? propertyType = 0, int? adType = 0, int? beds = 0, int? floor = -1, decimal? minPrice = 0, decimal? maxPrice = 0)
{
int pageSize = 8;
int pageNumber = (page ?? 1);
var model = new AdminSearchListingsViewModel()
{
ListingsList = Mapper.Map<IEnumerable<AdminListingsListViewModel>>(
_unitOfWork.Listings.SearchListings(sortOrder, null, listingNumber, agent, true, false, true, cityPartId, propertyType, adType, beds, floor, minPrice, maxPrice))
.ToPagedList(pageNumber, pageSize),
SearchForm = new AdminSearchFormViewModel()
{
PropertyTypes = _unitOfWork.PropertyTypes.GetPropertyTypes().AsEnumerable(),
AdTypes = _unitOfWork.AdTypes.GetAdTypes(),
CityParts = _unitOfWork.CityParts.GetCityParts(),
selectedListingNumber = listingNumber,
Agents = _unitOfWork.Users.GetActiveAgents(),
AdTypeId = (int)adType,
CityPartId = cityPartId,
AgentId = agent,
selectedBeds = beds,
selectedFloor = floor,
selectedListingType = propertyType,
selectedMaxPrice = maxPrice,
selectedMinPrice = minPrice,
selectedSaleLease = adType,
selectedSortOrder = sortOrder
}
};
ViewData["ResultNumber"] = model.ListingsList.TotalItemCount;
return View(model);
}
public ActionResult AddListing()
{
var model = new AddListingViewModel()
{
AdTypes = _unitOfWork.AdTypes.GetAdTypes(),
PropertyTypes = _unitOfWork.PropertyTypes.GetPropertyTypes().AsEnumerable(),
Agents = _unitOfWork.Users.GetActiveAgents().AsEnumerable(),
PropertyOwners = _unitOfWork.PropertyOwners.GetPropertyOwners(),
CityParts = _unitOfWork.CityParts.GetCityParts().AsEnumerable(),
Sources = _unitOfWork.Sources.GetSources().AsEnumerable(),
};
return View(model);
}
public ActionResult EditListing(int id)
{
var model = Mapper.Map<EditListingViewModel>(_unitOfWork.Listings.GetListing(id));
model.AdTypes = _unitOfWork.AdTypes.GetAdTypes();
model.PropertyTypes = _unitOfWork.PropertyTypes.GetPropertyTypes().AsEnumerable();
model.Agents = _unitOfWork.Users.GetActiveAgents().AsEnumerable();
model.PropertyOwners = _unitOfWork.PropertyOwners.GetPropertyOwners();
model.CityParts = _unitOfWork.CityParts.GetCityParts().AsEnumerable();
model.Sources = _unitOfWork.Sources.GetSources().AsEnumerable();
return View("EditListing", model);
}
public JsonResult checkListinUniqueCode(string ListingUniqueCode)
{
return Json(!_unitOfWork.Listings.CheckListingUniqueCode(ListingUniqueCode), JsonRequestBehavior.AllowGet);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveNewListing(AddListingViewModel listing)
{
List<ListingImage> images = new List<ListingImage>();
Directory.CreateDirectory(Server.MapPath("~/DynamicContent/ListingImages/Listing" + listing.ListingUniqueCode.Trim()));
var path = "~/DynamicContent/ListingImages/Listing" + listing.ListingUniqueCode.Trim();
var pathToSave = "DynamicContent/ListingImages/Listing" + listing.ListingUniqueCode.Trim();
var imgPath = "";
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
ListingImage fileDetail = new ListingImage()
{
FileName = fileName,
Extension = Path.GetExtension(fileName),
FileNameNoExt = Path.GetFileNameWithoutExtension(fileName),
FilePath = pathToSave
};
images.Add(fileDetail);
imgPath = Path.Combine(Server.MapPath(path), fileDetail.FileName);
file.SaveAs(imgPath);
}
}
var dbListing = Mapper.Map<Listing>(listing);
dbListing.Images = images;
_unitOfWork.Listings.AddListing(dbListing);
_unitOfWork.Complete();
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveEditedListing(EditListingViewModel listing)
{
var lisDb = Mapper.Map(listing, _unitOfWork.Listings.GetListing(listing.Id));
List<ListingImage> images = new List<ListingImage>();
var pathToSave = _unitOfWork.ListingImages.GetListingImageByListingId(listing.Id).FilePath;
var path = "~/" + pathToSave;
var imgPath = "";
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
ListingImage fileDetail = new ListingImage()
{
FileName = fileName,
Extension = Path.GetExtension(fileName),
FileNameNoExt = Path.GetFileNameWithoutExtension(fileName),
FilePath = pathToSave
};
images.Add(fileDetail);
imgPath = Path.Combine(Server.MapPath(path), fileDetail.FileName);
file.SaveAs(imgPath);
}
}
var newImages = lisDb.Images.Concat(images).ToList();
lisDb.Images = newImages;
_unitOfWork.Complete();
//Clear OutupCache for that listing after changed
ClearCache(lisDb.Id);
return RedirectToAction("EditListing", new { id = listing.Id });
}
public ActionResult SetAsSold(int id)
{
var model = new AddAsSoldViewModel
{
ListingId = id
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveAsSold(AddAsSoldViewModel sold)
{
var newBuyer = Mapper.Map<PropertyBuyer>(sold);
var listing = _unitOfWork.Listings.GetListing(sold.Id);
listing.isSold = true;
listing.isReserved = false;
_unitOfWork.PropertyBuyers.AddPropertyBuyer(newBuyer);
_unitOfWork.Complete();
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteListing(int id)
{
_unitOfWork.Listings.RemoveListing(id);
_unitOfWork.Complete();
return RedirectToAction("Index");
}
public void ClearCache(int id)
{
Response.RemoveOutputCacheItem(Url.Action("Listing", "Search", new { id, area = "" }));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AudioManager : MonoBehaviour
{
public AudioSource music;
public Slider volume;
public Slider fxVolume;
void Start()
{
volume.value = PlayerPrefs.GetFloat("MusicVolume");
fxVolume.value = PlayerPrefs.GetFloat("FxVolume");
}
void Update()
{
if(music!=null)//prevent null errors
music.volume = volume.value;
}
public void VolumePrefs()
{
PlayerPrefs.SetFloat("MusicVolume", music.volume);
PlayerPrefs.SetFloat("FxVolume", fxVolume.value);
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Coldairarrow.Entity.Sto_BaseInfo
{
/// <summary>
/// Sto_StoreUnit
/// </summary>
[Table("Sto_StoreUnit")]
public class Sto_StoreUnit
{
/// <summary>
/// Id
/// </summary>
[Key]
public String Id { get; set; }
/// <summary>
/// StoreId
/// </summary>
public String StoreId { get; set; }
/// <summary>
/// UnitNo
/// </summary>
public String UnitNo { get; set; }
/// <summary>
/// UnitName
/// </summary>
public String UnitName { get; set; }
/// <summary>
/// UnitClass
/// </summary>
public String UnitClass { get; set; }
/// <summary>
/// UsedState
/// </summary>
public Boolean? UsedState { get; set; }
/// <summary>
/// CreateTime
/// </summary>
public DateTime? CreateTime { get; set; }
/// <summary>
/// Context
/// </summary>
public String Context { get; set; }
}
} |
using ConfigureSettings.API.Context;
using ConfigureSettings.API.Repository;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ConfigureSettings.API.Models.DataManager
{
public class AplicationManager : IDataRepository<Aplications>
{
readonly SettingsContext _settingsContext;
public AplicationManager(SettingsContext context)
{
_settingsContext = context;
}
public async Task AddAsync(Aplications entity)
{
_settingsContext.Set<Aplications>().Add(entity);
await _settingsContext.SaveChangesAsync();
}
public async Task DeleteAsync(Aplications entity)
{
_settingsContext.Aplications.Remove(entity);
await _settingsContext.SaveChangesAsync();
}
public async Task<Aplications> GetByIdAsync(int id)
{
return await _settingsContext.Aplications
.FirstOrDefaultAsync(e => e.AplicationId == id);
}
public async Task<IEnumerable<Aplications>> GetAllAsync() => await _settingsContext.Aplications.ToListAsync();
public async Task UpdateAsync(Aplications aplications, Aplications entity)
{
aplications.Name = entity.Name;
await _settingsContext.SaveChangesAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiveDemoLecture
{
class LectureDemo
{
static void Main(string[] args)
{
Console.WriteLine(5 % 2);
Console.WriteLine(1.5 / 0.0);
//try
//{
// Console.WriteLine( 5 / Convert.ToInt32("0"));
//}
//catch (System.DivideByZeroException dbze)
//{
// Console.WriteLine("Message = {0}", dbze.Message);
// Console.WriteLine("Stacktrace = {0}", dbze.StackTrace);
// Console.WriteLine("Source = {0}", dbze.Source);
//}
//catch (System.Exception e)
//{
// Console.WriteLine("Message = {0}", e.Message);
// Console.WriteLine("Stacktrace = {0}", e.StackTrace);
// Console.WriteLine("Source = {0}", e.Source);
//}
string someString = "EKostadinov";
Console.WriteLine("The 4th symbol of {0} is {1}", someString, someString[4]);
Console.WriteLine("The length is: " + someString.Length + " "+ "symbols");
}
}
}
|
using System.Collections.Generic;
using MealTime.Interface;
namespace MealTime.Domain
{
public abstract class BaseOrderRule : IRule
{
protected IDictionary<int, string> dishMap;
protected IEnumerable<int> dishes;
protected IList<string> output;
public BaseOrderRule(IDictionary<int, string> dishMap, IEnumerable<int> dishes, IList<string> output)
{
this.dishMap = dishMap;
this.dishes = dishes;
this.output = output;
}
public abstract void Execute();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MobilePhoneRetailer.DataLayer;
namespace MobilePhoneRetailer.BusinessLayer.Cart
{
public abstract class ICart
{
public abstract double getTotal(int custID);
}
} |
using EduHome.Models.Base;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace EduHome.Models.Entity
{
public class Address : BaseEntity
{
[Required,StringLength(maximumLength:25)]
public string City { get; set; }
[Required, StringLength(maximumLength: 50)]
public string Street { get; set; }
[BindNever]
public string Image { get; set; }
[Required, NotMapped]
public IFormFile Photo { get; set; }
public bool IsDeleted { get; set; }
public Contact Contact { get; set; }
public int? ContactId { 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.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mond;
namespace Mondbox
{
public partial class MainForm : Form
{
MondState mondState;
string scriptFilename;
MondProgram compiledProgram;
string originalText;
public string startFile;
delegate void AppendOutputText(string text, object[] args);
delegate void ToggleInputControls(bool state);
AppendOutputText appendOutputText;
ToggleInputControls toggleInputControls;
public MainForm()
{
InitializeComponent();
appendOutputText = new AppendOutputText((msg, args) =>
{
textOutput.AppendText(String.Format(msg, args) + Environment.NewLine);
});
toggleInputControls = new ToggleInputControls((state) =>
{
btnSendInput.Enabled = state;
textInput.Enabled = state;
if (!state)
textInput.Clear();
});
}
void WriteOutput(string message, params object[] args)
{
if (this.InvokeRequired)
this.Invoke(appendOutputText, message, args);
else
appendOutputText(message, args);
}
private async void MainForm_Load(object sender, EventArgs e)
{
originalText = labelDrop.Text;
labelDrop.DragEnter += (s, args) =>
{
if (args.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] data = args.Data.GetData(DataFormats.FileDrop) as string[];
string filename = data[0];
if (Path.GetExtension(filename) == ".mnd")
{
labelDrop.Text = "Drop that right here :]";
args.Effect = DragDropEffects.Link;
}
else
labelDrop.Text = "What is that " + Path.GetExtension(filename) + " thing? :[";
}
};
labelDrop.DragLeave += (s, args) =>
{
labelDrop.Text = originalText;
};
labelDrop.DragDrop += async (s, args) =>
{
string file = (args.Data.GetData(DataFormats.FileDrop) as string[])[0];
labelDrop.Text = String.Format("Got it! Gonna run that for you. In case you forgot, it's called{0}\"{1}\"",
Environment.NewLine, file);
PrintMondValue(await RunScript(File.ReadAllText(file), file), true);
};
mondState = new MondState();
mondState["print"] = new MondFunction((_, args) =>
{
PrintMondValue(args[0]);
return MondValue.Null;
});
mondState["input"] = new MondFunction((_, args) =>
{
return GetUserInputAsync().Result;
});
if (startFile != null)
{
string extension = Path.GetExtension(startFile);
if (extension != ".mnd")
labelDrop.Text = "What is that " + extension + " thing? :[";
else
{
labelDrop.Text = String.Format("Got it! Gonna run that for you. In case you forgot, it's called{0}\"{1}\"",
Environment.NewLine, startFile);
PrintMondValue(await RunScript(File.ReadAllText(startFile), startFile), true);
}
}
}
async Task<MondValue> GetUserInputAsync()
{
this.Invoke(toggleInputControls, true);
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
EventHandler click = new EventHandler((s, e) =>
{
tcs.SetResult(textInput.Text);
});
btnSendInput.Click -= click;
btnSendInput.Click += click;
string input = await tcs.Task;
this.Invoke(toggleInputControls, false);
return new MondValue(input);
}
private async void btnRunAgain_Click(object sender, EventArgs e)
{
PrintMondValue(await RunScript(compiledProgram), true);
}
private async void btnCompileAgain_Click(object sender, EventArgs e)
{
PrintMondValue(await RunScript(File.ReadAllText(scriptFilename), scriptFilename), true);
}
MondProgram CompileScript(string script, string filename = null)
{
try
{
WriteOutput("Compiling script...", filename);
MondProgram program = MondProgram.Compile(script, filename);
return program;
}
catch (MondCompilerException ex)
{
WriteOutput("Compiling failed: {0}", ex.Message);
return null;
}
}
async Task<MondValue> RunScript(string script, string filename)
{
WriteOutput("Running script (filename: {0})", filename);
MondProgram program = CompileScript(script, filename);
compiledProgram = program;
scriptFilename = filename;
btnRunAgain.Enabled = true;
btnCompileAgain.Enabled = true;
return await RunScript(program);
}
async Task<MondValue> RunScript(MondProgram program)
{
if (program == null)
return MondValue.Null;
WriteOutput("Running program...");
btnCompileAgain.Enabled = false;
btnRunAgain.Enabled = false;
System.Diagnostics.Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();
MondValue result = await Task.Run<MondValue>(() =>
{
MondValue value = MondValue.Undefined;
try
{
value = mondState.Load(program);
}
catch (MondRuntimeException ex)
{
WriteOutput("Run failed: {0}", ex.Message);
}
return value;
});
timer.Stop();
WriteOutput("Completed. Time: {0}", timer.Elapsed.ToString());
btnCompileAgain.Enabled = true;
btnRunAgain.Enabled = true;
return result;
}
void PrintMondValue(MondValue value, bool filter = false)
{
if (filter && value.Type == MondValueType.Undefined)
return;
string serialized = value.Serialize();
WriteOutput("> {0}", serialized);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fare
{
class Participant
{
public const double Speed = 160;
virtual public string Effect()
{
string ProblemWithTheBody;
if (Speed <= 180)
{
ProblemWithTheBody = "Everything is not good ";
}
return ProblemWithTheBody;
}
}
}
|
using Com.Colin.BusinessLayer;
using Com.Colin.Model;
using Com.Colin.Model.View;
using System.Collections.Generic;
using System.Web.Mvc;
namespace Com.Colin.UI.Controllers
{
[Authorize(Roles = "Admin")]
public class AnimalController : Controller
{
readonly IAnimalRepository repository;
/// <summary>
/// 构造器注入
/// </summary>
/// <param name="repository"></param>
public AnimalController(IAnimalRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
List<AnimalModel> animals = repository.GetAll();
List<AnimalViewModel> animalViewModels = new List<AnimalViewModel>();
foreach (AnimalModel animal in animals)
{
AnimalViewModel animalViewModel = new AnimalViewModel();
animalViewModel.Name = animal.Name;
//animalViewModel.SpeciesName = animal.Species.Name;
animalViewModel.BirthDay = animal.BirthDay.Value.ToString("yyyy-MM-dd");
animalViewModels.Add(animalViewModel);
}
return View(animalViewModels);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ChatApplication.Dtos;
using ChatApplication.Models;
namespace ChatApplication.Helpers
{
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
//CreateMap<TblBook, BookListDto>();
CreateMap<LoginDto, TblUser>();
CreateMap<RegisterDto, TblUser>();
}
}
}
|
using Newtonsoft.Json;
using System;
namespace Repositories.Entities
{
public class ExchangeTable
{
[JsonProperty("table")]
public string Table { get; set; }
[JsonProperty("no")]
public string No { get; set; }
[JsonProperty("effectiveDate")]
public DateTimeOffset EffectiveDate { get; set; }
[JsonProperty("rates")]
public ExchangeTableRate[] Rates { get; set; }
}
}
|
using System.Collections.Generic;
using BL;
using Shared.DTO;
using System.Web.Http;
using System.Web.Http.Results;
using System.Net.Http;
using System.Net;
using System.Linq;
namespace Nagarro_Exit_Test_Assignment.Controllers
{
public class HouseController : ApiController
{
public HttpResponseMessage GetAll()
{
HouseBL houseBL = new HouseBL();
ResponseFormat<IEnumerable<HouseDTO>> response = new ResponseFormat<IEnumerable<HouseDTO>>();
response.Data = houseBL.GetAll();
if(response.Data==null)
{
response.Message = "there was some error";
response.Success = false;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
else if (response.Data.Count()==0)
{
response.Message = "Empty List";
response.Success = false;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
else
{
response.Message = "Retrieved Successfully";
response.Success = true;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
}
[Route("api/house/state")]
public HttpResponseMessage GetStateReport(string state)
{
HouseBL houseBL = new HouseBL();
ResponseFormat<List<int>> response = new ResponseFormat<List<int>>();
response.Data = houseBL.StatePopulation();
response.Message= "Retrieved Successfully";
response.Success = true;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
public HttpResponseMessage Get(int id)
{
HouseBL houseBL = new HouseBL();
ResponseFormat<HouseDTO> response = new ResponseFormat<HouseDTO>();
response.Data = houseBL.GetById(id);
if (response.Data == null)
{
response.Success = false;
response.Message = "House Not Found";
return Request.CreateResponse(HttpStatusCode.OK, response);
}
else
{
response.Success = true;
response.Message = "Retrieved Successfully";
return Request.CreateResponse(HttpStatusCode.OK, response);
}
}
// POST: api/Home
public HttpResponseMessage Post(HouseDTO house)
{
HouseBL houseBL = new HouseBL();
ResponseFormat<HouseDTO> response = new ResponseFormat<HouseDTO>();
response.Data = houseBL.Create(house);
if (response.Data!=null)
{
response.Message = "House Created";
response.Success = true;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
else
{
response.Message = "There Was Some Error";
response.Success = false;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
}
//DELETE: api/Delete
public HttpResponseMessage Delete(int id)
{
HouseBL houseBL = new HouseBL();
ResponseFormat<bool> response = new ResponseFormat<bool>();
response.Data = houseBL.DeleteById(id);
if (response.Data)
{
response.Message = "House Deleted";
response.Success = true;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
else
{
response.Message = "Cannot Delete";
response.Success = false;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
}
////Update:
//public void Put(int id, [FromBody]MemberDTO member)
// {
// }
}
}
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Xml.Linq;
using NHibernate.Cfg;
using Xlns.BusBook.Core.DAL;
namespace Xlns.BusBook.UnitTest
{
[TestClass]
public class ConfigurationTest
{
[TestMethod]
public void se_non_ho_inizializzato_percorso_del_file_di_configurazione_non_riesco_a_recuperare_oggetto_configuratore()
{
try
{
var current = ConfigurationManager.Configurator.Istance.xml;
}
catch (Exception ex)
{
Assert.IsNotNull(ex);
}
}
[TestMethod]
public void inizializzando_percorso_del_file_di_configurazione_oggetto_configuratore_ha_struttura_caricata()
{
ConfigurationManager.Configurator.configFileName = @"C:\Xlns\BuX\BusBook\Xlns.BusBook.UI.Web\Config\BusBook.config";
var current = ConfigurationManager.Configurator.Istance.xml;
Assert.IsNotNull(ConfigurationManager.Configurator.Istance.xml);
}
[TestMethod]
public void inizializzando_in_modo_errato_percorso_del_file_di_configurazione_non_riesco_a_recuperare_oggetto_configuratore()
{
try
{
ConfigurationManager.Configurator.configFileName = @"percorso no valido";
var current = ConfigurationManager.Configurator.Istance.xml;
}
catch (Exception ex)
{
Assert.IsNotNull(ex);
}
}
[TestMethod()]
public void inizializzando_percorso_del_file_di_configurazione_recupero_valore_hibernateConfiguration()
{
string expected = "pippo";
ConfigurationManager.Configurator.configFileName = @"C:\Xlns\BuX\BusBook\Xlns.BusBook.UI.Web\Config\BusBook.config";
ConfigurationManager.Configurator.Istance.xml =
new XElement("configuration",
new XElement("core",
new XElement("DAL",
new XElement("hibernateConfiguration", "pippo")
)
)
);
string actual;
actual = ConfigurationManager.Configurator.Istance.hibernateConfiguration;
Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void inizializzando_percorso_del_file_di_configurazione_recupero_valore_connectionString()
{
string expected = "pippo";
ConfigurationManager.Configurator.configFileName = @"C:\Xlns\BuX\BusBook\Xlns.BusBook.UI.Web\Config\BusBook.config";
ConfigurationManager.Configurator.Istance.xml =
new XElement("configuration",
new XElement("core",
new XElement("DAL",
new XElement("connectionString", "pippo")
)
)
);
string actual;
actual = ConfigurationManager.Configurator.Istance.connectionString;
Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void inizializzando_percorso_del_file_di_configurazione_recupero_valore_itemsPerPage()
{
int expected = 5;
ConfigurationManager.Configurator.configFileName = @"C:\Xlns\BuX\BusBook\Xlns.BusBook.UI.Web\Config\BusBook.config";
ConfigurationManager.Configurator.Istance.xml =
new XElement("configuration",
new XElement("UI",
new XElement("Web",
new XElement("itemsPerPage", "5")
)
)
);
int actual;
actual = ConfigurationManager.Configurator.Istance.itemsPerPage;
Assert.AreEqual(expected, actual);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Dentistry
{
class Functions
{
public static string dateConvert(string date)
{
try
{
string[] str = date.Split('/');
if (str[1].Length == 1)
str[1] = "0" + str[1];
if (str[2].Length == 1)
str[2] = "0" + str[2];
string newDate = String.Format("{0}/{1}/{2}", numConvert(str[0]), numConvert(str[1]), numConvert(str[2]));
return newDate;
}
catch
{
return date;
}
}
public static string numConvert(string num)
{
string newStr = "";
for (int i = 0; i < num.Length; i++)
{
switch (num[i])
{
case '۱':
newStr = newStr + '1';
break;
case '۲':
newStr = newStr + '2';
break;
case '۳':
newStr = newStr + '3';
break;
case '۴':
newStr = newStr + '4';
break;
case '۵':
newStr = newStr + '5';
break;
case '۶':
newStr = newStr + '6';
break;
case '۷':
newStr = newStr + '7';
break;
case '۸':
newStr = newStr + '8';
break;
case '۹':
newStr = newStr + '9';
break;
case '۰':
newStr = newStr + '0';
break;
default:
newStr = newStr + num[i];
break;
}
}
return newStr;
}
public static void dgvKeyDown(DataGridView dgv, KeyEventArgs e)
{
try
{
switch (e.KeyCode)
{
case Keys.Up:
dgv.Rows[dgv.CurrentRow.Index - 1].Selected = true;
dgv.CurrentCell = dgv[0, dgv.CurrentRow.Index - 1];
dgv.FirstDisplayedScrollingRowIndex = dgv.CurrentRow.Index;
break;
case Keys.Down:
dgv.Rows[dgv.CurrentRow.Index + 1].Selected = true;
dgv.CurrentCell = dgv[0, dgv.CurrentRow.Index + 1];
dgv.FirstDisplayedScrollingRowIndex = dgv.CurrentRow.Index;
break;
case Keys.Escape:
dgv.Visible = false;
break;
default:
break;
}
}
catch (Exception ex)
{
return;
}
}
public static Double ConvertToDouble(object str)
{
try
{
if (str.ToString() == "") return 0;
return Convert.ToDouble(str);
}
catch
{
return 0;
}
}
public static string ConvertToString(object str)
{
try
{
try
{
if (str == null)
{
return "";
}
else
return (string)(str);
}
catch
{
return str.ToString();
}
}
catch
{
return "";
}
}
public static void Message(string text)
{
MessageBox.Show(text, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading);
}
public static Boolean CgetGrsanadCount(string collcode)
{
string s;
s = database_.ExeScalar("select count(*) from tblgrsanad where collcode='" + collcode + "'");
if ( Convert.ToDouble (s)> 0 )
return true ;
else
return false ;
}
public static Boolean GgetGrsanadCount(string gCode)
{
string s;
s = database_.ExeScalar("select COUNT(*) from tblgrsanad where substring((collcode),1,1)='"+ gCode +"'");
if (Convert.ToDouble(s) > 0)
return true;
else
return false;
}
public static void s(Control control)
{
foreach (Control c in control.Controls)
{
if (c is DevComponents.DotNetBar.RibbonBar)
{
if (c.Tag != null)
{
if (Functions_.getUserAccess(((c).Tag).ToString()))
{
MessageBox.Show("");
}
}
b(c as DevComponents.DotNetBar.RibbonBar);
}
}
}
public static void b(DevComponents.DotNetBar.RibbonBar control)
{
foreach (DevComponents.DotNetBar.ButtonItem c in control.Items )
{
if (c.Tag != null)
{
if (!Functions_.getUserAccess(((c).Tag).ToString()))
{
c.Enabled = false;
}
}
}
}
public static void Access(Control control)
{
foreach (Control c in control.Controls)
{
if (c is DevComponents.DotNetBar.RibbonPanel)
{
s(c);
}
//if (c is DevComponents.DotNetBar.RibbonBar)
//{
// Access(c);
//}
//if (c is DevComponents.DotNetBar.ButtonItem)
//{
// // if (Functions_.getUserAccess(((c).Tag).ToString()))
// {
// MessageBox.Show("");
// }
//}
//}
//else if (c is DevComponents.DotNetBar.ExpandablePanel)
//{
// //checkeboxState(c, State);
}
}
}
}
|
using System;
namespace src.SmartSchool.WebAPI.V1.Dtos
{
/// <summary>
/// Versão 1: classe responsável pela difinição de propriedade de registros da entidade Professor.
/// </summary>
public class ProfessorRegistrarDto
{
/// <summary>
/// Identificação de chave no banco de dados.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Define o registro do professor(a).
/// </summary>
public int Registro { get; set; }
/// <summary>
/// Define o Nome do professor(a).
/// </summary>
public string Nome { get; set; }
/// <summary>
/// Define o Sobrenome do professor(a).
/// </summary>
public string Sobrenome { get; set; }
/// <summary>
/// Define o Telefone do professor(a).
/// </summary>
public string Telefone { get; set; }
/// <summary>
/// Define a Data de Início de curso.
/// </summary>
public DateTime DataIni { get; set; } = DateTime.Now;
/// <summary>
/// Define a Data de Fim de curso.
/// </summary>
public DateTime? DataFim { get; set; } = null;
/// <summary>
/// Verifica se aluno(a) está ativo ou não.
/// </summary>
public bool Ativo { get; set; } = true;
}
}
|
namespace Vapoteur.Models
{
public class Accumulateur
{
public int Id { get; set; }
public string Marque { get; set; }
public int DechargeMax{ get; set; }
public int Capacité{ get; set; }
}
} |
using Arcgis.Directions.BL.Services;
using Arcgis.Directions.BL.SSOAuth;
using Arcgis.Directions.VM;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
namespace Arcgis.Directions.UI.Controllers
{
public class HomeController : Controller
{
PoiService _poiService;
public ActionResult Index()
{
var ssoOvreiden = false;
bool.TryParse(ConfigurationManager.AppSettings[@"SSOveriden"], out ssoOvreiden);
if (ssoOvreiden && Session[nameof(UserData)] == null)
{
var user = new UserData
{
UserID = ConfigurationManager.AppSettings[@"User_id"],
Username = ConfigurationManager.AppSettings[@"Username"]
};
Session[nameof(UserData)] = user;
Session["Username"] = user.Username;
return RedirectToAction(nameof(Index), @"Home");
}
if (Session[nameof(UserData)] == null)
return Redirect(ConfigurationManager.AppSettings[@"LoginRedirect"]);
var vm = GetPois();
return View(vm);
}
public ActionResult Login()
{
var authToken = Request.QueryString["SSO_AUTH_TOKEN"];
var ssoOvreiden = false;
bool.TryParse(ConfigurationManager.AppSettings[@"SSOveriden"], out ssoOvreiden);
if (ssoOvreiden)
{
var user = new UserData
{
UserID = ConfigurationManager.AppSettings[@"User_id"],
Username = ConfigurationManager.AppSettings[@"Username"]
};
Session[nameof(UserData)] = user;
return RedirectToAction(nameof(Index), @"Home");
}
if (!string.IsNullOrEmpty(authToken))
{
_poiService = new PoiService();
var user = _poiService.ValidateUser(authToken);
Session[nameof(UserData)] = user;
}
var vm = GetPois();
return View(vm);
}
public ActionResult Logout()
{
if (Session[nameof(UserData)] != null) Session.Remove(nameof(UserData));
return Redirect(ConfigurationManager.AppSettings[@"LoginRedirect"]);
}
public ActionResult ChangeLanguage(string lang) => Redirect($"~/{lang}");
GetPOIVM GetPois()
{
var lang = (string)ControllerContext.RouteData.Values[@"lang"];
var vm = new GetPOIVM();
_poiService = new PoiService();
vm = _poiService.GetStartupData();
var defaultLang = vm.LanguageList.FirstOrDefault(l => l.Name.Equals(lang));
if (defaultLang == null) defaultLang = vm.LanguageList.FirstOrDefault();
vm.Langugae = defaultLang;
return vm;
}
public ActionResult Error() => View();
[HttpPost]
public JsonResult GetPoiList(string keywords)
{
var vm = new GetPOIVM();
_poiService = new PoiService();
var user = new UserData();
user = Session[nameof(UserData)] as UserData;
var userID = 0;
int.TryParse(user.UserID, out userID);
vm = _poiService.GetAvailablePoiByDescription(keywords, userID);
return Json(vm?.CusPoiList ?? null, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult GetPoiByID(int id)
{
var vm = new GetPOIVM();
_poiService = new PoiService();
vm = _poiService.GetPoiByID(id);
return Json(vm?.CusPoi ?? null, JsonRequestBehavior.AllowGet);
}
}
} |
namespace BoatSimulator
{
using System;
public class StartUp
{
public static void Main()
{
char firstBoat = char.Parse(Console.ReadLine());
char secondBoat = char.Parse(Console.ReadLine());
int num = int.Parse(Console.ReadLine());
int pointsFirstBoat = 0;
int pointsSecondBoat = 0;
for (int i = 1; i <= num; i++)
{
string word = Console.ReadLine();
if (word == "UPGRADE")
{
firstBoat += (char)3;
secondBoat += (char)3;
}
else
{
if (i % 2 == 1)
pointsFirstBoat += word.Length;
else
pointsSecondBoat += word.Length;
}
if (pointsFirstBoat >= 50 || pointsSecondBoat >= 50)
break;
}
if (pointsFirstBoat > pointsSecondBoat)
Console.WriteLine(firstBoat);
else
Console.WriteLine(secondBoat);
}
}
}
|
using Pe.Stracon.Politicas.Aplicacion.Core.Base;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using System.Collections.Generic;
namespace Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract
{
/// <summary>
/// Definición del servicio de aplicación Plantilla Notificacion Service
/// </summary>
/// <remarks>
/// Creación: GMD 22150326 <br />
/// Modificación: <br />
/// </remarks>
public interface IPlantillaNotificacionService : IGenericService
{
/// <summary>
/// Realiza la busqueda de Plantilla Notificación
/// </summary>
/// <param name="filtro">Parametros a buscar</param>
/// <returns>Lista de Plantillas de Notificación</returns>
ProcessResult<List<PlantillaNotificacionResponse>> BuscarPlantillaNotificacion(PlantillaNotificacionRequest filtro);
/// <summary>
/// Registra Plantilla de Notificación
/// </summary>
/// <param name="data">data</param>
/// <returns>Indicador con el resultado de la operación</returns>
ProcessResult<PlantillaNotificacionRequest> RegistrarPlantillaNotificacion(PlantillaNotificacionRequest data);
}
}
|
using Foundation;
using Microsoft.Maui.LifecycleEvents;
using Sentry.Maui.Internal;
using Sentry.Maui.Tests.Mocks;
namespace Sentry.Maui.Tests;
public partial class SentryMauiAppBuilderExtensionsTests
{
[Fact]
public void UseSentry_BindsToApplicationStartupEvent_iOS()
{
// Arrange
var application = MockApplication.Create();
var binder = Substitute.For<IMauiEventsBinder>();
var builder = _fixture.Builder;
builder.Services.AddSingleton<IApplication>(application);
builder.Services.AddSingleton(binder);
builder.UseSentry(ValidDsn);
using var app = builder.Build();
var iosApplication = new MockIosApplication(application, app.Services);
// A bit of hackery here, because we can't mock UIKit.UIApplication.
var launchOptions = NSDictionary.FromObjectAndKey(iosApplication, new NSString("application"));
// Act
var lifecycleEventService = app.Services.GetRequiredService<ILifecycleEventService>();
lifecycleEventService.InvokeEvents<iOSLifecycle.WillFinishLaunching>
(nameof(iOSLifecycle.WillFinishLaunching), del =>
del.Invoke(null!, launchOptions));
// Assert
binder.Received(1).BindApplicationEvents(application);
}
private class MockIosApplication : NSObject, IPlatformApplication
{
public MockIosApplication(IApplication application, IServiceProvider services)
{
Application = application;
Services = services;
}
public IApplication Application { get; }
public IServiceProvider Services { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xlns.BusBook.Core.Model;
using Xlns.BusBook.Core.Repository;
namespace Xlns.BusBook.Core
{
public class UtenteManager
{
public void Save(Utente utente)
{
if (utente.Id != 0 && utente.Agenzia == null)
{
AgenziaRepository ar = new AgenziaRepository();
utente.Agenzia = ar.GetAgenziaByIdUtente(utente.Id);
UtenteRepository ur = new UtenteRepository();
ur.Save(utente);
}
}
}
}
|
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Input.StylusPlugIns;
using System.Windows.Media;
namespace Client.Helpers.Paint
{
public class W2_DrawEllipse : W0_DrawObject
{
public W2_DrawEllipse(MyInkCanvas myInkCanvas) : base(myInkCanvas)
{
}
public override void CreateNewStroke(InkCanvasStrokeCollectedEventArgs e)
{
InkStroke = new DrawEllipseStroke(this, e.Stroke.StylusPoints);
}
public override Point Draw(Point first, DrawingContext dc, StylusPointCollection points)
{
Point pt = (Point)points.Last();
Vector v = Point.Subtract(pt, first);
double radiusX = (pt.X - first.X) / 2.0;
double radiusY = (pt.Y - first.Y) / 2.0;
Point center = new Point((pt.X + first.X) / 2.0, (pt.Y + first.Y) / 2.0);
//填充
//画轮廓
Pen pen = new Pen(colorBrush, 1.0);
dc.DrawEllipse(null, pen, center, radiusX, radiusY);
return first;
}
protected override void OnStylusDown(RawStylusInput rawStylusInput)
{
base.OnStylusDown(rawStylusInput);
previousPoint = (Point)rawStylusInput.GetStylusPoints().First();
}
protected override void OnStylusMove(RawStylusInput rawStylusInput)
{
StylusPointCollection stylusPoints = rawStylusInput.GetStylusPoints();
this.Reset(Stylus.CurrentStylusDevice, stylusPoints);
base.OnStylusMove(rawStylusInput);
}
protected override void OnDraw(DrawingContext drawingContext, StylusPointCollection stylusPoints, Geometry geometry, Brush fillBrush)
{
Draw(previousPoint, drawingContext, stylusPoints);
base.OnDraw(drawingContext, stylusPoints, geometry, brush);
}
}
public class DrawEllipseStroke : DrawObjectStroke
{
public DrawEllipseStroke(W2_DrawEllipse ink, StylusPointCollection stylusPoints)
: base(ink, stylusPoints)
{
this.RemoveDirtyStylusPoints();
}
protected override void DrawCore(DrawingContext drawingContext, DrawingAttributes drawingAttributes)
{
base.DrawCore(drawingContext, drawingAttributes);
Point pt1 = (Point)StylusPoints.First();
ink.Draw(pt1, drawingContext, StylusPoints);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Ricky.Infrastructure.Core.ObjectContainer.Dependency;
namespace Ricky.Infrastructure.Core.ObjectContainer.Autofac.DependencyManagement
{
public class AutofacContainerManager : IContainerManager
{
private IContainer _container;
public IContainer Container { get { return _container; } }
public AutofacContainerManager(IContainer container)
{
this._container = container;
}
public void Dispose()
{
if (_container != null)
{
_container.Dispose();
_container = null;
}
}
public void AddResolvingObserver(IResolvingObserver observer)
{
}
public void AddComponent<TService>(string key = "", ComponentLifeStyle lifeStyle = ComponentLifeStyle.Transient)
{
AddComponent<TService, TService>(key, lifeStyle);
}
public void AddComponent(Type service, string key = "", ComponentLifeStyle lifeStyle = ComponentLifeStyle.Transient)
{
AddComponent(service, service, key, lifeStyle);
}
public void AddComponent<TService, TImplementation>(string key = "", ComponentLifeStyle lifeStyle = ComponentLifeStyle.Transient)
{
UpdateContainer(x =>
{
var serviceTypes = new List<Type> { typeof(TService) };
if ((typeof(TService)).IsGenericType)
{
var temp = x.RegisterGeneric(typeof(TImplementation)).As(serviceTypes.ToArray()).PerLifeStyle(lifeStyle);
if (!string.IsNullOrEmpty(key))
{
temp.Keyed(key, typeof(TService));
}
}
else
{
var temp = x.RegisterType(typeof(TImplementation)).As(
serviceTypes.ToArray()).PerLifeStyle(lifeStyle);
if (!string.IsNullOrEmpty(key))
{
temp.Keyed(key, typeof(TService));
}
}
});
}
public void AddComponent(Type service, Type implementation, string key = "", ComponentLifeStyle lifeStyle = ComponentLifeStyle.Singleton,
params Parameter[] parameters)
{
UpdateContainer(x =>
{
var serviceTypes = new List<Type> { service };
if (service.IsGenericType)
{
var temp = x.RegisterGeneric(implementation).As(serviceTypes.ToArray()).PerLifeStyle(lifeStyle);
if (parameters != null && parameters.Any())
{
temp = temp.WithParameters(parameters.Select(p => new NamedParameter(p.Name, p.ValueCallback())));
}
if (!string.IsNullOrEmpty(key))
{
temp.Keyed(key, service);
}
}
else
{
var temp = x.RegisterType(implementation).As(serviceTypes.ToArray()).PerLifeStyle(lifeStyle);
if (parameters != null && parameters.Any())
{
temp = temp.WithParameters(parameters.Select(p => new NamedParameter(p.Name, p.ValueCallback())));
}
if (!string.IsNullOrEmpty(key))
{
temp.Keyed(key, service);
}
}
});
// UpdateContainer(x =>
// {
// var serviceTypes = new List<Type> { service };
// var temp = x.RegisterType(implementation).As(serviceTypes.ToArray()).
// WithParameters(properties.Select(y => new NamedParameter(y.Key, y.Value)));
// if (!string.IsNullOrEmpty(key))
// {
// temp.Keyed(key, service);
// }
// });
}
public void AddComponentInstance<TService>(object instance, string key = "")
{
AddComponentInstance(typeof(TService), instance, key);
}
public void AddComponentInstance(object instance, string key = "")
{
AddComponentInstance(instance.GetType(), instance, key);
}
public void AddComponentInstance(Type service, object instance, string key = "")
{
UpdateContainer(x =>
{
var registration = x.RegisterInstance(instance).Keyed(key, service).As(service).PerLifeStyle(ComponentLifeStyle.Transient);
});
}
public T Resolve<T>(string key = "", params Parameter[] parameters) where T : class
{
if (string.IsNullOrEmpty(key))
{
return Scope().Resolve<T>();
}
return Scope().ResolveKeyed<T>(key);
}
public object Resolve(Type type, string key = "", params Parameter[] parameters)
{
if (String.IsNullOrEmpty(key))
{
return Scope().Resolve(type);
}
return Scope().ResolveKeyed(key, type);
}
public object ResolveGeneric(Type genericType, params Type[] genericTypeParameters)
{
throw new NotImplementedException();
}
public T[] ResolveAll<T>(string key = "")
{
if (string.IsNullOrEmpty(key))
{
return Scope().Resolve<IEnumerable<T>>().ToArray();
}
return Scope().ResolveKeyed<IEnumerable<T>>(key).ToArray();
}
public object[] ResolveAll(Type type, string key = "")
{
return null;
}
public T TryResolve<T>(string key = "", params Parameter[] parameters)
{
return (T)TryResolve(typeof(T), key, parameters);
}
public object TryResolve(Type type, string key = "", params Parameter[] parameters)
{
return Resolve(type, key, parameters);
}
public T ResolveUnregistered<T>() where T : class
{
return null;
}
public object ResolveUnregistered(Type type)
{
return null;
}
public void InjectProperties(object instance)
{
this.Container.InjectProperties(instance);
}
private void UpdateContainer(Action<ContainerBuilder> action)
{
var builder = new ContainerBuilder();
action.Invoke(builder);
builder.Update(_container);
}
public ILifetimeScope Scope()
{
try
{
return AutofacRequestLifetimeHttpModule.GetLifetimeScope(Container, null);
}
catch (Exception)
{
return Container;
}
//try
//{
// if (HttpContext.Current != null)
// return AutofacDependencyResolver.Current.RequestLifetimeScope;
// //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
// return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
//}
//catch (Exception)
//{
// //we can get an exception here if RequestLifetimeScope is already disposed
// //for example, requested in or after "Application_EndRequest" handler
// //but note that usually it should never happen
// //when such lifetime scope is returned, you should be sure that it'll be disposed once used (e.g. in schedule tasks)
// return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
//}
}
}
}
|
using UnityEngine;
using System.Collections;
public class Turret : MonoBehaviour
{
/// <summary>
/// The body rotation.
/// </summary>
[SerializeField] private Rotation bodyRotation = null;
/// <summary>
/// The gun rotation.
/// </summary>
[SerializeField] private Rotation gunRotation = null;
/// <summary>
/// The projectile prefab.
/// </summary>
[SerializeField] private GameObject projectilePrefab = null;
/// <summary>
/// The projectile spawn position and orientation.
/// </summary>
[SerializeField] private Transform projectileSpawn = null;
/// <summary>
/// The rotation speed.
/// </summary>
[SerializeField] private float rotationSpeed = 1;
/// <summary>
/// The movement speed.
/// </summary>
[SerializeField] private float movementSpeed = 0.1f;
void Update ()
{
// Check for input each frame.
CheckInput();
}
/// <summary>
/// Checks the input.
/// </summary>
void CheckInput ()
{
// Check input for body rotation.
RotateBodyInput();
// Check input for gun rotation.
RotateGunInput();
// Check input for forward and backward movement.
Move();
// Check input for base rotation.
RotateBase();
// Check input for turret fire.
FireInput();
}
/// <summary>
/// Checks input for body rotation.
/// </summary>
private void RotateBodyInput ()
{
// Check horizontal input to rotate body.
if (Input.GetKey(KeyCode.RightArrow))
{
this.bodyRotation.Rotate(this.rotationSpeed);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
this.bodyRotation.Rotate(-this.rotationSpeed);
}
}
/// <summary>
/// Checks input for gun rotation.
/// </summary>
private void RotateGunInput ()
{
// Check vertical input to rotate gun.
if (Input.GetKey(KeyCode.UpArrow))
{
this.gunRotation.Rotate(this.rotationSpeed);
}
if (Input.GetKey(KeyCode.DownArrow))
{
this.gunRotation.Rotate(-this.rotationSpeed);
}
}
/// <summary>
/// Moves the turret forward or backward.
/// </summary>
private void Move ()
{
if (Input.GetKey(KeyCode.W))
{
this.transform.Translate(new Vector3(0, 0, this.movementSpeed));
}
if (Input.GetKey(KeyCode.S))
{
this.transform.Translate(new Vector3(0, 0, -this.movementSpeed));
}
}
/// <summary>
/// Rotates the turret base.
/// </summary>
private void RotateBase ()
{
if (Input.GetKey(KeyCode.A))
{
this.transform.Rotate(new Vector3(0, -this.rotationSpeed, 0));
}
if (Input.GetKey(KeyCode.D))
{
this.transform.Rotate(new Vector3(0, this.rotationSpeed, 0));
}
}
/// <summary>
/// Fires a projectile.
/// </summary>
private void FireInput ()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// Instantiate a projectile.
GameObject projectile = Instantiate(this.projectilePrefab) as GameObject;
// Match the projectile's position and orientation to its spawner transform,
// so it can travel in the correct direction.
projectile.transform.eulerAngles = this.projectileSpawn.eulerAngles;
projectile.transform.position = this.projectileSpawn.position;
}
}
}
|
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Dto;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
namespace MediaBrowser.Controller.LiveTv
{
/// <summary>
/// Represents a single live tv back end (next pvr, media portal, etc).
/// </summary>
public interface ILiveTvService
{
/// <summary>
/// Occurs when [data source changed].
/// </summary>
event EventHandler DataSourceChanged;
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
string Name { get; }
/// <summary>
/// Gets the home page URL.
/// </summary>
/// <value>The home page URL.</value>
string HomePageUrl { get; }
/// <summary>
/// Gets the channels async.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IEnumerable{ChannelInfo}}.</returns>
Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken);
/// <summary>
/// Cancels the timer asynchronous.
/// </summary>
/// <param name="timerId">The timer identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task CancelTimerAsync(string timerId, CancellationToken cancellationToken);
/// <summary>
/// Cancels the series timer asynchronous.
/// </summary>
/// <param name="timerId">The timer identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken);
/// <summary>
/// Creates the timer asynchronous.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken);
/// <summary>
/// Creates the series timer asynchronous.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken);
/// <summary>
/// Updates the timer asynchronous.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken);
/// <summary>
/// Updates the series timer asynchronous.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken);
/// <summary>
/// Gets the recordings asynchronous.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IEnumerable{RecordingInfo}}.</returns>
Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the new timer defaults asynchronous.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="program">The program.</param>
/// <returns>Task{SeriesTimerInfo}.</returns>
Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null);
/// <summary>
/// Gets the series timers asynchronous.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IEnumerable{SeriesTimerInfo}}.</returns>
Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the programs asynchronous.
/// </summary>
/// <param name="channelId">The channel identifier.</param>
/// <param name="startDateUtc">The start date UTC.</param>
/// <param name="endDateUtc">The end date UTC.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IEnumerable{ProgramInfo}}.</returns>
Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel stream.
/// </summary>
/// <param name="channelId">The channel identifier.</param>
/// <param name="streamId">The stream identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{Stream}.</returns>
Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel stream media sources.
/// </summary>
/// <param name="channelId">The channel identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task<List<MediaSourceInfo>>.</returns>
Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken);
/// <summary>
/// Closes the live stream.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task CloseLiveStream(string id, CancellationToken cancellationToken);
/// <summary>
/// Records the live stream.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task RecordLiveStream(string id, CancellationToken cancellationToken);
/// <summary>
/// Resets the tuner.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task ResetTuner(string id, CancellationToken cancellationToken);
}
public interface ISupportsNewTimerIds
{
/// <summary>
/// Creates the timer asynchronous.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task<string> CreateTimer(TimerInfo info, CancellationToken cancellationToken);
/// <summary>
/// Creates the series timer asynchronous.
/// </summary>
/// <param name="info">The information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken);
}
public interface ISupportsDirectStreamProvider
{
Task<Tuple<MediaSourceInfo, ILiveStream>> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, CancellationToken cancellationToken);
}
public interface ISupportsUpdatingDefaults
{
Task UpdateTimerDefaults(SeriesTimerInfo info, CancellationToken cancellationToken);
}
}
|
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.Business.Master
{
public class LogGoogleAPILogic
{
MyContext _context = null;
public LogGoogleAPILogic()
{
_context = new MyContext();
}
public LogGoogleAPILogic(MyContext context)
{
_context = context;
}
public void SaveLogGoogleAPI(LogGoogleAPI loggoogleAPI)
{
var req = new Repository<LogGoogleAPI>(_context);
loggoogleAPI.CreateDate = DateTime.Now;
req.Add(loggoogleAPI);
req.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
class WebHandler
{
public String url;
static int count;
WebClient client;
List<string> links = new List<string>();
List<string> images = new List<string>();
public string HTML;
public WebHandler( string url )
: this( url, false )
{
}
/*
* url: Location to acces
* execute: Execute request when initializing? (False: Execute with executeRequest() instead when needed)
*/
public WebHandler( string url, bool execute )
{
this.url = url;
this.client = new WebClient();
if ( execute )
{
executeRequest();
}
}
public void executeRequest()
{
try
{
if ( this.url.EndsWith( ".jpg" ) || this.url.EndsWith( ".png" ) || this.url.EndsWith( ".gif" ) )
{
if ( WebHandler.count > 0 ) WebHandler.count++;
else WebHandler.count = 1;
client.DownloadFile( url, "C:\\Users\\Kjeld\\Desktop\\CrawledImages\\" + WebHandler.count + url.Remove( 0, url.Length - 4 ) );
}
else
{
this.HTML = client.DownloadString( this.url );
}
}
catch ( Exception ex )
{
Console.WriteLine( ex.ToString() );
}
}
public void findLinks()
{
Regex anchorMatch = new Regex( "<a[^>]*" ); //Matches anchor tags
Regex linkMatch = new Regex( "(?<=href=\")[^\"]*" ); // Inside an anchor tag, matches the HREF.
if ( this.HTML != null )
{
MatchCollection matches = anchorMatch.Matches( this.HTML );
if ( matches != null )
{
foreach ( Match match in matches )
{
String potentialLink = linkMatch.Match( match.Value ).Value;
if ( Uri.IsWellFormedUriString( potentialLink, UriKind.Absolute ) )
{
this.links.Add( potentialLink );
}
}
}
}
}
public void findImages()
{
Regex imageMatch = new Regex( "<img[^>]*" ); //Matches image tags
Regex sourceMatch = new Regex( "(?<=src=\")[^\"]*" ); // Inside an image tag, matches the SRC
if ( this.HTML != null )
{
MatchCollection matches = imageMatch.Matches( this.HTML );
if ( matches != null )
{
foreach ( Match match in matches )
{
String potentialImage = sourceMatch.Match( match.Value ).Value;
if ( Uri.IsWellFormedUriString( potentialImage, UriKind.Absolute ) )
{
this.images.Add( potentialImage );
}
}
}
}
}
public String getResponse()
{
return this.HTML;
}
public List<string> Links
{
get
{
return this.links;
}
set
{
this.links = value;
}
}
public List<string> Images
{
get
{
return this.images;
}
set
{
this.images = value;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AxisPosCore.Common;
using KartObjects;
namespace AxisPosCore
{
public class CancelSubtotalActionExecutor:POSActionExecutor
{
public CancelSubtotalActionExecutor(POSActionMnemonic action)
: base(action)
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.SubTotal);
}
public CancelSubtotalActionExecutor()
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.SubTotal);
}
protected override void InnerExecute(PosCore model, params object[] args)
{
POSEnvironment.CurrReceipt.Payment.Clear();
POSEnvironment.CurrReceipt.CancelDiscounts();
model.RegistrationState.StateMode = POSRegistrationState.RegistrationStateMode.Specification;
model.RegistrationState.ChangeState();
POSEnvironment.SendEvent(TypeExtEvent.eeExitSubtotal);
}
}
}
|
using NUnit.Framework;
using NUnitTestProject1.Methods;
namespace NUnitTestProject1.JavaAlertsTest
{
public class JavaAlertests
{
private JavaScriptAlerts JavaScriptAlerts1 = new JavaScriptAlerts();
// Test for JavaScript Alerts
[Test, Order(1)]
public void ClickOnJSAlert()
{
JavaScriptAlerts1.StartBrowser();
JavaScriptAlerts1.ClickOnButtons(0);
JavaScriptAlerts1.ClickOKButton();
Assert.That(JavaScriptAlerts1.Result().Contains("You successfully clicked an alert"));
}
// Test for JavaScript Confirm
[Test, Order(2)]
public void ClickOnJSConfirm()
{
//clicking on OK button for JS Confirm
JavaScriptAlerts1.ClickOnButtons(1);
JavaScriptAlerts1.ClickOKButton();
Assert.That(JavaScriptAlerts1.Result().Contains("You clicked: Ok"));
//clicking on cancel button for JS Confirm
JavaScriptAlerts1.ClickOnButtons(1);
JavaScriptAlerts1.ClickCancelButton();
Assert.That(JavaScriptAlerts1.Result().Contains("You clicked: Cancel"));
}
// Test for JavaScript Prompt
[Test, Order(3)]
public void ClickForJSPrompt()
{
// Clicking OK button for JS Prompt
JavaScriptAlerts1.ClickOnButtons(2);
JavaScriptAlerts1.WriteOnPopUpWindow("Accepted");
JavaScriptAlerts1.ClickOKButton();
Assert.That(JavaScriptAlerts1.Result().Contains("You entered: Accepted"));
// Clicking cancel button for JS Prompt
JavaScriptAlerts1.ClickOnButtons(2);
JavaScriptAlerts1.ClickCancelButton();
Assert.That(JavaScriptAlerts1.Result().Contains("You entered: null"));
}
//Close the browser
[OneTimeTearDown]
public void OneTimeTearDown()
{
JavaScriptAlerts1.CloseBrowser();
}
}
}
|
using API.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace API.Dtos
{
public class UserBudgetDto
{
public List<User> users { get; set; }
public int RecordCount {get; set;}
public int PageCount {get; set; }
public Nullable<int> GroupCount { get; set; }
public Nullable<int> GroupPageCount { get; set; }
public Nullable<int> SubGroupCount { get; set; }
public Nullable<int> SubGroupPageCount { get; set; }
public Nullable<int> AgencyCount { get; set; }
public Nullable<int> AgencyPageCount { get; set; }
public Nullable<int> ConsultantCount { get; set; }
public Nullable<int> ConsultantPageCount { get; set; }
}
}
|
using Alabo.Cloud.Support.Domain.Enum;
using Alabo.Domains.Entities;
using Alabo.Domains.Enums;
using Alabo.Validations;
using Alabo.Web.Mvc.Attributes;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Alabo.Cloud.Support.Domain.Entities
{
/// <summary>
/// 工单系统
/// </summary>
[BsonIgnoreExtraElements]
[Table("Cms_WorkOrder")]
[ClassProperty(Name = "工单系统", Icon = "fa fa-puzzle-piece", Description = "工单系统",
PageType = ViewPageType.List )]
public class WorkOrder : AggregateMongodbRoot<WorkOrder>
{
/// <summary>
/// 标题
/// </summary>
[Display(Name = "标题")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
[Field(ControlsType = ControlsType.TextBox, Width = "80", SortOrder = 1, ListShow = true)]
[StringLength(50)]
public string Title { get; set; }
/// <summary>
/// 分类ID
/// </summary>
public int ClassId { get; set; }
/// <summary>
/// 问题回复
/// </summary>
[Display(Name = "问题回复")]
// [Required( ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public string Reply { get; set; }
/// <summary>
/// <summary>
/// 问题描述
/// </summary>
[Display(Name = "问题描述")]
[Field(ControlsType = ControlsType.TextArea, Width = "80", SortOrder = 2)]
public string Description { get; set; }
/// <summary>
/// 附件
/// </summary>
[Display(Name = "附件")]
public string Attachment { get; set; }
/// <summary>
/// 回复内容
/// </summary>
public string ReplyContent { get; set; }
/// <summary>
/// 回复内容
/// List<ReplyContent>的Json对象
/// </summary>
public string ReplyComment { get; set; }
/// <summary>
/// 发布用户Id
/// 工单发起人
/// </summary>
[Display(Name = "工单发起人")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public long UserId { get; set; }
/// <summary>
/// 受理人
/// </summary>
public long AcceptUserId { get; set; }
/// <summary>
/// 是否标记为星
/// </summary>
[Display(Name = "是否标记为星")]
public bool IsStar { get; set; } = false;
/// <summary>
/// 优先级
/// </summary>
[Display(Name = "优先级")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public WorkOrderPriority Priority { get; set; } = WorkOrderPriority.Hight;
/// <summary>
/// 回复方式
/// </summary>
[Display(Name = "回复方式")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public WorkOrderReplyWay ReplayWay { get; set; } = WorkOrderReplyWay.PublicWay;
/// <summary>
/// 工单状态
/// </summary>
[Display(Name = "工单状态")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public WorkOrderState State { get; set; }
/// <summary>
/// 工单类型
/// </summary>
[Display(Name = "工单类型")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public WorkOrderType Type { get; set; }
/// <summary>
/// 服务评分
/// </summary>
public long ServiceSore { get; set; } = 7;
/// <summary>
/// 受理时间
/// </summary>
[Display(Name = "受理时间")]
public DateTime AcceptTime { get; set; } = DateTime.Now;
/// <summary>
/// 解决时间
/// </summary>
[Display(Name = "解决时间")]
public DateTime SolveTime { get; set; } = DateTime.Now;
/// <summary>
/// 确认时间
/// </summary>
[Display(Name = "确认时间")]
public DateTime ConfirmTime { get; set; } = DateTime.Now;
/// <summary>
/// 是否公开
/// </summary>
[Display(Name = "是否私有")]
public PublishWay PublishWay { get; set; } = PublishWay.Pri;
}
} |
using Alabo.Web.Mvc.Attributes;
using System.Collections.Generic;
namespace Alabo.Framework.Core.WebUis.Models.Lists {
/// <summary>
/// 通过列表输出,对应前端Api接口
/// </summary>
[ClassProperty(Name = "链接")]
public class ListOutput : BaseComponent {
/// <summary>
/// 样式格式,不通的数据可能显示不同的格式
/// </summary>
public int StyleType { get; set; } = 1;
/// <summary>
/// 返回数据源的总页数
/// </summary>
public long TotalSize { get; set; }
/// <summary>
/// Api数据列表
/// </summary>
public List<ListItem> ApiDataList { get; set; } = new List<ListItem>();
}
public class ListItem {
/// <summary>
/// 主键ID
/// </summary>
public object Id { get; set; }
/// <summary>
/// 网址
/// </summary>
public string Url { get; set; }
/// <summary>
/// 图标或图片
/// </summary>
public string Image { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 标题额外数据
/// </summary>
public string Extra { get; set; }
/// <summary>
/// 描述,可以通过拼接完成
/// </summary>
public string Intro { get; set; }
}
} |
using AutoMapper;
using Backend.Communication.SftpCommunicator;
using Grpc.Core;
using IntegrationAdapters.Apis.Grpc;
using IntegrationAdapters.Apis.Http;
using IntegrationAdapters.Dtos;
using IntegrationAdapters.MapperProfiles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace IntegrationAdapters.Adapters.Development
{
public class PharmacySystemAdapter_Id1 : IPharmacySystemAdapter
{
private IMapper _mapper;
private PharmacySystemAdapterParameters _parameters;
private Channel _grpcChannel;
private DrugAvailability.DrugAvailabilityClient _grpcClient;
private SftpCommunicator _sftpCommunicator;
private bool _grpc;
private bool _sftp;
private PharmacySystemApi_Id1 _api;
public void Initialize(PharmacySystemAdapterParameters parameters, HttpClient httpClient)
{
var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile(new PharmacySystemProfile_Id1()));
_mapper = new Mapper(mapperConfig);
_parameters = parameters;
InitializeGrpc();
InitializeSftp();
_api = new PharmacySystemApi_Id1(_parameters.Url, httpClient);
}
public void CloseConnections()
{
if (_grpcChannel != null && _grpcChannel.State != ChannelState.Shutdown)
_grpcChannel.ShutdownAsync().Wait();
}
public List<DrugDto> DrugAvailibility(string name)
{
if (!_grpc)
return new List<DrugDto>();
FindDrugRequest request = new FindDrugRequest();
request.ApiKey = _parameters.ApiKey;
request.Name = name;
FindDrugResponse response = null;
try
{
response = _grpcClient.FindDrug(request);
}
catch (RpcException rex)
{
Console.WriteLine(rex);
}
if (response != null && response.Drugs != null && response.Drugs.Count > 0)
{
return _mapper.Map<List<DrugDto>>(response.Drugs);
}
return new List<DrugDto>();
}
public bool SendDrugConsumptionReport(string reportFilePath, string reportFileName)
{
if (!_sftp)
return false;
Task<bool> task = Task.Run<bool>(async () => await _sftpCommunicator.UploadFile(reportFilePath + "/" + reportFileName, $"/PSW-uploads/{reportFileName}"));
bool ret = false;
try
{
ret = task.Result;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return ret;
}
public List<DrugListDTO> GetAllDrugs()
{
var task =
Task.Run<List<DrugListDTO>>(async () => await _api.GetAllDrugs(_parameters.ApiKey));
var ret = new List<DrugListDTO>();
try
{
ret = task.Result;
}
catch (AggregateException agex)
{
Console.WriteLine(agex);
}
return ret;
}
public bool GetDrugSpecifications(int id)
{
var task = Task.Run<string>(async () => await _api.GetDrugSpecificationsSftp(_parameters.ApiKey, id));
var ret = "";
try
{
ret = task.Result;
}
catch (AggregateException agex)
{
Console.WriteLine(agex);
}
if (ret == "") return false;
_sftpCommunicator.DownloadFile(ret, $"Resources/{Path.GetFileName(ret)}");
return true;
}
private void InitializeGrpc()
{
if (_parameters.GrpcAdress.GrpcHost == null || _parameters.GrpcAdress.GrpcHost == "" || _parameters.GrpcAdress.GrpcPort == -1)
_grpc = false;
else
_grpc = true;
_grpcChannel = new Channel(_parameters.GrpcAdress.GrpcHost, _parameters.GrpcAdress.GrpcPort, ChannelCredentials.Insecure);
_grpcClient = new DrugAvailability.DrugAvailabilityClient(_grpcChannel);
}
private void InitializeSftp()
{
if (_parameters.SftpConfig == null)
_sftp = false;
else
_sftp = true;
_sftpCommunicator = new SftpCommunicator(_parameters.SftpConfig);
}
public bool OrderDrugs(int pharmacyId, int drugId, int quantity)
{
if (!_grpc)
return false;
OrderDrugRequest request = new OrderDrugRequest();
request.ApiKey = _parameters.ApiKey;
request.IdPharmacy = pharmacyId;
request.IdDrug = drugId;
request.Quantity = quantity;
OrderDrugResponse response = null;
try
{
response = _grpcClient.OrderDrug(request);
}
catch (RpcException rex)
{
Console.WriteLine(rex);
}
if (response != null)
{
return response.Success;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Infrastructure.Extension;
using EBS.Domain.Entity;
using Dapper.DBContext;
namespace EBS.Domain.Service
{
public class TransferOrderService
{
IDBContext _db;
public TransferOrderService(IDBContext dbcontext)
{
this._db = dbcontext;
}
public void EditItem(TransferOrder entity)
{
//明细
if (_db.Table.Exists<TransferOrderItem>(n => n.TransferOrderId == entity.Id))
{
_db.Delete<TransferOrderItem>(n => n.TransferOrderId == entity.Id);
}
_db.Insert(entity.Items.ToArray());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CPClient.Domain.Entities
{
public class TelefoneTipo : BaseEntity
{
public string Descricao { get; set; }
public virtual ICollection<ClienteTelefone> ClienteTelefone { get; set; }
}
}
|
namespace ClosestTwoPoints
{
using System;
using System.Collections.Generic;
using System.Linq;
public class StartUp
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
var points = new List<double>();
var firstPoint = new List<double>();
var secondPoint = new List<double>();
var closestCoordinates = new List<double>();
var minDistance = double.MaxValue;
for (int i = 0; i < n; i++)
{
var coordinates = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(double.Parse)
.ToList();
points.AddRange(coordinates);
}
for (int i = 0; i < points.Count; i += 2)
{
firstPoint.Clear();
firstPoint.Add(points[i]);
firstPoint.Add(points[i + 1]);
for (int j = i + 2; j < points.Count; j += 2)
{
secondPoint.Clear();
secondPoint.Add(points[j]);
secondPoint.Add(points[j + 1]);
var distance = CalculateDistance(firstPoint, secondPoint);
if (distance < minDistance)
{
closestCoordinates.Clear();
minDistance = distance;
closestCoordinates.AddRange(firstPoint);
closestCoordinates.AddRange(secondPoint);
}
}
}
Console.WriteLine($"{minDistance:f3}");
Console.WriteLine($"({closestCoordinates[0]}, {closestCoordinates[1]})");
Console.WriteLine($"({closestCoordinates[2]}, {closestCoordinates[3]})");
}
public static double CalculateDistance(List<double> firstPoint, List<double> secondPoint)
{
var point1 = new Point();
var point2 = new Point();
point1.X = firstPoint[0];
point1.Y = firstPoint[1];
point2.X = secondPoint[0];
point2.Y = secondPoint[1];
var sideA = (point1.X - point2.X);
var sideB = (point1.Y - point2.Y);
var sideC = Math.Sqrt(Math.Pow(sideA, 2) + Math.Pow(sideB, 2));
return sideC;
}
}
public class Point
{
public double X { get; set; }
public double Y { get; set; }
}
}
|
using System;
namespace Atomic.DbProvider
{
/// <summary>
/// 执行DB语句后返回无记录结果集
/// </summary>
public sealed class DbNonRecord : DbRecordBase
{
#region Constructors
/// <summary>
/// 构造函数
/// </summary>
public DbNonRecord() : base() { }
#endregion
#region Propertys
private int _affectedRow = -1;
/// <summary>
/// 受影响行数
/// </summary>
public int AffectedRow
{
get { return _affectedRow; }
set { _affectedRow = value; }
}
#endregion
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
namespace TagParsing
{
/// <summary>
/// This class provides the character input stream to the Parser class.
/// It supports a pushback queue to assist the Parser class deal with unexpected input.
/// </summary>
public class ParseReader
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Optional filename or URL to identify the stream.
/// </summary>
private readonly string filename;
/// <summary>
/// Input stream reader
/// </summary>
private readonly TextReader stream;
/// <summary>
/// Pushback queue is used to push characters back onto input stream to be re-parsed.
/// </summary>
private readonly Stack<int> pushbackQueue;
/// <summary>
/// The character count is simply used for keeping a note of the size of the document.
/// </summary>
private int charCount;
/// <summary>
/// The column number is used in reporting errors.
/// </summary>
private int columnNumber;
/// <summary>
/// The line number is used in reporting errors.
/// </summary>
private int lineNumber = 1;
/// <summary>
/// Constructor using a content string.
/// </summary>
/// <param name="text">Content string.</param>
public ParseReader(string text)
{
stream = new StringReader(text);
pushbackQueue = new Stack<int>();
}
/// <summary>
/// Constructor for the ParseReader class.
/// </summary>
/// <param name="reader">The character input stream.</param>
public ParseReader(TextReader reader)
{
stream = reader;
pushbackQueue = new Stack<int>();
}
/// <summary>
/// Constructor for the ParseReader class.
/// </summary>
/// <param name="reader">The character input stream.</param>
/// <param name="filename">Optional filename or URL to identify the stream.</param>
public ParseReader(TextReader reader, string filename)
{
stream = reader;
this.filename = filename;
pushbackQueue = new Stack<int>();
}
/// <summary>
/// Filename or URL string to identify the string.
/// </summary>
public string Filename
{
get { return filename; }
}
/// <summary>
/// Push character back into the stream.
/// </summary>
/// <param name="c">Character to push back into the stream.</param>
public void Pushback(char c)
{
Log.InfoFormat("Pushback Char: '{0}'", c);
pushbackQueue.Push(c);
}
/// <summary>
/// Push whole string back into the stream.
/// </summary>
/// <param name="str">String to push back into the stream.</param>
public void Pushback(string str)
{
if (string.IsNullOrEmpty(str)) return;
Log.InfoFormat("Pushback string: \"{0}\"", str);
for (int i = str.Length - 1; i >= 0; i--)
pushbackQueue.Push(str[i]);
}
/// <summary>
/// The current line number.
/// </summary>
public int LineNumber
{
get { return lineNumber; }
}
/// <summary>
/// The current column position.
/// </summary>
public int ColumnNumber
{
get { return columnNumber; }
}
/// <summary>
/// The character read count.
/// </summary>
public int CharCount
{
get { return charCount; }
}
/// <summary>
/// This method reads a single character from the raw input stream.
/// </summary>
/// <returns>Next character from input.</returns>
private int RawRead()
{
int c = stream.Read();
if (c != -1)
{
// Count new lines and track column position.
if (c == '\n')
{
lineNumber += 1;
columnNumber = 0;
}
else
{
columnNumber++;
}
// Count characters read.
charCount++;
}
return c;
}
/// <summary>
/// This method reads a single character from the input buffer.
/// </summary>
/// <returns>Next character from input.</returns>
public int Read()
{
int nextChar;
do
{
// Pop last character on the queue if there are items pushed-back.
nextChar = pushbackQueue.Count > 0 ? pushbackQueue.Pop() : RawRead();
} while (nextChar == '\r'); // Ignore linefeed.
Log.InfoFormat("Char: {0}", Parser.ToNamestring(nextChar));
return nextChar;
}
}
}
|
//using System.Collections;
//using System.Collections.Generic;
//using UnityEngine;
//using UnityEngine.UI;
//public class DialogueSystem : MonoBehaviour {
// //potato1
// public static DialogueSystem Instance { get; set; }
// public List<string> dialogueLines = new List<string>(); //list of things we can populate with the lines taht we passed over from that new dialogue.
// //our new dialogue with the string that gets passed into the "AddNewDialogue" function
// public string npcName;
// public GameObject dialoguePanel; //use this to reference the dialogue panel. Which we can then use to grab the children of the dialogue panel. And this will give us
// //continue, text, and name
// Button continueButton; //the dialogue's continue button
// Text dialogueText; //the text that is in the dialogue
// Text nameText; //the name of the character we are talking to
// int dialogueIndex; //the index to which message in the dialogue we are in
// // Use this for initialization
// void Awake () {
// continueButton = dialoguePanel.transform.Find("Continue").GetComponent<Button>(); //now we have the Dialogue's continue button
// dialogueText = dialoguePanel.transform.Find("Text").GetComponent<Text>(); //now we have the dialogue's text
// nameText = dialoguePanel.transform.Find("Name").GetChild(0).GetComponent<Text>(); //if you look in the Hierachy, "Name" is a panel and in there, there is a "Text"
// //GetChild(0) gets the first child (the zero'th child) of Name.
// continueButton.onClick.AddListener(delegate { ContinueDialogue(); });
// dialoguePanel.SetActive(false); //set the active state of dialogue panel game object to false. On awake there should be no reasoon for the dialogue to show
// //because teher is not going to be dialogue unless you want to start a new dialogue. So make sure that at start teh dialogue panel is false
// //if theses conditions are met then taht means taht an instance exists taht isn't this instance
// //does it exist and if it does exist is it equal to this object. This dialogue system we have created here: potato1
// if (Instance != null && Instance != this)
// {
// Destroy(gameObject); //so we destroy it
// }
// //else if those conditions are not met then that means that an instance does not exist. And we
// else
// {
// Instance = this; //this is a refernece to this instance. The one we have created by dragging and dropping hte component on a game object in our heirarchy
// //so now it exists and we can reference it with "Instance"
// }
// }
// public void AddNewDialogue(string[] lines, string npcName)
// {
// dialogueIndex = 0; //the dialogue index should be zero whenever we add new dialogue.
// dialogueLines = new List<string>(lines.Length); //makes a new dialoguelines the size of the string array the function takes in.
// dialogueLines.AddRange(lines); //we add them to the dialogueLines list.
// Debug.Log(dialogueLines.Count);
// this.npcName = npcName; //the npc name given in this funciton is the npc name of this instance
// CreateDialogue(); //call the function that creates a dialogue
// }
// //going to handle enabling the dialogue panel as well as assigning the text values to the elements inside of that panel
// public void CreateDialogue()
// {
// dialogueText.text = dialogueLines[dialogueIndex]; //we want the first index in dialogue lines. we want to show the first bit of text.
// nameText.text = npcName; //the name box thing is the NPCs name
// dialoguePanel.SetActive(true); //re enable the panel thing.
// }
// //increase teh dialogue index and show the new message
// public void ContinueDialogue()
// {
// if (dialogueIndex < dialogueLines.Count - 1) //if the index is less than how many messages we have
// {
// dialogueIndex = dialogueIndex + 1; //move the index by one.
// dialogueText.text = dialogueLines[dialogueIndex]; //the new stuff shown on the dialogue screen should be the next element in the dialoguelines array
// }
// else //else if we've seen all the text there is to see and now it is time to close the panel
// {
// dialoguePanel.SetActive(false);
// }
// }
//}
|
namespace CurrencyLibs.Interfaces
{
public interface IBankNote : ICurrency
{
public int Year { get; }
}
} |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Configuration;
using SSDAssignmentBOX.Models;
using System.IO;
namespace SSDAssignmentBOX
{
public class SSDAssignmentBOXContextFactory : IDesignTimeDbContextFactory<BookContext>
{
public BookContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<BookContext> ();
var connectionString = configuration.GetConnectionString("BookContext");
builder.UseSqlServer(connectionString);
return new BookContext(builder.Options);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JDWinService.Model
{
public class Json_Bill_Page1
{
public page1 Page1 { get; set; }
public class page1
{
public string FBillNo { get; set; }
public string FStatus { get; set; }
public Fdeptid FDeptID { get; set; }
public Fproposerid FProposerID { get; set; }
public Fproducterid FProducterID { get; set; }
public Fdesignerid FDesignerID { get; set; }
public string FDescription { get; set; }
public Fbiller FBiller { get; set; }
public string FDate { get; set; }
public Fcheckerid FCheckerID { get; set; }
public string FClassTypeID { get; set; }
public string FCheckDate { get; set; }
}
public class Fdeptid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fproposerid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fproducterid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fdesignerid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fbiller
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fcheckerid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
}
}
|
using Abstract;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using GUI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace Functions
{
public class CalculationSupport : CustomFunction
{
public ExternalEvent TheEvent { get; set; }
public ManualResetEvent SignalEvent { get; set; }
public Calculations.Action Action { get; set; }
UIDocument _uiDocument;
public void DisplayWindow()
{
Thread windowThread = new Thread(delegate ()
{
CalculationSupportWindow window = new CalculationSupportWindow(this);
window.Show();
Dispatcher.Run();
});
windowThread.SetApartmentState(ApartmentState.STA);
windowThread.Start();
}
public void Initialize(UIDocument uIDocument)
{
SignalEvent = new ManualResetEvent(false);
_uiDocument = uIDocument;
}
public void SetEvent(ExternalEvent theEvent)
{
TheEvent = theEvent;
}
public void FindDisconnectedFitting()
{
Document doc = _uiDocument.Document;
List<FamilyInstance> pFittings = new FilteredElementCollector(doc, doc.ActiveView.Id).OfClass(typeof(FamilyInstance)).Select(e => e as FamilyInstance).Where(e => e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeFitting).ToList();
foreach (FamilyInstance fi in pFittings)
{
Parameter systemClass = fi.get_Parameter(BuiltInParameter.RBS_SYSTEM_CLASSIFICATION_PARAM);
string name = systemClass.AsString();
if (name == "Abwasser") continue;
MechanicalFitting mf = fi.MEPModel as MechanicalFitting;
ConnectorManager cm = mf.ConnectorManager;
if (cm == null) continue;
ConnectorSet csun = cm.UnusedConnectors;
if (csun == null) continue;
if (csun.Size > 0)
{
_uiDocument.Selection.SetElementIds(new List<ElementId>() { fi.Id });
_uiDocument.ShowElements(fi.Id);
return;
}
}
}
public void FindFittingsWithReducers()
{
Document doc = _uiDocument.Document;
List<FamilyInstance> pFittings = new FilteredElementCollector(doc, doc.ActiveView.Id).OfClass(typeof(FamilyInstance)).Select(e => e as FamilyInstance).Where(e => e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeFitting).ToList();
foreach (FamilyInstance fi in pFittings)
{
Parameter systemClass = fi.get_Parameter(BuiltInParameter.RBS_SYSTEM_CLASSIFICATION_PARAM);
string name = systemClass.AsString();
if (name == "Abwasser") continue;
MechanicalFitting mf = fi.MEPModel as MechanicalFitting;
ConnectorManager cm = mf.ConnectorManager;
if (cm == null) continue;
foreach (Connector c in cm.Connectors)
{
foreach (Connector cref in c.AllRefs)
{
Element e = cref.Owner;
if (e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeFitting)
{
FamilyInstance instance = e as FamilyInstance;
if (instance.Symbol.Family.Name.Contains("Übergang"))
{
_uiDocument.Selection.SetElementIds(new List<ElementId>() { fi.Id });
_uiDocument.ShowElements(fi.Id);
return;
}
}
}
}
}
}
public void ExtractPlumbingFixtures()
{
Document doc = _uiDocument.Document;
List<FamilyInstance> fixtures = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).Select(e => e as FamilyInstance).Where(e => e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PlumbingFixtures).ToList();
List<Space> spaces = new FilteredElementCollector(doc).OfCategoryId(new ElementId((int)BuiltInCategory.OST_MEPSpaces)).Select(e => e as Space).ToList();
List<FamilyInstance> usedFixtures = new List<FamilyInstance>();
List<Space> orderedSpaces = spaces.OrderBy(e => e.Number).ToList();
Dictionary<string, List<FamilyInstance>> list = new Dictionary<string, List<FamilyInstance>>();
foreach (Space space in orderedSpaces)
{
foreach (FamilyInstance fi in fixtures)
{
LocationPoint lp = fi.Location as LocationPoint;
XYZ point = lp.Point;
if (space.IsPointInSpace(point))
{
if (list.ContainsKey(space.Name))
{
list[space.Name].Add(fi);
usedFixtures.Add(fi);
}
else
{
list.Add(space.Name, new List<FamilyInstance>() { fi });
usedFixtures.Add(fi);
}
}
}
}
List<FamilyInstance> result = fixtures.Where(e => !usedFixtures.Contains(e)).ToList();
TaskDialog.Show("Info", "Unassigned elements: " + result.Count.ToString());
string text = "Room Name & No.;ElementId;FamilyName;FamilyType;SC_S90DurchflussKalt;SC_S90DurchflussWarm;SC_S90MindestfließdruckKalt;SC_S90MindestfließdruckWarm;SC_S90Dauerverbraucher;SC_S90Mindestfließdruck;SC_S90Durchfluss" + Environment.NewLine;
foreach (KeyValuePair<string, List<FamilyInstance>> pair in list)
{
//text += pair.Key + Environment.NewLine;
foreach (FamilyInstance fi in pair.Value)
{
Parameter kaltFlow = fi.get_Parameter(new Guid("01c3713a-9ea8-45b9-b887-aedad8e42ac5"));
Parameter warmFlow = fi.get_Parameter(new Guid("ee272d98-a8fd-432e-bf69-7e5a5fab3c5c"));
Parameter kaltPres = fi.get_Parameter(new Guid("711ff1d3-b377-4914-9199-2c03a715a412"));
Parameter warmPres = fi.get_Parameter(new Guid("2bf5f13e-bfee-4f00-ab2a-7abe43dec00b"));
Parameter dauerVerbraucher = fi.get_Parameter(new Guid("6ff8aefe-d5c4-4eba-ab59-a108e4f0e3e7"));
Parameter pdruck = fi.get_Parameter(new Guid("ce08b3f9-8ebf-4fbd-b17e-b34cb05403ae"));
Parameter durschfluss = fi.get_Parameter(new Guid("563f59ae-5587-44bb-a343-55ba4dd75449"));
string kalt = "NA";
string warm = "NA";
string kaltPre = "NA";
string warmPre = "NA";
string dauerVer = "NA";
string druck = "NA";
string durschflussStr = "NA";
if (kaltFlow != null) kalt = kaltFlow.AsValueString();
if (warmFlow != null) warm = warmFlow.AsValueString();
if (kaltPres != null) kaltPre = kaltPres.AsValueString();
if (warmPres != null) warmPre = warmPres.AsValueString();
if (dauerVerbraucher != null) dauerVer = dauerVerbraucher.AsValueString();
if (pdruck != null) druck = pdruck.AsValueString();
if (durschfluss != null) durschflussStr = durschfluss.AsValueString();
text += pair.Key + ";" + fi.Id.IntegerValue.ToString() + ";" + fi.Symbol.Family.Name + ";" + fi.Symbol.Name + ";" + kalt + ";" + warm + ";" + kaltPre + ";" + warmPre + ";" + dauerVer + ";" + druck + ";" + durschflussStr + Environment.NewLine;
}
}
//text += "Room unassigned:" + Environment.NewLine;
foreach (FamilyInstance fi in result)
{
Parameter kaltFlow = fi.get_Parameter(new Guid("01c3713a-9ea8-45b9-b887-aedad8e42ac5"));
Parameter warmFlow = fi.get_Parameter(new Guid("ee272d98-a8fd-432e-bf69-7e5a5fab3c5c"));
Parameter kaltPres = fi.get_Parameter(new Guid("711ff1d3-b377-4914-9199-2c03a715a412"));
Parameter warmPres = fi.get_Parameter(new Guid("2bf5f13e-bfee-4f00-ab2a-7abe43dec00b"));
Parameter dauerVerbraucher = fi.get_Parameter(new Guid("6ff8aefe-d5c4-4eba-ab59-a108e4f0e3e7"));
Parameter pdruck = fi.get_Parameter(new Guid("ce08b3f9-8ebf-4fbd-b17e-b34cb05403ae"));
Parameter durschfluss = fi.get_Parameter(new Guid("563f59ae-5587-44bb-a343-55ba4dd75449"));
string kalt = "NA";
string warm = "NA";
string kaltPre = "NA";
string warmPre = "NA";
string dauerVer = "NA";
string druck = "NA";
string durschflussStr = "NA";
if (kaltFlow != null) kalt = kaltFlow.AsValueString();
if (warmFlow != null) warm = warmFlow.AsValueString();
if (kaltPres != null) kaltPre = kaltPres.AsValueString();
if (warmPres != null) warmPre = warmPres.AsValueString();
if (dauerVerbraucher != null) dauerVer = dauerVerbraucher.AsValueString();
if (pdruck != null) druck = pdruck.AsValueString();
if (durschfluss != null) durschflussStr = durschfluss.AsValueString();
text += "Room unassigned" + ";" + fi.Id.IntegerValue.ToString() + ";" + fi.Symbol.Family.Name + ";" + fi.Symbol.Name + ";" + kalt + ";" + warm + ";" + kaltPre + ";" + warmPre + ";" + dauerVer + ";" + druck + ";" + durschflussStr + Environment.NewLine;
}
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
string date = DateTime.Now.ToString("dd.MM.yy HH-mm-ss");
string name = "EntnahmeArmaturExtract" + date;
dlg.FileName = name; // Default file name
dlg.DefaultExt = ".csv"; // Default file extension
string initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
dlg.InitialDirectory = initialDirectory;
Nullable<bool> dialogResult = dlg.ShowDialog();
if (dialogResult == true)
{
string filename = dlg.FileName;
Encoding encoding = Encoding.UTF8;
File.WriteAllText(filename, text, encoding);
}
//string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//string path = Path.Combine(desktop, "extract_fixtures.csv");
//Encoding encoding = Encoding.UTF8;
//File.WriteAllText(path, text, encoding);
}
public void SelectFromClipboard()
{
string clipboard = System.Windows.Forms.Clipboard.GetText();
string[] lines = clipboard.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
List<ElementId> ids = new List<ElementId>();
foreach (string line in lines)
{
int convert;
bool result = Int32.TryParse(line, out convert);
if (result)
{
ElementId id = new ElementId(convert);
ids.Add(id);
}
}
if (ids.Count == 0)
{
TaskDialog.Show("Info", "Keine ID gefunden in clipboard");
return;
}
_uiDocument.Selection.SetElementIds(ids);
}
public void ConnectDisconnected()
{
Document doc = _uiDocument.Document;
Reference reference = _uiDocument.Selection.PickObject(ObjectType.Element);
Element element = doc.GetElement(reference);
List<Connector> unusedConnectors = new List<Connector>();
List<Pipe> pipes = new FilteredElementCollector(doc, doc.ActiveView.Id).OfClass(typeof(Pipe)).Select(e => e as Pipe).ToList();
foreach (Pipe p in pipes)
{
ConnectorSet cset = p.ConnectorManager.UnusedConnectors;
foreach (Connector c in cset)
{
unusedConnectors.Add(c);
}
}
List<FamilyInstance> instances = new FilteredElementCollector(doc, doc.ActiveView.Id).OfClass(typeof(FamilyInstance)).Select(e => e as FamilyInstance).ToList();
foreach (FamilyInstance fi in instances)
{
if (fi.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeFitting)
{
ConnectorManager cm = (fi.MEPModel as MechanicalFitting).ConnectorManager;
if (cm == null) continue;
ConnectorSet cset = cm.UnusedConnectors;
foreach (Connector c in cset)
{
unusedConnectors.Add(c);
}
}
if (fi.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeAccessory)
{
ConnectorManager cm = fi.MEPModel.ConnectorManager;
if (cm == null) continue;
ConnectorSet cset = cm.UnusedConnectors;
foreach (Connector c in cset)
{
unusedConnectors.Add(c);
}
}
if (fi.Category.Id.IntegerValue == (int)BuiltInCategory.OST_MechanicalEquipment)
{
ConnectorManager cm = fi.MEPModel.ConnectorManager;
if (cm == null) continue;
ConnectorSet cset = cm.UnusedConnectors;
foreach (Connector c in cset)
{
unusedConnectors.Add(c);
}
}
if (fi.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PlumbingFixtures)
{
ConnectorManager cm = fi.MEPModel.ConnectorManager;
if (cm == null) continue;
ConnectorSet cset = cm.UnusedConnectors;
foreach (Connector c in cset)
{
unusedConnectors.Add(c);
}
}
}
switch (element.Category.Id.IntegerValue)
{
case (int)BuiltInCategory.OST_PipeCurves:
ConnectPipe(doc, element, unusedConnectors);
break;
case (int)BuiltInCategory.OST_PipeFitting:
ConnectFitting(doc, element, unusedConnectors);
break;
case (int)BuiltInCategory.OST_PipeAccessory:
ConnectAccessory(doc, element, unusedConnectors);
break;
case (int)BuiltInCategory.OST_MechanicalEquipment:
ConnectMeEq(doc, element, unusedConnectors);
break;
case (int)BuiltInCategory.OST_PlumbingFixtures:
ConnectPlFi(doc, element, unusedConnectors);
break;
default:
TaskDialog.Show("Info", "Element has 0 connectors!");
break;
}
}
private void ConnectPipe(Document doc, Element pipe, List<Connector> unconnectedList)
{
ConnectorSet cset = (pipe as Pipe).ConnectorManager.UnusedConnectors;
if (cset.Size == 0)
{
TaskDialog.Show("Info", "Pipe has 0 opened connectors!");
return;
}
foreach (Connector c1 in cset)
{
foreach (Connector c2 in unconnectedList)
{
if (c1.Id == c2.Id) continue;
if (c1.Origin.DistanceTo(c2.Origin) < UnitUtils.ConvertToInternalUnits(10, DisplayUnitType.DUT_MILLIMETERS))
{
Transaction tx = new Transaction(doc, "Connecting elements");
tx.Start();
c1.ConnectTo(c2);
tx.Commit();
return;
}
}
}
TaskDialog.Show("Info", "Can't find the right connector anywhere near!");
}
private void ConnectFitting(Document doc, Element fitting, List<Connector> unconnectedList)
{
ConnectorManager cm = ((fitting as FamilyInstance).MEPModel as MechanicalFitting).ConnectorManager;
if (cm == null) return;
ConnectorSet cset = cm.UnusedConnectors;
if (cset.Size == 0)
{
TaskDialog.Show("Info", "Pipe fitting has 0 opened connectors!");
return;
}
foreach (Connector c1 in cset)
{
foreach (Connector c2 in unconnectedList)
{
if (c1.Id == c2.Id) continue;
if (c1.Origin.DistanceTo(c2.Origin) < UnitUtils.ConvertToInternalUnits(10, DisplayUnitType.DUT_MILLIMETERS))
{
Transaction tx = new Transaction(doc, "Connecting elements");
tx.Start();
c1.ConnectTo(c2);
tx.Commit();
return;
}
}
}
TaskDialog.Show("Info", "Can't find the right connector anywhere near!");
}
private void ConnectAccessory(Document doc, Element accessory, List<Connector> unconnectedList)
{
ConnectorManager cm = (accessory as FamilyInstance).MEPModel.ConnectorManager;
if (cm == null) return;
ConnectorSet cset = cm.UnusedConnectors;
if (cset.Size == 0)
{
TaskDialog.Show("Info", "Pipe accessory has 0 opened connectors!");
return;
}
foreach (Connector c1 in cset)
{
foreach (Connector c2 in unconnectedList)
{
if (c1.Id == c2.Id) continue;
if (c1.Origin.DistanceTo(c2.Origin) < UnitUtils.ConvertToInternalUnits(10, DisplayUnitType.DUT_MILLIMETERS))
{
Transaction tx = new Transaction(doc, "Connecting elements");
tx.Start();
c1.ConnectTo(c2);
tx.Commit();
return;
}
}
}
TaskDialog.Show("Info", "Can't find the right connector anywhere near!");
}
private void ConnectMeEq(Document doc, Element me, List<Connector> unconnectedList)
{
ConnectorManager cm = (me as FamilyInstance).MEPModel.ConnectorManager;
if (cm == null) return;
ConnectorSet cset = cm.UnusedConnectors;
if (cset.Size == 0)
{
TaskDialog.Show("Info", "Mechanical equipment has 0 opened connectors!");
return;
}
foreach (Connector c1 in cset)
{
foreach (Connector c2 in unconnectedList)
{
if (c1.Id == c2.Id) continue;
if (c1.Origin.DistanceTo(c2.Origin) < UnitUtils.ConvertToInternalUnits(10, DisplayUnitType.DUT_MILLIMETERS))
{
Transaction tx = new Transaction(doc, "Connecting elements");
tx.Start();
c1.ConnectTo(c2);
tx.Commit();
return;
}
}
}
TaskDialog.Show("Info", "Can't find the right connector anywhere near!");
}
private void ConnectPlFi(Document doc, Element pf, List<Connector> unconnectedList)
{
ConnectorManager cm = (pf as FamilyInstance).MEPModel.ConnectorManager;
if (cm == null) return;
ConnectorSet cset = cm.UnusedConnectors;
if (cset.Size == 0)
{
TaskDialog.Show("Info", "Plumbing fixture has 0 opened connectors!");
return;
}
foreach (Connector c1 in cset)
{
foreach (Connector c2 in unconnectedList)
{
if (c1.Id == c2.Id) continue;
if (c1.Origin.DistanceTo(c2.Origin) < UnitUtils.ConvertToInternalUnits(10, DisplayUnitType.DUT_MILLIMETERS))
{
Transaction tx = new Transaction(doc, "Connecting elements");
tx.Start();
c1.ConnectTo(c2);
tx.Commit();
return;
}
}
}
TaskDialog.Show("Info", "Can't find the right connector anywhere near!");
}
}
}
|
using Dwjk.Dtp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using trade.client.Trade;
using trade.client.UIUtils;
using static Dwjk.Dtp.QueryFillsResponse.Types;
namespace trade.client
{
public partial class FrmQueryFills : Form
{
private DefaultGridView<Fill> _Grid;
private QueryPagination _NextPage;
public string ExchangeId { set; get; }
public string OriginalId { set; get; }
public string Code { set; get; }
public OrderSide Side { set; get; }
public bool IncludeCancelFill { set; get; }
public Exchange Exchange { set; get; }
public QueryFillsResponse Fills { set; get; }
public FrmQueryFills()
{
InitializeComponent();
_Grid = new DefaultGridView<Fill>(grid);
_NextPage = new QueryPagination
{
Size = (uint)PageSize.Value,
Offset = 0
};
}
private void InitQueryParams()
{
_NextPage.Size = (uint)PageSize.Value;
_NextPage.Offset = 0;
Exchange = TradeDict.Exchange[cboFillExchange.Text];
Side = TradeDict.OrderSide[cboFillOrderSide.Text];
Code = txtFillCode.Text;
ExchangeId = txtFillExchangeId.Text;
OriginalId = txtFillOriginalId.Text;
IncludeCancelFill = chkFillIncludeCancel.Checked;
_Grid.Clear();
}
private void BtnQueryFills_Click(object sender, EventArgs e)
{
RefreshQuery();
}
private void RefreshQuery()
{
InitQueryParams();
QueryAsync();
}
private void QueryAsync()
{
Thread thread = new Thread(new ThreadStart(Query));
thread.Start();
}
private void Query()
{
var fills = AccountToolbar.Current?.QueryFill(
exchange: Exchange,
side: Side,
code: Code,
exchangeId: ExchangeId,
originalId: OriginalId,
includeCancelFill: IncludeCancelFill,
pagination: _NextPage
);
if (fills == null || fills.FillList.Count() == 0)
{
MessageBox.Show("没有了!");
return;
}
if (fills.Pagination.Offset <= _NextPage.Offset) return;
_NextPage.Offset = fills.Pagination.Offset;
Invoke(
new MethodInvoker(() =>
{
_Grid.Add(fills.FillList.ToList());
}));
}
private void FrmQueryFills_Shown(object sender, EventArgs e)
{
RefreshQuery();
}
private void NextPage_Click(object sender, EventArgs e)
{
QueryAsync();
}
}
}
|
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace HttpContextSubs
{
public class SessionSub : ISession {
public bool IsAvailable { get; }
public string Id { get; }
public IEnumerable<string> Keys => _dic.Keys;
private readonly Dictionary<string, byte[]> _dic = new Dictionary<string, byte[]>();
public void Clear() {
_dic.Clear();
}
public Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken)) {
return Task.CompletedTask;
}
public Task LoadAsync(CancellationToken cancellationToken = default(CancellationToken)) {
return Task.CompletedTask;
}
public void Remove(string key) {
_dic.Remove(key);
}
public void Set(string key, byte[] value) {
_dic[key] = value;
}
public bool TryGetValue(string key, out byte[] value) {
return _dic.TryGetValue(key, out value);
}
}
} |
namespace BudgetApp_v11.Shared
{
public enum InOutType
{
Unknow,
In,
Out
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace BradfordLaserTagStats
{
public class GameData : LaserTagEntity
{
public GameData(object[] details, List<string> fieldNames, List<Type> fieldTypes) : base(details, fieldNames, fieldTypes)
{
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2018 {
public class Problem02 : AdventOfCodeBase {
public override string ProblemName {
get { return "Advent of Code 2018: 2"; }
}
public override string GetAnswer() {
return Answer1();
}
public override string GetAnswer2() {
return Answer2();
}
private string Answer1() {
ulong two = 0;
ulong three = 0;
var input = Input();
input.ForEach(x => {
var hash = new Dictionary<char, ulong>();
for (int index = 0; index < x.Length; index++) {
var ch = x[index];
if (!hash.ContainsKey(ch)) {
hash.Add(ch, 1);
} else {
hash[ch]++;
}
}
if (hash.Values.Where(y => y == 3).Count() > 0) {
three++;
}
if (hash.Values.Where(y => y == 2).Count() > 0) {
two++;
}
});
return (three * two).ToString();
}
private string Answer2() {
var input = Input();
char[] diff = new char[input[0].Length - 1];
for (int index1 = 0; index1 < input.Count; index1++) {
var line1 = input[index1];
for (int index2 = index1 + 1; index2 < input.Count; index2++) {
var line2 = input[index2];
int differCount = 0;
int diffIndex = 0;
for (int charIndex = 0; charIndex < line1.Length; charIndex++) {
if (line1[charIndex] != line2[charIndex]) {
differCount++;
if (differCount > 1) {
break;
}
} else {
diff[diffIndex] = line1[charIndex];
diffIndex++;
}
}
if (differCount == 1) {
return new string(diff);
}
}
}
return "";
}
}
}
|
using System;
namespace Tuple
{
public class StartUp
{
public static void Main(string[] args)
{
string[] firstLine = Console.ReadLine().Split();
string fullName = firstLine[0] + " " + firstLine[1];
string address = firstLine[2];
string[] secondLine = Console.ReadLine().Split();
string name = secondLine[0];
int beer = int.Parse(secondLine[1]);
string[] numbers = Console.ReadLine().Split();
int intNumber = int.Parse(numbers[0]);
double doubleNumber = double.Parse(numbers[1]);
SpecialTuple<string, string> addressTuple = new SpecialTuple<string, string>(fullName, address);
SpecialTuple<string, int> beerTuple = new SpecialTuple<string, int>(name, beer);
SpecialTuple<int, double> numberTuple = new SpecialTuple<int, double>(intNumber, doubleNumber);
Console.WriteLine(addressTuple);
Console.WriteLine(beerTuple);
Console.WriteLine(numberTuple);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ConsoleApp1
{
class HandleServer
{
private TcpClient serverSocket;
private int serverID;
HashSet<string> clientsList;
//private List<string> clientsList;
private Log log = Log.GetLog;
private string serverIP;
private int port;
private bool connected = false;
private bool sender;
public void StartServer()
{
serverSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//IList<string> msgSplit;
//msgSplit = serverSocket.Client.RemoteEndPoint.ToString().Split(':');
//ServerIP = msgSplit[0];
//port = Int32.Parse(msgSplit[1]);
//ServerIP = serverSocket.Client.RemoteEndPoint.ToString();
log.Write("Starting Listening Thread for Server " + ServerIP + " : " + port);
Console.WriteLine("Starting Listening Thread for Server " + ServerIP + " : " + port);
if (null == clientsList)
clientsList = new HashSet<string>();
Connected = true;
Thread ctThread = new Thread(Listen);
ctThread.Start();
}
private void Listen()
{
NetworkStream networkStream = null;
try
{
networkStream = serverSocket.GetStream();
Byte[] buffer = new Byte[8];
Byte[] sizeBuff = new Byte[4];
Byte[] typeBuff = new Byte[4];
int msgType, msgSize = 0, sizeIndex = 0, remainingSize = 8, startIndex = 0;
SendMsg send = new SendMsg();
log.Write("enterred and started listening");
while (true)
{
try
{
sizeIndex += networkStream.Read(buffer, startIndex, remainingSize);
}
catch (ObjectDisposedException)
{
log.Write("Socket Connection with Server " + serverID + " has crashed. Local try Catch");
lock (ServerMain.disconnectedServerList)
{
if (!ServerMain.disconnectedServerList.Contains(serverID))
{
serverSocket.Close();
Connected = false;
Console.WriteLine("adding listen");
ServerMain.disconnectedServerList.Add(serverID);
ServerMain.reconnectServerWait.Set();
}
}
startIndex = sizeIndex = msgSize = 0;
remainingSize = 8;
break;
}
catch (IOException)
{
log.Write("Socket Connection with Server " + serverID + " has crashed. Local try Catch");
lock (ServerMain.disconnectedServerList)
{
if (!ServerMain.disconnectedServerList.Contains(serverID))
{
serverSocket.Close();
Connected = false;
Console.WriteLine("adding listen");
ServerMain.disconnectedServerList.Add(serverID);
ServerMain.reconnectServerWait.Set();
}
}
startIndex = sizeIndex = msgSize = 0;
remainingSize = 8;
break;
}
if (sizeIndex > 0 && sizeIndex < 8)
{
remainingSize = 8 - sizeIndex;
startIndex = sizeIndex;
continue;
}
else if (sizeIndex == 0)
{
log.Write("closing connection for " + serverID);
networkStream.Close();
serverSocket.Close();
return;
}
Array.Copy(buffer, typeBuff, 4);
Array.Copy(buffer, 4, sizeBuff, 0, 4);
using (MemoryStream mem = new MemoryStream(typeBuff))
{
using (BinaryReader BR = new BinaryReader(mem))
{
msgType = BR.ReadInt32();
}
}
using (MemoryStream mem = new MemoryStream(sizeBuff))
{
using (BinaryReader BR = new BinaryReader(mem))
{
msgSize = BR.ReadInt32();
}
}
networkStream.Flush();
if (msgType == 1)
{
GetClientList(msgSize, networkStream);
}
else if (msgType == 2)
{
send.SendMsgToClient(msgSize, networkStream, true);
}
else if (msgType == 3)
{
RecRemoveClientMsg(msgSize, networkStream);
}
startIndex = sizeIndex = msgSize = 0;
remainingSize = 8;
}
}
catch (ObjectDisposedException)
{
log.Write("Socket Connection with Server " + serverID + " has crashed. Going to close it EXCEP");
Console.WriteLine("Socket Connection with Server " + serverID + " has crashed. Going to close it EXCEP");
lock (ServerMain.disconnectedServerList)
{
if (!ServerMain.disconnectedServerList.Contains(serverID))
{
serverSocket.Close();
Connected = false;
Console.WriteLine("adding listen");
ServerMain.disconnectedServerList.Add(serverID);
ServerMain.reconnectServerWait.Set();
}
}
}
catch (IOException)
{
log.Write("Socket Connection with Server " + serverID + " has crashed. Going to close it EXCEP");
Console.WriteLine("Socket Connection with Server " + serverID + " has crashed. Going to close it EXCEP");
lock (ServerMain.disconnectedServerList)
{
if (!ServerMain.disconnectedServerList.Contains(serverID))
{
serverSocket.Close();
Connected = false;
Console.WriteLine("adding listen");
ServerMain.disconnectedServerList.Add(serverID);
ServerMain.reconnectServerWait.Set();
}
}
}
catch (Exception)
{
log.Write("An Exception has occured in Server Listen msg for server " + serverID + " Going to close it ");
Console.WriteLine("Socket Connection with Server " + serverID + " has crashed. Going to close it EXCEP");
serverSocket.Close();
}
}
private void RecRemoveClientMsg(int msgSize, NetworkStream networkStream)
{
int msgIndex = 0;
int startIndex, remainingSize;
byte[] bytesFrom;
string client;
remainingSize = msgSize;
bytesFrom = new byte[msgSize];
startIndex = 0;
try
{
while (msgIndex < msgSize)
{
msgIndex += networkStream.Read(bytesFrom, startIndex, remainingSize);
if (msgIndex > 0 && msgIndex < msgSize)
{
remainingSize = msgSize - msgIndex;
startIndex = msgIndex;
continue;
}
else if (0 == msgIndex)
{
networkStream.Close();
return;
}
networkStream.Flush();
client = Encoding.ASCII.GetString(bytesFrom);
log.Write("Server requested so Removing ClientID " + client + " from client List for server " + ServerIP);
lock (ClientsList)
ClientsList.Remove(client);
}
}
catch (ObjectDisposedException)
{
throw;
}
catch (IOException)
{
throw;
}
catch (Exception ex)
{
log.Write("Exception in RemoveClient " + ex);
Console.WriteLine("Exception in RemoveClient " + ex);
}
}
private void GetClientList(int msgSize, NetworkStream networkStream)
{
int msgIndex = 0;
int startIndex, remainingSize;
byte[] bytesFrom;
remainingSize = msgSize;
bytesFrom = new byte[msgSize];
startIndex = 0;
try
{
while (msgIndex < msgSize)
{
msgIndex += networkStream.Read(bytesFrom, startIndex, remainingSize);
if (msgIndex > 0 && msgIndex < msgSize)
{
remainingSize = msgSize - msgIndex;
startIndex = msgIndex;
continue;
}
else if (0 == msgIndex)
{
networkStream.Close();
return;
}
string msg = Encoding.ASCII.GetString(bytesFrom);
networkStream.Flush();
List<string> tempList = msg.Split(',').ToList();
tempList.RemoveAt(0);
//ClientsList.AddRange(tempList);
ClientsList.UnionWith(tempList);
log.Write(" .Printing servers List of clients: " + msg);
}
}
catch (ObjectDisposedException)
{
throw;
}
catch (IOException)
{
throw;
}
catch (Exception ex)
{
log.Write("Exception in SendMsgToClient " + ex);
Console.WriteLine("Exception in SendMsgToClient " + ex);
}
}
public void ReconnectServer()
{
log.Write("Reconnecting server " + ServerIP);
Console.WriteLine("=================== Reconnecting server with" + ServerIP + ':' + Port);
serverSocket = new TcpClient();
serverSocket.Connect(ServerIP, Port);
if (serverSocket.Connected)
{
log.Write("successfully connected with " + ServerIP + ":" + Port);
Console.WriteLine("successfully connected with " + ServerIP + ":" + Port);
Connected = true;
StartServer();
}
else
{
log.Write("Error in connecting with " + ServerIP + ":" + Port);
Console.WriteLine("Error in connecting with " + ServerIP + ":" + Port);
}
}
public TcpClient ServerSocket { get => serverSocket; set => serverSocket = value; }
public int ServerID { get => serverID; set => serverID = value; }
public string ServerIP { get => serverIP; set => serverIP = value; }
public int Port { get => port; set => port = value; }
public HashSet<string> ClientsList { get => clientsList; set => clientsList = value; }
public bool Connected { get => connected; set => connected = value; }
public bool Sender { get => sender; set => sender = value; }
}
}
|
namespace Sila.Controllers
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Sila.Models.Database;
using Sila.Models.Rest.Requests;
using Sila.Services.MongoDb;
/// <summary>
/// The controller for interacting with parts.
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class PartController : ControllerBase
{
private readonly IMongoDbService _mongoDbService;
/// <summary>
/// The controller for interacting with parts.
/// </summary>
/// <param name="mongoDbService">The MongoDb service to use.</param>
public PartController(IMongoDbService mongoDbService)
{
_mongoDbService = mongoDbService;
}
/// <summary>
/// Create a new part
/// </summary>
/// <param name="createPartRequest">The create part request.</param>
/// <returns>A task containing an HTTP response.</returns>
[HttpPost]
public async Task<IActionResult> CreatePart([FromBody] CreatePartRequest createPartRequest)
{
// Create the new part
Part part = new(ObjectId.GenerateNewId().ToString(), createPartRequest.Name)
{
Color = createPartRequest.Color,
Material = createPartRequest.Material
};
// Add the part to the database
await _mongoDbService.InsertDocumentAsync(nameof(Part), part).ConfigureAwait(false);
// Return the created part
return Ok(part);
}
/// <summary>
/// Delete a part.
/// </summary>
/// <param name="id">The ID of the part to delete.</param>
/// <returns>A task containing an HTTP response.</returns>
[HttpDelete("{id}")]
public async Task<IActionResult> DeletePart(String id)
{
// Delete the part with the given ID
await _mongoDbService.RemoveDocumentAsync<Part>(nameof(Part), part => part.Id == id).ConfigureAwait(false);
// Return no content
return NoContent();
}
/// <summary>
/// Get a part.
/// </summary>
/// <param name="id">The ID of the part.</param>
/// <returns>A task containing an HTTP response with the part.</returns>
[HttpGet("{id}")]
public async Task<IActionResult> GetPart(String id)
{
// Find the part with the given ID
Part part = await _mongoDbService.GetCollection<Part>(nameof(Part)).FirstOrDefaultAsync(part => part.Id == id);
// Return the part
return Ok(part);
}
/// <summary>
/// Get all parts.
/// </summary>
/// <returns>A task containing an HTTP response with the parts.</returns>
[HttpGet]
public async Task<IActionResult> GetParts([FromQuery] Boolean componentPartsOnly, [FromQuery] Boolean orphanPartsOnly)
{
// Get the parts as a mongo queryable
IMongoQueryable<Part>? parts = _mongoDbService.GetCollection<Part>(nameof(Part));
if (componentPartsOnly && orphanPartsOnly)
{
return BadRequest($"Please specify true for only one of {nameof(componentPartsOnly)} or {nameof(orphanPartsOnly)}.");
}
else if (componentPartsOnly)
{
return Ok(await parts.Where(part => part.ParentAssemblyId != null).ToListAsync().ConfigureAwait(false));
}
else if (orphanPartsOnly)
{
return Ok(await parts.Where(part => part.ParentAssemblyId == null).ToListAsync().ConfigureAwait(false));
}
else
{
return Ok(await parts.ToListAsync().ConfigureAwait(false));
}
}
/// <summary>
/// Get all the parent assemblies for a part.
/// </summary>
/// <param name="id">The ID of the part.</param>
/// <returns>A task containing an HTTP response.</returns>
[HttpGet("{id}/parent")]
public async Task<IActionResult> GetParentAssemblies(String id)
{
// Get the first parent ID
String? parentId = await _mongoDbService.GetCollection<Part>(nameof(Part)).Where(part => part.Id == id).Select(part => part.ParentAssemblyId).FirstOrDefaultAsync().ConfigureAwait(false);
// Instantiate the list of parents
List<String> parents = new();
// While the current parent is not null, look for the next parent
while (parentId != null)
{
parents.Add(parentId);
parentId = await _mongoDbService.GetCollection<Assembly>(nameof(Assembly)).Where(assembly => assembly.Id == parentId).Select(assembly => assembly.ParentAssemblyId).FirstOrDefaultAsync().ConfigureAwait(false);
}
// Return the parents
return Ok(parents);
}
/// <summary>
/// Update the parent of a part.
/// </summary>
/// <param name="id">The ID of a part to update.</param>
/// <param name="updateParentRequest">The update parent request.</param>
/// <returns>A task containing an HTTP response.</returns>
[HttpPut("{id}")]
public async Task<IActionResult> UpdateParent(String id, [FromBody] UpdateParentRequest updateParentRequest)
{
// Add the parent ID to the part
await _mongoDbService.AddPropertyToObject<Assembly, String?>(nameof(Part), part => part.Id == id, null, nameof(Part.ParentAssemblyId), updateParentRequest.ParentAssemblyId);
// Return an OK response
return Ok();
}
}
}
|
namespace ExtractSentencesByKeyword
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class StartUp
{
public static void Main()
{
var keyWord = Console.ReadLine();
var text = Console.ReadLine()
.Split(new char[] { '.', '!', '?' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.ToArray();
var pattern = $"\\b{keyWord}\\b";
foreach (var sentence in text)
{
var match = Regex.Match(sentence, pattern);
if (match.Success)
{
Console.WriteLine(sentence);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Library
{
public class SampleSettings
{
public string ComputerName { get; set; }
public string ConfigValue { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using static PlayerPrefsX;
public class QuizHandlerScript : MonoBehaviour
{
[SerializeField]Text _soalnya, _pilA, _pilB, _pilC, _pilD;
string _kunci;
[SerializeField]GameObject _ifTrue, _ifFalse;
void Start()
{
_ifTrue.SetActive(false);
_ifFalse.SetActive(false);
setSoal();
}
void setSoal(){
string[] tempSoal, tempA, tempB, tempC, tempD, tempKunci;
tempSoal = PlayerPrefsX.GetStringArray("SoalPilgan");
tempA = PlayerPrefsX.GetStringArray("PilihanA");
tempB = PlayerPrefsX.GetStringArray("PilihanB");
tempC = PlayerPrefsX.GetStringArray("PilihanC");
tempD = PlayerPrefsX.GetStringArray("PilihanD");
tempKunci = PlayerPrefsX.GetStringArray("KunciJwbn");
int noSoal = PlayerPrefs.GetInt("nomorquiz");
_soalnya.text = tempSoal[noSoal];
_pilA.text = tempA[noSoal];
_pilB.text = tempB[noSoal];
_pilC.text = tempC[noSoal];
_pilD.text = tempD[noSoal];
_kunci = tempKunci[noSoal].Trim();
}
public void checkJawaban(Text _jwbnnnya){
Debug.Log("ini jawaban"+_jwbnnnya.text);
Debug.Log("ini kunci"+_kunci);
Debug.Log("panjang jawaban"+_jwbnnnya.text.Length);
Debug.Log("panjang kunci"+_kunci.Length);
Debug.Log("tipe jawaban"+_jwbnnnya.text.GetType());
Debug.Log("tipe kunci"+_kunci.GetType());
if (_jwbnnnya.text != _kunci)
{
_ifFalse.SetActive(true);
}else{
_ifTrue.SetActive(true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MIDIDotNet;
namespace Launchpad
{
public delegate void ButtonPressDelegate(bool pressed);
public delegate void GridButtonPressDelegate(int x, int y, bool pressed);
public class Controller : IDisposable
{
Win32MIDI win32Midi = null;
DeviceManager deviceManager = null;
GMInDevice inDevice = null;
GMOutDevice outDevice = null;
public Controller()
{
win32Midi = new Win32MIDI();
deviceManager = new DeviceManager(win32Midi);
foreach(InDevice inDevice in deviceManager.InDevices)
{
if (inDevice.DeviceName.Contains("Launchpad"))
{
this.inDevice = new GMInDevice(inDevice);
break;
}
}
foreach (OutDevice outDevice in deviceManager.OutDevices)
{
if (outDevice.DeviceName.Contains("Launchpad"))
{
this.outDevice = new GMOutDevice(outDevice);
break;
}
}
this.inDevice.Open();
this.inDevice.HandleDataDelegate = new HandleDataDelegate(this.HandleData);
this.inDevice.NoteOnDelegate = new NoteOnDelegate(this.NoteOn);
this.inDevice.NoteOffDelegate = new NoteOffDelegate(this.NoteOff);
this.inDevice.Start();
this.outDevice.Open();
Reset();
}
public GridButtonPressDelegate GridButtonPressDelegate { set; private get; }
public ButtonPressDelegate UpButtonPressDelegate { set; private get; }
public ButtonPressDelegate DownButtonPressDelegate { set; private get; }
public ButtonPressDelegate LeftButtonPressDelegate { set; private get; }
public ButtonPressDelegate RightButtonPressDelegate { set; private get; }
public ButtonPressDelegate SessionButtonPressDelegate { set; private get; }
public ButtonPressDelegate User1ButtonPressDelegate { set; private get; }
public ButtonPressDelegate User2ButtonPressDelegate { set; private get; }
public ButtonPressDelegate MixerButtonPressDelegate { set; private get; }
public void Dispose()
{
inDevice.Stop();
inDevice.Close();
outDevice.Close();
}
public void HandleData(IntPtr dwParam1, IntPtr dwParam2)
{
uint param1 = (uint)dwParam1;
uint param2 = (uint)dwParam2;
byte status = (byte)(param1 & 0xff);
byte data1 = (byte)((param1 >> 8) & 0xff);
byte data2 = (byte)((param1 >> 16) & 0xff);
if (status == 0xb0)
{
if (data1 == 0x68 && UpButtonPressDelegate != null)
{
UpButtonPressDelegate(data2 == 0x7f);
}
if (data1 == 0x69 && DownButtonPressDelegate != null)
{
DownButtonPressDelegate(data2 == 0x7f);
}
if (data1 == 0x6a && LeftButtonPressDelegate != null)
{
LeftButtonPressDelegate(data2 == 0x7f);
}
if (data1 == 0x6b && RightButtonPressDelegate != null)
{
RightButtonPressDelegate(data2 == 0x7f);
}
if (data1 == 0x6c && SessionButtonPressDelegate != null)
{
SessionButtonPressDelegate(data2 == 0x7f);
}
if (data1 == 0x6d && User1ButtonPressDelegate != null)
{
User1ButtonPressDelegate(data2 == 0x7f);
}
if (data1 == 0x6e && User2ButtonPressDelegate != null)
{
User2ButtonPressDelegate(data2 == 0x7f);
}
if (data1 == 0x6f && MixerButtonPressDelegate != null)
{
MixerButtonPressDelegate(data2 == 0x7f);
}
}
}
public void NoteOn(byte note, byte velocity)
{
if (GridButtonPressDelegate != null)
{
int x = note & 0x0f;
if (x > 8) x = 8;
int y = (note & 0xf0) >> 4;
if (y > 8) y = 8;
GridButtonPressDelegate(x, y, velocity == 0x7f);
}
}
public void NoteOff(byte note, byte velocity)
{
}
public override String ToString()
{
StringBuilder s = new StringBuilder();
s.Append(String.Format("InDevice: {0}\n", inDevice.DeviceName));
s.Append(String.Format("OutDevice: {0}\n", outDevice.DeviceName));
return s.ToString();
}
public void Reset()
{
outDevice.SendShortMsg(0x000000b0);
}
public void Set(int x, int y, Color color)
{
Set(x, y, color.Byte);
}
public void Set(int x, int y, byte colour)
{
x = x & 0xf;
y = y & 0x7;
outDevice.SendNoteOn( 0, (byte)(x + (y * 16)), colour);
}
public void Clear(int x, int y)
{
x = x & 0xf;
y = y & 0x7;
outDevice.SendNoteOff( 0, (byte)(x + (y*16)), 0);
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
namespace Quick_Note
{
public partial class Form1 : Form
{
List<Note> listNote = new List<Note>();
List<string> listFind = new List<string>();
Hook _keyboardHook;
public Form1()
{
InitializeComponent();
if (File.Exists(@"data.json"))
{
listNote = JsonConvert.DeserializeObject<List<Note>>(File.ReadAllText(@"data.json"));
}
if (listNote.Count > 0)
{
MakeItemWihListNode();
}
_keyboardHook = new Hook();
_keyboardHook.Install();
_keyboardHook.KeyDown += (sender, e) =>
{
if (e.KeyCode == Keys.Space && (Keyboard.IsKeyDown(Key.LWin) || Keyboard.IsKeyDown(Key.RWin)))
{
if (this.WindowState == FormWindowState.Minimized)
{
//this.Show();
//this.WindowState = FormWindowState.Normal;
Note item = new Note();
new AddNote(item).ShowDialog();
if (item.isDelete == true) return;
listNote.Add(item);
ClearNote();
MakeItemWihListNode();
SaveData();
}
}
};
}
void UpdateTag()
{
string data = tbFindTag.Text;
if (data == "")
{
this.ClearNote();
this.Update();
MakeItemWihListNode();
return;
}
string[] listString = data.Split(',');
listFind = new List<string>(listString);
if (listNote.Count != 0)
{
this.ClearNote();
this.Update();
}
if (listFind.Count == 0) MakeItemWihListNode();
int lengthNote = listNote.Count;
for (int i = 0; i < lengthNote; ++i)
{
int lengthTags = listNote[i].Tags.Count;
bool isAddNote = false;
for (int j = 0; j < lengthTags; ++j)
{
if (listFind.Any(item => item != "" && item.Trim() == listNote[i].Tags[j].name))
{
isAddNote = true;
}
}
if (isAddNote)
{
this.AddItemToPanel(MakeItem(listNote[i]));
this.Update();
}
}
}
public void MakeItemWihListNode()
{
int lengthNote = listNote.Count;
for (int i = lengthNote - 1; i >= 0; --i)
{
this.AddItemToPanel(MakeItem(listNote[i]));
}
}
private void item_Click(object sender, EventArgs e)
{
Item item = (Item)sender;
Note note = (Note)item.Tag;
new EditNote(note).ShowDialog();
if (note.isDelete)
{
listNote.Remove(note);
flowLayoutPanel1.Controls.Remove(item);
}
item.ReMake(note);
SaveData();
}
public void AddItemToPanel(Item item)
{
flowLayoutPanel1.Controls.Add(item);
item.Parent = flowLayoutPanel1;
item.BackColor = Color.Transparent;
item.InnerButtonClick += item_Click;
}
public Item MakeItem(Note note)
{
Item item = new Item(note);
item.Tag = note;
return item;
}
public void ClearNote()
{
flowLayoutPanel1.Controls.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
Note item = new Note();
new AddNote(item).ShowDialog();
if (item.isDelete == true) return;
listNote.Add(item);
ClearNote();
MakeItemWihListNode();
SaveData();
}
public void SaveData()
{
File.WriteAllText(@"data.json", JsonConvert.SerializeObject(listNote));
}
private void tbFindTag_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
UpdateTag();
}
}
private void label1_Click(object sender, EventArgs e)
{
this.ClearNote();
this.Update();
MakeItemWihListNode();
}
private void button2_Click(object sender, EventArgs e)
{
new Analytic(listNote).ShowDialog();
}
private void viewStaticToolStripMenuItem_Click(object sender, EventArgs e)
{
new Analytic(listNote).ShowDialog();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Move(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
private void viewNoteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
}
private void Setting_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace GFW
{
public class BusinessManager : ServiceModule<BusinessManager>
{
class MessageObject
{
public string target;
public string msg;
public object[] args;
public bool isCall;
}
private string m_domain;
private Dictionary<string, BusinessModule> m_mapModules;
private Dictionary<string, List<MessageObject>> m_mapCacheMessage;
private Dictionary<string, EventTable> m_mapPreListenEvents;
public BusinessManager()
{
m_mapModules = new Dictionary<string, BusinessModule>();
m_mapCacheMessage = new Dictionary<string, List<MessageObject>>();
m_mapPreListenEvents = new Dictionary<string, EventTable>();
}
public void Init(string domain = "")
{
m_domain = domain;
}
/// <summary>
/// 显示业务模块的默认UI
/// </summary>
/// <param name="name"></param>
public void StartModule(string name, object arg = null)
{
CallMethod(name, "Start", arg);
}
/// <summary>
/// 通过类型创建业务模块
/// </summary>
public T CreateModule<T>(object args = null) where T : BusinessModule
{
return (T)CreateModule(typeof(T).Name, args);
}
/// <summary>
/// 通过反射创建业务模块
/// </summary>
public BusinessModule CreateModule(string name, object arg = null)
{
if (m_mapModules.ContainsKey(name))
{
LogMgr.LogWarning("The Module<{0}> Has Existed!", name);
return null;
}
BusinessModule module = null;
Type type = Type.GetType(m_domain + "." + name);
if (type != null)
{
module = Activator.CreateInstance(type) as BusinessModule;
}
else
{
module = new LuaModule(name);
LogMgr.LogWarning("The Module<{0}> Is LuaModule!", name);
}
m_mapModules.Add(name, module);
//处理预监听的事件
EventTable eventTable = null;
if (m_mapPreListenEvents.ContainsKey(name))
{
eventTable = m_mapPreListenEvents[name];
m_mapPreListenEvents.Remove(name);
}
module.SetEventTable(eventTable);
module.Create(arg);
//处理缓存的消息
if (m_mapCacheMessage.ContainsKey(name))
{
List<MessageObject> messageList = m_mapCacheMessage[name];
foreach (MessageObject item in messageList)
{
if (item.isCall)
module.CallMethod(item.msg, item.args);
else
module.HandleMessage(item.msg, item.args);
}
m_mapCacheMessage.Remove(name);
}
return module;
}
public void ReleaseModule(BusinessModule module)
{
if (module != null)
{
if (m_mapModules.ContainsKey(module.Name))
{
LogMgr.Log("ReleaseModule name = {0}",module.Name);
m_mapModules.Remove(module.Name);
module.Release();
}
else
{
LogMgr.LogError("模块不是由ModuleManager创建的! name = {0}", module.Name);
}
}
else
{
LogMgr.LogError("module = null!");
}
}
public BusinessModule GetModule(string name)
{
if (m_mapModules.ContainsKey(name))
{
return m_mapModules[name];
}
return null;
}
public void ReleaseAll()
{
foreach (var @event in m_mapPreListenEvents)
{
@event.Value.UnBindAll();
}
m_mapPreListenEvents.Clear();
m_mapCacheMessage.Clear();
foreach (var module in m_mapModules)
{
module.Value.Release();
}
m_mapModules.Clear();
}
/// <summary>
/// 向指定的模块发送消息
/// </summary>
public void SendMessage(string target, string msg, params object[] args)
{
SendMessage_Internal(false, target, msg, args);
}
public void CallMethod(string target, string name, params object[] args)
{
SendMessage_Internal(true, target, name, args);
}
private void SendMessage_Internal(bool isCall, string target, string msg, object[] args)
{
BusinessModule module = GetModule(target);
if (module != null)
{
if (isCall)
module.CallMethod(msg, args);
else
module.HandleMessage(msg, args);
}
else
{
List<MessageObject> list = GetCacheMessageList(target);
MessageObject obj = new MessageObject();
obj.target = target;
obj.msg = msg;
obj.args = args;
obj.isCall = isCall;
list.Add(obj);
}
}
private List<MessageObject> GetCacheMessageList(string target)
{
List<MessageObject> list = null;
if (!m_mapCacheMessage.ContainsKey(target))
{
list = new List<MessageObject>();
m_mapCacheMessage.Add(target, list);
}
else
{
list = m_mapCacheMessage[target];
}
return list;
}
private EventTable GetPreEventTable(string target)
{
EventTable table = null;
if (!m_mapPreListenEvents.ContainsKey(target))
{
table = new EventTable();
m_mapPreListenEvents.Add(target, table);
}
else
{
table = m_mapPreListenEvents[target];
}
return table;
}
}
}
|
using System;
using System.Net;
using System.Net.Mail;
namespace Langium.Domain
{
public class GmailSMTPHelper
{
private readonly string _smtpUrl = "smtp.gmail.com";
private readonly int _port = 587;
private readonly string _email = "langium.dictionary@gmail.com";
private readonly string _password = "Langium123";
public void SendEmail(string receiverEmail, string emailSubject, string emailBody)
{
if (!string.IsNullOrEmpty(receiverEmail) && !string.IsNullOrEmpty(emailBody))
{
var client = new SmtpClient(_smtpUrl, _port)
{
Credentials = new NetworkCredential(_email, _password),
EnableSsl = true
};
client.Send(_email, receiverEmail, emailSubject, emailBody);
}
}
}
}
|
using Pe.Stracon.SGC.Aplicacion.TransferObject.Base;
using System;
using System.Collections.Generic;
namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual
{
/// <summary>
/// Representa el objeto request del contrato corporativo
/// </summary>
/// <remarks>
/// Creación : GMD 20170623 <br />
/// Modificación : <br />
/// </remarks>
public class ContratoCorporativoRequest : Filtro
{
/// <summary>
/// Código de Unidad Operativa
/// </summary>
public string CodigoUnidadOperativa { get; set; }
/// <summary>
/// Número de Contrato
/// </summary>
public string NumeroContrato { get; set; }
/// <summary>
/// Descripción
/// </summary>
public string Descripcion { get; set; }
/// <summary>
/// Código de Tipo de Servicio
/// </summary>
public string CodigoTipoServicio { get; set; }
/// <summary>
/// Código de Tipo de Requerimiento
/// </summary>
public string CodigoTipoRequerimiento { get; set; }
/// <summary>
/// Código de Tipo de Documento
/// </summary>
public string CodigoTipoDocumento { get; set; }
/// <summary>
/// Fecha de Inicio de Vigencia
/// </summary>
public DateTime? FechaInicioVigencia { get; set; }
/// <summary>
/// Fecha de Fin de Vigencia
/// </summary>
public DateTime? FechaFinVigencia { get; set; }
/// <summary>
/// Fecha de Inicio de Vigencia
/// </summary>
public string FechaInicioVigenciaString { get; set; }
/// <summary>
/// Fecha de Fin de Vigencia
/// </summary>
public string FechaFinVigenciaString { get; set; }
/// <summary>
/// Código de Estado de Contrato
/// </summary>
public string CodigoEstado { get; set; }
/// <summary>
/// Nombre Proveedor
/// </summary>
public string NombreProveedor { get; set; }
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SpeedSlidingTrainer.Core.Model.State.Validation;
using SpeedSlidingTrainer.CoreTests.Utils;
namespace SpeedSlidingTrainer.CoreTests.Model.State.Validation
{
[TestClass]
public partial class BoardValidatorTests
{
[TestMethod]
public void Common_ValuesIsNull_ThrowsException()
{
ValuesIsNull_ThrowsException(ValidationType.BoardGoal);
ValuesIsNull_ThrowsException(ValidationType.BoardState);
ValuesIsNull_ThrowsException(ValidationType.BoardTemplate);
}
[TestMethod]
public void Common_HeightLessThanTwo_ThrowsException()
{
HeightLessThanTwo_ThrowsException(ValidationType.BoardGoal);
HeightLessThanTwo_ThrowsException(ValidationType.BoardState);
HeightLessThanTwo_ThrowsException(ValidationType.BoardTemplate);
}
[TestMethod]
public void Common_WidthLessThanTwo_ThrowsException()
{
WidthLessThanTwo_ThrowsException(ValidationType.BoardGoal);
WidthLessThanTwo_ThrowsException(ValidationType.BoardState);
WidthLessThanTwo_ThrowsException(ValidationType.BoardTemplate);
}
[TestMethod]
public void Common_TooBigValue_IsInvalid()
{
TooBigValue_IsInvalid(ValidationType.BoardGoal);
TooBigValue_IsInvalid(ValidationType.BoardState);
TooBigValue_IsInvalid(ValidationType.BoardTemplate);
}
[TestMethod]
public void Common_NegativeValue_IsInvalid()
{
NegativeValue_IsInvalid(ValidationType.BoardGoal);
NegativeValue_IsInvalid(ValidationType.BoardState);
NegativeValue_IsInvalid(ValidationType.BoardTemplate);
}
[TestMethod]
public void Common_Duplication_IsInvalid()
{
Duplication_IsInvalid(ValidationType.BoardGoal);
Duplication_IsInvalid(ValidationType.BoardState);
Duplication_IsInvalid(ValidationType.BoardTemplate);
}
private static void ValuesIsNull_ThrowsException(ValidationType validationType)
{
ExceptionAssert.Throws(
() =>
{
// Arrange
BoardValidationError[] errors;
// Act
// ReSharper disable once AssignNullToNotNullAttribute
BoardValidator.Validate(3, 3, null, validationType, out errors);
},
typeof(ArgumentNullException));
}
private static void HeightLessThanTwo_ThrowsException(ValidationType validationType)
{
ExceptionAssert.Throws(
() =>
{
// Arrange
BoardValidationError[] errors;
// Act
BoardValidator.Validate(5, 1, new[] { 1, 2, 3, 4, 0 }, validationType, out errors);
},
typeof(ArgumentException));
}
private static void WidthLessThanTwo_ThrowsException(ValidationType validationType)
{
ExceptionAssert.Throws(
() =>
{
// Arrange
BoardValidationError[] errors;
// Act
BoardValidator.Validate(1, 5, new[] { 1, 2, 3, 4, 0 }, validationType, out errors);
},
typeof(ArgumentException));
}
private static void TooBigValue_IsInvalid(ValidationType validationType)
{
// Arrange
BoardValidationError[] errors;
// Act
bool isValid = BoardValidator.Validate(3, 3, new[] { 1, 2, 3, 4, 5, 6, 7, 99, 0 }, validationType, out errors);
// Assert
Assert.IsFalse(isValid);
Assert.IsTrue(errors.Length > 0);
Assert.AreEqual(BoardValidationErrorType.ValueOutOfRange, errors[0].ErrorType);
Assert.IsNotNull(errors[0].Position);
Assert.AreEqual(1, errors[0].Position.X);
Assert.AreEqual(2, errors[0].Position.Y);
}
private static void NegativeValue_IsInvalid(ValidationType validationType)
{
// Arrange
BoardValidationError[] errors;
// Act
bool isValid = BoardValidator.Validate(3, 3, new[] { 1, 2, 3, 4, 5, 6, 7, -99, 0 }, validationType, out errors);
// Assert
Assert.IsFalse(isValid);
Assert.IsTrue(errors.Length > 0);
Assert.AreEqual(BoardValidationErrorType.ValueOutOfRange, errors[0].ErrorType);
Assert.IsNotNull(errors[0].Position);
Assert.AreEqual(1, errors[0].Position.X);
Assert.AreEqual(2, errors[0].Position.Y);
}
private static void Duplication_IsInvalid(ValidationType validationType)
{
// Arrange
BoardValidationError[] errors;
// Act
bool isValid = BoardValidator.Validate(3, 3, new[] { 1, 2, 3, 4, 5, 6, 7, 7, 0 }, validationType, out errors);
// Assert
Assert.IsFalse(isValid);
Assert.IsTrue(errors.Length > 0);
Assert.AreEqual(BoardValidationErrorType.Duplication, errors[0].ErrorType);
Assert.IsNotNull(errors[0].Position);
Assert.AreEqual(1, errors[0].Position.X);
Assert.AreEqual(2, errors[0].Position.Y);
}
}
}
|
using System.Net;
using Bulksign.Extensibility;
namespace CustomIpGeolocationProvider
{
public class CustomIpGeolocationProvider : IIPGeolocationProvider
{
public IJsonSerializer JsonSerializer { get; set; }
public event LogDelegate Log;
public string RunIpGeolocation(IPAddress address)
{
//this provider receives the signer IP address and must return geo-location information for that IP address.
//this information is then added to the envelope audit trail
//based on the provided IP address, retrieve the geo-location data here
return string.Empty;
}
public Dictionary<string, string> Settings
{
get;
set;
}
public string ProviderName => "CustomIpGeolocationProvider";
public HttpClient HttpClient { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CoinSpawner : MonoBehaviour
{
[SerializeField] private GameObject coinPrefab;
void Start()
{
//spawns 2 coins for now
GameObject coin = Instantiate(coinPrefab, new Vector3(13,0,0), transform.rotation);
GameObject coin2 = Instantiate(coinPrefab, new Vector3(11,0,0), transform.rotation);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace _3_Rage_Quit
{
public class _3_Rage_Quit
{
public static void Main()
{
var input = Console.ReadLine().ToUpper();
var pattern = new Regex(@"(\D+)(\d+)");
var matches = pattern.Matches(input);
var newString = new StringBuilder();
foreach (Match item in matches)
{
var newStringToAdd = new StringBuilder();
var count = int.Parse(item.Groups[2].Value);
var stringNew = item.Groups[1].Value;
for (int i = 0; i < count; i++)
{
newStringToAdd.Append(stringNew);
}
newString.Append(newStringToAdd);
}
var line = newString.ToString();
Console.WriteLine($"Unique symbols used: {line.Distinct().Count()}");
Console.WriteLine(line);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using DFC.ServiceTaxonomy.JobProfiles.Module.Models;
namespace DFC.ServiceTaxonomy.JobProfiles.Module.Interfaces
{
public interface ISkillFrameworkBusinessRuleEngine
{
IQueryable<OnetSkill> GetAllRawOnetSkillsForOccupation(string onetOccupationalCode);
IEnumerable<OnetSkill> AverageOutscoreScales(IEnumerable<OnetSkill> attributes);
IEnumerable<OnetSkill> MoveBottomLevelAttributesUpOneLevel(IEnumerable<OnetSkill> attributes);
IEnumerable<OnetSkill> RemoveDuplicateAttributes(IEnumerable<OnetSkill> attributes);
IEnumerable<OnetSkill> RemoveDFCSuppressions(IEnumerable<OnetSkill> attributes);
IEnumerable<OnetSkill> AddTitlesToAttributes(IEnumerable<OnetSkill> attributes);
IEnumerable<OnetSkill> BoostMathsSkills(IEnumerable<OnetSkill> attributes);
IEnumerable<OnetSkill> CombineSimilarAttributes(IList<OnetSkill> attributes);
IEnumerable<OnetSkill> SelectFinalAttributes(IEnumerable<OnetSkill> attributes);
IEnumerable<OnetSkill> UpdateGDSDescriptions(IEnumerable<OnetSkill> attributes);
}
}
|
using EmptyFlow.ConsolePresentation.Enumerators;
namespace EmptyFlow.ConsolePresentation {
public interface IElement {
int Width {
get;
set;
}
int Height {
get;
set;
}
int ActualWidth {
get;
}
int ActualHeight {
get;
}
int ZIndex {
get;
set;
}
VerticalAlignment VerticalAlignment {
get;
set;
}
HorizontalAlignment HorizontalAlignment {
get;
set;
}
// Calculate actual properties
void Measure(Size allowableSize);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace learn_180412_tmp
{
public class Point
{
public string point;
public int x
{
get
{
return int.Parse(point.PadLeft(4, '0').Substring(0, 2));
}
set
{
x = value;
}
}
public int y
{
get
{
return int.Parse(point.PadLeft(4, '0').Substring(2, 2));
}
set
{
y = value;
}
}
public int pointType;
public int pointDescription;
public int pointNo;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Final_Exam
{
class Dog
{
public string name;
public string breed;
private int age;
public string color;
public Dog(string name, string breed, int age, string color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
public int Age // property
{
get { return age; }
set { age = value; }
}
public string getName()
{
return name;
}
public string getBreed()
{
return breed;
}
public int getage()
{
return age;
}
public string getcolor()
{
return color;
}
public void makeString()
{
Console.WriteLine("The dog's name is {0}. The breed is {1}. The age is {2}. The color is {3}.", name, breed, age, color);
}
}
}
|
using Alabo.Web.Mvc.Attributes;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Framework.Core.Enums.Enum {
/// <summary>
/// 频道枚举
/// </summary>
[ClassProperty(Name = "频道枚举")]
public enum ChannelType {
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "文章")]
[Field(IsDefault = true, GuidId = "E02220001110000000000000", Icon = "fa fa-copy")]
Article = 0,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "评论")]
[Field(IsDefault = false, GuidId = "E02220001110000000000001", Icon = "fa fa-comment-o")]
Comment = 1,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "帮助")]
[Field(IsDefault = true, GuidId = "E02220001110000000000003", Icon = "flaticon-support")]
Help = 2,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "图片")]
[Field(IsDefault = false, GuidId = "E02220001110000000000004", Icon = "fa fa-file-image-o")]
Images = 4,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "视频")]
[Field(IsDefault = false, GuidId = "E02220001110000000000005", Icon = "fa fa-video-camera")]
Video = 5,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "下载")]
[Field(IsDefault = false, GuidId = "E02220001110000000000006", Icon = "fa fa-cloud-download")]
Down = 6,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "问答")]
[Field(IsDefault = false, GuidId = "E02220001110000000000007", Icon = " fa fa-question-circle-o ")]
Question = 7,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "招聘")]
[Field(IsDefault = false, GuidId = "E02220001110000000000008", Icon = "fa fa-user-circle-o")]
Job = 8,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "头条")]
[Field(IsDefault = true, GuidId = "E02220001110000000000009", Icon = "fa fa-newspaper-o")]
TopLine = 9,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "消息")]
[Field(IsDefault = false, GuidId = "E02220001110000000000010", Icon = "fa fa-flickr")]
Message = 10,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "会员通知")]
[Field(IsDefault = true, GuidId = "E02220001110000000000011", Icon = "fa fa-envelope-o")]
UserNotice = 11,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "产品手册")]
[Field(IsDefault = true, GuidId = "E02220001110000000000012", Icon = "flaticon-list-3")]
NoteBook = 12,
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "自定义")]
Customer = -1
}
} |
using ProjetctTiGr13.Domain.FicheComponent;
namespace ProjetctTiGr13.Domain
{
public interface IFiche
{
public int IdFiche { get; set; }
public string IdJoueur { get; set; }
public string Equipement { get; set; }
public string CapaciteEtTrait { get; set; }
public string Note { get; set; }
public bool Inspiration { get; set; }
//Composant de la fiche
public BasicCharacterInfo BasicInfo { get; set; }
public HealthPointManager HpManager { get; set; }
public SaveRollManager SaveRolls { get; set; }
public DeathRollManager DeathRolls { get; set; }
public MoneyManager Wallet { get; set; }
public PersonalityAndBackground BackgroundAndTrait { get; set; }
public CharacterMasteries Masteries { get; set; }
public CaracteristicsManager Caracteristics { get; set; }
public CharacterStatus Status { get; set; }
}
} |
using System;
namespace _12_Lesson
{
class Program
{
static void Main(string[] args)
{
int x = -1;
int y;
y = 2;
var a = 1; /* есть сложные типы которые имеют длинную запись, в этом случае
* применяют var
*/
string name = "John";
Console.WriteLine(a);
Console.WriteLine(name);
// переменные нужно именовать значимо!!!
}
}
}
|
// File Prologue
// Name: Darren Moody
// CS 1400 Section 005
// Project: CS1400 Lab 11
// Date: 10/03/2013
//
// I declare that the following code was written by me or provided
// by the instructor for this project. I understand that copying source
// code from any other source constitutes cheating, and that I will receive
// a zero on this project if I am found in violation of this policy.
// ---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TokenMachine
{
public partial class Form1 : Form
{
// a class level reference to a token machine
private TokenMachine tm;
public Form1()
{
InitializeComponent();
// create a token machine object
tm = new TokenMachine();
// this pretty much does the job of a constructor here
tm.Reset();
txtBoxTokens.Text = string.Format("{0}", tm.CountTokens());
txtBoxQuarters.Text = string.Format("{0}", tm.CountQuarters());
}
// The exitToolStripMenuItem_Click method
// Purpose: To close the window and terminate the application
// Parameters: The object generating the event
// and the event arguments
// Returns: None
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
// The aboutToolStripMenuItem_Click method
// Purpose: To open a message box showing my information
// Parameters: The object generating the event
// and the event arguments
// Returns: None
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Darren Moody\nCS1400-005\nLab #11");
}
// The btnGetToken_Click method
// Purpose: subtracts one token, adds one quarter, updates text box values
// Parameters: The object generating the event
// and the event arguments
// Returns: None
private void btnGetToken_Click(object sender, EventArgs e)
{
tm.GetToken();
txtBoxTokens.Text = string.Format("{0}", tm.CountTokens());
txtBoxQuarters.Text = string.Format("{0}", tm.CountQuarters());
}
// The btnReset_Click method
// Purpose: Resets the value of tokens to 100, and quarters to 0
// and updates the text box values
// Parameters: The object generating the event
// and the event arguments
// Returns: None
private void btnReset_Click(object sender, EventArgs e)
{
tm.Reset();
txtBoxTokens.Text = string.Format("{0}", tm.CountTokens());
txtBoxQuarters.Text = string.Format("{0}", tm.CountQuarters());
}
}
}
|
using UnityEngine;
using System.Collections;
public class LivingEntity : MonoBehaviour, IDamageable { // This is a parent class for anything "living", i.e. can (at least) take and (optionally) deal damage.
public float startingHealth;
protected float health;
protected bool dead;
public event System.Action OnDeath;
protected virtual void Start() {
health = startingHealth;
}
public void TakeHit(float damage, RaycastHit hit) {
// Use RaycastHit for things
TakeDamage(damage); // Calls TakeDamage() for convenience
}
public void TakeDamage(float damage) {
health -= damage;
if (health <= 0 && !dead) // Die if you run out of health
{
Die();
}
}
protected void Die() {
dead = true;
if (OnDeath != null) {
OnDeath(); // Broadcast an event when you die
}
GameObject.Destroy(gameObject); // Destroy your game object once you have died
}
}
|
namespace ComputersApplication
{
using System.Collections.Generic;
public class Computer
{
//fields
private readonly LaptopBattery battery;
//constructors
internal Computer(ComputerTypes type, ComputerCpu cpu, ComputerRam ram, IEnumerable<HardDrive> hardDrives, HardDrive videoCard, LaptopBattery battery)
{
this.Cpu = cpu;
this.Ram = ram;
this.HardDrives = hardDrives;
this.VideoCard = videoCard;
if (type != ComputerTypes.Laptop && type != ComputerTypes.Pc)
{
this.VideoCard.IsMonochrome = true;
}
this.battery = battery;
}
//properties
public IEnumerable<HardDrive> HardDrives { get; set; }
public HardDrive VideoCard { get; set; }
public ComputerCpu Cpu { get; set; }
public ComputerRam Ram { get; set; }
//methods
public void Play(int guessNumber)
{
this.Cpu.RandomNumber(1, 11);
var randNumber = Ram.LoadValue();
if (randNumber + 1 != guessNumber + 1)
{
this.VideoCard.Draw(string.Format("You didn't guess the number {0}.", randNumber));
}
else
{
this.VideoCard.Draw("You win!");
}
}
internal void ChargeBattery(int percentage)
{
battery.Charge(percentage);
VideoCard.Draw(string.Format("Battery status: {0}%", battery.Percentage));
}
internal void Process(int inputData)
{
//Number 1000 is too high for HP, but not for Dell. Manifacturers' logic is corrected, because of their RAM.
Ram.SaveValue(inputData);
Cpu.SquareNumber();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotate : MonoBehaviour {
Quaternion rotate;
// Use this for initialization
void Start () {
}
void Update()
{
if (Input.GetKey(KeyCode.D))
{
transform.Rotate(Vector3.forward * 50 * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.back * 50 * Time.deltaTime);
}
}
}
|
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
[SerializeField]private Transform _playerSprite;
[SerializeField]private float _movementSpeed;
private Rigidbody2D _rb2D;
private float _moveDirection;
void Start ()
{
_rb2D = GetComponent<Rigidbody2D>();
InputDelegates.MovementInput += Move;
}
void Move(Vector2 moveDir)
{
_rb2D.MovePosition(_rb2D.position + moveDir * _movementSpeed * Time.deltaTime);
//Rotates the player towards its moving direction
if (moveDir.x < 0)
{
_playerSprite.rotation = Quaternion.Euler(0, 180, 0);
}
else if (moveDir.x > 0)
{
_playerSprite.rotation = Quaternion.Euler(0, 0, 0);
}
}
void OnDisable()
{
InputDelegates.MovementInput -= Move;
}
}
|
// <copyright file="MasterDataBL.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
namespace SmartLibrary.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using Infrastructure;
using SmartLibrary.Models;
/// <summary>
/// This class is used to Define Database object for Save, Search, Delete
/// </summary>
/// <CreatedBy>Tirthak Shah</CreatedBy>
/// <CreatedDate>30-Aug-2018</CreatedDate>
public class MasterDataBL
{
#region :: page ::
/// <summary>
/// Save Page
/// </summary>
/// <param name="page">Page</param>
/// <returns>Id</returns>
public int SavePage(Page page)
{
using (ServiceContext service = new ServiceContext(false, "Name"))
{
if (page.Id > 0)
{
page.ModifiedBy = ProjectSession.UserId;
page.ModifiedDate = DateTime.Now;
}
else
{
page.CreatedBy = ProjectSession.UserId;
page.CreatedDate = DateTime.Now;
}
return service.Save<Page>(page);
}
}
/// <summary>
/// GetPageList
/// </summary>
/// <param name="model">model</param>
/// <returns> return List Of page to display in grid </returns>
public List<Page> GetPageList(Page model)
{
using (ServiceContext service = new ServiceContext())
{
return service.Search<Page>(model, model.StartRowIndex, model.EndRowIndex, model.SortExpression, model.SortDirection).ToList();
}
}
/// <summary>
/// DeletepageList
/// </summary>
/// <param name="id">id</param>
/// <returns>Delete page</returns>
public int DeletePage(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<Page>(id);
}
}
#endregion
#region :: Book Location ::
/// <summary>
/// Save Location
/// </summary>
/// <param name="location">Page</param>
/// <returns>Id</returns>
public int SaveBookLocation(BookLocation location)
{
using (ServiceContext service = new ServiceContext(false, "Name"))
{
if (location.ID > 0)
{
location.ModifiedBy = ProjectSession.UserId;
location.ModifiedDate = DateTime.Now;
}
else
{
location.CreatedBy = ProjectSession.UserId;
location.CreatedDate = DateTime.Now;
}
return service.Save<BookLocation>(location);
}
}
/// <summary>
/// GetLocationList
/// </summary>
/// <param name="location">model</param>
/// <returns> return List Of page to display in grid </returns>
public List<BookLocation> GetLocationList(BookLocation location)
{
using (ServiceContext service = new ServiceContext())
{
return service.Search<BookLocation>(location, location.StartRowIndex, location.EndRowIndex, location.SortExpression, location.SortDirection).ToList();
}
}
/// <summary>
/// DeleteLocationList
/// </summary>
/// <param name="id">id</param>
/// <returns>Delete Location</returns>
public int DeleteBookLocation(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<BookLocation>(id);
}
}
#endregion
#region :: BookGenre ::
/// <summary>
/// Save BookGenre
/// </summary>
/// <param name="bookGenre">BookGenre</param>
/// <returns>Id</returns>
public int SaveBookGenre(BookGenre bookGenre)
{
using (ServiceContext service = new ServiceContext(false, "Name"))
{
if (bookGenre.ID > 0)
{
bookGenre.ModifiedBy = ProjectSession.UserId;
bookGenre.ModifiedDate = DateTime.Now;
}
else
{
bookGenre.CreatedBy = ProjectSession.UserId;
bookGenre.CreatedDate = DateTime.Now;
}
return service.Save<BookGenre>(bookGenre);
}
}
/// <summary>
/// GetBookGenreList
/// </summary>
/// <param name="model">model</param>
/// <returns> return List Of BookGenre to display in grid </returns>
public List<BookGenre> GetBookGenreList(BookGenre model)
{
using (ServiceContext service = new ServiceContext())
{
return service.Search<BookGenre>(model, model.StartRowIndex, model.EndRowIndex, model.SortExpression, model.SortDirection).ToList();
}
}
/// <summary>
/// Delete BookGenre
/// </summary>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public int DeleteBookGenre(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<BookGenre>(id);
}
}
#endregion
#region ::Space::
/// <summary>
/// Save Space
/// </summary>
/// <param name="space">Space</param>
/// <returns>Id</returns>
public int SaveSpace(Space space)
{
using (ServiceContext service = new ServiceContext(false, "Name"))
{
if (space.ID > 0)
{
space.ModifiedBy = ProjectSession.UserId;
space.ModifiedDate = DateTime.Now;
}
else
{
space.CreatedBy = ProjectSession.UserId;
space.CreatedDate = DateTime.Now;
}
return service.Save<Space>(space);
}
}
/// <summary>
/// Get Space
/// </summary>
/// <param name="model">model</param>
/// <returns> return List Of Space to display in grid </returns>
public List<Space> GetSpaceList(Space model)
{
using (ServiceContext service = new ServiceContext())
{
return service.Search<Space>(model, model.StartRowIndex, model.EndRowIndex, model.SortExpression, model.SortDirection).ToList();
}
}
/// <summary>
/// Delete Spaces
/// </summary>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public int DeleteSpace(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<Space>(id);
}
}
#endregion
#region ::Customer::
/// <summary>
/// Save Customer
/// </summary>
/// <param name="customer">Customer</param>
/// <returns>Id</returns>
public int SaveCustomer(Customer customer)
{
using (ServiceContext service = new ServiceContext(false, "Name"))
{
if (customer.Id > 0)
{
customer.ModifiedBy = ProjectSession.UserId;
customer.ModifiedDate = DateTime.Now;
}
else
{
customer.CreatedBy = ProjectSession.UserId;
customer.CreatedDate = DateTime.Now;
}
return service.Save<Customer>(customer);
}
}
/// <summary>
/// Get Customer
/// </summary>
/// <param name="model">model</param>
/// <returns> return List Of Customer to display </returns>
public List<Customer> GetCustomerList(Customer model)
{
using (ServiceContext service = new ServiceContext())
{
return service.Search<Customer>(model, model.StartRowIndex, model.EndRowIndex, model.SortExpression, model.SortDirection).ToList();
}
}
/// <summary>
/// Delete Customers
/// </summary>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public int DeleteCustomer(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<Customer>(id);
}
}
#endregion
#region :: Space Booking ::
/// <summary>
/// Add Space Booking
/// </summary>
/// <param name="spaceBooking">spaceBooking</param>
/// <param name="statusId">Status Id</param>
/// <returns>Id</returns>
public int AddSpaceBooking(SpaceBooking spaceBooking, int? statusId)
{
using (ServiceContext service = new ServiceContext())
{
spaceBooking.StatusId = statusId.ToInteger();
spaceBooking.CustomerId = ProjectSession.CustomerId > 0 ? ProjectSession.CustomerId : spaceBooking.CustomerId;
return service.Save<SpaceBooking>(spaceBooking, "CUSPSpaceBookingsSave");
}
}
#endregion
#region :: Generic CRUD ::
/// <summary>
/// Save the Current Model
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="entity">Model Object</param>
/// <param name="combinationCheckRequired">Combination Check Required</param>
/// <param name="checkForDuplicate">checkForDuplicate</param>
/// <param name="columns">column Name array to check duplicate, Maximum 3 columns</param>
/// <returns>Id</returns>
public int Save<TEntity>(TEntity entity, bool combinationCheckRequired = true, bool checkForDuplicate = true, params string[] columns)
{
using (ServiceContext service = new ServiceContext(combinationCheckRequired, checkForDuplicate, columns))
{
if ((int)entity.GetType().GetProperty("ID").GetValue(entity) > 0)
{
this.SetPropertyValue(entity, "ModifiedBy", ProjectSession.UserId);
this.SetPropertyValue(entity, "ModifiedDate", DateTime.Now);
}
else
{
this.SetPropertyValue(entity, "CreatedBy", ProjectSession.UserId);
this.SetPropertyValue(entity, "CreatedDate", DateTime.Now);
}
return service.Save<TEntity>(entity);
}
}
/// <summary>
/// Return the list of model for given search criteria
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="model">model</param>
/// <returns> return List Of BookGenre to display in grid </returns>
public List<TEntity> Search<TEntity>(TEntity model)
{
using (ServiceContext service = new ServiceContext())
{
BaseModel baseModel = (BaseModel)((object)model);
return service.Search<TEntity>(model, baseModel.StartRowIndex, baseModel.EndRowIndex, baseModel.SortExpression, baseModel.SortDirection).ToList();
}
}
/// <summary>
/// Get only one object from id
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public TEntity SelectObject<TEntity>(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.SelectObject<TEntity>(id);
}
}
/// <summary>
/// Delete BookGenre
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public int Delete<TEntity>(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<TEntity>(id);
}
}
/// <summary>
/// Delete BookGenre
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public TEntity GetBookDetail<TEntity>(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.SelectObject<TEntity>(id);
}
}
/// <summary>
/// Save Book Borrow
/// </summary>
/// <param name="borrowedbook">borrowedbook</param>
/// <returns>Id</returns>
public int SaveBorrowBook(BorrowedBook borrowedbook)
{
return this.Save(borrowedbook, false, false);
}
/// <summary>
/// Delete BookGenre
/// </summary>
/// <param name="entity">entity object</param>
/// <param name="propertyName">Property Name to be set</param>
/// <param name="value">value to assign</param>
private void SetPropertyValue(object entity, string propertyName, object value)
{
if (entity.GetType().GetProperty(propertyName) != null)
{
entity.GetType().GetProperty(propertyName).SetValue(entity, value);
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlogEngine.Domain.Entities
{
public class Comment
{
public int CommentId { get; set; }
public string Content { get; set; }
public DateTime DateCreated { get; set; }
public bool IsEdited { get; set; }
public int Karma { get; set; }
public CommentStatus Status { get; set; }
public int PostId { get; set; }
public virtual Post Post { get; set; }
public int BlogUserId { get; set; }
public virtual BlogUser BlogUser { get; set; }
}
public enum CommentStatus
{
Active,
DeletedByAuthor,
DeletedByAdmin
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosionBehavior : MonoBehaviour {
//this is the behavior of the explosion when an enemy dies
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
this.transform.Translate(Vector3.down * 4 * Time.deltaTime);
if (this.transform.position.y < -6)
Destroy(this.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CommandLine
{
public class Example
{
public static ExampleOptions Options = new ExampleOptions();
public static int Main(string[] args)
{
try
{
Options = ExampleOptions.ParseArgs(args);
if (Options == null)
return 1;
Console.WriteLine("Successfully parsed the options");
}
catch (Exception ex)
{
Console.WriteLine("Example error: {0}", ex);
return 1;
}
return 0;
}
}
public class ExampleOptions : CommandLineOptionsBase
{
[ValueList(typeof(List<string>))]
public IList<string> Actions { get; set; }
[Option("g", "game", Required = true, HelpText = "Name of game. ex: 'Test'")]
public string Game { get; set; }
[Option("b", "build", Required = true, HelpText = "Build version of game. ex: 'XXXX'")]
public string Build { get; set; }
[Option("m", "Manifest", Required = false, HelpText = "Path to manifest file")]
public string Manifest { get; set; }
[Option("v", "verbose", Required = false, HelpText = "Turns on verbose output")]
public bool Verbose { get; set; }
[HelpOption]
public string GetUsage()
{
// this without using CommandLine.Text
var usage = new StringBuilder();
usage.AppendLine("");
usage.AppendLine("CommandLine Example");
usage.AppendLine(" Example.exe someAction --game Test --build Foo --Manifest bar");
usage.AppendLine("");
return usage.ToString();
}
public static ExampleOptions ParseArgs(string[] args)
{
var options = new ExampleOptions();
var settings = new CommandLineParserSettings { CaseSensitive = false };
var parser = new CommandLineParser(settings);
var results = parser.ParseArguments(args, options);
if (!results)
return null;
if (!string.IsNullOrEmpty(options.Manifest) && !File.Exists(options.Manifest))
{
Console.WriteLine("Missing manifest file: {0}", options.Manifest);
return null;
}
return options;
}
}
}
|
using System.Collections.Generic;
namespace E7
{
public class Argentina
{
List<Alfajor> alfajores = new List<Alfajor>();
public Argentina(){
Alfajor alfajor1 = new Alfajor("Triple fruta", 100, "Waymayen");
Alfajor alfajor2 = new Alfajor("Triple chocolate", 50, "Capitan del Espacio");
Alfajor alfajor3 = new Alfajor("Triple chocolate blanco", 37, "Jorgito");
alfajores.Add(alfajor1);
alfajores.Add(alfajor2);
alfajores.Add(alfajor3);
}
public void bajarElPrecioDelPetroleo(){
foreach (var i in alfajores){
i.Aumentos(1);
}
}
public void milllaiHablaPorTv(){
foreach (var i in alfajores){
i.Aumentos(2);
}
}
public void CoronaVairas(){
foreach (var i in alfajores){
i.Aumentos(3);
}
}
public int inflacion(){
int suma = 0;
foreach (var i in alfajores){
suma += i.Precio;
}
return suma;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace _09.CatalanNumbers
{
class CatalanN
{
static void Main()
{
Console.WriteLine("Enter witch Catalan number you want to see: ");
int userInput = int.Parse(Console.ReadLine());
while (userInput < 0)
{
Console.WriteLine("Please enter a positive number:");
userInput = int.Parse(Console.ReadLine());
}
BigInteger factorialOfN = 1;
BigInteger factorialOfNextN = 1;
BigInteger factorialDoubleN = 1;
for (int index = 1; index <= userInput; index++)
{
factorialOfN *= index;
}
for (int inner = 1; inner <= userInput + 1; inner++)
{
factorialOfNextN *= inner;
}
for (int index2 = 1; index2 <= userInput*2; index2++)
{
factorialDoubleN *= index2;
}
Console.WriteLine("n! = {0}", factorialOfN);
Console.WriteLine("(n+1)! = {0}", factorialOfNextN);
Console.WriteLine("(2*n)! = {0}", factorialDoubleN);
Console.WriteLine("The {0} number of Catalan is: {1}", userInput, factorialDoubleN / (factorialOfNextN * factorialOfN));
}
}
}
|
using System.Runtime.InteropServices.WindowsRuntime;
namespace Interpreter
{
public class ManyExpression : Expression
{
public override string One()
{
return "C";
}
public override string Nine()
{
return "CM";
}
public override string Four()
{
return "CD";
}
public override string Five()
{
return "D";
}
public override int Multiply()
{
return 1000;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Kulula.com.Models
{
class PreferredClass
{
public int PreferredClassID { get; set; }
public int AirportID { get; set; }
public string PreferredClassType { get; set; }
public string FlightType { get; set; }
public double Price { get; set; }
public double Quantity { get; set; }
public double Total { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace StockAnalyzer
{
public partial class mainWindow : Form
{
public mainWindow()
{
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
goButton.Image = System.Drawing.Image.FromFile(@"../../../images/goButton_MouseUp.png");
}
private void quotesBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.quotesBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.db1DataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'db1DataSet.quotes' table. You can move, or remove it, as needed.
//this.quotesTableAdapter.Fill(this.db1DataSet.quotes);
}
private void saveButton_Click(object sender, EventArgs e)
{
foreach (DataRow row in this.db1DataSet.Tables["quotes"].Rows)
{
System.Diagnostics.Debug.Write(row["Symbol"] + ": " + row["Close"]);
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
//Form NewMdiChild = new graph_frame();
//NewMdiChild.MdiParent = this;
//NewMdiChild.Text = "Graph Frame " + this.MdiChildren.Count();
//NewMdiChild.Show();
}
private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade);
}
private void tileHorizontallyToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(System.Windows.Forms.MdiLayout.TileHorizontal);
}
private void tileVerticallyToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(System.Windows.Forms.MdiLayout.TileVertical);
}
private void goButton_Click(object sender, EventArgs e)
{
try
{
string symbol = symbolTextBox.Text.ToUpper();
stockData stock = new stockData();
Form NewMdiChild = new graph_frame(stock.getData(symbol), symbol);
NewMdiChild.MdiParent = this;
NewMdiChild.Text = symbol + this.MdiChildren.Count();
NewMdiChild.Show();
}
catch (NotSupportedException)
{
MessageBox.Show("Sorry, couldn't locate that symbol. Please try another one.");
}
catch (FileNotFoundException)
{
MessageBox.Show("Sorry, couldn't locate that symbol. Please try another one.");
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void goButton_MouseUp(object sender, MouseEventArgs e)
{
goButton.Image = System.Drawing.Image.FromFile(@"../../../images/goButton_MouseUp.png");
}
private void goButton_MouseDown(object sender, MouseEventArgs e)
{
goButton.Image = System.Drawing.Image.FromFile(@"../../../images/goButton_MouseDown.png");
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Form childForm = this.ActiveMdiChild;
graph_frame castForm = (graph_frame)childForm;
castForm.showMovingAverage();
}
private void movingAverageToolStripMenuItem_Click(object sender, EventArgs e)
{
Form childForm = this.ActiveMdiChild;
graph_frame castForm = (graph_frame)childForm;
if (movingAverageToolStripMenuItem.Checked)
{
castForm.showMovingAverage();
}
else
{
castForm.hideMovingAverage();
}
}
private void exponentialMovingAverageToolStripMenuItem_Click(object sender, EventArgs e)
{
Form childForm = this.ActiveMdiChild;
graph_frame castForm = (graph_frame)childForm;
if (exponentialMovingAverageToolStripMenuItem.Checked)
{
castForm.showExponentialMovingAverage();
}
else
{
castForm.hideExponentialMovingAverage();
}
}
private void bollingerBandsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form childForm = this.ActiveMdiChild;
graph_frame castForm = (graph_frame)childForm;
if (bollingerBandsToolStripMenuItem.Checked)
{
castForm.showBollingerBands();
}
else
{
castForm.hideBollingerBands();
}
}
//Reset everything when the active MDI child window changes
private void mdiActiveChildChange(object sender, EventArgs e)
{
Form childForm = this.ActiveMdiChild;
graph_frame castForm = (graph_frame)childForm;
if (castForm.checkMovingAverage()) { movingAverageToolStripMenuItem.Checked = true;}
else {movingAverageToolStripMenuItem.Checked = false;}
if (castForm.checkExponentialMovingAverage()) { exponentialMovingAverageToolStripMenuItem.Checked = true; }
else { exponentialMovingAverageToolStripMenuItem.Checked = false; }
if (castForm.checkBollingerBands()) { bollingerBandsToolStripMenuItem.Checked = true; }
else { bollingerBandsToolStripMenuItem.Checked = false; }
if (castForm.checkCandlestick()) { candlestickToolStripMenuItem.Checked = true; }
else { candlestickToolStripMenuItem.Checked = false; }
if (castForm.checkLine()) { lineToolStripMenuItem.Checked = true; }
else { lineToolStripMenuItem.Checked = false; }
//Update Company Info from Database
string connectionStringLaptop = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\crommie\Dropbox\stock_analyzer\StockAnalyzer_windows\StockAnalyzer\prices.mdf;Integrated Security=True";
string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\aaron\documents\visual studio 2012\Projects\StockAnalyzer\StockAnalyzer\prices.mdf;Integrated Security=True";
SqlConnection db2Connection = new SqlConnection(connectionStringLaptop);
db2Connection.Open();
//TODO: Figure out a better way to pass the symbol name into this function!!!
//Right now we are reading the title of the active chart. Not a good method!!
string sym = castForm.getSymbol();
string sqlStr = "SELECT * FROM companyData where symbol = '" + sym + "'";
SqlDataAdapter myCommand = new SqlDataAdapter(sqlStr, db2Connection);
DataSet ds = new DataSet();
myCommand.Fill(ds);
db2Connection.Close();
string tempPrice = ds.Tables[0].Rows[0]["price"].ToString();
string price = tempPrice.Split('>', '<')[2];
price = Convert.ToDouble(price).ToString("0.00");
priceLabel.Text = price;
string name = ds.Tables[0].Rows[0]["name"].ToString();
nameLabel.Text = name;
string change = ds.Tables[0].Rows[0]["change"].ToString();
change = change.Split('"', '"')[1];
changeLabel.Text = change;
string prevClose = ds.Tables[0].Rows[0]["prevClose"].ToString();
try
{
float changePercent = float.Parse(change) / float.Parse(prevClose);
changePercentLabel.Text = (changePercent * 100).ToString("0.00") + "%";
if (float.Parse(change) > 0)
{
changeLabel.ForeColor = Color.Green;
changePercentLabel.ForeColor = Color.Green;
}
else
{
changeLabel.ForeColor = Color.Red;
changePercentLabel.ForeColor = Color.Red;
}
}
catch { //MessageBox.Show("Detailed Data Not Available For " + symbol);
}
string openVal = ds.Tables[0].Rows[0]["openVal"].ToString();
openText.Text = openVal;
string ask = ds.Tables[0].Rows[0]["ask"].ToString();
askLabel.Text = "ask " + ask;
string bid = ds.Tables[0].Rows[0]["bid"].ToString();
bidLabel.Text = "bid " + bid;
//string prevClose = ds.Tables[0].Rows[0]["prevClose"].ToString();
//prevClose defined above already
prevCloseText.Text = prevClose;
string dailyHigh = ds.Tables[0].Rows[0]["dailyHigh"].ToString();
string dailyLow = ds.Tables[0].Rows[0]["dailyLow"].ToString();
dailyLow = Convert.ToDouble(dailyLow).ToString("0.00"); //Only show 2 decimal places
dailyHigh = Convert.ToDouble(dailyHigh).ToString("0.00"); //Only show 2 decimal places
dailyRangeText.Text = dailyLow + " - " + dailyHigh;
string fiftytwoWeekHigh = ds.Tables[0].Rows[0]["fiftytwoWeekHigh"].ToString();
string fiftytwoWeekLow = ds.Tables[0].Rows[0]["fiftytwoWeekLow"].ToString();
fiftytwoWeekLow = Convert.ToDouble(fiftytwoWeekLow).ToString("0.00"); //Only show 2 decimal places
fiftytwoWeekHigh = Convert.ToDouble(fiftytwoWeekHigh).ToString("0.00"); //Only show 2 decimal places
fiftytwoWeekRangeText.Text = fiftytwoWeekLow + " - " + fiftytwoWeekHigh;
string avgVol = ds.Tables[0].Rows[0]["avgDailyVol"].ToString();
avgVolText.Text = avgVol;
string mktcap = ds.Tables[0].Rows[0]["mktCap"].ToString();
mktCapText.Text = mktcap;
string pe = ds.Tables[0].Rows[0]["pe"].ToString();
peText.Text = pe;
string pb = ds.Tables[0].Rows[0]["pb"].ToString();
pbText.Text = pb;
string ps = ds.Tables[0].Rows[0]["ps"].ToString();
psText.Text = ps;
string div = ds.Tables[0].Rows[0]["div"].ToString();
string divYield = ds.Tables[0].Rows[0]["divYield"].ToString();
divText.Text = div + " / " + divYield + "%";
}
private void candlestickToolStripMenuItem_Click(object sender, EventArgs e)
{
Form childForm = this.ActiveMdiChild;
graph_frame castForm = (graph_frame)childForm;
if (candlestickToolStripMenuItem.Checked)
{
castForm.showCandlestick();
this.lineToolStripMenuItem.Checked = false;
}
else
{
castForm.hideCandlestick();
}
}
private void lineToolStripMenuItem_Click(object sender, EventArgs e)
{
Form childForm = this.ActiveMdiChild;
graph_frame castForm = (graph_frame)childForm;
if (lineToolStripMenuItem.Checked)
{
castForm.showLine();
candlestickToolStripMenuItem.Checked = false;
}
else
{
castForm.hideLine();
}
}
private void loadDefaultsToolStripMenuItem_Click(object sender, EventArgs e)
{
using (StreamReader defaultsReader = new StreamReader("../defaults.dat"))
{
string line;
string[] vals;
while ((line = defaultsReader.ReadLine()) != null)
{
vals = line.Split(',');
foreach (string val in vals)
{
try
{
string symbol = val.ToUpper();
stockData stock = new stockData();
Form NewMdiChild = new graph_frame(stock.getData(symbol), symbol);
NewMdiChild.MdiParent = this;
NewMdiChild.Text = symbol + this.MdiChildren.Count();
NewMdiChild.Show();
}
catch (NotSupportedException)
{
MessageBox.Show("Not Supported Exception");
}
catch (FileNotFoundException)
{
MessageBox.Show("File Not Found Exception");
}
}
}
}
this.LayoutMdi(System.Windows.Forms.MdiLayout.TileHorizontal);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BackGroundScroller2 : MonoBehaviour
{
public float speed1 = 0;
public float speed2 = 0;
public static BackGroundScroller2 current;
float pos1 = 0;
float pos2 = 0;
public Texture[] textures;
// Use this for initialization
void Start()
{
current = this;
}
// Update is called once per frame
void Update()
{
pos1 += speed1;
if (pos1 > 1.0f)
pos1 -= 1.0f;
GetComponent<Renderer>().material.mainTextureOffset = new Vector2(pos1, 0);
}
public void Go()
{
pos2 += speed2;
if (pos2 > 1.0f)
pos2 -= 1.0f;
GetComponent<Renderer>().material.mainTextureOffset = new Vector2(0, pos2);
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FIMMonitoring.Domain
{
public class Import : EntityBase
{
public DateTime? CreatedAt { get; set; }
[StringLength(10)]
public string Encoding { get; set; }
[Required]
public string Filename { get; set; }
public virtual ImportSource ImportSource { get; set; }
public int ImportSourceID { get; set; }
public virtual MappingType MappingType { get; set; }
public int MappingTypeId { get; set; }
[ForeignKey("RawContentBlobID")]
public virtual Blob RawContent { get; set; }
public Guid RawContentBlobID { get; set; }
[ForeignKey("DocumentContentBlobID")]
public virtual Blob DocumentContent { get; set; }
public Guid? DocumentContentBlobID { get; set; }
public string DocumentContentName { get; set; }
public string DocumentContentMimeType { get; set; }
public ImportDataType ImportDataType { get; set; }
[NotMapped]
public bool IsSelected { get; set; }
public bool IsDownloaded { get; set; }
public bool IsValidated { get; set; }
public bool IsParsed { get; set; }
public bool IsChecked { get; set; }
public bool IsFinished { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocGen.ObjectModel;
using Word = DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace DocGen.OOXML
{
/// <summary>
/// Responsible for converting a given Chapter object to formatted OpenXML objects.
/// </summary>
public class ChapterFormatter
{
private static bool stylesAdded = false;
public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedChapter(Chapter chapter) {
if(!stylesAdded) StyleCreator.AddStylePart();
List<OpenXmlElement> result = new List<OpenXmlElement>();
//Setting up Heading style
Word.ParagraphProperties paraProps = new Word.ParagraphProperties();
Word.ParagraphStyleId style = new Word.ParagraphStyleId()
{
Val = "Heading1"
};
paraProps.Append(style);
//Adding chapter title
Word.Paragraph para = new Word.Paragraph();
Word.Run run = new Word.Run();
Word.Text text = new Word.Text()
{
Text = chapter.Title
};
run.Append(text);
para.Append(paraProps);
para.Append(run);
result.Add(para);
//Add all child elements
foreach (Element element in chapter.SubElements)
{
if (element.GetElementType() == ElementType.MultiColumnSection)
{
result.AddRange(MultiColumnSectionFormatter.GetFormattedSection((MultiColumnSection)element));
}
else if (element.GetElementType() == ElementType.Section) result.AddRange(SectionFormatter.GetFormattedSection((Section)element));
else throw new InvalidSubFeatureException( chapter.GetElementType().ToString() , element.GetElementType().ToString());
}
return result.ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Integer.Domain.Agenda
{
public class TipoEvento
{
public string Id { get; set; }
public string Nome { get; set; }
//public int NivelPrioridade { get; set; }
}
}
|
namespace Exercises.Models.Queries
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using CodeFirstFromDatabase;
/// <summary>
/// Problem10 - Employee with id 147 sorted by project names
/// </summary>
public class EmployeeWithId147SortedByProjectNames : Query<SoftuniContext>
{
public override string QueryResult(SoftuniContext context)
{
var employee = context
.Employees
.Include(e => e.Projects)
.FirstOrDefault(e => e.EmployeeID == 147);
if (employee != null)
{
this.Result.AppendLine(
string.Format(
"{0} {1} {2}{3}{4}{5}",
employee.FirstName,
employee.LastName,
employee.JobTitle,
Environment.NewLine,
string.Join(Environment.NewLine, GetProjectNames(employee)),
Environment.NewLine));
}
return this.Result.ToString();
}
private static IEnumerable<string> GetProjectNames(Employee employee)
{
return employee
.Projects
.OrderBy(p => p.Name)
.Select(p => $"{p.Name}");
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using ParPorApp.Views;
using Xamarin.Forms;
namespace ParPorApp.ViewModels
{
public class MasterPageViewModel
{
public UserViewModel UserViewModel { get; set; }
public MainPageMaster.MainPageMasterViewModel MainPageMasterViewModel { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CallPauseScene : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// When the Escape Key is pressed. open up scene 'Pause menu' Over the top of current scene.
if (Input.GetKeyDown(KeyCode.Escape))
{
Time.timeScale = 0;
SceneManager.LoadScene("Pause Menu", LoadSceneMode.Additive);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CollaborativeFilteringUI.Core.Utils
{
public class Pair<T,W> : BaseNotification
{
public Pair(T item1, W item2)
{
Item1 = item1;
Item2 = item2;
}
public T Item1 { get; set; }
public W Item2 { get; set; }
public override string ToString()
{
return Item1.ToString() + "," + Item2.ToString();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions.Must;
public class NavBarButton
{
public RectTransform button;
public Vector2 origin;
public bool dirty;
public float time;
public bool selected;
public NavBarButton(RectTransform _button, Vector2 _origin, float _time)
{
button = _button;
origin = _origin;
dirty = false;
time = _time;
selected = false;
}
public void Move(Vector2 des)
{
LeanTween.move(button, des, time).setEaseInOutCirc();
dirty = true;
}
public void Reset()
{
if (dirty)
{
LeanTween.move(button, origin, time);
dirty = false;
}
}
}
public class NavBarTweening : MonoBehaviour
{
public static NavBarTweening current;
NavBarButton shop;
NavBarButton pudding;
NavBarButton play;
NavBarButton upgrade;
NavBarButton option;
public RectTransform Indicator;
public RectTransform ShopButton;
public RectTransform PuddingButton;
public RectTransform PlayButton;
public RectTransform UpgradeButton;
public RectTransform SettingsButton;
public Vector2 shop_pos;
public Vector2 pudding_pos;
public Vector2 play_pos;
public Vector2 upgrade_pos;
public Vector2 setting_pos;
public float tween_time;
void Start()
{
current = this;
shop = new NavBarButton(ShopButton, shop_pos, tween_time);
pudding = new NavBarButton(PuddingButton, pudding_pos, tween_time);
play = new NavBarButton(PlayButton, play_pos, tween_time);
play.selected = true;
upgrade = new NavBarButton(UpgradeButton, upgrade_pos, tween_time);
option = new NavBarButton(SettingsButton, setting_pos, tween_time);
}
public void ShopButtonPressed()
{
if (!shop.selected)
{
UnselectAll();
LeanTween.move(Indicator, new Vector2(-276, 0), tween_time).setEaseInOutCirc();
shop.Move(new Vector2(-276, 0));
shop.selected = true;
pudding.Move(new Vector2(-69, 0));
play.Move(new Vector2(69, 0));
upgrade.Reset();
option.Reset();
}
}
public void PuddingButtonPressed()
{
if (!pudding.selected)
{
UnselectAll();
LeanTween.move(Indicator, new Vector2(-138, 0), tween_time).setEaseInOutCirc();
shop.Reset();
pudding.Move(new Vector2(-138, 0));
pudding.selected = true;
play.Move(new Vector2(69, 0));
upgrade.Reset();
option.Reset();
}
}
public void PlayButtonPressed()
{
if (!play.selected)
{
UnselectAll();
LeanTween.move(Indicator, new Vector2(0, 0), tween_time).setEaseInOutCirc();
shop.Reset();
pudding.Reset();
play.Reset();
play.selected = true;
upgrade.Reset();
option.Reset();
}
}
public void UpgradeButtonPressed()
{
if (!upgrade.selected)
{
UnselectAll();
LeanTween.move(Indicator, new Vector2(138, 0), tween_time).setEaseInOutCirc();
shop.Reset();
pudding.Reset();
play.Move(new Vector2(-69, 0));
upgrade.Move(new Vector2(138, 0));
upgrade.selected = true;
option.Reset();
}
}
public void OptionButtonPressed()
{
if (!option.selected)
{
UnselectAll();
LeanTween.move(Indicator, new Vector2(276, 0), tween_time).setEaseInOutCirc();
shop.Reset();
pudding.Reset();
play.Move(new Vector2(-69, 0));
upgrade.Move(new Vector2(69, 0));
option.Move(new Vector2(276, 0));
option.selected = true;
}
}
public void UnselectAll()
{
shop.selected = false;
pudding.selected = false;
play.selected = false;
upgrade.selected = false;
option.selected = false;
}
}
|
using System.Collections.Concurrent;
using System.Collections.Generic;
using NLog;
using NLog.Targets;
namespace Simple.Wpf.Composition.Core.Infrastructure
{
[Target("LimitedMemory")]
public sealed class LimitedMemoryTarget : TargetWithLayout
{
private readonly ConcurrentQueue<string> _entries = new ConcurrentQueue<string>();
private readonly object _sync = new object();
public LimitedMemoryTarget()
{
Limit = 1000;
}
public int Limit { get; set; }
public IEnumerable<string> Logs => _entries;
protected override void Write(LogEventInfo logEvent)
{
var msg = Layout.Render(logEvent);
_entries.Enqueue(msg);
if (_entries.Count > Limit)
{
string output;
_entries.TryDequeue(out output);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.