text
stringlengths
13
6.01M
using DIPS.Samsnakk.Server.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DIPS.Samsnakk.Server.Interfaces { public interface IGroups { public List<Group> GetGroups(); public void AddGroup(Group group); public List<Group> GetJoinedGroups(string username); public Group GetGroup(string groupName); } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Text; namespace testMonogame { class StartMenuScreen { Texture2D texture; SpriteFont header; SpriteFont font; GameManager game; //a bunch of rectangles for drawing. Rectangle background = new Rectangle(0, 0, 256, 175); Rectangle destRect = new Rectangle(130, 100, 256 * 2, 175 * 2); Rectangle boxRectangle = new Rectangle (0, 181, 64, 20); Rectangle difficultyDestRect = new Rectangle(130 + (96 * 2), 100 + (24 * 2), 128, 40); Rectangle modeDestRect = new Rectangle(130 + (96 * 2), 100 + (56 * 2), 128, 40); Rectangle playDestRect = new Rectangle(130 + (96 * 2), 100 + (88 * 2), 128, 40); Rectangle selectionSourceRect = new Rectangle(72, 182, 68, 24); Rectangle[] selectionDestRect = { new Rectangle(130 + (94 * 2), 100 + (22 * 2), 128+8, 40+8), new Rectangle(130 + (94 * 2), 100 + (54 * 2), 128+8, 40+8), new Rectangle(130 + (94 * 2), 100 + (86 * 2), 128+8, 40+8) }; int selectedBox;//0=diff,1=mode,2=play int buttonX = 365; int difficultyY = 160; Vector2 modeLocation = new Vector2(360, 224); Vector2 playLocation = new Vector2(365, 288); public StartMenuScreen(Texture2D intexture, SpriteFont smallFont, SpriteFont bigFont, GameManager inGame) { texture = intexture; font = smallFont; header = bigFont; selectedBox = 0; game = inGame; } public void nextOption() { selectedBox++; if (selectedBox > 2) selectedBox = 2; } public void previousOption() { selectedBox--; if (selectedBox <0) selectedBox = 0; } public int getSelectedBox() { return selectedBox; } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(texture, destRect, background, Color.White); spriteBatch.DrawString(header, "New Game", new Vector2(250, 0), Color.White); String difficulty = ""; Color difficultyColor = Color.White; int diffX = buttonX; int diffValue = game.GetDifficulty(); //figure out our difficuly and adjust accordingly if (diffValue == 0) { //easy difficulty = "Easy"; difficultyColor = Color.Green; } else if (diffValue == 1) { //normal difficulty = "Normal"; difficultyColor = Color.Blue; diffX -= 5; } else if (diffValue == 2) { //hard difficulty = "Hard"; difficultyColor = Color.Red; } //mode box is blue if not horde, red if horde. its a toggle Color modeColor = Color.Blue; if (game.IsHorde()) { modeColor = Color.Red; } spriteBatch.Draw(texture, difficultyDestRect, boxRectangle, difficultyColor); spriteBatch.Draw(texture, modeDestRect, boxRectangle, modeColor); spriteBatch.Draw(texture, playDestRect, boxRectangle, Color.Blue); spriteBatch.Draw(texture, selectionDestRect[selectedBox], selectionSourceRect, Color.White); spriteBatch.DrawString(font, difficulty, new Vector2(diffX, difficultyY), Color.Black); spriteBatch.DrawString(font, "Horde", modeLocation, Color.Black); spriteBatch.DrawString(font, "Play", playLocation, Color.Black); } public void Update(GameManager game) { //NA } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Net; namespace PingerProject { class MinecraftPinger : Pinger { /// <summary> /// Constructeur récupérant les valeurs du serveur /// </summary> /// <param name="serveur">Adresse IP du serveur</param> /// <param name="port">Port du serveur</param> /// <param name="servertype">Nom du serveur</param> public MinecraftPinger(string server, uint port, string servertype) : base(server, port, servertype) { } /// <summary> /// Ping le serveur /// </summary> /// <returns>Retourne l'état du serveur</returns> public override bool Ping() { var client = new TcpClient(); // Initialisation du client TCP var task = client.ConnectAsync(this.ServerIP, (int) this.Port); // Connection au serveur Console.WriteLine("Connexion au serveur " + this.ServerType + "..."); /* Attend la connectin */ while (!task.IsCompleted) continue; if (client.Connected) { client.Close(); return true; } else { client.Close(); return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Collections; using IRAP.Global; using IRAP.Entities.SCES; namespace IRAP.WCF.Client.Method { public class IRAPSCESClient { private static IRAPSCESClient _instance = null; private static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private IRAPSCESClient() { } public static IRAPSCESClient Instance { get { if (_instance == null) _instance = new IRAPSCESClient(); return _instance; } } /// <summary> /// 获取待配送到指定目标仓储地址的制造订单列表 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="dstT173LeafID">目标仓储地点叶标识</param> /// <param name="sysLogID">系统登录标识</param> /// <param name="orderFactID">工单 FactID(0:-全部工单)</param> public void ufn_GetList_ProductionWorkOrdersToDeliverMaterial( int communityID, int dstT173LeafID, long sysLogID, long orderFactID, ref List<ProductionWorkOrder> datas, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { datas.Clear(); #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("dstT173LeafID", dstT173LeafID); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 ufn_GetList_ProductionWorkOrdersToDeliverMaterial 函数, " + "参数:CommunityID={0}|DstT173LeafID={1}|SysLogID={2}", communityID, dstT173LeafID, sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "ufn_GetList_ProductionWorkOrdersToDeliverMaterial", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { datas = rlt as List<ProductionWorkOrder>; if (orderFactID != 0) { List<ProductionWorkOrder> filterDatas = new List<ProductionWorkOrder>(); foreach (ProductionWorkOrder order in datas) { if (order.FactID == orderFactID) { filterDatas.Add(order.Clone()); break; } } datas = filterDatas; } } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 获取待配送到指定目标仓储地址的制造订单列表 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="dstT173LeafID">目标仓储地点叶标识</param> /// <param name="sysLogID">系统登录标识</param> /// <param name="orderFactID">工单 FactID(0:-全部工单)</param> public void ufn_GetList_ProductionWorkOrdersToDeliverMaterial_N( int communityID, int dstT173LeafID, long sysLogID, long orderFactID, ref List<ProductionWorkOrderEx> datas, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { datas.Clear(); #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("dstT173LeafID", dstT173LeafID); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 ufn_GetList_ProductionWorkOrdersToDeliverMaterial_N 函数, " + "参数:CommunityID={0}|DstT173LeafID={1}|SysLogID={2}", communityID, dstT173LeafID, sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "ufn_GetList_ProductionWorkOrdersToDeliverMaterial_N", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { datas = rlt as List<ProductionWorkOrderEx>; if (orderFactID != 0) { List<ProductionWorkOrderEx> filterDatas = new List<ProductionWorkOrderEx>(); foreach (ProductionWorkOrderEx order in datas) { if (order.FactID == orderFactID) { filterDatas.Add(order.Clone()); break; } } datas = filterDatas; } } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 获取待配送到指定目标仓储地址的制造订单列表 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="subMaterialCode">子项物料号</param> /// <param name="sysLogID">系统登录标识</param> public void ufn_GetList_PWOToDeliverByMaterialCode( int communityID, string subMaterialCode, long sysLogID, ref List<PWOToDeliverByMaterialCode> datas, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { datas.Clear(); #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("subMaterialCode", subMaterialCode); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 ufn_GetList_PWOToDeliverByMaterialCode 函数, " + "参数:CommunityID={0}|SubMaterialCode={1}|SysLogID={2}", communityID, subMaterialCode, sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "ufn_GetList_PWOToDeliverByMaterialCode", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { datas = rlt as List<PWOToDeliverByMaterialCode>; } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 获取工单物料配送指令单 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="pwoIssuingFactID">工单签发事实编号</param> /// <param name="sysLogID">系统登录标识</param> public void ufn_GetList_MaterialToDeliverForPWO( int communityID, long pwoIssuingFactID, long sysLogID, ref List<MaterialToDeliver> datas, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { datas.Clear(); #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("pwoIssuingFactID", pwoIssuingFactID); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 ufn_GetList_MaterialToDeliverForPWO 函数, " + "参数:CommunityID={0}|PWOIssuingFactID={1}|SysLogID={2}", communityID, pwoIssuingFactID, sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "ufn_GetList_MaterialToDeliverForPWO", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { datas = rlt as List<MaterialToDeliver>; } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 打印生产工单流转卡,并生成工单原辅材料配送临时记录 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="transactNo">申请到的交易号</param> /// <param name="pwoIssuingFactID">工单签发事实编号</param> /// <param name="srcT173LeafID">发料库房叶标识</param> /// <param name="dstT173LeafID">目标超市叶标识</param> /// <param name="dstT106LeafID_Recv">目标超市收料库位叶标识</param> /// <param name="dstT1LeafID_Recv">目标超市物料员部门叶标识</param> /// <param name="pickUpSheetXML">备料清单XML</param> /// <param name="sysLogID">系统登录标识</param> public void usp_PrintVoucher_PWOMaterialDelivery( int communityID, long transactNo, long pwoIssuingFactID, int srcT173LeafID, int dstT173LeafID, int dstT106LeafID_Recv, int dstT1LeafID_Recv, string pickUpSheetXML, long sysLogID, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("transactNo", transactNo); hashParams.Add("pwoIssuingFactID", pwoIssuingFactID); hashParams.Add("srcT173LeafID", srcT173LeafID); hashParams.Add("dstT173LeafID", dstT173LeafID); hashParams.Add("dstT106LeafID_Recv", dstT106LeafID_Recv); hashParams.Add("dstT1LeafID_Recv", dstT1LeafID_Recv); hashParams.Add("pickUpSheetXML", pickUpSheetXML); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 usp_PrintVoucher_PWOMaterialDelivery,输入参数:" + "CommunityID={0}|TransactNo={1}|PWOIssuingFactID={2}|SrcT173LeafID={3}|" + "DstT173LeafID={4}|DstT106LeafID_Recv={5}|DstT1LeafID_Recv={6}|" + "PickUpSheetXML={7}|SysLogID={8}", communityID, transactNo, pwoIssuingFactID, srcT173LeafID, dstT173LeafID, dstT106LeafID_Recv, dstT1LeafID_Recv, pickUpSheetXML, sysLogID), strProcedureName); #endregion #region 调用应用服务过程,并解析返回值 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "usp_PrintVoucher_PWOMaterialDelivery", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); } #endregion } catch (Exception error) { errCode = -1001; errText = error.Message; WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } public void ufn_GetList_ProductionFlowCard( int communityID, long pwoIssuingFactID, long sysLogID, ref List<ProductionFlowCard> datas, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { datas.Clear(); #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("pwoIssuingFactID", pwoIssuingFactID); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 ufn_GetList_ProductionFlowCard 函数, " + "参数:CommunityID={0}|PWOIssuingFactID={1}|SysLogID={2}", communityID, pwoIssuingFactID, sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "ufn_GetList_ProductionFlowCard", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { datas = rlt as List<ProductionFlowCard>; } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// /// </summary> /// <param name="communityID">社区标识</param> /// <param name="materialCode">物料代码</param> /// <param name="customerCode">物料标签代码</param> /// <param name="shipToParty">发运地点</param> /// <param name="qtyInStore">物料计划量</param> /// <param name="dateCode">物料生产日期</param> /// <param name="sysLogID">系统登录标识</param> /// <param name="errCode"></param> /// <param name="errText"></param> /// <returns></returns> public void usp_PokaYoke_PallPrint( int communityID, string materialCode, string customerCode, string shipToParty, string qtyInStore, string dateCode, long sysLogID, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("materialCode", materialCode); hashParams.Add("customerCode", customerCode); hashParams.Add("shipToParty", shipToParty); hashParams.Add("qtyInStore", qtyInStore); hashParams.Add("dateCode", dateCode); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 usp_PokaYoke_PallPrint,输入参数:" + "CommunityID={0}|MaterialCode={1}|CustomerCode={2}|" + "ShipToParty={3}|QtyInStore={4}|DateCode={5}|SysLogID={6}", communityID, materialCode, customerCode, shipToParty, qtyInStore, dateCode, sysLogID), strProcedureName); #endregion #region 调用应用服务过程,并解析返回值 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "usp_PokaYoke_PallPrint", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); } #endregion } catch (Exception error) { errCode = -1001; errText = error.Message; WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 获取生产工单发料的未结配送指令清单,包括: /// ⒈ 已排产但尚未配送的 /// ⒉ 已配送但尚未接收的 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="dstT173LeafID">目标仓储地点叶标识</param> /// <param name="sysLogID">系统登录标识</param> public void ufn_GetList_UnclosedDeliveryOrdersForPWO( int communityID, int dstT173LeafID, long sysLogID, ref List<UnclosedDeliveryOrdersForPWO> datas, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { datas.Clear(); #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("dstT173LeafID", dstT173LeafID); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 ufn_GetList_UnclosedDeliveryOrdersForPWO 函数, " + "参数:CommunityID={0}|DstT173LeafID={1}|SysLogID={2}", communityID, dstT173LeafID, sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "ufn_GetList_UnclosedDeliveryOrdersForPWO", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { datas = rlt as List<UnclosedDeliveryOrdersForPWO>; } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 生产工单配送流转卡打印后实际配送操作前撤销 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="af482PK">辅助事实分区键</param> /// <param name="pwoIssuingFactID">工单签发事实编号</param> /// <param name="sysLogID">系统登录标识</param> public void usp_UndoPrintVoucher_PWOMaterialDelivery( int communityID, long af482PK, long pwoIssuingFactID, long sysLogID, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("af482PK", af482PK); hashParams.Add("pwoIssuingFactID", pwoIssuingFactID); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 usp_UndoPrintVoucher_PWOMaterialDelivery,输入参数:" + "CommunityID={0}|AF482PK={1}|PWOIssuingFactID={2}|" + "SysLogID={3}", communityID, af482PK, pwoIssuingFactID, sysLogID), strProcedureName); #endregion #region 调用应用服务过程,并解析返回值 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "usp_UndoPrintVoucher_PWOMaterialDelivery", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); } #endregion } catch (Exception error) { errCode = -1001; errText = error.Message; WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 根据制造订单号和制造订单行号,获取工单信息 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="dstT173LeafID">目标仓储地点</param> /// <param name="moNumber">制造订单号</param> /// <param name="moLineNo">制造订单行号</param> /// <param name="sysLogID">系统登录标识</param> public void mfn_GetInfo_PWOToReprint( int communityID, int dstT173LeafID, string moNumber, int moLineNo, long sysLogID, ref ReprintPWO data, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { data = new ReprintPWO(); #region 将函数调用参数加入 Hashtable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("dstT173LeafID", dstT173LeafID); hashParams.Add("moNumber", moNumber); hashParams.Add("moLineNo", moLineNo); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 mfn_GetInfo_PWOToReprint,输入参数:" + "CommunityID={0}|DstT173LeafID={1}|MONumber={2}|"+ "MOLineNo={3}|SysLogID={4}", communityID, dstT173LeafID, moNumber, moLineNo, sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "mfn_GetInfo_PWOToReprint", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) data = rlt as ReprintPWO; } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 获取指定期间指定库房工单物料配送历史记录 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="t173LeafID">仓储地点叶标识</param> /// <param name="beginDT">开始日期时间</param> /// <param name="endDT">结束日期时间</param> public void ufn_GetFactList_RMTransferForPWO( int communityID, int t173LeafID, DateTime beginDT, DateTime endDT, long sysLogID, ref List<RMTransferForPWO> datas, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { datas.Clear(); #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("t173LeafID", t173LeafID); hashParams.Add("beginDT", beginDT); hashParams.Add("endDT", endDT); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 ufn_GetFactList_RMTransferForPWO 函数,参数:" + "CommunityID={0}|T173LeafID={1}|BeginDT={2}|"+ "EndDT={3}|SysLogID={4}", communityID, t173LeafID, beginDT.ToString("yyyy-MM-dd HH:mm:ss.fff"), endDT.ToString("yyyy-MM-dd HH:mm:ss.fff"), sysLogID), strProcedureName); #endregion #region 执行存储过程或者函数 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "ufn_GetFactList_RMTransferForPWO", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format( "({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { datas = rlt as List<RMTransferForPWO>; } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); errCode = -1001; errText = error.Message; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 修改指定生产工单的配送数量 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="factID">生产工单事实编号</param> /// <param name="actualQtyToDeliver">配送数量</param> /// <param name="subTreeID">子项树标识</param> /// <param name="subLeafID">子项叶标识</param> /// <param name="sysLogID">系统登录标识</param> /// <param name="errCode"></param> /// <param name="errText"></param> /// <returns></returns> public void usp_SaveFact_PWODeliveryQty( int communityID, long factID, long actualQtyToDeliver, int subTreeID, int subLeafID, long sysLogID, out int errCode, out string errText) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { #region 将函数调用参数加入 HashTable 中 Hashtable hashParams = new Hashtable(); hashParams.Add("communityID", communityID); hashParams.Add("factID", factID); hashParams.Add("actualQtyToDeliver", actualQtyToDeliver); hashParams.Add("subTreeID", subTreeID); hashParams.Add("subLeafID", subLeafID); hashParams.Add("sysLogID", sysLogID); WriteLog.Instance.Write( string.Format( "调用 usp_SaveFact_PWODeliveryQty,输入参数:" + "CommunityID={0}|FactID={1}|ActualQtyToDeliver={2}|"+ "SubTreeID={3}|SubLeafID={4}|SysLogID={5}", communityID, factID, actualQtyToDeliver, subTreeID, subLeafID, sysLogID), strProcedureName); #endregion #region 调用应用服务过程,并解析返回值 using (WCFClient client = new WCFClient()) { object rlt = client.WCFRESTFul( "IRAP.BL.SCES.dll", "IRAP.BL.SCES.IRAPSCES", "usp_SaveFact_PWODeliveryQty", hashParams, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); } #endregion } catch (Exception error) { errCode = -1001; errText = error.Message; WriteLog.Instance.Write(errText, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } }
using System; using System.Collections.Generic; namespace BeeKeeping { class Program { static void Main(string[] args) { Bee b1 = new Bee("John", 3.2); Bee b2 = new Bee("Paul", 2.7); Bee b3 = new Bee("George", 1.1); Bee b4 = new Bee("Ringo", 2.0); Bee b5 = new Bee("Kurt", 2.3); Bee b6 = new Bee("Dave", 7.4); Bee b7 = new Bee("Krist", 1.5); List<Bee> beeList1 = new List<Bee>(); beeList1.Add(b1); beeList1.Add(b2); beeList1.Add(b3); beeList1.Add(b4); List<Bee> beeList2 = new List<Bee>(); beeList2.Add(b5); beeList2.Add(b6); beeList2.Add(b7); Hive h1 = new Hive(beeList1, 4); Hive h2 = new Hive(beeList2, 3); Console.WriteLine("Collecting last 4 days honey from Hive 1:"); Console.WriteLine(h1.Honey(h1.Bees, 4)); Console.WriteLine("Collecting last 4 days of honey from Hive 2:"); Console.WriteLine(h2.Honey(h2.Bees, 4)); } } public class Bee { public string Name; public double Size; public Bee(string name, double size) { this.Name = name; this.Size = size; } } public class Hive { public int MaxBees; public List<Bee> Bees; public Hive(List<Bee> bees, int maxBees) { this.MaxBees = maxBees; this.Bees = bees; } public double Honey(List<Bee> bees, int days) { double totalHoney = 0.0; for (int i = 0; i < bees.Count; i++) { totalHoney = totalHoney + (bees[i].Size * 0.2); } return totalHoney; } } }
namespace Krafteq.ElsterModel.Common { using Krafteq.ElsterModel.ValidationCore; using LanguageExt; public class Zip : NewType<Zip, string> { static readonly Validator<StringError, string> Validator = Validators.All( StringValidators.ExactLength(5), StringValidators.DigitsOnly() ); Zip(string value) : base(value) { } public static Validation<StringError, Zip> Create(string value) => Validator(value).Map(x => new Zip(x)); } }
using ExitGames.Client.Photon; using Photon.Pun; using Photon.Realtime; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EventManager : MonoBehaviourPunCallbacks, IOnEventCallback, IPunCallbacks { private readonly byte CarCollision = 1; private readonly byte BombHolderDies = 2; private readonly byte FirstBombHolder = 3; private readonly byte DisplayLeaderboard = 4; private readonly byte GameStart = 5; private Stack<Player> playerRanks; [SerializeField] private LeaderboardListing[] leaderboardListings = new LeaderboardListing[1]; [SerializeField] private GameObject chargeMeter = null, waitingText = null; public override void OnEnable() { playerRanks = new Stack<Player>(PhotonNetwork.PlayerList.Length); PhotonNetwork.AddCallbackTarget(this); } public override void OnDisable() => PhotonNetwork.RemoveCallbackTarget(this); // Events called in other scripts are processed here. One client will send an event and all players will call it public void OnEvent(EventData photonEvent) { byte eventCode = photonEvent.Code; // Event for when cars collide and bomb must transfer from one car to another if (eventCode == CarCollision) { object[] data = (object[])photonEvent.CustomData; // Get the Photon ID's of both cars involved in car collision short bombHolderID = (short)data[0]; short targetID = (short)data[1]; // Get the Gameobjects of both cars GameObject bombHolder = PhotonNetwork.GetPhotonView(bombHolderID).gameObject; GameObject target = PhotonNetwork.GetPhotonView(targetID).gameObject; // Getting the car components of the gameobjects so we can set and remove bombs Car bombHolderCar = bombHolder.GetComponent<Car>(); Car targetCar = target.GetComponent<Car>(); // If the target car isn't dead (so the bomb doesn't get lost) if (bombHolderCar.hasBomb && !targetCar.dead) { bombHolderCar.hasBomb = false; targetCar.hasBomb = true; // transfer bomb to car collided with bombHolderCar.RemoveBomb(); targetCar.SetBomb(); bombHolderCar.timeHeld = targetCar.timeHeld = 0; // set timeHeld back to zero so when it gets bomb again it has to wait to transfer // Timer decrease is increased everytime the bomb transfers, e.g. (maxTime - timerDecrease) World.currentWorld.timerDecrease += 1; World.currentWorld.startTime = PhotonNetwork.Time; // Decrease timer's max time everytime transfer occurs World.currentWorld.bombTimer = World.currentWorld.maxBombTimer = Mathf.Clamp(30 - World.currentWorld.timerDecrease, 5, 30); } } else if (eventCode == BombHolderDies) { object[] data = (object[])photonEvent.CustomData; short bombHolderID = (short)data[0]; short targetID = (short)data[1]; bool isGameOver = (bool)data[2]; GameObject bombHolder = PhotonNetwork.GetPhotonView(bombHolderID).gameObject; GameObject target = PhotonNetwork.GetPhotonView(targetID).gameObject; Car bombHolderCar = bombHolder.GetComponent<Car>(); Car targetCar = target.GetComponent<Car>(); if (World.currentWorld.playerList.Exists(t => t.playerGameObject == bombHolder)) { World.UnityPlayer bombPlayer = World.currentWorld.playerList.Find(t => t.playerGameObject == bombHolder); World.currentWorld.playerList.Remove(bombPlayer); } bombHolderCar.RemoveBomb(); bombHolderCar.SetCarDead(); playerRanks.Push(PhotonNetwork.GetPhotonView(bombHolderID).Owner); if (!isGameOver) { targetCar.SetBomb(); // transfer bomb to car collided with bombHolderCar.timeHeld = targetCar.timeHeld = 0; // set timeHeld back to zero so when it gets bomb again it has to wait to transfer // Timer decrease is increased everytime the bomb transfers, e.g. (maxTime - timerDecrease) World.currentWorld.timerDecrease += 1; World.currentWorld.startTime = PhotonNetwork.Time; // Decrease timer's max time everytime transfer occurs World.currentWorld.bombTimer = World.currentWorld.maxBombTimer = Mathf.Clamp(30 - World.currentWorld.timerDecrease, 5, 30); } else { targetCar.RemoveBomb(); } } else if(eventCode == FirstBombHolder) { object[] data = (object[])photonEvent.CustomData; short targetID = (short)data[0]; GameObject target = PhotonNetwork.GetPhotonView(targetID).gameObject; Car targetCar = target.GetComponent<Car>(); targetCar.SetBomb(); targetCar.timeHeld = 0; // set timeHeld back to zero so when it gets bomb again it has to wait to transfer World.currentWorld.startTime = PhotonNetwork.Time; // Decrease timer's max time everytime transfer occurs World.currentWorld.bombTimer = World.currentWorld.maxBombTimer = Mathf.Clamp(30 - World.currentWorld.timerDecrease, 5, 30); // Timer decrease is increased everytime the bomb transfers, e.g. (maxTime - timerDecrease) World.currentWorld.timerDecrease += 1; } else if (eventCode == DisplayLeaderboard) { // Add the last living player (the winner) to the player ranks stack playerRanks.Push(PhotonNetwork.GetPhotonView(World.currentWorld.playerList[0].playerID).Owner); int stackSize = playerRanks.Count; // List the end game leaderboard based on when the player was pushed to the playerRank stack for (int i = 0; i < stackSize; i++) { leaderboardListings[i].SetPlayerInfo(playerRanks.Pop()); } } else if (eventCode == GameStart) { // Allow player control of their car and show ability UI once everyone has connected if(PhotonNetwork.LocalPlayer.TagObject != null) { GameObject playerObj = (GameObject)PhotonNetwork.LocalPlayer.TagObject; chargeMeter.SetActive(true); waitingText.SetActive(false); Car_Control carControl = playerObj.GetComponent<Car_Control>(); carControl.SetInputsActive(true); } } } public override void OnPlayerLeftRoom(Player otherPlayer) { base.OnPlayerLeftRoom(otherPlayer); // Getting the left players object still on our local client GameObject playerObj = (GameObject)otherPlayer.TagObject; // Check that the players object still exists on our local client before doing anything if (playerObj != null && World.currentWorld.playerList.Exists(t => t.playerGameObject == playerObj)) { Car playerCar = playerObj.GetComponent<Car>(); World.UnityPlayer leavingPlayer = World.currentWorld.playerList.Find(t => t.playerGameObject == playerObj); World.currentWorld.playerList.Remove(leavingPlayer); //Remove this player from the list so to not target them with the next bomb playerCar.RemoveBomb(); playerCar.SetCarDead(); playerRanks.Push(otherPlayer); if (playerCar.hasBomb == true && PhotonNetwork.IsMasterClient && World.currentWorld.playerList.Count > 1) { int randomInt = Random.Range(0, World.currentWorld.playerList.Count); // Choice for new target accounting for one less player alive when this car is removed int targetID = World.currentWorld.playerList[randomInt].playerID; byte evCode = 3; // Custom Event 3: Used as "FirstBombHolder" event object[] content = new object[] { (short)targetID }; // current bomb holder and a boolean to tell whether the car died or not RaiseEventOptions raiseEventOptions = new RaiseEventOptions { Receivers = ReceiverGroup.All }; SendOptions sendOptions = new SendOptions { Reliability = true }; PhotonNetwork.RaiseEvent(evCode, content, raiseEventOptions, sendOptions); PhotonNetwork.SendAllOutgoingCommands(); //Send outgoing event immediately before the application closes and it fails } } } }
using System; using System.Collections.Generic; using System.Linq; using Sirenix.OdinInspector; using UnityEngine; namespace GunSystem { [CreateAssetMenu(fileName = "new BaseGun", menuName = "Guns/BaseGun", order = 0)] public abstract class BaseGun : SerializedScriptableObject { public GameObject gunMesh; public Dictionary<AttributeType, AttribProp> attributes; public Dictionary<AttachmentType , List<GunAttachment>> availableAttachments; [ReadOnly] public Dictionary<AttachmentType,GunAttachment> equippedAttachments; [Button("Button")] private void Awake() { equippedAttachments = new Dictionary<AttachmentType, GunAttachment>(); foreach (var i in availableAttachments.Where(i => !equippedAttachments.ContainsKey(i.Key))) { equippedAttachments.Add(i.Key,null); } foreach (var i in availableAttachments) { if (!equippedAttachments.ContainsKey(i.Key)) { equippedAttachments.Add(i.Key,null); } } } public void AddAttachment(AttachmentType type,GunAttachment newAttachment) { if (equippedAttachments.ContainsKey(type)) { equippedAttachments.Remove(type); } equippedAttachments.Add(type,newAttachment); UpdateStatOnAttachment(); } public void RemoveAttachment(AttachmentType type) { GunAttachment removedAttachment = null; if (equippedAttachments.ContainsKey(type)) { removedAttachment = equippedAttachments[type]; equippedAttachments.Remove(type); } Debug.Log($"Removing attachment : {removedAttachment}"); UpdateStatOnAttachment(); } private Dictionary<AttributeType, List<ModDetails>> UpdateStatOnAttachment() { Dictionary<AttributeType, List<ModDetails>> dictUpdatingAttributes = new Dictionary<AttributeType, List<ModDetails>>(); foreach (var i in equippedAttachments) { GunAttachment attachment = i.Value; AttachmentType type = i.Key; foreach (var current in attachment.attachmentDetails) { //add each attribute type to its own specific list if (!dictUpdatingAttributes.ContainsKey(current.Key)) { dictUpdatingAttributes.Add(current.Key,new List<ModDetails>()); dictUpdatingAttributes[current.Key].Add(current.Value); } else { dictUpdatingAttributes[current.Key].Add(current.Value); } } } return dictUpdatingAttributes; } private void UpdateValue() { var x = UpdateStatOnAttachment(); foreach (var i in x) { var newList = i.Value.OrderBy(c => (int) c.modType); AttributeType currentAttributeType = i.Key; if(!attributes.ContainsKey(currentAttributeType)) continue; float currentValue = attributes[currentAttributeType].baseValue;; foreach (var modDetails in newList) { switch (modDetails.modType) { case ModifierType.Flat: currentValue = modDetails.updatingValue; break; case ModifierType.Multiplicative: currentValue *= modDetails.updatingValue; break; case ModifierType.Additive: currentValue += modDetails.updatingValue; break; default : throw new Exception("Mod Type is wrong"); } } //double checking the if, as might add the stat above later if (attributes.ContainsKey(currentAttributeType)) attributes[currentAttributeType].currentValue = currentValue; //above vs below if (attributes.ContainsKey(currentAttributeType)) { if (attributes[currentAttributeType].currentValue != currentValue) attributes[currentAttributeType].currentValue = currentValue; } } } protected abstract void Fire(); } }
using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201512080943)] public class AddOperationNameChange : Migration { public override void Down() { if (Schema.Table("PRF_Operation").Column("NextOperationID").Exists()) { Delete.ForeignKey().FromTable("PRF_Operation").ForeignColumn("NextOperationID").ToTable("PRF_Operation").PrimaryColumn("OperationID"); Delete.Column("NextOperationID").FromTable("PRF_Operation_AUD"); Delete.Column("NextOperationID").FromTable("PRF_Operation"); } } public override void Up() { if (!Schema.Table("PRF_Operation").Column("NextOperationID").Exists()) { Alter.Table("PRF_Operation").AddColumn("NextOperationID").AsInt32().Nullable(); Alter.Table("PRF_Operation_AUD").AddColumn("NextOperationID").AsInt32().Nullable(); Create.ForeignKey().FromTable("PRF_Operation").ForeignColumn("NextOperationID").ToTable("PRF_Operation").PrimaryColumn("OperationID"); } } } }
using System; using System.Globalization; namespace EPI.Strings { /// <summary> /// Find the nth number in the look and say sequence /// 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ... /// </summary> public static class LookAndSay { public static int FindNthNumber(int n) { if (n <= 0) { throw new ArgumentException("Must specify n > 0"); } int number = 1; for(int i = 2; i <= n; i++) { number = FindNextNumber(number); } return number; } private static int FindNextNumber(int number) { string nextNumber = ""; string numberAsString = number.ToString(CultureInfo.CurrentCulture); char currentDigit = numberAsString[0]; int currentDigitCount = 1; for(int i = 1; i < numberAsString.Length; i++) { if (numberAsString[i] == currentDigit) { currentDigitCount++; } else { nextNumber += currentDigitCount.ToString() + currentDigit; currentDigitCount = 1; currentDigit = numberAsString[i]; } } nextNumber += currentDigitCount.ToString() + currentDigit; return Convert.ToInt32(nextNumber); } } }
using System; using CoherentSolutions.Extensions.Configuration.AnyWhere.Abstractions; using Microsoft.Extensions.Configuration; namespace CoherentSolutions.Extensions.Configuration.AnyWhere.EnvironmentVariables { public class AnyWhereEnvironmentVariablesConfigurationSourceAdapter : IAnyWhereConfigurationAdapter { public void ConfigureAppConfiguration( IConfigurationBuilder configurationBuilder, IAnyWhereConfigurationEnvironmentReader environmentReader) { if (configurationBuilder == null) { throw new ArgumentNullException(nameof(configurationBuilder)); } if (environmentReader == null) { throw new ArgumentNullException(nameof(environmentReader)); } configurationBuilder.AddEnvironmentVariables( environmentReader.GetString("PREFIX", string.Empty, true)); } } }
using System; using System.Collections; using UnityEngine; using DG.Tweening; using Random = UnityEngine.Random; public class FruitScript : MonoBehaviour { private Material _double_Material; //双倍分数的材质 private GameObject _canvas; //游戏界面的画布 private Material _default_Material;//默认材质 private SkinnedMeshRenderer _target; //磁铁状态下的目标 private float _fly_Speed;//磁铁状态下的飞行速度 private bool _rotate_Bool;//水果自旋转的开关 //此水果是否双倍分数的标记 public bool Is_Double_Bool { get; set; } //双倍材质 public Material DoubleMaterial { get { return _double_Material; } } public SkinnedMeshRenderer Target//磁铁状态下的目标 { set { _target = value; StartCoroutine(Move()); } } public void OnEnable() { if (_default_Material != null) { transform.GetComponent<MeshRenderer>().material = _default_Material; } } // Use this for initialization void Start() { _default_Material = transform.GetComponent<MeshRenderer>().material; //for temp(O' 170224) if (transform.parent.name.IndexOf("shoulijian") != -1) { transform.parent.Rotate(180, 0, 0, Space.World); transform.parent.localScale = Vector3.one; } //从resources文件夹读取资源 _double_Material = (Material)StaticParameter.LoadObject("Materials", "Golden"); //判断人物自身技能(这里只判断人物双倍分数技能) JudgeSkill(HumanManager.Nature, _double_Material); _fly_Speed = 15.0f; _rotate_Bool = true; } //判断人物自身技能(这里只判断人物双倍分数技能) void JudgeSkill(GameResource.HumanNature nature, Material double_Material) { foreach (HumanSkill i in nature.Skill_List) { if (i == HumanSkill.DoubleGold) { MeshRenderer render = transform.GetComponent<MeshRenderer>(); if (double_Material) { render.material = _double_Material; } else { Debug.Log(name + "少个材质"); } } } } // Update is called once per frame void Update() { if (StaticParameter.ComparePosition(transform, HumanManager.Nature.Human) > 80.0f) return; if (_rotate_Bool) { transform.Rotate(0, -2, 0, Space.World); } } public void CutFruit() { if (ItemColliction.Dash.IsRun()) { //播放音效 MyAudio.PlayAudio(StaticParameter.s_Score, false, StaticParameter.s_Score_Volume * 0.5f); } else { //播放音效 MyAudio.PlayAudio(StaticParameter.s_Score, false, StaticParameter.s_Score_Volume); //刀光 //SwordLight(this.transform); } //计算并显示分数 Score(); //喷溅果汁 Juice(this.transform); transform.GetComponent<SphereCollider>().enabled = false; //RandonVelocity();//被切后的速度生成函数 _target = null; //水果被切后磁铁目标修改为空 ClearData(); GoldAnimation(); } //清空数据 void ClearData() { _rotate_Bool = false; Destroy(this.gameObject, 2.0f); _canvas = null; } //吃了磁铁后,水果的移动 IEnumerator Move() { yield return new WaitUntil(() => { if (_target) { Vector3 temp = _target.bounds.center; Vector3 direction = temp - this.transform.position; this.transform.Translate(direction * Time.deltaTime * _fly_Speed, Space.World); } else { GoldAnimation(); } return _target == null; }); } //吃金币时金币动画 void GoldAnimation() { Vector3 scale = transform.localScale * 1.6f; transform.DOScale(scale, 0.1f).OnComplete(() => { Destroy(transform.parent.gameObject); }); transform.DOPlay(); } //显示分数 void Score() { if (Is_Double_Bool) { MyKeys.Game_Score += 2;//加分静态变量 } else { MyKeys.Game_Score++; } Window_Succeed.Cut_Number++;//切到水果的数量 try { Window_Ingame.Instance.ShowGold(MyKeys.Game_Score.ToString()); } catch (Exception) { throw; } } //刀光 void SwordLight(Transform fruit) { MyPool.Instance.Spawn(StaticParameter.s_Prefab_SwordLight, fruit.position + Vector3.up * fruit.localScale.y / 2, Quaternion.identity); } //喷溅果汁 void Juice(Transform fruit) { MyPool.Instance.Spawn(StaticParameter.s_Prefab_Juice, fruit.position, Quaternion.identity); } //水果解体后的随机速度生成函数 void RandonVelocity() { foreach (Transform child in transform) { if (child.name.Contains("A")) { float x_A = Random.Range(1, 3); float y_A = Random.Range(2, 5); Vector3 target_A = Vector3.right * (-x_A) + Vector3.up * (y_A); child.DOBlendableMoveBy(target_A, 1f).SetEase(Ease.OutExpo); child.DOBlendableMoveBy(Vector3.up * (-30f), 1f).SetEase(Ease.InExpo); child.DOLocalRotate(new Vector3(5, 4, 3), 0.4f).SetLoops(-1, LoopType.Incremental).SetEase(Ease.Linear); child.DOPlay(); } else { float x_B = Random.Range(1, 3); float y_B = Random.Range(2, 5); Vector3 target = Vector3.right * (x_B) + Vector3.up * (y_B); child.DOBlendableMoveBy(target, 1f).SetEase(Ease.OutExpo); child.DOBlendableMoveBy(Vector3.up * (-30f), 1f).SetEase(Ease.InExpo); child.DOLocalRotate(new Vector3(-5, -4, -3), 0.4f).SetLoops(-1, LoopType.Incremental).SetEase(Ease.Linear); child.DOPlay(); } } } }
/* Program Name: Movies Library System * * Author: Kazembe Rodrick * * Author Description: Freelancer software/web developer & Technical writter. Has over 7 years experience developing software * in Languages such as VB 6.0, C#.Net,Java, PHP and JavaScript & HTML. Services offered include custom * development, writting technical articles,tutorials and books. * Website: http://www.kazemberodrick.com * * Project URL: http://www.kazemberodrick.com/movies-library-system.html * * Email Address: kr@kazemberodrick. * * Purpose: Fairly complex Movies Library System For Educational purposes. Demonstrates how to develop complete database powered * Applications that Create and Update data in the database. The system also demonstrates how to create reports from * the database. * * Limitations: The system is currently a standalone. It does not support multiple users. This will be implemented in future * versions. * The system does not have a payments module. This can be developed upon request. Just sent an email to kr@kazemberodrick.com * The system does not have keep track of the number of movies to check for availability. This can be developed upon request. * * Movies Library System Road Map: This system is for educational purposes. I will be writting step-by-step tutorials on my * website http://www.kazemberodrick.com that explain; * -System Specifications for Movies Library System * -System Design Considerations * -System Database ERD * -System Class Diagram * -Explainations of the codes in each window * -Multiple-database support. The Base class BaseDBUtilities will be extended to create * classes that will support client-server database engines such as MySQL, MS SQL Server etc. * * Support Movies Library System: The System is completely free. Please support it by visiting http://www.kazemberodrick.com/c-sharp.html and recommending the site to * your friends. Share the tutorials on social media such as twitter and facebook. * * Github account: https://github.com/KazembeRodrick I regulary post and update sources on my Github account.Make sure to follow me * and never miss an update. * Facebook page: http://www.facebook.com/pages/Kazembe-Rodrick/487855197902730 Please like my page and get updates on latest articles * and source codes. You can get to ask questions too about the system and I will answer them. * * Twitter account: https://twitter.com/KazembeRodrick Spread the news. Tweet the articles and source code links on twitter. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Movies_Library_System { public partial class frmReturnMovie : Form { #region Private Variables string sql_stmt = string.Empty; #endregion #region Private Methods private void load_issued_movies() { sql_stmt = "SELECT * FROM query_issued_movies;"; DataTable dtCustomers = clsPublicMethods.DBUtilies.get_data_table(sql_stmt); cboRefNumber.DataSource = dtCustomers; cboRefNumber.ValueMember = "RefNo"; } private void display_details() { sql_stmt = "SELECT * FROM query_issued_movies WHERE RefNo = '" + cboRefNumber.Text + "';"; DataTable dtDetails = clsPublicMethods.DBUtilies.get_data_table(sql_stmt); if (dtDetails.Rows.Count > 0) { foreach (DataRow dr in dtDetails.Rows) { txtCustomerName.Text = dr["CustomerName"].ToString(); txtMovieTitle.Text = dr["MovieTitle"].ToString(); dtpIssueDate.Value = DateTime.Parse( dr["DateIssued"].ToString()); dtpReturnDate.Value = DateTime.Parse( dr["ReturnDate"].ToString()); } } else { txtCustomerName.Text = string.Empty; txtMovieTitle.Text = string.Empty; dtpIssueDate.Value = DateTime.Now.Date; dtpReturnDate.Value = DateTime.Now.Date; } } #endregion #region Form Init Method and Control Events public frmReturnMovie() { InitializeComponent(); } private void frmReturnMovie_Load(object sender, EventArgs e) { load_issued_movies(); cboRefNumber.Text = string.Empty; } private void btnUpdate_Click(object sender, EventArgs e) { if (txtCustomerName.Text == string.Empty) { clsPublicMethods.required_field_msg("Valid Ref Number"); cboRefNumber.Focus(); return; } if (clsPublicMethods.confirm_save_update() == DialogResult.Yes) { sql_stmt = "UPDATE issued_movies SET ReturnDate = " + clsPublicMethods.DBUtilies.sql_date_format(dtpReturnDate.Value) + ",Returned = 1 WHERE RefNo = '" + cboRefNumber.Text + "';"; clsPublicMethods.DBUtilies.execute_sql_statement(sql_stmt); load_issued_movies(); cboRefNumber.Text = string.Empty; clsPublicMethods.saved_updated_msg(); } } private void cboRefNumber_TextChanged(object sender, EventArgs e) { display_details(); } #endregion } }
using System; using System.Reflection; using System.Reflection.Emit; namespace IronAHK.Scripting { partial class ILMirror { public ConstructorInfo GrabConstructor(ConstructorInfo Original) { return GrabConstructor(Original, null); } protected ConstructorInfo GrabConstructor(ConstructorInfo Original, TypeBuilder On) { if (Original == null) return null; if (ConstructorsDone.ContainsKey(Original)) return ConstructorsDone[Original]; if (!Sources.Contains(Original.Module)) return ConstructorReplaceGenerics(Original); if (On == null) On = GrabType(Original.DeclaringType) as TypeBuilder; ConstructorBuilder Builder = On.DefineConstructor(Original.Attributes, Original.CallingConvention, ParameterTypes(Original)); Builder.SetImplementationFlags(Original.GetMethodImplementationFlags()); if (ConstructorsDone.ContainsKey(Original)) return ConstructorsDone[Original]; ConstructorsDone.Add(Original, Builder); CopyMethodBody(Original, Builder); return Builder; } private ConstructorInfo ConstructorReplaceGenerics(ConstructorInfo Orig) { if (Orig.DeclaringType.IsGenericType) { Type NewDeclarator = TypeReplaceGenerics(Orig.DeclaringType); if (NewDeclarator == Orig.DeclaringType) return Orig; ConstructorInfo Generic = FindMatchingGenericMethod(Orig) as ConstructorInfo; return TypeBuilder.GetConstructor(NewDeclarator, Generic); } else return Orig; } private ConstructorInfo FindStaticConstructor(Type Origin) { foreach (ConstructorInfo Info in Origin.GetConstructors(BindingFlags.NonPublic | BindingFlags.Static)) { if (Info.GetParameters().Length == 0) return Info; } return null; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.ComponentModel; using System.Configuration; using CIPMSOfficeObjects; using System.Reflection; namespace CIPMSBC { public class General { //to fill the grid for camper details public DataSet get_AllFederations() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsFederations; var param = new SqlParameter[1]; param[0] = new SqlParameter("@Action", "All"); dsFederations = dal.getDataset("usp_GetAllFederations", param); return dsFederations; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet get_AllFederationsFJCFunding() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsFederations; var param = new SqlParameter[1]; param[0] = new SqlParameter("@Action", "FJCFunding"); dsFederations = dal.getDataset("usp_GetAllFederations", param); return dsFederations; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the country dropdown -added by sandhya public DataSet get_AllCountries() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCountries; dsCountries = dal.getDataset("usp_GetAllContries", null); return dsCountries; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the Camps dropdown public DataSet get_AllCamps(string CampYear, int fedID = -1) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCamps; SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@CampYear", CampYear); param[1] = new SqlParameter("@FedID", fedID); dsCamps = dal.getDataset("usp_GetAllCamps", param); return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the Camps dropdown public DataSet get_AllCampsBackend(string CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCamps; SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampYear", CampYear); dsCamps = dal.getDataset("usp_GetAllCamps", param); for (int i = 0; i < dsCamps.Tables[0].Rows.Count; i++) { if (dsCamps.Tables[0].Rows[i]["Camp"].ToString().ToLower() == "camp menorah") dsCamps.Tables[0].Rows.RemoveAt(i); } return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the admin search camps list public DataSet get_AllCampsList(string CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCamps; SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampYear", CampYear); dsCamps = dal.getDataset("usp_GetAllCampsList", param); for (int i = 0; i < dsCamps.Tables[0].Rows.Count; i++) { if (dsCamps.Tables[0].Rows[i]["Camp"].ToString().ToLower() == "camp menorah") dsCamps.Tables[0].Rows.RemoveAt(i); } return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the Status dorpdown/list public DataSet get_AllStatus() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsStatus; dsStatus = dal.getDataset("usp_GetAllStatus", null); return dsStatus; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the list of users public DataSet get_Users() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsUsers; dsUsers = dal.getDataset("usp_GetAllUsers", null); return dsUsers; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the state values to the dropdown public DataSet get_States() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsStates; dsStates = dal.getDataset("USP_GetAllStates", null); return dsStates; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the cities based on the state selected public DataSet get_Cities(string stateId) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@State", stateId); DataSet dsCities; dsCities = dal.getDataset("[USP_GetCities]", param); return dsCities; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the cities based on the state selected public DataSet get_CityState(string ZipCode, string CountryCode) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@ZipCode", ZipCode); param[1] = new SqlParameter("@CountryCode", CountryCode); DataSet dsCityState; dsCityState = dal.getDataset("[usp_GetCityState]", param); return dsCityState; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the cities based on the state selected public DataSet get_ApplicationChangeHistory(string FJCID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@FJCID", FJCID); DataSet dsApplicationHistory; dsApplicationHistory = dal.getDataset("[usp_getApplicationChangeHistory]", param); return dsApplicationHistory; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the Camps based on FederationID //TV: 02/2009 - changed function into an overloaded function, and removed most //of the logic from this function into the version that accepts a string paramter //to keep all of the logic in one place - the overloaded function will provide the //same functionality as this function, plus allow the ability to handle a comma //delimited list of FederationIDs public DataSet GetFedCamps(int FedID,string CampYear,bool isJDS = false) { return GetFedCamps(FedID.ToString(),CampYear, isJDS); } //********************************************************************************************* // Name: GetFedCamps // Description: Will get all the Camps associated with the list of Federations in the // input parameter. (Overloaded method) // // Parameters: sFedIDs - a comma delimited list of Federations IDs // Returns: DataSet - will contain the list of Camp records // History: 02/2009 - TV: Initial coding. Originally added for Issue # 4-002 //********************************************************************************************* public DataSet GetFedCamps(string sFedIDs,string CampYear, bool isJDS = false) { CIPDataAccess dal = new CIPDataAccess(); try { string sProcName = ""; string sParamName = ""; if (sFedIDs.Contains(",") == true) { //note the difference in proc name - DOES contain //an "s" after the word "Federation" sProcName = "[usp_GetFederationsCamps]"; sParamName = "@FedIDs"; } else { //note the difference in proc name - it DOES NOT //contains an "s" after the word "Federation" sProcName = "[usp_GetFederationCamps]"; sParamName = "@FedID"; } SqlParameter[] param = new SqlParameter[3]; param[0] = new SqlParameter(sParamName, sFedIDs); param[1] = new SqlParameter("@CampYear", CampYear); param[2] = new SqlParameter("@isJDS", isJDS); DataSet dsFederationsCamps; dsFederationsCamps = dal.getDataset(sProcName, param); for (int i = 0; i < dsFederationsCamps.Tables[0].Rows.Count; i++) { if (dsFederationsCamps.Tables[0].Rows[i]["Camp"].ToString().ToLower() == "camp menorah") dsFederationsCamps.Tables[0].Rows.RemoveAt(i); } return dsFederationsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the Camps based on UserID public DataSet GetUserCamps(int UserID,int CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@UsrID", UserID); param[1] = new SqlParameter("@CampYear", CampYear); DataSet dsUsrCamps; dsUsrCamps = dal.getDataset("[usp_GetUserCamps]", param); return dsUsrCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the camps for a given state. public DataSet get_CampsForState(string stateId) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@State", stateId); DataSet dsCamps; dsCamps = dal.getDataset("[usp_GetCampsByState]", param); for (int i = 0; i < dsCamps.Tables[0].Rows.Count; i++) { if (dsCamps.Tables[0].Rows[i]["Camp"].ToString().ToLower() == "camp menorah") dsCamps.Tables[0].Rows.RemoveAt(i); } return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the camps for a given state. public DataSet get_CampsForFederationState(int FederationID, string stateId) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@FederationID", FederationID); param[1] = new SqlParameter("@State", stateId); DataSet dsCamps; dsCamps = dal.getDataset("[usp_GetCampsByFederationState]", param); for (int i = 0; i < dsCamps.Tables[0].Rows.Count; i++) { if (dsCamps.Tables[0].Rows[i]["Camp"].ToString().ToLower() == "camp menorah") dsCamps.Tables[0].Rows.RemoveAt(i); } return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the users for a given federation. public DataSet GetUsersByFederation(string strFedID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@FedID", strFedID); DataSet dsCamps; dsCamps = dal.getDataset("[usp_GetUsersByFederation]", param); return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the details like fedferation name and URL etc for a given federation. //TV: 02/2009 - Issue # 4-002: added new stored proc to handle more than one //Federation listed via a comma delimted list public DataSet GetFederationDetails(string strFedID) { CIPDataAccess dal = new CIPDataAccess(); try { //*********** //TV: 02/2009 - Issue # 4-002: string sProcName = ""; string sParamName = ""; if (strFedID.Contains(",") == true) { //note the difference in proc name - DOES contain //an "s" after the word "Federation" sProcName = "[usp_GetFederationsDetails]"; sParamName = "@FedIDs"; } else { //note the difference in proc name - it DOES NOT //contains an "s" after the word "Federation" sProcName = "[usp_GetFederationDetails]"; sParamName = "@FederationID"; } //*********** SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter(sParamName, strFedID); DataSet dsFedDetails; dsFedDetails = dal.getDataset(sProcName, param); return dsFedDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the Roles dropdown public DataSet get_AllRoles() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsRoles; dsRoles = dal.getDataset("usp_GetAllUserRoles", null); return dsRoles; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get the federation details assosiated to the zipcode. public DataSet GetFederationForZipCode(string strZipcode) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; // in clase if the zip code is Canadian if (strZipcode.Length > 6 && !strZipcode.StartsWith("T")) strZipcode = strZipcode.Substring(0, 3); param[0] = new SqlParameter("@Zipcode", strZipcode); DataSet dsFedDetails; dsFedDetails = dal.getDataset("[usp_GetFederationForZipCode]", param); return dsFedDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the Camp Sessions for a Camp public DataSet GetCampSessionsForCamp(int CampID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampID", CampID); DataSet dsCampSessions; dsCampSessions = dal.getDataset("[usp_GetCampSessionsByCamp]", param); return dsCampSessions; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the Camp Session details public DataSet GetCampSessionDetail(int CampSessionID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampSessionID", CampSessionID); DataSet dsCampSessionDetail; dsCampSessionDetail = dal.getDataset("[usp_GetCampSessionDetail]", param); return dsCampSessionDetail; } catch (Exception ex) { throw ex; } finally { dal = null; } } //Get Next possible status for a given role and current status public DataSet GetNextPossibleStatus(int RoleID, int CurrentStatus, int FederationID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[3]; param[0] = new SqlParameter("@Role", RoleID); param[1] = new SqlParameter("@CurrentStatus", CurrentStatus); param[2] = new SqlParameter("FederationID", FederationID); DataSet dsStatus; dsStatus = dal.getDataset("[usp_GetNextPossibleStatus]", param); return dsStatus; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the School values to the dropdown public DataSet GetAllSchoolList(string CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsSchools; SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampYear", CampYear); dsSchools = dal.getDataset("usp_GetAllSchoolList",param); return dsSchools; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get all the Camp Session details public DataSet GetSchoolListByFederation(int FederationID,string CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@FederationID", FederationID); param[1] = new SqlParameter("@CampYear", CampYear); DataSet dsSchoolListByFederation; dsSchoolListByFederation = dal.getDataset("[usp_GetSchoolListByFederation]", param); return dsSchoolListByFederation; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to check whether the given expression is a date public Boolean IsDate(string Date) { DateTime convertdate; if (DateTime.TryParse(Date, out convertdate)) { return true; } else return false; } //to get the Grade values to be displayed in the Questionnaire public DataTable getGrades(string fedId, string campYear) { var dtGrades = new DataTable(); dtGrades.Columns.Add(new DataColumn("EligibleGrade")); for (int i = 1; i <= 12; i++) { DataRow dr = dtGrades.NewRow(); dr["EligibleGrade"] = i.ToString(); dtGrades.Rows.Add(dr); } return dtGrades; } //to get the Synagogue list. public DataSet GetSynagogueListByFederation(int FederationID,string CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@FederationID", FederationID); param[1] = new SqlParameter("@CampYear", CampYear); DataSet dsSynagogueListByFederation; dsSynagogueListByFederation = dal.getDataset("[usp_GetSynagogueListByFederation]", param); return dsSynagogueListByFederation; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get the JCC list. public DataSet GetJCCListByFederation(int FederationID, string CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@FederationID", FederationID); param[1] = new SqlParameter("@CampYear", CampYear); DataSet dsJCCListByFederation; dsJCCListByFederation = dal.getDataset("[usp_GetJCCListByFederation]", param); return dsJCCListByFederation; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetAllSchoolTypes() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCamps; SqlParameter[] param = new SqlParameter[1]; dsCamps = dal.getDataset("usp_SchoolTypeSelect", null); return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the Camps dropdown public DataSet GetNationalCamps(string CampYear) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCamps; SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampYear", CampYear); dsCamps = dal.getDataset("usp_GetNationalCamps", param); return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get national program for camp public DataSet GetNationalProgram(int CampID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampID", CampID); DataSet dsNationalPrograms; dsNationalPrograms = dal.getDataset("[usp_GetNationalProgram]", param); return dsNationalPrograms; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get the LA Federation public DataSet GetLAFederationForCamper(string strFirstName, string strLastName,string strDateOfBirth) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[3]; DateTime dtDateOfBirth = Convert.ToDateTime(strDateOfBirth); strDateOfBirth=dtDateOfBirth.Month+"/"+dtDateOfBirth.Day+"/"+dtDateOfBirth.Year; param[0] = new SqlParameter("@FirstName", strFirstName); param[1] = new SqlParameter("@LastName", strLastName); param[2] = new SqlParameter("@DateOfBirth", dtDateOfBirth.ToString()); DataSet dsFedDetails; dsFedDetails = dal.getDataset("[usp_GetLAFederationForCamper]", param); return dsFedDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get the OC Federation public DataSet GetOCFederationForCamper(string strFirstName, string strLastName) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@FirstName", strFirstName); param[1] = new SqlParameter("@LastName", strLastName); DataSet dsFedDetails; dsFedDetails = dal.getDataset("[usp_GetOCFederationForCamper]", param); return dsFedDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } //********************************************************************************************* // Name: GetConfigValue // Description: Will get the Configuration value (ConfigValue) from the Config table // (tblConfig) for the given ConfigName. // // Parameters: sConfigName - the name of the Configuration setting whose value is being // requested // Returns: DataSet - will contain the ConfigValue for the given ConfigName // History: 03/2009 - TV: Initial coding. Originally added for Issue # A-016 //********************************************************************************************* public DataSet GetConfigValue(string sConfigName) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@ConfigName", sConfigName); DataSet dsConfigValue; dsConfigValue = dal.getDataset("[usp_GetConfigValue]", param); return dsConfigValue; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to get the state for a Camp public DataSet GetCampState(int CampID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@CampID", CampID); DataSet dsCampState; dsCampState = dal.getDataset("[usp_GetCampState]", param); return dsCampState; } catch (Exception ex) { throw ex; } finally { dal = null; } } //********************************************************************************************* // Name: IsApplicationReadOnly // Description: Will determin if the camper application for the given FJCID is a // "read-only" application or not. To make it read only, the application // needs to have been submitted or modified by an Admin user. // (most of this code was copied from another location in the CIMPS project in // an attempt to cetralize this logic in one place) // // Parameters: sFJCID - the FCJID for the application in question // sCamperIserID - the CamperUserID for the application // Returns: bool - true - the application is a read only type of application // false - the application is NOT a read only type of application // History: 03/2009 - TV: Initial coding. //********************************************************************************************* public bool IsApplicationReadOnly(string sFJCID, string sCamperUserID) { bool bReturnCode = false; bool isAdminUserEmpty = string.IsNullOrEmpty(Convert.ToString(System.Web.HttpContext.Current.Session["UsrID"])); string sSubmittedDate = string.Empty; DataSet dsApplSubmitInfo = new DataSet(); CamperApplication oCamperAppl = new CamperApplication(); DataRow dr; int iModifiedBy = Convert.ToInt32(sCamperUserID); dsApplSubmitInfo = oCamperAppl.GetApplicationSubmittedInfo(sFJCID); int iCount = dsApplSubmitInfo.Tables[0].Rows.Count; if (isAdminUserEmpty && (iCount > 0)) { dr = dsApplSubmitInfo.Tables[0].Rows[0]; //to get the submitted date if (!dr["SubmittedDate"].Equals(DBNull.Value)) { sSubmittedDate = dr["SubmittedDate"].ToString(); } //to get the modified by user6 if (!dr["ModifiedUser"].Equals(DBNull.Value)) { iModifiedBy = Convert.ToInt32(dr["ModifiedUser"]); } var currentStatus = (StatusInfo)dr["Status"]; if (currentStatus != StatusInfo.EligibleContactParentsAagain) if (!string.IsNullOrEmpty(sSubmittedDate) || (iModifiedBy != Convert.ToInt32(sCamperUserID) && iModifiedBy > 0 && currentStatus != StatusInfo.WinnerPJLottery)) { //Camper Application has been submitted (or) the Application has been modified by a Admin bReturnCode = true; } } return bReturnCode; } // to get the federation details for given fjcid public DataSet GetFedDetailsForFJCID(string FJCID) { var dal = new CIPDataAccess(); try { var param = new SqlParameter[1]; param[0] = new SqlParameter("@FJCID", FJCID); DataSet dsFedDetails; dsFedDetails = dal.getDataset("[usp_GetFedDetailsForFJCID]", param); return dsFedDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } // to get the aplication submitted status public bool IsApplicationSubmitted(string sFJCID) { bool bReturnCode = false; string sSubmittedDate = string.Empty; DataSet dsApplSubmitInfo = new DataSet(); CamperApplication oCamperAppl = new CamperApplication(); DataRow dr; int iModifiedBy = 0; dsApplSubmitInfo = oCamperAppl.GetApplicationSubmittedInfo(sFJCID); int iCount = dsApplSubmitInfo.Tables[0].Rows.Count; if (iCount > 0) { dr = dsApplSubmitInfo.Tables[0].Rows[0]; //to get the submitted date if (!dr["SUBMITTEDDATE"].Equals(DBNull.Value)) { sSubmittedDate = dr["SUBMITTEDDATE"].ToString(); } //Camper Application has been submitted (or) the Application has been modified by a Admin if (!string.IsNullOrEmpty(sSubmittedDate)) { bReturnCode = true; } } return bReturnCode; } /// <summary> /// To get all the details like fedferation name and URL etc for a given federation and camp. /// </summary> /// <param name="strFedID">FederationID (list comma seperated or single id</param> /// <param name="strCampID">CampID</param> /// <returns></returns> public DataSet GetFederationCampContactDetails(string strFedID, string strCampID) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@FederationID", strFedID); param[1] = new SqlParameter("@CampID", strCampID); DataSet dsFedDetails; dsFedDetails = dal.getDataset("[usp_GetFederationCampContactDetails]", param); return dsFedDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetMiiPReferalCode(string referalCode,string strCampYear) { CIPDataAccess dal = new CIPDataAccess(); try { SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@ReferalCode", referalCode); param[1] = new SqlParameter("@CampYear", strCampYear); DataSet dsMiiPReferalCodes = dal.getDataset("[usp_GetMiiPReferalCodes]", param); return dsMiiPReferalCodes; } catch (Exception ex) { throw ex; } finally { dal = null; } } ///to retrieve the Camp on CampID public DataSet GetCampByCampID(string strCampID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCamps; SqlParameter param = new SqlParameter("@CampID", strCampID); dsCamps = dal.getDataset("usp_GetCampByCampID", param); return dsCamps; } catch (Exception ex) { throw ex; } finally { dal = null; } } /// <summary> /// To retrieve referral code on camp and federationids /// </summary> /// <param name="strCampID">CampID</param> /// <param name="strFederationID">FederationID</param> /// <returns></returns> public DataSet GetCampReferralCodesByCampIDFederationID(string strCampID, string strFederationID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsReferralCodes; SqlParameter[] parameters = new SqlParameter[2]; parameters[0] = new SqlParameter("@CampID", strCampID); parameters[1] = new SqlParameter("@FederationID", strFederationID); dsReferralCodes = dal.getDataset("usp_GetCampReferralCodesByCampIDFederationID", parameters); return dsReferralCodes; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetEmailNotification(string FJCID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsEmailNotification; SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@FJCID", FJCID); dsEmailNotification = dal.getDataset("usp_GetEmailNotificationDetails", parameters); return dsEmailNotification; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetPJLNotification(string FJCID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsPJLNotification; SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@FJCID", FJCID); dsPJLNotification = dal.getDataset("usp_getPJLData", parameters); return dsPJLNotification; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet get_CamperStatusDetils(string strFJCID) { CIPDataAccess dal = new CIPDataAccess(); DataSet dsCamperStatusDetails; try { SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@FJCID", strFJCID); dsCamperStatusDetails = dal.getDataset("usp_GetCamperTrackingDetails", parameters); return dsCamperStatusDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } public void ProduceCSV(DataTable dt, System.IO.StreamWriter file, bool WriteHeader, int colNumberToAddQuotes) { if (WriteHeader) { string[] arr = new String[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { arr[i] = dt.Columns[i].ColumnName; arr[i] = GetWriteableValue(arr[i]); } file.WriteLine(string.Join(",", arr)); } for (int j = 0; j < dt.Rows.Count; j++) { string[] dataArr = new String[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { object o ; if (i == colNumberToAddQuotes) { o = "'" + dt.Rows[j][i]; } else { o = CheckForDataConsistency(dt.Rows[j][i].ToString()); } dataArr[i] = GetWriteableValue(o); } file.WriteLine(string.Join(",", dataArr)); } file.Close(); } private string CheckForDataConsistency(string value) { if (String.Equals(value, String.Empty)) { value = "\"\""; } else if (value.Contains(",")) { value = string.Concat("\"", value, "\""); } else if (value.Contains("\r")) { value = value.Replace("\r", " "); } else if (value.Contains("\n")) { value = value.Replace("\n", " "); } else if (value.Contains("\'")) value = value.Replace("\'", "\"\'\""); return value; } public void ProduceCSV(DataTable dt, System.IO.StreamWriter file, bool WriteHeader) { if (WriteHeader) { string[] arr = new String[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { arr[i] = dt.Columns[i].ColumnName; arr[i] = GetWriteableValue(arr[i]); } file.WriteLine(string.Join(",", arr)); } for (int j = 0; j < dt.Rows.Count; j++) { string[] dataArr = new String[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { object o; if (dt.Columns[i].ColumnName == "FJCID" || dt.Columns[i].ColumnName == "Camper FJCID") { o = "'" + dt.Rows[j][i]; } else { o = dt.Rows[j][i]; } dataArr[i] = GetWriteableValue(o); } file.WriteLine(string.Join(",", dataArr)); } file.Close(); } public string GetWriteableValue(object o) { if (o == null || o == Convert.DBNull) return ""; else if (o.ToString().IndexOf(",") == -1) return o.ToString(); else return "\"" + o.ToString() + "\""; } public void ProduceTabDelimitedFile(DataTable dt, System.IO.StreamWriter file, bool WriteHeader, int colNumberToAddQuotes) { if (WriteHeader) { StringBuilder sb = new StringBuilder(); string[] arr = new String[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { //arr[i] = dt.Columns[i].ColumnName; //arr[i] = GetWriteableValue(arr[i]); if (i < dt.Columns.Count - 1) sb.AppendFormat("{0}\t", GetWriteableValue(dt.Columns[i].ColumnName)); else if(i == dt.Columns.Count - 1) sb.AppendFormat("{0}\n",GetWriteableValue(dt.Columns[i].ColumnName)); } //file.WriteLine(string.Join(",",arr); file.WriteLine(sb.ToString()); } for (int j = 0; j < dt.Rows.Count; j++) { //string[] dataArr = new String[dt.Columns.Count]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < dt.Columns.Count; i++) { object o; o = dt.Rows[j][i].ToString(); if (i < dt.Columns.Count - 1) sb.AppendFormat("{0}\t", GetWriteableValue(o)); else if (i == dt.Columns.Count - 1) sb.AppendFormat("{0}\n", GetWriteableValue(o)); //dataArr[i] = GetWriteableValue(o); } //file.WriteLine(string.Join(",", dataArr)); file.WriteLine(sb.ToString()); } file.Close(); } public DataSet GetFederationAndQuestionnaireDetails(string strFederationIds, int campYearId) { var dal = new CIPDataAccess(); try { var parameters = new SqlParameter[2]; parameters[0] = new SqlParameter("@FederationIds", strFederationIds); parameters[1] = new SqlParameter("@CampYearID", campYearId); return dal.getDataset("usp_GetFederationAndQuestionnaireDetails", parameters); } catch (Exception ex) { throw ex; } finally { dal = null; } } public void CreateWord(DataTable dt) { CustomWord objCustomWord = new CustomWord(); objCustomWord.CreateWord(dt); } public string GetEligiblityForGrades(string FJCID,string grade) { DataTable dtGrades; DataRow dr; int i; try { CIPDataAccess dal = new CIPDataAccess(); DataSet dsFederationGrades=new DataSet(); SqlParameter[] parameters = new SqlParameter[2]; parameters[0] = new SqlParameter("@FJCID", FJCID); parameters[1] = new SqlParameter("@grade", grade); dsFederationGrades = dal.getDataset("usp_GetEligiblityForGrades", parameters); return dsFederationGrades.Tables[0].Rows[0][0].ToString(); } catch (Exception ex) { throw ex; } finally { //dal = null; } } public static String GetEnumDescription(Enum e) { FieldInfo fieldInfo = e.GetType().GetField(e.ToString()); if (fieldInfo == null) return "false"; DescriptionAttribute[] enumAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (enumAttributes.Length > 0) { return enumAttributes[0].Description; } return e.ToString(); } // 2016-09-27 Basically this function will return true ONLY if the zip code // is national zip code OR this zip code has community AND this community is Active public Boolean ValidateZipCode(string ZipCode,string DisabledFed) { DataSet dsFederation = new DataSet(); DataRow dr; dsFederation = GetFederationForZipCode(ZipCode); if (dsFederation.Tables[0].Rows.Count > 0) { dr = dsFederation.Tables[0].Rows[0]; string strFedId = dr["Federation"].ToString(); //string isActive = dr["isActive"].ToString(); //if (isActive == "False") //{ // return false; //} string[] DisabledFeds = DisabledFed.Split(','); for (int i = 0; i < DisabledFeds.Length; i++) { if (DisabledFeds[i] == strFedId) { // this zip code has a fed associated with, AND is OPEN, so we return true return true; } } } else { // this zip code has no federation associated, so we return true return true; } // this zip code has a fed asscoiated with, and has is NOT OPEN, so we return false return false; } public DataSet GetTimeInCampForFederation(int FederationID) { CIPDataAccess dal = new CIPDataAccess(); DataSet dsTimeInCamp; try { SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@FederationId", FederationID); dsTimeInCamp = dal.getDataset("usp_GetTimeInCampForFederation", parameters); return dsTimeInCamp; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetAllCampYears() { CIPDataAccess dal = new CIPDataAccess(); DataSet dsCampYears; try { dsCampYears = dal.getDataset("GetAllCampYears"); return dsCampYears; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetSchoolType() { CIPDataAccess dal = new CIPDataAccess(); DataSet dsSchoolType; try { dsSchoolType = dal.getDataset("usp_SchoolTypeSelect"); return dsSchoolType; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetPJLCodes(string strCampYear) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsPJLCodes; SqlParameter param = new SqlParameter("@CampYear", strCampYear); dsPJLCodes = dal.getDataset("[usp_GetPJLCodesCodes]",param); return dsPJLCodes; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetCurrentYear() { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsCurrentYear; dsCurrentYear = dal.getDataset("[usp_GetCurrentYear]"); return dsCurrentYear; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetJCCByID(string strJccID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsJcc; SqlParameter param = new SqlParameter("@JccID", strJccID); dsJcc = dal.getDataset("usp_GetJCCByID", param); return dsJcc; } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet GetSynagogueByID(string strSynID, int FederationID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsSyn; SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@ID", strSynID); param[1] = new SqlParameter("@FederationID", FederationID); dsSyn = dal.getDataset("usp_GetSynagogueByID", param); return dsSyn; } catch (Exception ex) { throw ex; } finally { dal = null; } } public string GetCanadianZipCode(string strZip) { string CJA = ConfigurationManager.AppSettings["CanadaCJAZipCodes"]; string Montreal = ConfigurationManager.AppSettings["CanadaMontrealZipCodes"]; string Toronto = ConfigurationManager.AppSettings["CanadaTorontoZipCodes"]; //string CJA = "A,B,C,E", Montreal = "G, H, J", Toronto = "L, M, N", string FedId = ""; if (CJA.IndexOf(strZip.Substring(0, 1)) >= 0) { // A, B, C, E // 2015-11-11 temporarily disable the code below, so AJC zip codes won't be used since it's still using special case zip codes, not fedZipCodes table like Toronto. FedId = "65"; } else if (Montreal.IndexOf(strZip.Substring(0, 1)) >= 0) { FedId = "69"; } else if (Toronto.IndexOf(strZip.Substring(0, 1)) >= 0) { FedId = ""; //2015-05-17 Toronto has its own zip codes list now DataSet dsFed = this.GetFederationForZipCode(strZip.Substring(0, 3)); if (dsFed.Tables.Count > 0) { if (dsFed.Tables[0].Rows.Count == 1) { FedId = dsFed.Tables[0].Rows[0][0].ToString(); } else if (dsFed.Tables[0].Rows.Count > 1) { FedId = "Duplicate"; } } } else if (strZip.Substring(0, 1) == "T") FedId = "59"; return FedId; } public DataSet GetFederationDetailsUsingCampID(string strFedID, string strCampID) { CIPDataAccess dal = new CIPDataAccess(); try { string sProcName = ""; sProcName = "[usp_GetFederationDetails]"; SqlParameter[] param = new SqlParameter[2]; param[0] = new SqlParameter("@FederationID", strFedID); param[1] = new SqlParameter("@CampID", strCampID); DataSet dsFedDetails; dsFedDetails = dal.getDataset(sProcName, param); return dsFedDetails; } catch (Exception ex) { throw ex; } finally { dal = null; } } //to fill the School values to the dropdown public string GetSchoolName(string FJCID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsSchools; SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@FJCID", FJCID); dsSchools = dal.getDataset("usp_GetSchoolName", param); return dsSchools.Tables[0].Rows[0][0].ToString(); } catch (Exception ex) { throw ex; } finally { dal = null; } } public DataSet getJWestGrant(string FJCID) { CIPMSBC.SrchCamperDetails S = new SrchCamperDetails(); SrchCamperDetails srch = new SrchCamperDetails(); DataSet dsCamper = srch.SearchCamperDetails(FJCID,"Test"); return dsCamper; } public string GetPreviousFJCID(string FJCID,string strFederationId) { General g = new General(); DataSet dsCamperDetails = g.getJWestGrant(FJCID); SrchCamperDetails Srch = new SrchCamperDetails(); if (dsCamperDetails.Tables[0].Rows.Count > 0) { DateTime DOB = Convert.ToDateTime(dsCamperDetails.Tables[0].Rows[0][20]); DataSet ds = Srch.getReturningCamperDetails(dsCamperDetails.Tables[0].Rows[0][6].ToString(), dsCamperDetails.Tables[0].Rows[0][7].ToString(), DOB.Date.ToString()); DataRow [] dsExistingCampers = ds.Tables[0].Select("campyearid=2"); if (dsExistingCampers.Length > 0) { return dsExistingCampers[0].ItemArray[0].ToString(); } } return string.Empty; } //added by sandhya to get returning camper previous fjcids public DataSet GetPreviousFJCIDs(string FJCID) { General g = new General(); DataSet dsCamperDetails = g.getJWestGrant(FJCID); SrchCamperDetails Srch = new SrchCamperDetails(); DateTime DOB = Convert.ToDateTime(dsCamperDetails.Tables[0].Rows[0][20]); DataSet ds = Srch.getAllReturningCamperDetails(dsCamperDetails.Tables[0].Rows[0][6].ToString(), dsCamperDetails.Tables[0].Rows[0][7].ToString(), DOB.Date.ToString()); return ds; } public DataSet GetPreviousManualCamperDetails(string FJCID) { General g = new General(); DataSet dsCamperDetails = g.getJWestGrant(FJCID); SrchCamperDetails Srch = new SrchCamperDetails(); DateTime DOB = Convert.ToDateTime(dsCamperDetails.Tables[0].Rows[0][20]); DataSet ds = Srch.getManualReturningCamperDetails(dsCamperDetails.Tables[0].Rows[0][6].ToString(), dsCamperDetails.Tables[0].Rows[0][7].ToString(), DOB.Date.ToString()); return ds; } public int ValidateNYZipCode(string ZipCode) { DataSet dsZipCodeCount; CIPDataAccess dal = new CIPDataAccess(); SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@ZipCode", ZipCode); dsZipCodeCount = dal.getDataset("usp_ValidateNYZipCode", param); return Convert.ToInt32(dsZipCodeCount.Tables[0].Rows[0][0]); } //To get the grade range for PPIR public string GetGradeEligibilityRange(int FederationID) { CIPDataAccess dal = new CIPDataAccess(); try { DataSet dsGrades; SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@FederationID", FederationID); dsGrades = dal.getDataset("usp_GetGradeDescription", param); return dsGrades.Tables[0].Rows[0][0].ToString(); } catch (Exception ex) { throw ex; } finally { dal = null; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SwipeController : MonoBehaviour { private PlayerCollision _playercollision; private Vector2 touchStartposition; private Vector2 touchEndposition; [SerializeField]public bool swipeLeft = false; [SerializeField]public bool swipeRight = false; [SerializeField]public bool swipeUp = false; public float differenceInUnit; public float differenceInUnitForYaxis; private void Start() { _playercollision = GetComponent<PlayerCollision>(); } private void Update() { if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { touchStartposition = Input.GetTouch(0).position; } if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended) { touchEndposition = Input.GetTouch(0).position; #region //This part checks the touch properties related to y axis if (touchEndposition.y > (touchStartposition.y + differenceInUnitForYaxis) && _playercollision.LeftBoundaryTouch) { swipeUp = true; } if (touchEndposition.y > (touchStartposition.y + differenceInUnitForYaxis) && _playercollision.RightBoundaryTouch) { swipeUp = true; } #endregion //for test #region //This part calculates the touch properties related x axis //if(swipeUp) //{ // //for test // swipeLeft = false; // swipeRight = false; //} if(!swipeUp) { if ((touchEndposition.x > (touchStartposition.x + differenceInUnit)) && _playercollision.LeftBoundaryTouch) { swipeRight = true; } if ((touchEndposition.x > touchStartposition.x) && _playercollision.RightBoundaryTouch) { swipeRight = false; } if ((touchEndposition.x < (touchStartposition.x - differenceInUnit)) && _playercollision.RightBoundaryTouch) { swipeLeft = true; } if ((touchEndposition.x < touchStartposition.x) && _playercollision.LeftBoundaryTouch) { swipeLeft = false; } } #endregion } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Oracle.DataAccess.Client; using Oracle.DataAccess.Types; namespace outlook_system { public partial class signin : Form { static string conString = "Data source=orcl;User Id=scott; Password=tiger;"; public signin() { InitializeComponent(); OracleConnection c = new OracleConnection(conString); } private void signInButton_Click(object sender, EventArgs e) { this.Hide(); mainMenu main = new mainMenu(); main.Closed += (s, args) => this.Close(); main.Show(); } } }
 using Android.App; using Android.OS; using Android.Widget; using Android.Support.V7.App; using Toolbar = Android.Support.V7.Widget.Toolbar; using System.Threading.Tasks; using SmartHome.Util; using SmartHome.Service.Response; using SmartHome.Service; using SmartHome.Model; using System.Collections.Generic; using SmartHome.Droid.Common; using System; using Android.Content; namespace SmartHome.Droid.Activities { [Activity(Label = "Smart Home - Room", ParentActivity = typeof(HomeActivity))] public class RoomActivity : AppCompatActivity { #region Parameter string houseId = string.Empty; List<Room> lstRoom = null; GridView grdHouse; #endregion #region Common //private async Task GetRoomData(string houseId) //{ // House objHouse = await APIManager.GetHouseByHouseId(houseId); // if (objHouse != null) // { // lstRoom = objHouse.rooms; // var grdHouse = FindViewById<GridView>(Resource.Id.grdHouse); // grdHouse.Adapter = new RoomAdapter(this, lstRoom); // grdHouse.ItemClick += GrdHouse_ItemClick; // } //} #endregion #region Event protected override async void OnResume() { base.OnResume(); // Create your application here SetContentView(Resource.Layout.Room); //// Init toolbar var toolbar = FindViewById<Toolbar>(Resource.Id.app_bar); SetSupportActionBar(toolbar); SupportActionBar.SetDisplayHomeAsUpEnabled(true); SupportActionBar.SetDisplayShowHomeEnabled(true); //Lấy obj house đã lưu trước đó House objHouse_Result = AppInstance.houseData; //Nếu house trước đó ==NULL, thì gọi lại API GetHouse if (objHouse_Result == null) { houseId = Intent.GetStringExtra("houseId") ?? "houseId not available"; objHouse_Result = await APIManager.GetHouseByHouseId(houseId); } else { lstRoom = objHouse_Result.rooms; } if (objHouse_Result !=null) { houseId = objHouse_Result.houseId; Title = objHouse_Result.name ?? "houseName not available"; var grdHouse = FindViewById<GridView>(Resource.Id.grdHouse); grdHouse.Adapter = new RoomAdapter(this, lstRoom); grdHouse.ItemClick += GrdHouse_ItemClick; } } protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); } private void GrdHouse_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { string roomId = lstRoom[e.Position].roomId; string roomName = lstRoom[e.Position].name; var deviceActivity = new Intent(this, typeof(DeviceActivity)); deviceActivity.PutExtra("houseId", houseId); deviceActivity.PutExtra("roomId", roomId); deviceActivity.PutExtra("roomName", roomName); StartActivity(deviceActivity); } #endregion } }
using PaperPlane.API.Global; using PaperPlane.API.MemoryManager; using PaperPlane.API.Util; using System; using System.Collections.Generic; using System.IO; using System.Text; using static PaperPlane.API.Log.GlobalLogger; namespace PaperPlane.API.ProtocolStack.Security.Messaging { internal class UnsecuredMessage { private readonly MemoryLine _memory; public ReadOnlyMemory<byte> Payload { get; private set; } private UnsecuredMessage(ReadOnlyMemory<byte> payload) { Payload = payload; } public UnsecuredMessage(MemoryLine payload) : this((ReadOnlyMemory<byte>)payload.ToArray()) { _memory = MemoryLine.Create( (long)0, TimeService.Instance.GenerateMsgId(), payload.Length, payload); } public static bool TryParse(ReadOnlyMemory<byte> data, out UnsecuredMessage message) { message = null; if (data.Length == 4) { Error($"Error from server {BitConverter.ToInt32(data.Span.Slice(0, 4))}"); return false; } int pointer = 8; var messageId = data.Int64At(ref pointer); var serverTime = messageId >> 32; TimeService.Instance.CheckServerTimeOffset(serverTime); var length = data.Int32At(ref pointer); message = new UnsecuredMessage(data.Slice(pointer, length)); return true; } public static implicit operator MemoryLine(UnsecuredMessage message) => message._memory; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace digitRecognizerAndroidTrain { class Neuron { float output; float error; int index; List<float> inputWeights; List<float> inputValues; /*functions*/ public Neuron(int nInput) { inputWeights = new List<float>(nInput); inputValues = new List<float>(nInput); Random rand = new Random(Guid.NewGuid().GetHashCode()); Random r = new Random(Guid.NewGuid().GetHashCode()); for (int i = 0; i < nInput; i++) { float val; int v; do { val = (float)rand.NextDouble(); } while (val > (1 / Math.Pow(nInput, 0.5)) || val == 0); v = r.Next(1, 50); if (v > 25) { inputWeights.Add(-val); } else { inputWeights.Add(val); } inputValues.Add(0f); } } private void activationFunction(float outputValue) { output = (float)(1 / (1 + 1 / Math.Pow(Math.E, outputValue))); //output = (float)Math.Tanh(outputValue); } public void processInput() { float sum = 0; for (int i = 0; i < inputValues.Count; i++) { sum += inputValues[i] * inputWeights[i]; } activationFunction(sum); } /*get and set function*/ public void setIndex(int index) { this.index = index; } public int getIndex() { return index; } public void setInputWeight(int index, float newWeight) { inputWeights[index] = newWeight; } public float getWeightValue(int index) { return inputWeights[index]; } public float getInputValue(int index) { return inputValues[index]; } public void setinputValue(int index, float newInputValues) { inputValues[index] = newInputValues; } public float Error { get { return error; } set { error = value; } } public int nInput { get { return inputValues.Count; } } public float Output { get { return output; } set { output = value; } } } }
using FBS.Domain.Booking; using FBS.Domain.Core; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace FBS.Booking.Read.API { public class BookingQueryHandler : IQueryHandler<GetBookingsByFlightQuery, IEnumerable<BookingAggregate>> { private readonly IAggregateContext<BookingAggregate> bookingContext; public BookingQueryHandler(IAggregateContext<BookingAggregate> bookingContext) { this.bookingContext = bookingContext; } public async Task<IEnumerable<BookingAggregate>> Handle(GetBookingsByFlightQuery request, CancellationToken cancellationToken) { return await bookingContext.GetAggregatesWhere(booking => booking.FlightId == request.FlightId && booking.CustomerId == request.CustomerId); } } }
using System.IO; using System.Windows.Forms; namespace gView.Framework.UI.Dialogs { public partial class FormCopyrightInformation : Form { public FormCopyrightInformation(string html) { InitializeComponent(); html = @" <html> <head> <style> body { font-family:verdana;font-size:8.5pt } h1 { font-family:verdana;font-size:12pt } </style> </head> <body> " + html + "</body></html>"; MemoryStream ms = new MemoryStream( System.Text.Encoding.Default.GetBytes(html)); webBrowser1.DocumentStream = ms; } } }
using BradescoPGP.Common; using BradescoPGP.Repositorio; using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; namespace BradescoPGP.Web.Services { public class CaptacaoLiquidaRepository { public List<CaptacaoLiquida> ObterCapLiq(string mesDataBase = null, string matriclaConsultor = null, string MatriculaCordenador = null) { var connStr = ConfigurationManager.ConnectionStrings["PGP"].ConnectionString; var retorno = new List<CaptacaoLiquida>(); using (var conn = new SqlConnection(connStr)) { conn.Open(); using (var cmd = new SqlCommand("sp_ObterCapLiq", conn)) { cmd.CommandTimeout = 300; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@matriculaConsultor", matriclaConsultor ?? string.Empty); cmd.Parameters.AddWithValue("@matriculaCord", MatriculaCordenador ?? string.Empty); cmd.Parameters.AddWithValue("@mesDataBase", mesDataBase); using (var rd = cmd.ExecuteReader()) { while (rd.Read()) { var capLiq = new CaptacaoLiquida(); capLiq.Diretoria = rd["Diretoria"]?.ToString(); capLiq.GerenciaRegional = rd["GerenciaRegional"]?.ToString(); capLiq.Produto = rd["Produto"]?.ToString(); capLiq.MatriculaConsultor = rd["MatriculaConsultor"]?.ToString(); capLiq.Consultor = rd["Consultor"]?.ToString(); capLiq.MatriculaCordenador = rd["MatriculaCordenador"]?.ToString(); capLiq.CordenadorPGP = rd["CordenadorPGP"]?.ToString(); capLiq.ValorNET = decimal.Parse(rd["ValorNET"]?.ToString() ?? "0"); retorno.Add(capLiq); } return retorno; } } } } public List<CaptacaoLiquida> ObterDetalheCapLiq(string dataBase, string matriculaConsultor = null, string matrculCordenador = null) { var connStr = ConfigurationManager.ConnectionStrings["PGP"].ConnectionString; var retorno = new List<CaptacaoLiquida>(); using (var conn = new SqlConnection(connStr)) { conn.Open(); using (var cmd = new SqlCommand("sp_ObterDetalheCaptacaoLiquida", conn)) { cmd.CommandTimeout = 300; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@matriculaConsultor", matriculaConsultor); cmd.Parameters.AddWithValue("@matriculaCordenador", matrculCordenador); cmd.Parameters.AddWithValue("@mesDataBase", dataBase); using (var rd = cmd.ExecuteReader()) { while (rd.Read()) { var capLiq = new CaptacaoLiquida(); capLiq.Diretoria = rd["Diretoria"]?.ToString(); capLiq.GerenciaRegional = rd["GerenciaRegional"]?.ToString(); capLiq.Produto = rd["Produto"]?.ToString(); capLiq.MatriculaConsultor = rd["MatriculaConsultor"]?.ToString(); capLiq.Consultor = rd["Consultor"]?.ToString(); capLiq.MatriculaCordenador = rd["MatriculaCordenador"]?.ToString(); capLiq.CordenadorPGP = rd["CordenadorPGP"]?.ToString(); capLiq.ValorNET = decimal.Parse(rd["ValorNET"]?.ToString() ?? "0"); capLiq.Agencia = rd["Agencia"]?.ToString(); capLiq.Conta = rd["Conta"]?.ToString(); capLiq.Ag_Conta = rd["Ag_Conta"]?.ToString(); capLiq.CodAgencia = rd["CodAgencia"]?.ToString(); capLiq.TipoPessoa = rd["TipoPessoa"]?.ToString(); if (DateTime.TryParse(rd["DataBase"]?.ToString(), out var dataBaseConvert)) capLiq.DataBase = dataBaseConvert; capLiq.ValorAplicacao = decimal.Parse(rd["ValorAplicacao"]?.ToString() ?? "0"); capLiq.ValorResgate = decimal.Parse(rd["ValorResgate"]?.ToString() ?? "0"); capLiq.ValorNET = decimal.Parse(rd["ValorNET"]?.ToString() ?? "0"); retorno.Add(capLiq); } return retorno; } } } } //TODO: Adicionar Mesdatabase para consulta public List<vw_CaminhoDinheiroAgrupado> ObterCaminhoDinheiroAgrupado(NivelAcesso nivelAcesso, string matricula, string anoMes) { using (var db = new PGPEntities()) { var result = default(List<vw_CaminhoDinheiroAgrupado>); switch (nivelAcesso) { case NivelAcesso.Master: result = db.vw_CaminhoDinheiroAgrupado.Where(s => s.MesDataBase == anoMes).ToList(); break; case NivelAcesso.Especialista: result = db.vw_CaminhoDinheiroAgrupado.Where(s => s.MatriculaConsultor == matricula && s.MesDataBase == anoMes).ToList(); break; case NivelAcesso.Gestor: result = db.vw_CaminhoDinheiroAgrupado.Where(s => s.MatriculaCordenador == matricula && s.MesDataBase == anoMes).ToList(); break; } return result; } } public List<CaminhoDinheiro> ObterCaminhoDinheiroAnalitico(NivelAcesso nivelAcesso, string matricula, string anoMes) { using (var db = new PGPEntities()) { var result = default(List<CaminhoDinheiro>); switch (nivelAcesso) { case NivelAcesso.Master: result = db.CaminhoDinheiro.Where(s => s.MesDataBase == anoMes).ToList(); break; case NivelAcesso.Especialista: result = db.CaminhoDinheiro.Where(s => s.MatriculaConsultor == matricula && s.MesDataBase == anoMes).ToList(); break; case NivelAcesso.Gestor: result = db.CaminhoDinheiro.Where(s => s.MatriculaCordenador == matricula && s.MesDataBase == anoMes).ToList(); break; } return result; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PokerEnumLibrary { [Flags] public enum Colours { Red = 1 << 0, Orange = 1 << 1, Yellow = 1 << 2, Green = 1 << 3, Blue = 1 << 4, Indigo = 1 << 5, Violet = 1 << 6, Purple = Red | Blue, } }
using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.system; using System.IO; using System.Threading.Tasks; namespace gView.DataSources.Raster.File { public class RasterFileClass : IRasterClass, IRasterFileBitmap, IRasterFile { private string _filename, _title; private bool _valid = true; private int _iWidth = 0, _iHeight = 0; internal TFWFile _tfw; private IPolygon _polygon; private ISpatialReference _sRef = null; private IRasterDataset _dataset; public RasterFileClass() { } public RasterFileClass(IRasterDataset dataset, string filename) : this(dataset, filename, null) { } public RasterFileClass(IRasterDataset dataset, string filename, IPolygon polygon) { try { FileInfo fi = new FileInfo(filename); _title = fi.Name; _filename = filename; _dataset = dataset; string tfwfilename = filename.Substring(0, filename.Length - fi.Extension.Length); if (fi.Extension.ToLower() == ".jpg") { tfwfilename += ".jgw"; } else { tfwfilename += ".tfw"; } _tfw = new TFWFile(tfwfilename); //if (!_tfw.isValid) //{ // _valid = false; // return; //} FileInfo fiPrj = new FileInfo(fi.FullName.Substring(0, fi.FullName.Length - fi.Extension.Length) + ".prj"); if (fiPrj.Exists) { StreamReader sr = new StreamReader(fiPrj.FullName); string wkt = sr.ReadToEnd(); sr.Close(); _sRef = gView.Framework.Geometry.SpatialReference.FromWKT(wkt); } if (polygon != null) { _polygon = polygon; } else { calcPolygon(); } } catch { _valid = false; } } public bool isValid { get { return _valid; } } private void calcPolygon() { try { if (_tfw == null) { FileInfo fi = new FileInfo(_filename); string tfwfilename = _filename.Substring(0, _filename.Length - fi.Extension.Length); if (fi.Extension.ToLower() == ".jpg") { tfwfilename += ".jgw"; } else { tfwfilename += ".tfw"; } _tfw = new TFWFile(tfwfilename); } if (_iWidth == 0 || _iHeight == 0) { using (var image = GraphicsEngine.Current.Engine.CreateBitmap(_filename)) { SetBounds(image); } } } catch { _polygon = null; } } private void SetBounds(GraphicsEngine.Abstraction.IBitmap bitmap) { if (bitmap != null) { _iWidth = bitmap.Width; _iHeight = bitmap.Height; } _polygon = new Polygon(); Ring ring = new Ring(); gView.Framework.Geometry.Point p1 = new gView.Framework.Geometry.Point( _tfw.X - _tfw.dx_X / 2.0 - _tfw.dy_X / 2.0, _tfw.Y - _tfw.dx_Y / 2.0 - _tfw.dy_Y / 2.0); ring.AddPoint(p1); ring.AddPoint(new gView.Framework.Geometry.Point(p1.X + _tfw.dx_X * _iWidth, p1.Y + _tfw.dx_Y * _iWidth)); ring.AddPoint(new gView.Framework.Geometry.Point(p1.X + _tfw.dx_X * _iWidth + _tfw.dy_X * _iHeight, p1.Y + _tfw.dx_Y * _iWidth + _tfw.dy_Y * _iHeight)); ring.AddPoint(new gView.Framework.Geometry.Point(p1.X + _tfw.dy_X * _iHeight, p1.Y + _tfw.dy_Y * _iHeight)); _polygon.AddRing(ring); } #region IRasterClass public IPolygon Polygon { get { return _polygon; } } public Task<IRasterPaintContext> BeginPaint(gView.Framework.Carto.IDisplay display, ICancelTracker cancelTracker) { var bitmap = GraphicsEngine.Current.Engine.CreateBitmap(_filename); return Task.FromResult<IRasterPaintContext>(new RasterPaintContext(bitmap)); } public GraphicsEngine.ArgbColor GetPixel(IRasterPaintContext context, double X, double Y) { //return Color.Beige; if (context?.Bitmap == null) { return GraphicsEngine.ArgbColor.Transparent; } int x, y; _tfw.World2Image(X, Y, out x, out y); if (x < 0 || y < 0 || x >= _iWidth || y >= _iHeight) { return GraphicsEngine.ArgbColor.Transparent; } return context.Bitmap.GetPixel(x, y); } public double oX { get { return _tfw.X; } } public double oY { get { return _tfw.Y; } } public double dx1 { get { return _tfw.dx_X; } } public double dx2 { get { return _tfw.dx_Y; } } public double dy1 { get { return _tfw.dy_X; } } public double dy2 { get { return _tfw.dy_Y; } } public ISpatialReference SpatialReference { get { return _sRef; } set { _sRef = value; } } public IRasterDataset Dataset { get { return _dataset; } } #endregion #region IBitmap Members public GraphicsEngine.Abstraction.IBitmap LoadBitmap() { try { if (_filename == "" || _filename == null) { return null; } return GraphicsEngine.Current.Engine.CreateBitmap(_filename); } catch { return null; } } #endregion #region IRasterFile Members public string Filename { get { return _filename; } } public IRasterWorldFile WorldFile { get { return _tfw; } } #endregion #region IClass Member public string Name { get { return _title; } } public string Aliasname { get { return _title; } } IDataset IClass.Dataset { get { return _dataset; } } #endregion } }
using GardenControlCore.Enums; using GardenControlCore.Scheduler; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GardenControlRepositories.Entities { [Table("Schedule")] public class ScheduleEntity { [Key] public int ScheduleId { get; init; } [Required] public string Name { get; set; } public bool IsActive { get; set; } [Required] public TriggerType TriggerTypeId { get; set; } public DateTime? TriggerTimeOfDay { get; set; } public int? TriggerOffsetAmount { get; set; } public TimeIntervalUnit? TriggerOffsetAmountTimeIntervalUnitId { get; set; } public int? IntervalAmount { get; set; } public TimeIntervalUnit? IntervalAmountTimeIntervalUnitId { get; set; } [Required] public DateTime NextRunDateTime { get; set; } public virtual ICollection<ScheduleTaskEntity> ScheduleTasks { get; set; } } }
using CutieBox.API.RandomApi; using Discord.Commands; using System.Threading.Tasks; namespace CutieBox.Commands { [Group("catfact")] public class CatFact : ModuleBase { private readonly RandomApi _randomApi; public CatFact(RandomApi randomApi) => _randomApi = randomApi; [Command] public async Task ExecuteAsync() { var response = await _randomApi.Facts.GetCatAsync(); await ReplyAsync(response.Fact); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Numerics; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Silk.NET.OpenGL; using Silk.NET.Windowing; using SixLabors.ImageSharp.PixelFormats; namespace Jypeli.Rendering.OpenGl { /// <summary> /// OpenGL renderöintilaite /// </summary> public unsafe class GraphicsDevice : IGraphicsDevice { /// <inheritdoc/> public GL Gl; private BufferObject<VertexPositionColorTexture> Vbo; private BufferObject<uint> Ebo; private VertexArrayObject<VertexPositionColorTexture, uint> Vao; private BasicLightRenderer bl; /// <inheritdoc/> public int BufferSize { get; } = 16384; private uint[] Indices; private VertexPositionColorTexture[] Vertices; /// <inheritdoc/> public string Name { get; internal set; } /// <inheritdoc/> public string Version { get => throw new NotImplementedException(); } private IRenderTarget SelectedRendertarget; /// <inheritdoc/> public GraphicsDevice(IView window) { Indices = new uint[BufferSize * 2]; Vertices = new VertexPositionColorTexture[BufferSize]; Create(window); } /// <summary> /// Alustaa näyttökortin käyttöön /// </summary> /// <param name="window">Pelin ikkuna</param> public void Create(IView window) { Gl = GL.GetApi(window); try { Gl.DebugMessageCallback(PrintError, null); } catch { Debug.WriteLine("DebugMessageCallback not available"); } Name = window.API.API.ToString(); Ebo = new BufferObject<uint>(Gl, Indices, BufferTargetARB.ElementArrayBuffer); Vbo = new BufferObject<VertexPositionColorTexture>(Gl, Vertices, BufferTargetARB.ArrayBuffer); Vao = new VertexArrayObject<VertexPositionColorTexture, uint>(Gl, Vbo, Ebo); Vao.VertexAttributePointer(0, 3, VertexAttribPointerType.Float, (uint)sizeof(VertexPositionColorTexture), 0); Vao.VertexAttributePointer(1, 4, VertexAttribPointerType.Float, (uint)sizeof(VertexPositionColorTexture), 12); Vao.VertexAttributePointer(2, 2, VertexAttribPointerType.Float, (uint)sizeof(VertexPositionColorTexture), 28); bl = new BasicLightRenderer(this); } private void PrintError(GLEnum source, GLEnum type, int id, GLEnum severity, int length, nint message, nint userParam) { Debug.WriteLine($"ERROR {source}: {type}, {id}, {severity}, {length}, {message}, {userParam}"); } /// <inheritdoc/> public IShader CreateShader(string vert, string frag) { return new Shader(Gl, vert, frag); } /// <inheritdoc/> public IShader CreateShaderFromInternal(string vertPath, string fragPath) { return CreateShader(Game.ResourceContent.LoadInternalText($"Shaders.{Name}.{vertPath}"), Game.ResourceContent.LoadInternalText($"Shaders.{Name}.{fragPath}")); } /// <inheritdoc/> public void DrawIndexedPrimitives(PrimitiveType primitivetype, VertexPositionColorTexture[] vertexBuffer, uint numIndices, uint[] indexBuffer) { Gl.Enable(GLEnum.Blend); Gl.BlendFunc(GLEnum.SrcAlpha, GLEnum.OneMinusSrcAlpha); Ebo.UpdateBuffer(0, indexBuffer); Vbo.UpdateBuffer(0, vertexBuffer); Vao.Bind(); Gl.DrawElements((GLEnum)primitivetype, numIndices, DrawElementsType.UnsignedInt, null); } /// <inheritdoc/> public void DrawPrimitives(PrimitiveType primitivetype, VertexPositionColorTexture[] vertexBuffer, uint numIndices, bool normalized = false) { if(primitivetype == PrimitiveType.OpenGLLines) Gl.Enable(GLEnum.LineSmooth); Gl.Enable(GLEnum.Blend); Gl.BlendFunc(GLEnum.SrcAlpha, GLEnum.OneMinusSrcAlpha); Vbo.UpdateBuffer(0, vertexBuffer); Vao.Bind(); Gl.DrawArrays((GLEnum)primitivetype, 0, numIndices); } /// <inheritdoc/> public void DrawPrimitivesInstanced(PrimitiveType primitivetype, VertexPositionColorTexture[] textureVertices, uint count, uint instanceCount, bool normalized = false) { Gl.DrawArraysInstanced((GLEnum)primitivetype, 0, count, instanceCount); } public void DrawLights(Matrix4x4 matrix) { if (Game.Lights.Count == 0) return; bl.Draw(matrix); SetRenderTarget(Game.Screen.RenderTarget); Graphics.LightPassTextureShader.Use(); Graphics.LightPassTextureShader.SetUniform("world", Matrix4x4.Identity); Graphics.LightPassTextureShader.SetUniform("texture0", 0); Graphics.LightPassTextureShader.SetUniform("texture1", 1); Graphics.LightPassTextureShader.SetUniform("ambientLight", Game.Instance.Level.AmbientLight.ToNumerics()); Game.Screen.RenderTarget.TextureSlot(0); Game.Screen.RenderTarget.BindTexture(); BasicLightRenderer.RenderTarget.TextureSlot(1); BasicLightRenderer.RenderTarget.BindTexture(); DrawPrimitives(PrimitiveType.OpenGlTriangles, Graphics.TextureVertices, 6, true); } /// <inheritdoc/> public void Clear(Color bgColor) { Gl.ClearColor(bgColor.RedComponent / 255f, bgColor.GreenComponent / 255f, bgColor.BlueComponent / 255f, bgColor.AlphaComponent / 255f); Gl.Clear((uint)(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit)); } /// <inheritdoc/> public void SetRenderTarget(IRenderTarget renderTarget) { if (renderTarget is null) Gl.BindFramebuffer(GLEnum.Framebuffer, 0); else renderTarget.Bind(); SelectedRendertarget = renderTarget; } /// <inheritdoc/> public void Dispose() { Vbo.Dispose(); Ebo.Dispose(); Vao.Dispose(); GC.SuppressFinalize(this); } /// <inheritdoc/> public IRenderTarget CreateRenderTarget(uint width, uint height) { return new RenderTarget(this, width, height); } /// <inheritdoc/> public void LoadImage(Image image) { void* data = GetImageDataPtr(image); image.handle = Gl.GenTexture(); BindTexture(image); Gl.TexImage2D(TextureTarget.Texture2D, 0, InternalFormat.Rgba, (uint)image.Width, (uint)image.Height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, data); GLEnum scaling = image.Scaling == ImageScaling.Linear ? GLEnum.Linear : GLEnum.Nearest; Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)scaling); Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)scaling); Gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureWrapS, (int)GLEnum.ClampToEdge); Gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureWrapT, (int)GLEnum.ClampToEdge); } /// <inheritdoc/> public void UpdateTextureData(Image image) { void* data = GetImageDataPtr(image); BindTexture(image); Gl.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, (uint)image.Width, (uint)image.Height, PixelFormat.Rgba, PixelType.UnsignedByte, data); GLEnum scaling = image.Scaling == ImageScaling.Linear ? GLEnum.Linear : GLEnum.Nearest; Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)scaling); Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)scaling); Gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureWrapS, (int)GLEnum.Repeat); } /// <inheritdoc/> public void UpdateTextureScaling(Image image) { GLEnum scaling = image.Scaling == ImageScaling.Linear ? GLEnum.Linear : GLEnum.Nearest; BindTexture(image); Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)scaling); // TODO: Entä jos halutaan vain muuttaa skaalausta, ilman kuvan datan muuttamista? Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)scaling); } /// <inheritdoc/> public void BindTexture(Image image) { // Jos kuvaa ei ole vielä viety näytönohjaimelle. if (image.handle == 0) LoadImage(image); Gl.ActiveTexture(TextureUnit.Texture0); Gl.BindTexture(TextureTarget.Texture2D, image.handle); } /// <inheritdoc/> public void ResizeWindow(Vector newSize) { Gl.Viewport(new System.Drawing.Size((int)newSize.X, (int)newSize.Y)); } /// <inheritdoc/> public void SetTextureToRepeat(Image image) { BindTexture(image); Gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureWrapS, (int)GLEnum.Repeat); Gl.TexParameter(GLEnum.Texture2D, GLEnum.TextureWrapT, (int)GLEnum.Repeat); } /// <inheritdoc/> public void GetScreenContents(void* ptr) { if (SelectedRendertarget == null) Gl.ReadPixels(0, 0, (uint)Game.Screen.Width, (uint)Game.Screen.Height, GLEnum.Rgba, GLEnum.UnsignedByte, ptr); else Gl.ReadPixels(0, 0, (uint)SelectedRendertarget.Width, (uint)SelectedRendertarget.Height, GLEnum.Rgba, GLEnum.UnsignedByte, ptr); } /// <inheritdoc/> public void GetScreenContentsToImage(Image img) { void* p = GetImageDataPtr(img); GetScreenContents(p); } /// <inheritdoc/> public int GetMaxTextureSize() { return Gl.GetInteger(GLEnum.MaxTextureSize); } private void* GetImageDataPtr(Image image) { var bytes = new byte[image.Width * image.Height * sizeof(Rgba32)]; image.rawImage.ProcessPixelRows ( a => { for (var y = 0; y < a.Height; y++) { MemoryMarshal.Cast<Rgba32, byte>(a.GetRowSpan(y)).CopyTo(bytes.AsSpan().Slice((y * a.Width * sizeof(Rgba32)))); } } ); fixed (void* ptr = bytes) return ptr; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DistCWebSite.Common { [Serializable] public class UploadToken { public string name { get; set; } public long size { get; set; } public string token { get; set; } public long upsize { get; set; } public string filePath { get; set; } public string modified { get; set; } } }
using Whathecode.System; using Whathecode.System.Algorithm; using Xunit; namespace Whathecode.Tests.System.Algorithm { public class BinarySearchTest { [Fact] public void SearchTest() { int[] numbers = new [] { -10, -8, 0, 10, 500 }; var indexerDelegates = new IndexerDelegates<int, int>( index => numbers[ index ], index => index ); // Object found. BinarySearchResult<int> result = BinarySearch<int, int>.Search( 0, numbers.GetIndexInterval(), indexerDelegates ); Assert.Equal( true, result.IsObjectFound ); Assert.Equal( true, result.IsObjectInRange ); Assert.Equal( 0, result.Found.Object ); Assert.Null( result.NotFound ); // Object found, border. result = BinarySearch<int, int>.Search( 500, numbers.GetIndexInterval(), indexerDelegates ); Assert.Equal( true, result.IsObjectFound ); Assert.Equal( true, result.IsObjectInRange ); Assert.Equal( 500, result.Found.Object ); Assert.Null( result.NotFound ); // Object not found, but in range. result = BinarySearch<int, int>.Search( -9, numbers.GetIndexInterval(), indexerDelegates ); Assert.Equal( false, result.IsObjectFound ); Assert.Equal( true, result.IsObjectInRange ); Assert.Equal( -10, result.NotFound.Smaller ); Assert.Equal( -8, result.NotFound.Bigger ); Assert.Null( result.Found ); // Object not found, out of range, left. result = BinarySearch<int, int>.Search( -20, numbers.GetIndexInterval(), indexerDelegates ); Assert.Equal( false, result.IsObjectFound ); Assert.Equal( false, result.IsObjectInRange ); Assert.Null( result.NotFound ); Assert.Null( result.Found ); // Object not found, out of range, right. result = BinarySearch<int, int>.Search( 600, numbers.GetIndexInterval(), indexerDelegates ); Assert.Equal( false, result.IsObjectFound ); Assert.Equal( false, result.IsObjectInRange ); Assert.Null( result.NotFound ); Assert.Null( result.Found ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TaskDemo { public class JusTest : CCF.Task.TaskBase { public override void Run() { Log("运行了一次!"); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Sport_Store.Models; namespace Sport_Store.Infrastructure { public class DataRepository : IRepository { // private List<Product> data = new List<Product>(); private DataContext context; public DataRepository(DataContext dataContext) { context = dataContext; } public IEnumerable<Product> Products => context.Products; public void AddProduct (Product product) { this.context.Add(product); this.context.SaveChanges(); } } }
namespace MordorCrueltyPlan.Models.Foods { public class Junk : Food { private const int HappinessPoints = -1; public Junk() : base(HappinessPoints) { } } }
using System.Runtime.Serialization; namespace PipServices.Sms.Client.Version1 { [DataContract] public class SmsMessageV1 { [DataMember(Name = "from")] public string From { get; set; } [DataMember(Name = "to")] public string To { get; set; } [DataMember(Name = "text")] public object Text { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; namespace XH.Labs.AngularJs { public class MailServer { private Hashtable serverNode; public MailServer() { serverNode = new Hashtable(); } public Hashtable ServerNode { get { return serverNode; } } public string Address { get { return serverNode["address"] as string; } } public string UserName { get { return serverNode["userName"] as string; } } public string Password { get { return serverNode["password"] as string; } } public string Client { get { return serverNode["client"] as string; } } } public class MailServerConfig : List<MailServer> { public string Provider { get; set; } } }
namespace ApartmentApps.Api { public interface ISendAlert { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Weapon : MonoBehaviour { public enum Type { Melee, Range }; public Type type; public int damage; public float rate; public int maxAmmo; public int curAmmo; public BoxCollider meleeArea; public TrailRenderer trailEffect; public Transform bulletPos; // 총알 생성 위치 public GameObject bullet; public Transform bulletCasePos; public GameObject bulletCase; public void Use() { if(type == Type.Melee) { StopCoroutine("Swing"); // 코루틴 정지 함수 (지금 동작중인) StartCoroutine("Swing"); // 코루틴 실행 함수 } else if (type == Type.Range && curAmmo > 0) { curAmmo--; StartCoroutine("Shot"); } } IEnumerator Swing() { // yield break; // yield break로 코루틴 탈출 가능 // 1번 구역 yield return new WaitForSeconds(0.1f); // 0.1 초 대기 (return null -> 1 프레임 대기) meleeArea.enabled = true; trailEffect.enabled = true; // 2번 구역 yield return new WaitForSeconds(0.6f); // 0.3 초 대기 meleeArea.enabled = false; // 3번 구역 yield return new WaitForSeconds(0.6f); trailEffect.enabled = false; } IEnumerator Shot() { // #1 총알 발사 GameObject intantBullet = Instantiate(bullet, bulletPos.position, bulletPos.rotation); Rigidbody bulletRigid = intantBullet.GetComponent<Rigidbody>(); bulletRigid.velocity = bulletPos.forward * 50; yield return null; // #2 탄피 배출 GameObject intantCase = Instantiate(bulletCase, bulletCasePos.position, bulletCasePos.rotation); Rigidbody caseRigid = intantCase.GetComponent<Rigidbody>(); Vector3 caseVec = bulletCasePos.forward * Random.Range(-3, -2) + Vector3.up * Random.Range(2, 3); caseRigid.AddForce(caseVec, ForceMode.Impulse); caseRigid.AddTorque(Vector3.up * 10, ForceMode.Impulse); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerFire : MonoBehaviour { private Light light; private ParticleSystem particlesystem; private LineRenderer lineRenderer; private AudioSource As; private float Attack = 5; private float AttackTime = 0.1f; private float timer = 1; // Use this for initialization void Start() { light = GetComponent<Light>(); particlesystem = GetComponentInChildren<ParticleSystem>(); lineRenderer = GetComponent<LineRenderer>(); As = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { timer += Time.deltaTime; if (Input.GetMouseButton(0)|| Input.GetMouseButtonDown(1)) { if (timer > AttackTime) { timer = 0; shoot(); } } } void shoot() { As.Play(); light.enabled = true; particlesystem.Play(); lineRenderer.enabled = true; lineRenderer.SetPosition(0,transform.position); Ray ray = new Ray(transform.position, transform.forward); RaycastHit raycastHit; //如果碰到东西,在raycastHit这个点上结束 if (Physics.Raycast(ray, out raycastHit)) { if (raycastHit.collider.tag == "Toy") { raycastHit.collider.GetComponent<ToyHealth>().Takedamage(Attack); } lineRenderer.SetPosition(1, raycastHit.point); } else { lineRenderer.SetPosition(1, transform.position + transform.forward * 100); } Invoke("ClearEffect",0.05f); } void ClearEffect() { light.enabled = false; lineRenderer.enabled = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using transport.Data; using transport.Models.ApplicationModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using transport.Models; namespace transport.Controllers { public class NaczepasController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly ApplicationDbContext _context; public NaczepasController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext context) { _userManager = userManager; _signInManager = signInManager; _context = context; } // GET: Naczepas [Authorize(Roles = "Firma, Admin, Spedytor")] public async Task<IActionResult> Index() { var currentuser = await _userManager.GetUserAsync(HttpContext.User); var firma = _context.Firmy.FirstOrDefault(f => f.UserId == currentuser.Id); if (firma != null) { var naczepy = _context.Naczepy.Where(p => p.IdFirma == firma.IdFirma); return View(await naczepy.ToListAsync()); //return View(firma.Pracownicy.ToList()); } else { return View(await _context.Naczepy.ToListAsync()); } // var applicationDbContext = _context.Naczepy.Include(n => n.Pracownik); // return View(await applicationDbContext.ToListAsync()); } // GET: Naczepas [Authorize(Roles = "Firma, Admin, Spedytor")] public async Task<IActionResult> IndexSpedytor() { var currentuser = await _userManager.GetUserAsync(HttpContext.User); var firma = _context.Pracownicy.FirstOrDefault(f => f.UserId == currentuser.Id); if (firma != null) { var naczepy = _context.Naczepy.Where(p => p.IdFirma == firma.FirmaId); return View(await naczepy.ToListAsync()); //return View(firma.Pracownicy.ToList()); } else { return View(await _context.Naczepy.ToListAsync()); } // var applicationDbContext = _context.Naczepy.Include(n => n.Pracownik); // return View(await applicationDbContext.ToListAsync()); } // GET: Naczepas [Authorize(Roles = "Kierowca")] public async Task<IActionResult> IndexKierowca() { var currentuser = await _userManager.GetUserAsync(HttpContext.User); var firma = _context.Pracownicy.FirstOrDefault(f => f.UserId == currentuser.Id); if (firma != null) { var naczepy = _context.Naczepy.Where(p => p.IdFirma == firma.FirmaId); return View(await naczepy.Where(p => p.IdPracownik == firma.PracownikId).ToListAsync()); //return View(firma.Pracownicy.ToList()); } else { return View(await _context.Naczepy.ToListAsync()); } // var applicationDbContext = _context.Naczepy.Include(n => n.Pracownik); // return View(await applicationDbContext.ToListAsync()); } // GET: Naczepas/Details/5 [Authorize(Roles = "Firma, Admin, Spedytor")] public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var naczepa = await _context.Naczepy .Include(n => n.Pracownik) .SingleOrDefaultAsync(m => m.IdNaczepa == id); if (naczepa == null) { return NotFound(); } return View(naczepa); } // GET: Naczepas/Create [Authorize(Roles = "Firma, Admin")] public IActionResult Create() { ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko}), "PracownikId", "FullName"); return View(); } // POST: Naczepas/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize(Roles = "Firma, Admin")] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("IdNaczepa,Firma,IdPracownik,Marka,Rodzaj,NrRejestr,DataProd,Wymiary,DataPrzegl,DataUbez,Wyposazenie,Aktywny")] Naczepa naczepa) { if (ModelState.IsValid) { var currentuser = await _userManager.GetUserAsync(HttpContext.User); var firma = _context.Firmy.FirstOrDefault(f => f.UserId == currentuser.Id); naczepa.Firma = firma; _context.Add(naczepa); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko}), "PracownikId", "FullName", null); return View(naczepa); } // GET: Naczepas/Create [Authorize(Roles = "Firma, Admin")] public IActionResult CreateAdmin() { ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko}), "PracownikId", "FullName"); return View(); } // POST: Naczepas/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize(Roles = "Firma, Admin")] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateAdmin([Bind("IdNaczepa,IdFirma,Pracownik,Marka,Rodzaj,NrRejestr,DataProd,Wymiary,DataPrzegl,DataUbez,Wyposazenie,Aktywny")] Naczepa naczepa) { if (ModelState.IsValid) { var currentuser = await _userManager.GetUserAsync(HttpContext.User); var firma = _context.Pracownicy.FirstOrDefault(f => f.UserId == currentuser.Id); naczepa.IdFirma = firma.FirmaId; naczepa.Pracownik = firma; _context.Add(naczepa); await _context.SaveChangesAsync(); return RedirectToAction("IndexSpedytor"); } ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko}), "PracownikId", "FullName", null); return View(naczepa); } // GET: Naczepas/Edit/5 [Authorize(Roles = "Firma, Admin")] public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var naczepa = await _context.Naczepy.SingleOrDefaultAsync(m => m.IdNaczepa == id); if (naczepa == null) { return NotFound(); } ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko }), "PracownikId", "FullName", null); return View(naczepa); } // POST: Naczepas/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize(Roles = "Firma, Admin")] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("IdNaczepa,Firma,IdPracownik,Marka,Rodzaj,NrRejestr,DataProd,Wymiary,DataPrzegl,DataUbez,Wyposazenie,Aktywny")] Naczepa naczepa) { var currentuser = await _userManager.GetUserAsync(HttpContext.User); var firma = _context.Firmy.FirstOrDefault(f => f.UserId == currentuser.Id); if (id != naczepa.IdNaczepa) { return NotFound(); } if (ModelState.IsValid) { try { naczepa.Firma = firma; _context.Update(naczepa); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NaczepaExists(naczepa.IdNaczepa)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko }), "PracownikId", "FullName", null); return View(naczepa); } // GET: Naczepas/Edit/5 [Authorize(Roles = "Firma, Admin")] public async Task<IActionResult> EditAdmin(int? id) { if (id == null) { return NotFound(); } var naczepa = await _context.Naczepy.SingleOrDefaultAsync(m => m.IdNaczepa == id); if (naczepa == null) { return NotFound(); } ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko }), "PracownikId", "FullName", null); return View(naczepa); } // POST: Naczepas/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize(Roles = "Firma, Admin")] [ValidateAntiForgeryToken] public async Task<IActionResult> EditAdmin(int id, [Bind("IdNaczepa,IdFirma,Pracownik,Marka,Rodzaj,NrRejestr,DataProd,Wymiary,DataPrzegl,DataUbez,Wyposazenie,Aktywny")] Naczepa naczepa) { var currentuser = await _userManager.GetUserAsync(HttpContext.User); var firma = _context.Pracownicy.FirstOrDefault(f => f.UserId == currentuser.Id); if (id != naczepa.IdNaczepa) { return NotFound(); } if (ModelState.IsValid) { try { naczepa.IdFirma = firma.FirmaId; naczepa.Pracownik = firma; _context.Update(naczepa); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NaczepaExists(naczepa.IdNaczepa)) { return NotFound(); } else { throw; } } return RedirectToAction("IndexSpedytor"); } ViewData["FullNamee"] = new SelectList((from s in _context.Pracownicy.ToList() select new { PracownikId = s.PracownikId, FullName = s.Imie + " " + s.Nazwisko }), "PracownikId", "FullName", null); return View(naczepa); } // GET: Naczepas/Delete/5 [Authorize(Roles = "Firma, Admin")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var naczepa = await _context.Naczepy .Include(n => n.Pracownik) .SingleOrDefaultAsync(m => m.IdNaczepa == id); if (naczepa == null) { return NotFound(); } return View(naczepa); } // POST: Naczepas/Delete/5 [HttpPost, ActionName("Delete")] [Authorize(Roles = "Firma, Admin")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var naczepa = await _context.Naczepy.SingleOrDefaultAsync(m => m.IdNaczepa == id); _context.Naczepy.Remove(naczepa); await _context.SaveChangesAsync(); if (User.IsInRole("Firma")) { return RedirectToAction("Index"); } else { return RedirectToAction("IndexSpedytor"); } } private bool NaczepaExists(int id) { return _context.Naczepy.Any(e => e.IdNaczepa == id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem4 : ProblemBase { public override string ProblemName { get { return "4: Largest palindrome product"; } } public override string GetAnswer() { return FindLargestPalindrome(3).ToString(); } private int FindLargestPalindrome(int digits) { int min = (int)Math.Pow(10, digits - 1); int max = (int)Math.Pow(10, digits) - 1; for (int num = max * max; num >= min * min; num--) { if (IsPalindrome(num.ToString())) { int subMax = (int)Math.Sqrt(num); for (int sub = min; sub <= subMax; sub++) { if (num % sub == 0 && num / sub >= min && num / sub <= max) return num; } } } return 0; } private bool IsPalindrome(string text) { for (int index = 0; index < text.Length / 2; index++) { if (text[index] != text[text.Length - index - 1]) return false; } return true; } } }
using DataAccesLayer; using DataAccesLayer.Repositorys; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ContentManagementSystem { public partial class AddCategory : System.Web.UI.Page { public List<Categories> catList; CategoriesRepository rep; protected void Page_Load(object sender, EventArgs e) { if (Request.Form["action"] == "save") { SaveToDb(); } rep = new CategoriesRepository(); catList = rep.List(); } private void SaveToDb() { rep = new CategoriesRepository(); Categories entity = new Categories(); entity.Type = Request.Form["CatName"].ToString(); rep.Add(entity); catList = rep.List(); } } }
using System; using com.Sconit.Entity.SYS; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; //TODO: Add other using statements here namespace com.Sconit.Entity.TMS { public partial class TransportBillMaster { #region Non O/R Mapping Properties [CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.BillStatus, ValueField = "Status")] [Display(Name = "TransportBillMaster_Status", ResourceType = typeof(Resources.TMS.TransportBillMaster))] public string StatusDescription { get; set; } public IList<TransportBillDetail> BillDetails { get; set; } public void AddBillDetail(TransportBillDetail billDetail) { if (this.BillDetails == null) { this.BillDetails = new List<TransportBillDetail>(); } this.BillDetails.Add(billDetail); } public void RemoveBillDetail(TransportBillDetail billDetail) { if (this.BillDetails != null) { this.BillDetails.Remove(billDetail); } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using Inventor; using Autodesk.DesignScript.Geometry; using Autodesk.DesignScript.Interfaces; using Autodesk.DesignScript.Runtime; using Dynamo.Models; using Dynamo.Utilities; using InventorLibrary.GeometryConversion; using InventorServices.Persistence; namespace InventorLibrary.API { [IsVisibleInDynamoLibrary(false)] public class InvInventorVBAProject { #region Internal properties internal Inventor.InventorVBAProject InternalInventorVBAProject { get; set; } //internal InvInventorVBAComponents InternalInventorVBAComponents //{ // get { return InvInventorVBAComponents.ByInvInventorVBAComponents(InventorVBAProjectInstance.InventorVBAComponents); } //} //internal InvApplication InternalParent //{ // get { return InvApplication.ByInvApplication(InventorVBAProjectInstance.Parent); } //} //internal InvVBAProjectTypeEnum InternalProjectType //{ // get { return InvVBAProjectTypeEnum.ByInvVBAProjectTypeEnum(InventorVBAProjectInstance.ProjectType); } //} internal bool InternalSaved { get { return InventorVBAProjectInstance.Saved; } } internal InvObjectTypeEnum InternalType { get { return InventorVBAProjectInstance.Type.As<InvObjectTypeEnum>(); } } internal Object InternalVBProject { get { return InventorVBAProjectInstance.VBProject; } } internal string InternalName { get; set; } #endregion //internal InventorVBAProject InternalkNoOwnership //{ // get { return Inventor.InventorVBAProject.kNoOwnership; } //} //internal InventorVBAProject InternalkSaveOwnership //{ // get { return Inventor.InventorVBAProject.kSaveOwnership; } //} //internal InventorVBAProject InternalkExclusiveOwnership //{ // get { return Inventor.InventorVBAProject.kExclusiveOwnership; } //} #region Private constructors private InvInventorVBAProject(InvInventorVBAProject invInventorVBAProject) { InternalInventorVBAProject = invInventorVBAProject.InternalInventorVBAProject; } private InvInventorVBAProject(Inventor.InventorVBAProject invInventorVBAProject) { InternalInventorVBAProject = invInventorVBAProject; } #endregion #region Private methods private void InternalClose() { InventorVBAProjectInstance.Close(); } private void InternalSave() { InventorVBAProjectInstance.Save(); } private void InternalSaveAs(string fullFileName) { InventorVBAProjectInstance.SaveAs( fullFileName); } #endregion #region Public properties public Inventor.InventorVBAProject InventorVBAProjectInstance { get { return InternalInventorVBAProject; } set { InternalInventorVBAProject = value; } } //public InvInventorVBAComponents InventorVBAComponents //{ // get { return InternalInventorVBAComponents; } //} //public InvApplication Parent //{ // get { return InternalParent; } //} //public InvVBAProjectTypeEnum ProjectType //{ // get { return InternalProjectType; } //} public bool Saved { get { return InternalSaved; } } public InvObjectTypeEnum Type { get { return InternalType; } } public Object VBProject { get { return InternalVBProject; } } public string Name { get { return InternalName; } set { InternalName = value; } } #endregion //public InventorVBAProject kNoOwnership //{ // get { return InternalkNoOwnership; } //} //public InventorVBAProject kSaveOwnership //{ // get { return InternalkSaveOwnership; } //} //public InventorVBAProject kExclusiveOwnership //{ // get { return InternalkExclusiveOwnership; } //} #region Public static constructors public static InvInventorVBAProject ByInvInventorVBAProject(InvInventorVBAProject invInventorVBAProject) { return new InvInventorVBAProject(invInventorVBAProject); } public static InvInventorVBAProject ByInvInventorVBAProject(Inventor.InventorVBAProject invInventorVBAProject) { return new InvInventorVBAProject(invInventorVBAProject); } #endregion #region Public methods public void Close() { InternalClose(); } public void Save() { InternalSave(); } public void SaveAs(string fullFileName) { InternalSaveAs( fullFileName); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WcfServiceHost { public interface IIsıNem { float Kat1_1Isı { get; set; } float Kat1_1Nem { get; set; } float Kat1_2Isı { get; set; } float Kat1_2Nem { get; set; } float Kat1_3Isı { get; set; } float Kat1_3Nem { get; set; } float Kat1_4Isı { get; set; } float Kat1_4Nem { get; set; } float Kat1_5Isı { get; set; } float Kat1_5Nem { get; set; } float Kat2_1Isı { get; set; } float Kat2_1Nem { get; set; } float Kat2_2Isı { get; set; } float Kat2_2Nem { get; set; } float Kat2_3Isı { get; set; } float Kat2_3Nem { get; set; } float Kat2_4Isı { get; set; } float Kat2_4Nem { get; set; } float Kat3_1Isı { get; set; } float Kat3_1Nem { get; set; } } }
using System; using System.Collections.Generic; using DAL.Models; namespace DAL.Contracts { public interface IGenreRepository : IBaseRepository<Genre> { } }
public class Solution { public bool SearchMatrix(int[,] matrix, int target) { int m = matrix.GetLength(0); int n = matrix.GetLength(1); if (m == 0 || n == 0) return false; if (matrix[0,0] > target || matrix[m-1,n-1] < target) return false; int x = m-1, y = 0; while (true) { if (matrix[x,y] == target) return true; else if (matrix[x,y] < target) y++; else x--; if (x < 0 || y >= n) return false; } return false; } }
using System; using System.Data; using System.Text; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Hosting; using netbu.Models; using System.IO; using System.Net; using System.Threading.Tasks; using System.Diagnostics; using System.Data.SqlClient; using WpfBu.Models; namespace netbu.Controllers { public class CunoController : Controller { private IHostingEnvironment _env; public CunoController(IHostingEnvironment env) { _env = env; } private string savefile(string id, string format, string path, string dateformat, string pref) { try { if (string.IsNullOrEmpty(format)) format = "csv"; var F = new Finder(); F.Account = "malkin"; F.Mode = "csv"; F.start(id); char r = ';'; if (format != "csv") r = '\t'; string s = F.ExportCSV(r); string filename = pref + DateTime.Now.ToString(dateformat) + "." + format; string filepath = Program.AppConfig[path]; string ff = filepath + @"\" + filename; System.IO.File.WriteAllText(ff, s, Encoding.GetEncoding(1251)); return ff; } catch (Exception err) { var webRoot = _env.WebRootPath; var errorpath = webRoot + @"\..\netbu_error.log"; string mes = $"{err.Message}\r\n{err.StackTrace} - {DateTime.Now}\r\n\r\n"; System.IO.File.AppendAllText(errorpath, mes); return ""; } } private async void savefileAsync(string id, string format, string path, string dateformat, string pref) { await Task.Run(() => savefile(id, format, path, dateformat, pref)); } public string save(string id, string format, string path, string dateformat, string pref, string copy) { if (string.IsNullOrEmpty(copy)) { savefileAsync(id, format, path, dateformat, pref); return "OK"; } else { string ff = savefile(id, format, path, dateformat, pref); string res = $"copy {ff} {copy}\r\n del {ff}"; return res; } } //Private Project public IActionResult update(string cur, string mode) { string res = "OK"; try { String sql = "p_cuno_update_usd"; if (cur == "rur") sql = "p_cuno_update_rur"; SqlDataAdapter da = new SqlDataAdapter(sql, Program.AppConfig["mscns"]); da.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable head = new DataTable(); da.Fill(head); sql = "select * from v_cuno_file_usd"; if (cur == "rur") sql = "select * from v_cuno_file_rur"; da = new SqlDataAdapter(sql, Program.AppConfig["mscns"]); DataTable body = new DataTable(); da.Fill(body); StringBuilder sb = new StringBuilder(); for (int i = 0; i < body.Rows.Count; i++) { string txtRow = body.Rows[i][0].ToString(); for (int j = 1; j < body.Columns.Count; j++) { txtRow = txtRow + ";" + body.Rows[i][j].ToString(); } sb.AppendLine(txtRow); } string resFile = sb.ToString(); if (mode == "show") { res = resFile; return Content(res); } else if (mode=="file") { byte[] buf = Encoding.GetEncoding(1251).GetBytes(resFile); string fname = ((DateTime)head.Rows[0][0]).ToString("UTG_yyyyMMddHHmmss") + ".txt"; string ctype = "application/octet-stream"; return File(buf, ctype, fname); } else { string path = Program.AppConfig["cuno_usd_files"] + @"\"; if (cur == "rur") path = Program.AppConfig["cuno_rur_files"] + @"\"; path = path + ((DateTime)head.Rows[0][0]).ToString("UTG_yyyyMMddHHmmss") + ".txt"; System.IO.File.WriteAllText(path, resFile, Encoding.GetEncoding(1251)); return Content(res); } } catch (Exception e) { res = "error:" + e.Message; return Content(res); } } public IActionResult update2(string cur, string mode) { string res = "OK"; try { String sql = "p_cuno_update_usd"; if (cur == "rur") sql = "p_cuno_update_rur"; SqlDataAdapter da = new SqlDataAdapter(sql, Program.AppConfig["mscns"]); da.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable head = new DataTable(); da.Fill(head); sql = "select * from v_cuno_file_usd2"; if (cur == "rur") sql = "select * from v_cuno_file_rur2"; da = new SqlDataAdapter(sql, Program.AppConfig["mscns"]); DataTable body = new DataTable(); da.Fill(body); StringBuilder sb = new StringBuilder(); for (int i = 0; i < body.Rows.Count; i++) { string txtRow = body.Rows[i][0].ToString(); for (int j = 1; j < body.Columns.Count; j++) { txtRow = txtRow + ";" + body.Rows[i][j].ToString(); } sb.AppendLine(txtRow); } string resFile = sb.ToString(); if (mode == "show") { res = resFile; return Content(res); } else if (mode=="file") { byte[] buf = Encoding.GetEncoding(1251).GetBytes(resFile); string fname = ((DateTime)head.Rows[0][0]).ToString("UTV_yyyyMMddHHmmss") + ".txt"; string ctype = "application/octet-stream"; return File(buf, ctype, fname); } else { string path = Program.AppConfig["cuno_usd_files2"] + @"\"; if (cur == "rur") path = Program.AppConfig["cuno_rur_files2"] + @"\"; path = path + ((DateTime)head.Rows[0][0]).ToString("UTV_yyyyMMddHHmmss") + ".txt"; System.IO.File.WriteAllText(path, resFile, Encoding.GetEncoding(1251)); return Content(res); } } catch (Exception e) { res = "error:" + e.Message; return Content(res); } } } }
using Android.Content; using Android.Preferences; using Android.Runtime; using Android.Util; using System; namespace aairvid.Settings { public class EditTextPreferenceShowSummary : EditTextPreference { public EditTextPreferenceShowSummary(Context context, IAttributeSet attrs) : base(context, attrs) { Init(); } public EditTextPreferenceShowSummary(Context context) : base(context) { Init(); } protected EditTextPreferenceShowSummary(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } private void Init() { this.PreferenceChange += EditTextPreferenceShowSummary_PreferenceChange; } void EditTextPreferenceShowSummary_PreferenceChange(object sender, Preference.PreferenceChangeEventArgs e) { SummaryFormatted = new Java.Lang.String(e.NewValue.ToString()); } private Java.Lang.ICharSequence _summary; public override Java.Lang.ICharSequence SummaryFormatted { get { if (_summary == null) { if (base.Text != null) { _summary = new Java.Lang.String(base.Text); } } return _summary; } set { _summary = value; base.SummaryFormatted = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fajlkezelesStringToInt { class Program { static void Main(string[] args) { string adat = "asdf5iu4535kjh24klh21m9"; bool szam; int n; char[] meh; Console.WriteLine("Eredeti string: " + adat); StringBuilder adatsb = new StringBuilder(adat); for (int i = 0; i < adatsb.Length; i++) { szam = int.TryParse(adatsb[i].ToString(), out n); if (szam) { n++; meh = n.ToString().ToCharArray(); adatsb[i] = meh[0]; } } adat = adatsb.ToString(); Console.WriteLine("Módosított string: " + adat); Console.ReadKey(); } } }
using TrainingWheels.Data; using TrainingWheels.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Security; namespace TrainingWheels.Services { public class ManageUsers { public ManageUsers() { } public IEnumerable<UsersListItem> GetUsers() { using(var context = new ApplicationDbContext()) { var query = context.Users.Select( e => new UsersListItem { UserId = e.Id, Email = e.Email, UserName = e.UserName } ); return query.ToArray(); } } } }
using System; using System.Linq; using MonoTouch.UIKit; namespace Screenmedia.IFTTT.JazzHands { public class AlphaAnimation : Animation { public AlphaAnimation(UIView view) : base(view) { } public override void Animate(int time) { if (KeyFrames.Count() <= 1) return; AnimationFrame animationFrame = AnimationFrameForTime(time); View.Alpha = animationFrame.Alpha; } public override AnimationFrame FrameForTime(int time, AnimationKeyFrame startKeyFrame, AnimationKeyFrame endKeyFrame) { AnimationFrame animationFrame = new AnimationFrame (); animationFrame.Alpha = TweenValueForStartTime (startKeyFrame.Time, endKeyFrame.Time, startKeyFrame.Alpha, endKeyFrame.Alpha, time); return animationFrame; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Explosive : MonoBehaviour { public float radius = 5.0F; public float power = 10.0F; void Start() { Vector3 explosionPos = transform.position; Collider2D[] colliders = Physics2D.OverlapCircleAll(explosionPos, radius); foreach (Collider2D hit in colliders) { Rigidbody2D rb = hit.GetComponent<Rigidbody2D>(); Vector2 a = explosionPos - hit.transform.position; if (rb != null) { rb.AddForce(-a * 10, ForceMode2D.Impulse); } } } }
using Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General; using Pe.Stracon.Politicas.Presentacion.Core.Controllers.Base; using Pe.Stracon.Politicas.Presentacion.Core.ViewModel.General.PlantillaNotificacion; using System.Web.Mvc; using System.Linq; using Pe.GyM.Security.Web.Session; using Pe.Stracon.PoliticasCross.Core.Util; namespace Pe.Stracon.Politicas.Presentacion.Core.Controllers.General { /// <summary> /// Controlador de Plantilla de Notificación /// </summary> public class PlantillaNotificacionController : GenericController { #region Parámetros public IPlantillaNotificacionService plantillaNotificacion { get; set; } #endregion #region Vistas /// <summary> /// Muestra la vista principal /// </summary> /// <returns>Vista Principal de la opción</returns> public ActionResult Index() { PlantillaNotificacionModel PlantillaNotif = new PlantillaNotificacionModel(); PlantillaNotif.ControlPermisos = Utilitario.ObtenerControlPermisos(HttpGyMSessionContext.CurrentAccount(), "General/PlantillaNotificacion/"); return View(PlantillaNotif); } #endregion #region Vistas Parciales /// <summary> /// Muestra la vista del Formulario Plantilla Notificacion /// </summary> /// <param name="codigoPlantillaNotificacion">CÓdigo Plantilla Notificacion</param> /// <returns>Vista de Formulario Plantilla Notificacion</returns> public ActionResult FormularioPlantillaNotificacion(string codigoPlantillaNotificacion) { var resultadoPlantillaNotificacion = plantillaNotificacion.BuscarPlantillaNotificacion(new PlantillaNotificacionRequest(){ CodigoPlantillaNotificacion = codigoPlantillaNotificacion }); var PlantillaNotificacion = resultadoPlantillaNotificacion.Result.FirstOrDefault(); var modelo = new PlantillaNotificacionFormulario(PlantillaNotificacion); return PartialView(modelo); } #endregion #region Json /// <summary> /// Realiza la busqueda de Plantilla Notificación /// </summary> /// <param name="filtro">Parametros a buscar</param> /// <returns>Lista de Plantillas de Notificación</returns> public JsonResult BuscarBandejaPlantillaNotificacion(PlantillaNotificacionRequest filtro) { var cuenta = HttpGyMSessionContext.CurrentAccount(); if (cuenta != null) { filtro.CodigoSistema = cuenta.CodigoSistema; } filtro.IndicadorActiva = string.IsNullOrEmpty(filtro.IndicadorActivaFiltro) ? (bool?)null : filtro.IndicadorActivaFiltro.Equals("1"); var resultado = plantillaNotificacion.BuscarPlantillaNotificacion(filtro); return Json(resultado); } /// <summary> /// Método que registra plantillas de notificación /// </summary> /// <param name="data">Información de la plantilla</param> /// <returns>Resultado de operación</returns> public JsonResult RegistraPlantillaNotificacion(PlantillaNotificacionRequest data) { if (string.IsNullOrEmpty(data.CodigoSistema)) { var cuenta = HttpGyMSessionContext.CurrentAccount(); if (cuenta != null) { data.CodigoSistema = cuenta.CodigoSistema; } } var resultado = plantillaNotificacion.RegistrarPlantillaNotificacion(data); return Json(resultado); } #endregion } }
using Domain.Common; using Domain.Enums; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Application.APIs { public interface IImageApi { Task<Result<Stream>> Get(ImageFilters? filter); } }
using StardewValley.Menus; using System; namespace ServerBookmarker { class CoopMenuPerformHoverListener : Patch { public static event Action<CoopMenu, int, int> PerformHover; protected override PatchDescriptor GetPatchDescriptor() => new PatchDescriptor(typeof(CoopMenu), "performHoverAction"); public static bool Prefix(int x, int y, CoopMenu __instance) { PerformHover?.Invoke(__instance, x, y); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xlns.BusBook.Core.DAL; using Xlns.BusBook.ConfigurationManager; namespace Xlns.BusBook.Core.Repository { public class AllegatoRepository : CommonRepository { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); public Model.Allegato GetAllegatoWithFileById(int id) { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var allegato = base.getDomainObjectById<Model.Allegato>(id); HydrateAllegato(allegato); om.CommitOperation(); return allegato; } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Error {0}", null); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } } private void HydrateAllegato(Model.Allegato allegato) { allegato.RawFile = System.IO.File.ReadAllBytes(allegato.FullName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using alg; /* * tags: dfs, backtracking * Time(2^n), Space(n) * try insert any hand ball into each position. incorrect pruning: only try to insert the same hand ball */ namespace leetcode { public class Lc488_Zuma_Game { public int FindMinStep(string board, string hand) { var handcs = hand.ToCharArray(); Array.Sort(handcs); hand = new string(handcs); return Dfs(board, hand, new Dictionary<string, int>()); } int Dfs(string board, string hand, Dictionary<string, int> memo) { if (string.IsNullOrEmpty(board)) return 0; var key = board + "=" + hand; if (memo.ContainsKey(key)) return memo[key]; int min = int.MaxValue; for (int i = 0; i < board.Length; i++) { if (i > 0 && board[i - 1] == board[i]) continue; int idx = hand.IndexOf(board[i]); if (idx < 0) continue; var newHand = hand.Substring(0, idx) + hand.Substring(idx + 1); var newBoard = MergeBoard(board.Insert(i, board[i].ToString()), i); int r = Dfs(newBoard, newHand, memo); if (0 <= r && r < min) min = r; } return memo[key] = min == int.MaxValue ? -1 : 1 + min; } string MergeBoard(string board, int pos) { int n = board.Length; if (pos >= n) return board; int i = pos - 1, j = pos + 1; while (i >= 0 && board[i] == board[pos]) i--; while (j < n && board[j] == board[pos]) j++; if (j - i <= 3) return board; return MergeBoard(board.Substring(0, i + 1) + board.Substring(j), i + 1); } public void Test() { Console.WriteLine(FindMinStep("WRRBBW", "RB") == -1); Console.WriteLine(FindMinStep("WWRRBBWW", "WRBRW") == 2); Console.WriteLine(FindMinStep("G", "GGGGG") == 2); Console.WriteLine(FindMinStep("RBYYBBRRB", "YRBGB") == 3); } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Marketplaces.Entityes; namespace Infra.Mapeamentos { public class MappingMetaCategory : EntityTypeConfiguration<MetaCategory> { public MappingMetaCategory() { // Primary Key this.HasKey(t => t.ID); // Properties // Table & Column Mappings this.ToTable("MetaCategories"); this.Property(t => t.ID).HasColumnName("ID"); this.Property(t => t.CategoryID).HasColumnName("CategoryID"); this.Property(t => t.FieldID).HasColumnName("FieldID"); // Relationships this.HasRequired(t => t.Category) .WithMany(t => t.MetaCategories) .HasForeignKey(d => d.CategoryID).WillCascadeOnDelete(); this.HasRequired(t => t.MetaField) .WithMany(t => t.MetaCategories) .HasForeignKey(d => d.FieldID).WillCascadeOnDelete(); } } }
namespace PatternsCore.FrameWorkStyleFactory.AbstractFactory.AnotherIsolatedExample { public interface IWheels { int TireSize(); string Move(); } public class FerrariWheels : IWheels { public int TireSize() { return 21; } public string Move() { return "Moving fast and not economically"; } } public class PriusWheels : IWheels { public int TireSize() { return 15; } public string Move() { return "moving slowly and economically";} } }
namespace API { internal enum MoveCategory { IncorrectFormatError, PositionAlreadyFilledError, SameMoveAsPreviousMoveError, MoveIsValid } }
using System.Web.Mvc; namespace Hdeleon_MVCRolesPermisos { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); //Se agrega filtro para vallidar Session de Usuario filters.Add(new Filters.UserSession()); } } }
using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using Framework.Core.Common; using Tests.Pages.Oberon.Common; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using OpenQA.Selenium.Support.UI; namespace Tests.Pages.Oberon.Contribution { public class ContributionBase : DoublePane { public ContributionBase(Driver driver) : base(driver) { } #region Page Objects public IWebElement DesignationSelect { get { return _driver.FindElement(By.Id("DesignationId")); } } public IWebElement AmountInput { get { return _driver.FindElement(By.CssSelector("#Amount")); } } public IWebElement DateReceivedInput { get { return _driver.FindElement(By.CssSelector("#ReceivedOn")); } } public IWebElement ExpandAdditionalInformation { get { return _driver.FindElement(By.CssSelector(".fieldSetTitle.isExpandable")); } } public IWebElement CollapseAdditionalInformation { get { return _driver.FindElement(By.CssSelector(".fieldSetTitle.isCollapsable")); } } // Additional Reporting Options public IWebElement AdvancedReportingOptionsExpandHeader { get { return _driver.FindElement(By.XPath ("//div[@class='fieldSetTitle isExpandable']/following::h4[contains(text(), 'Advanced Reporting Options')]"), 0); } } public IWebElement AdvancedReportingOptionsCollapseHeader { get { return _driver.FindElement(By.XPath ("//div[@class='fieldSetTitle isCollapsable']/following::h4[contains(text(), 'Advanced Reporting Options')]"), 0); } } public By ReportOptionOverrideDefaultsRadioLocator = By.XPath("//label[contains( text(),'Override defaults and use my changes below.')]/preceding-sibling::input"); public IWebElement ReportOptionOverrideDefaultsRadio { get { return _driver.FindElement(ReportOptionOverrideDefaultsRadioLocator); } } public IWebElement ShowAllFieldsCheckbox { get { return _driver.FindElement(By.XPath("//label[contains( text(),'Show All Fields:')]/following::input[@type='checkbox']")); } } // Additional Disclosure Information public IWebElement LinkToContactFindLink { get { return _driver.FindElement(By.CssSelector("#ContactLinkFindAddButtons .ajaxLink.addLink")); } } public By LinkToContributionFindLinkLocator = By.CssSelector("#ContributionLinkFindAddButtons .ajaxLink.addLink"); public IWebElement LinkToContributionFindLink { get { return _driver.FindElement(LinkToContributionFindLinkLocator); } } public IWebElement LinkToDisbursementFindLink { get { return _driver.FindElement(By.CssSelector("#DisbursementLinkFindAddButtons .ajaxLink.addLink")); } } public IWebElement LinkToDebtFindLink { get { return _driver.FindElement(By.CssSelector("#DebtLinkFindAddButtons .ajaxLink.addLink")); } } public By ContributionLinkSummaryDivLocator = By.CssSelector("#ContributionLinkSummary"); public IWebElement ContributionLinkSummaryDiv { get { return _driver.FindElement(ContributionLinkSummaryDivLocator); } } public IWebElement BatchInput { get { return _driver.FindElement(By.CssSelector("#FinancialBatchName")); } } public IWebElement MethodSelect { get { return _driver.FindElement(By.CssSelector("#Method")); } } public IWebElement CheckDateInput { get { return _driver.FindElement(By.CssSelector("#CheckDate")); } } public IWebElement CheckNumberInput { get { return _driver.FindElement(By.CssSelector("#CheckNumber")); } } public IWebElement OnlineReferenceNumberInput { get { return _driver.FindElement(By.CssSelector("#OnlineReferenceNumber")); } } public IWebElement DepositDateInput { get { return _driver.FindElement(By.CssSelector("#DepositDate")); } } public IWebElement BankAccountIdSelect { get { return _driver.FindElement(By.CssSelector("#BankAccountId")); } } public IWebElement StatusRadio { get { return _driver.FindElement(By.CssSelector(".formField.hasRadiogroup")); } } public IWebElement PartnershipLLCCheckbox { get { return _driver.FindElement(By.XPath ("//label[contains(text(), 'Partnership/LLC Transaction?:')]/following-sibling::div/input[@type='checkbox']")); } } public IWebElement PartnershipLinks { get { return _driver.FindElement(By.Id("PartnershipLinks")); } } public IWebElement LinkedPartnerContributionHeader { get { return _driver.FindElement(By.XPath("//h2[text()='Linked Partner/LLC Member Contributions']")); } } public IWebElement AddLinkedPartnerContributionLink { get { return LinkedPartnerContributionHeader.FindElement(By.CssSelector(".ajaxLink.add")); } } public By FindLinkedPartnerContributionLinkLocator = By.CssSelector(".ajaxLink.addLink"); public IWebElement FindLinkedPartnerContributionLink { get { return _driver.FindElement(FindLinkedPartnerContributionLinkLocator); } } // for Org public IWebElement FindLinkToPartnershipContributionLink { get { return _driver.FindElement(By.CssSelector(".ajaxLink.addLink")); } } // for Ind public IWebElement LinkToPartnershipContributionLabel { get { return _driver.FindElement(By.CssSelector("label[for='LinkToPartnershipLLCContribution']")); } } // for Ind // Report Specific public IWebElement ReportSpecificHeaderCollapsed { get { return _driver.FindElement(By.CssSelector(".sectionSubTitle.reportSpecificFields.isExpandable")); } } public IWebElement ReportSpecificHeaderExpanded { get { return _driver.FindElement(By.CssSelector(".sectionSubTitle.reportSpecificFields.isCollapsable")); } } public IWebElement DisclosureSection { get { return _driver.FindElement(By.Id("DisclosureSection")); } } public IWebElement ReportSpecificFields { get { return _driver.FindElement(By.CssSelector(".blockInner.subsection.reportSpecificFields")); } } // Advanced Reproting public IWebElement AdvancedReportingHeaderCollapsed { get { return _driver.FindElement(By.CssSelector(".fieldSetTitle.isExpandable")); } } public IWebElement AdvancedReportingSection { get { return _driver.FindElement(By.CssSelector(".AdvancedReporting")); } } public IWebElement ContributionType { get { return _driver.FindElement(By.XPath ("//li[@class='formRow ContributionType ']/label[contains(text(), 'Contribution Type')]/following::div/select")); } } public IWebElement InkindCategory { get { return _driver.FindElement(By.XPath("//label[contains(text(), 'Inkind Category')]/following::div/select")); } } public IWebElement TransferType { get { return _driver.FindElement(By.XPath("//label[contains(text(), 'Transfer Type')]/following::div/select")); } } public IWebElement LoanPurposeCode { get { return _driver.FindElement(By.XPath("//label[contains(text(), 'Loan Purpose Code')]/following::div/select")); } } public IWebElement Period { get { return _driver.FindElement(By.XPath("//label[contains(text(), 'Period')]/following::div/select")); } } public By CycleLocator = By.XPath("//label[contains(text(), 'Cycle')]/following::div/input[@type='text']"); public IWebElement Cycle { get { return _driver.FindElement(CycleLocator); } } public IWebElement StatusPendingRadio { get { return _driver.FindElement(By.XPath("//div[@class='formField hasRadiogroup']/span/input[@id='Status_0']")); } } public IWebElement StatusDepositedRadio { get { return _driver.FindElement(By.XPath("//div[@class='formField hasRadiogroup']/span/input[@id='Status_1']")); } } public IWebElement MemoMemoedRadio { get { return _driver.FindElement(By.XPath("//li[@class='formRow Memo ']/div/span/label[text()='Memoed']/preceding-sibling::input")); } } public IWebElement MemoNonMemoedRadio { get { return _driver.FindElement(By.XPath("//li[@class='formRow Memo ']/div/span/label[text()='Non-Memoed']/preceding-sibling::input")); } } public IWebElement InternalNoteTextArea { get { return _driver.FindElement(By.CssSelector("#InternalNote")); } } public IWebElement ScheduleLineNumber { get { return AdvancedReportingSection.FindElement(By.CssSelector("li.formRow.LineNumber div.formField select")); } } public IWebElement ThresholdFlag { get { return _driver.FindElement(By.XPath("//label[text()='Threshold Flag:']/following-sibling::div/select")); } } public IWebElement InternalOverrideNoteTextArea { get { return _driver.FindElement(By.XPath("//label[text()='Internal Override Note:']/following-sibling::div/textarea")); } } public IWebElement AggregateExclusionCheckBox { get { return _driver.FindElement(By.XPath ("//label[text()='Aggregate Exclusion:']/following-sibling::div/input[@type='checkbox']")); } } public IWebElement DueDateOfLoanInput { get { return _driver.FindElement(By.XPath ("//label[text()='Due Date of Loan:']/following-sibling::div/input[@class='noRange hasDatePicker hasDatepicker wm']")); } } public IWebElement InterestRateTextField { get { return _driver.FindElement( By.XPath("//label[text()='Interest Rate:']/following-sibling::div/input[@type='text']")); } } public IWebElement DebtRepaymentCheckBox { get { return _driver.FindElement(By.XPath("//label[text()='Debt Repayment?:']/following-sibling::div/input[@type='checkbox']")); } } public IWebElement SuccessMessageDiv { get { return _driver.FindElement(By.CssSelector(".alert.infoMessageContainer.success")); } } #endregion #region Methods /// <summary> /// sets date received by date /// </summary> public void SetDateReceived(string date) { _driver.ClearAndTab(DateReceivedInput); _driver.SendKeys(DateReceivedInput, date); } /// <summary> /// sets amount input by amount /// </summary> public void SetAmount(string amount) { _driver.ClearAndTab(AmountInput); _driver.ClearAndSendKeys(AmountInput, amount); //_driver.SendKeys(AmountInput, amount); } public void SetContributionType(string type) { //ExpandReportSpecificSection(); _driver.SelectOptionByText(ContributionType, type); } public string GetSelectedContributionType() { //ExpandReportSpecificSection(); Thread.Sleep(500); // too fast for Chrome... return _driver.GetSelectOptionText(ContributionType); } public void SetinkindCategory(string type) { //ExpandReportSpecificSection(); _driver.SelectOptionByText(InkindCategory, type); } public string GetSelectedInkindCategory() { //ExpandReportSpecificSection(); return _driver.GetSelectOptionText(InkindCategory); } public void SetTransferType(string type) { //ExpandReportSpecificSection(); _driver.SelectOptionByText(TransferType, type); } public string GetSelectedTransferType() { //ExpandReportSpecificSection(); return _driver.GetSelectOptionText(TransferType); } public void SetLoanPurposeCode(string val) { _driver.SelectOptionByText(LoanPurposeCode, val); } public string GetSelectedLoanPurposeCode() { return _driver.GetSelectOptionText(LoanPurposeCode); } public void ExpandReportSpecificSection() { ExpandHeader(ReportSpecificHeaderCollapsed); } public void ExpandAdvancedReportingSection() { Thread.Sleep(500); // kept getting stale element errors in Chrome. this seems to fix it. if (_driver.FindElementByExplicitWait(By.ClassName("AdvancedReporting")).GetAttribute("style") == "display: none;") { ExpandHeader(AdvancedReportingHeaderCollapsed); ; } } public new void ExpandHeader(IWebElement header) { if (_driver.IsElementPresent(header)) { _driver.Click(header); } } public string GetScheduleLineNumberSelectedValue() { return _driver.GetSelectOptionText(ScheduleLineNumber); } public void SetThresholdFlag(string flag) { _driver.SelectOptionByText(ThresholdFlag, flag); } public string GetSelectedThresholdFlag() { return _driver.GetSelectOptionText(ThresholdFlag); } public void ClickAggregateExclusion() { _driver.Click(AggregateExclusionCheckBox); } public bool IsAggregateExclusionSelected() { if (AggregateExclusionCheckBox.Selected) { return true; } else return false; } public bool PartnershipLLCCheckboxExists() { return _driver.IsElementPresent(PartnershipLLCCheckbox); } public string GetPartnershipLLCLabel() { var partnerLabel = _driver.FindElement( By.XPath("//label[contains(text(), 'Partnership/LLC Transaction?:')]/following-sibling::div/label")); return partnerLabel.Text; } public void ClickLinkToContactLink() { _driver.Click(LinkToContactFindLink); } public void ClickLinkToContributionLink() { _driver.Click(LinkToContributionFindLink); } public void ClickLinkToDisbursementLink() { _driver.Click(LinkToDisbursementFindLink); } public void ClickLinkToDebtLink() { _driver.Click(LinkToDebtFindLink); } /// <summary> /// clicks delete link, clicks yes in modal /// </summary> public void ClickContributionDeleteLink() { _driver.Click(DeleteLink); var modal = new DeleteConfirmationModal(_driver); modal.ClickYes(); } public void ClickContributionCancelLink() { //_driver.Click(CancelLink); //_driver.FindElement(By.XPath("//a[@title='Cancel and return to previous page.']")).Click(); _driver.ScrollToBottomOfPage(); IWebElement element = _driver.FindElement(By.CssSelector("span.buttonGroup a.cancelLink.exclude-For-Dirty")); _driver.Click(element); } #endregion } }
namespace Pobs.Domain.QueryObjects { public class CommentNotificationToPush { public long NotificationId { get; set; } public string PushToken { get; set; } public int QuestionId { get; set; } public string QuestionText { get; set; } public int AnswerId { get; set; } public string AnswerText { get; set; } public long CommentId { get; set; } public string CommentText { get; set; } } }
using DefaultEcs; using HarmonyLib; using RealisticBleeding.Components; using ThunderRoad; using UnityEngine; namespace RealisticBleeding { public static class EffectRevealPatches { [HarmonyPatch(typeof(EffectInstance), "AddEffect")] public static class AddEffectPatch { public static CollisionInstance LastCollisionInstance { get; private set; } public static void Prefix(CollisionInstance collisionInstance) { if (collisionInstance != null) { LastCollisionInstance = collisionInstance; } } } [HarmonyPatch(typeof(EffectReveal), "Play")] public static class PlayPatch { public static EntitySet ActiveBleeders { get; set; } public static void Postfix(EffectReveal __instance) { if (!Options.allowGore) return; var collisionInstance = AddEffectPatch.LastCollisionInstance; if (collisionInstance == null) return; var ragdollPart = collisionInstance.damageStruct.hitRagdollPart; if (ragdollPart == null) return; var creature = ragdollPart.ragdoll.creature; var pressureIntensity = Catalog.GetCollisionStayRatio(collisionInstance.pressureRelativeVelocity.magnitude); var damageType = collisionInstance.damageStruct.damageType; if (damageType == DamageType.Unknown || damageType == DamageType.Energy) return; const float minBluntIntensity = 0.45f; const float minSlashIntensity = 0.01f; const float minPierceIntensity = 0.001f; var intensity = Mathf.Max(collisionInstance.intensity, pressureIntensity); var minIntensity = damageType == DamageType.Blunt ? minBluntIntensity : damageType == DamageType.Pierce ? minPierceIntensity : minSlashIntensity; if (intensity < minIntensity) return; if (damageType == DamageType.Blunt) { intensity *= 0.5f; } else if (damageType == DamageType.Pierce) { intensity *= 2.5f; } var multiplier = Mathf.Lerp(0.6f, 1.5f, Mathf.InverseLerp(minIntensity, 1, intensity)); var durationMultiplier = multiplier; var frequencyMultiplier = multiplier; var sizeMultiplier = multiplier; switch (ragdollPart.type) { case RagdollPart.Type.Neck: durationMultiplier *= 5; frequencyMultiplier *= 4f; sizeMultiplier *= 1.4f; break; case RagdollPart.Type.Head: durationMultiplier *= 2f; frequencyMultiplier *= 1.7f; sizeMultiplier *= 0.9f; break; case RagdollPart.Type.Torso: if (damageType != DamageType.Blunt) { durationMultiplier *= 2f; frequencyMultiplier *= 2f; } break; } Vector2 dimensions = new Vector2(0.01f, 0.01f); if (damageType == DamageType.Slash) { dimensions = new Vector2(0, Mathf.Lerp(0.06f, 0.12f, intensity)); } var position = __instance.transform.position; var rotation = __instance.transform.rotation; if (damageType == DamageType.Blunt && ragdollPart.type == RagdollPart.Type.Head) { if (EntryPoint.Configuration.NoseBleedsEnabled) { if (NoseBleed.TryGetNosePosition(creature, out var nosePosition)) { if (Vector3.Distance(nosePosition, position) < 0.1f) { NoseBleed.SpawnOnDelayed(creature, Random.Range(0.75f, 1.75f), 1, 1, 0.7f); return; } } if (collisionInstance.intensity > 0.5f) { NoseBleed.SpawnOnDelayed(creature, Random.Range(1f, 2), intensity, intensity, Mathf.Max(0.3f, intensity)); } } } if (EntryPoint.Configuration.MouthBleedsEnabled && damageType == DamageType.Pierce && ragdollPart.type == RagdollPart.Type.Torso) { if (intensity > 0.2f) { NoseBleed.SpawnOnDelayed(creature, Random.Range(2f, 4f), 0.2f, 0.1f, 0.7f); MouthBleed.SpawnOnDelayed(creature, Random.Range(2, 4f), 1, 1); } } if (!EntryPoint.Configuration.BleedingFromWoundsEnabled) return; foreach (var entity in ActiveBleeders.GetEntities()) { ref var activeBleeder = ref entity.Get<Bleeder>(); var sqrDistance = (activeBleeder.WorldPosition - position).sqrMagnitude; const float minDistance = 0.05f; if (sqrDistance < minDistance * minDistance) return; } var bleeder = SpawnBleeder(position, rotation, ragdollPart.transform, durationMultiplier, frequencyMultiplier, sizeMultiplier, dimensions); bleeder.Set(new DisposeWithCreature(creature)); } private static Entity SpawnBleeder(Vector3 position, Quaternion rotation, Transform parent, float durationMultiplier, float frequencyMultiplier, float sizeMultiplier, Vector2 dimensions) { return Bleeder.Spawn(parent, position, rotation, dimensions, frequencyMultiplier, sizeMultiplier, durationMultiplier); } } } }
using UnityEngine; using System.Collections; /* * Entity * Prepares the Networking and contains functionality to start/connect to a server */ public class NetEnvironment : MonoBehaviour { NetworkHelper networkHelper; //For "low-level" network tasks void Start () { Chat chat = GameObject.Find ("GUI").GetComponent<Chat>(); //For system- and debug messages //Initialize the networkHelper to perform lowlevel-commands (not really, but sounds good) networkHelper = (NetworkHelper)gameObject.AddComponent(typeof(NetworkHelper)); if (chat == null) { Debug.LogWarning ("Unable to find Chat. System messages will be Logged."); }else{ networkHelper.SetSystemMessageHandler ( chat.SystemMessage ); } networkHelper.SetNetworkingErrorHandler(NetworkingError); networkHelper.SetOnDisconnectedHandler(OnDisconnected); //networkHelper.SetOnLobbyJoinedHandler(OnLobbyJoined); //Start server or client, depending on how the lobby was entered StartupNetwork (); } void StartupNetwork(){ if(!Settings.UseUnityMasterServer){ MasterServer.ipAddress = Settings.MasterServerUrl; MasterServer.port = Settings.MasterServerPort; Network.natFacilitatorIP = Settings.MasterServerUrl; Network.natFacilitatorPort = 50005; //Settings.MasterServerPort; } if (ApplicationModel.lobbyEnteredAs == LobbyEnteredAs.PublicServer || ApplicationModel.lobbyEnteredAs == LobbyEnteredAs.PrivateServer) { networkHelper.StartServer( ApplicationModel.lobbyEnteredAs == LobbyEnteredAs.PrivateServer ); }else{ networkHelper.ConnectToServer(ApplicationModel.HostToUse); } } //Leaves the network immediately, and goes to the main menue public void ShutdownNetwork(){ networkHelper.Disconnect(); ApplicationModel.EnterMainMenue(); } //Is called, when a networking issue appears void NetworkingError(string errorMessage){ networkHelper.Disconnect(); ApplicationModel.EnterMainMenue("Networking Error \n"+errorMessage); } //Is called, if the connection got closed void OnDisconnected(string message){ ApplicationModel.EnterMainMenue(message); } }
using System.Collections.Generic; using System.Threading; namespace FxNet { public class IoThread : TSingleton<IoThread> { void ThrdFunc() { while (!m_bStop) { foreach (IFxClientSocket poSock in m_setDelSockets) { poSock.Disconnect(); m_setConnectSockets.Remove(poSock); } m_setDelSockets.Clear(); foreach (IFxClientSocket poSock in m_setConnectSockets) { if (poSock.IsConnected()) { poSock.Update(); } else { poSock.Disconnect(); } } lock(m_pLock) { foreach (IFxClientSocket poSock in m_setAddSockets) { poSock.AsynReceive(); m_setConnectSockets.Add(poSock); } m_setAddSockets.Clear(); } Thread.Sleep(1); } } public bool Start() { m_poThrdHandler.Start(); return true; } public void Stop() { m_bStop = true; } public bool Init() { m_pLock = new object(); m_setConnectSockets = new HashSet<IFxClientSocket>(); m_setAddSockets = new HashSet<IFxClientSocket>(); m_setDelSockets = new HashSet<IFxClientSocket>(); m_poThrdHandler = new Thread(new ThreadStart(this.ThrdFunc)); m_bStop = false; return true; } public void Uninit() { } /// <summary> /// 主线程执行 /// </summary> /// <param name="pSock"></param> public void AddConnectSocket(IFxClientSocket pSock) { lock(m_pLock) { m_setAddSockets.Add(pSock); } } /// <summary> /// 工作线程执行 /// </summary> /// <param name="pSock"></param> public void DelConnectSocket(IFxClientSocket pSock) { lock(m_pLock) { m_setDelSockets.Add(pSock); } } object m_pLock; Thread m_poThrdHandler; bool m_bStop; //存放连接指针 HashSet<IFxClientSocket> m_setConnectSockets; HashSet<IFxClientSocket> m_setAddSockets; HashSet<IFxClientSocket> m_setDelSockets; } }
using System; using System.Text.RegularExpressions; namespace useSOLIDin { class GameBoard { public String CodedLevelData { get; set; } public string LevelName { get; set; } public string LevelData { get; set; } public int LevelNo { get; set; } public IOutPut OutPut { get; set; } public INoReader NoReader { get; set; } public ICode Code { get; set; } public GameBoard(IOutPut outPut, INoReader noReader, ICode code) { OutPut = outPut; NoReader = noReader; Code = code; } public void PrintLevelName() => OutPut.Print(this.LevelName); public void PrintLevelData() { string pattern = @"[x|o]{5}"; MatchCollection matchCollection = Regex.Matches(LevelData, pattern); foreach (Match match in matchCollection) { OutPut.Print(match.Value); } } public void PrintCodedData() { string pattern = @"[x|o]{5}"; MatchCollection matchCollection = Regex.Matches(CodedLevelData, pattern); foreach (Match match in matchCollection) { OutPut.Print(match.Value); } } public void GetNoValue() { Console.WriteLine("Enter Level No: "); LevelNo = NoReader.No; } public void OnPublished(object source, EventArgs args) { PrintLevelData(); } public void CodeLevel() { Code.Code(this); } } }
using System; namespace Game { abstract class Item { public string Name { get; private set; } public Player Player { get; set; } public Room Room { get; private set; } public Item(string name) { Name = name; } public virtual void Drop(Room room) { if (Room != room) { if (Room != null) { Room.Items.Remove(this); } Room = room; if (Room != null) { Room.Items.Add(this); } } if (Player != null) { Player.Items.Remove(this); Player = null; } } public virtual void Take(Player player) { if (!player.Items.Contains(this)) { Drop(null); player.Items.Add(this); } } public abstract bool Use(Player player); } class MapToVillageKey : Item { private bool Taken { get; set; } public MapToVillageKey() : base("map") {} public override void Take(Player player) { base.Take(player); if (!Taken) { Console.WriteLine("The maps appears to be in a completely different language, but is appears to be of your surroundings. You looks futher and can make out where you are. There seems to be a waterfall up ahead through the cave that has an X on it."); Taken = true; } } public override bool Use(Player player) { return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _12.Null_Values_Arithmetic { class NullValueArithmetic { static void Main(string[] args) { string nonNum = null; int num1 = (int)(null+1); double num2 = (int)(null*1); Console.WriteLine(num1 + " " + num2); } } }
using System; using Automatonymous; namespace Meetup.Sagas.BackendCartService { public class ShoppingCart : SagaStateMachineInstance { public Guid CorrelationId { get; set; } public int CurrentState { get; set; } public string UserName { get; set; } public DateTime Created { get; set; } public DateTime Updated { get; set; } /// <summary> /// The expiration tag for the shopping cart, which is scheduled whenever /// the cart is updated /// </summary> public Guid? ExpirationId { get; set; } } }
using Mettes_Planteskole.Models.Linq; using Mettes_Planteskole.Models.UI; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Mettes_Planteskole { public partial class Vare : CustomPage { protected void Page_Load(object sender, EventArgs e) { LiteralTitle.Text = "<title>" + VareHelperClass.VareHelper.titleKategori(VareHelperClass.VareHelper.ReturnGetId()) + "</title>"; h2Title.InnerText = VareHelperClass.VareHelper.titleKategori(VareHelperClass.VareHelper.ReturnGetId()); int produkterId = Convert.ToInt32(VareHelperClass.VareHelper.ReturnGetId()); RepeaterVare.DataSource = db.produkters.Where(i => i.fk_kategoriid == VareHelperClass.VareHelper.ReturnGetId()).ToList(); RepeaterVare.DataBind(); //finder ud af om der findes noget med denne kategori... int indhold = db.produkters.Where(i => i.fk_kategoriid == VareHelperClass.VareHelper.ReturnGetId()).Count(); if(indhold == 0) { LabelError.Visible = true; LabelError.Text = "Der er desværre intet i denne kategori!"; } } } }
namespace entidad.inventario { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class INV_MEDIDA { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public INV_MEDIDA() { INV_PRODUCTO = new HashSet<INV_PRODUCTO>(); } [Key] public int INV_ID_MEDIDA { get; set; } [Required] public string INV_DETALLE_MEDIDA { get; set; } [Required] [StringLength(1)] public string INV_ESTADO { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<INV_PRODUCTO> INV_PRODUCTO { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NPC_FollowScript : MonoBehaviour { PointerClicker PClick; Transform ThisFleet; Vector3 ToPosition, ToPosToDist; Quaternion LookingToRotation; public float FleetSpeed, RotSpeed, Z_Ang; // Use this for initialization void Start () { PClick = GameObject.FindGameObjectWithTag ("CursorManager").GetComponent<PointerClicker> (); ThisFleet = this.transform; } // Update is called once per frame void Update () { ToPosition = PClick.CursorToWorld; //Debug.DrawRay (Vector3.zero, ToPosition, Color.green); MovingTo (); } void MovingTo(){ ToPosToDist = new Vector3(ToPosition.x,ToPosition.y,0.0f) - new Vector3(ThisFleet.position.x, ThisFleet.position.y, 0.0f); //creates angle in rads AngleUpdater(); ThisFleet.rotation = Quaternion.Slerp(ThisFleet.rotation,LookingToRotation, Time.deltaTime * RotSpeed); ThisFleet.transform.Translate (Vector3.up * FleetSpeed * Time.deltaTime, Space.Self); } void AngleUpdater(){ float angleRad = Mathf.Atan2 (ToPosToDist.y, ToPosToDist.x); //TheDrawRay //Debug.DrawRay (Vector3.zero, Quaternion.EulerAngles(0.0f,0.0f,angleRad)*Vector3.right*100.0f, Color.green); Z_Ang = angleRad * Mathf.Rad2Deg; if (Z_Ang < 0) { Z_Ang += 360; } //float angleDegrees LookingToRotation = Quaternion.Euler (0.0f, 0.0f, Z_Ang-90.0f); } }
using System.Linq; using System.Reflection; using AutoTests.Framework.Core.Exceptions; using AutoTests.Framework.Web.Attributes; namespace AutoTests.Framework.Web.Configurators { public class ElementLocatorConfigurator { private readonly ConfiguratorsDependencies dependencies; public ElementLocatorConfigurator(ConfiguratorsDependencies dependencies) { this.dependencies = dependencies; } public virtual void Configure(Element element, string locator) { var property = GetTargetProperty(element); property.SetValue(element, locator); } private PropertyInfo GetTargetProperty(Element element) { var property = FindLocatorProperty(element); CheckPropertyAttribute(element, property); CheckPropertyType(property); return property; } private PropertyInfo FindLocatorProperty(Element element) { return dependencies.PageObjectPropertiesProvider.GetAllProperties(element) .SingleOrDefault(x => x.GetCustomAttributes<FromLocatorAttribute>().Any()); } private void CheckPropertyAttribute(Element element, PropertyInfo property) { if (property == null) { throw new ClassConstraintException(element.GetType(), $"Element '{{0}}' should contains property with '{nameof(FromLocatorAttribute)}' attribute"); } } private void CheckPropertyType(PropertyInfo property) { if (property.PropertyType != typeof(string)) { throw new PropertyConstraintException(property, $"Property '{{0}}' should be string type"); } } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using TaxiService.Discount.DbContexts; using TaxiService.Discount.Models; namespace TaxiService.Discount.Repositories { public class CouponRepository : ICouponRepository { private readonly DiscountDbContext _discountDbContext; public CouponRepository(DiscountDbContext discountDbContext) { _discountDbContext = discountDbContext; } public async Task<Coupon> GetCouponByCode(string code) { return await _discountDbContext.Coupons.Where(c => c.Code == code).FirstOrDefaultAsync(); } public async Task<Coupon> GetCouponById(int couponId) { return await _discountDbContext.Coupons.Where(c => c.CouponId == couponId).FirstOrDefaultAsync(); } public async Task UseCoupon(int CouponId) { var couponToUpdate = await _discountDbContext.Coupons.Where(c => c.CouponId == CouponId).FirstOrDefaultAsync(); if (couponToUpdate == null) throw new Exception(); couponToUpdate.AlreadyUsed = true; await _discountDbContext.SaveChangesAsync(); } } }
using System; using System.Collections.Generic; using System.Text; namespace RoadSimLib { public interface ITile { int X { get; } int Y { get; } int Pattern { get; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Newtonsoft.Json; using System; using System.Reflection; using System.Threading.Tasks; namespace WebCore.CustomerActionResult { public class MyContentResultExecutor : IActionResultExecutor<MyContentResult> { private const string DefaultContentType = "text/plain; charset=utf-8"; private readonly IHttpResponseStreamWriterFactory _httpResponseStreamWriterFactory; public MyContentResultExecutor(IHttpResponseStreamWriterFactory httpResponseStreamWriterFactory) { _httpResponseStreamWriterFactory = httpResponseStreamWriterFactory; } public async Task ExecuteAsync(ActionContext context, MyContentResult result) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (result == null) { throw new ArgumentNullException(nameof(result)); } var response = context.HttpContext.Response; //ResponseContentTypeHelper.ResolveContentTypeAndEncoding( // null, // response.ContentType, // DefaultContentType, // out var resolvedContentType, // out var resolvedContentTypeEncoding); response.ContentType = response.ContentType ?? DefaultContentType; var defaultContentTypeEncoding = MediaType.GetEncoding(response.ContentType); if (result.Content != null) { string content = JsonConvert.SerializeObject(result.Content); response.ContentLength = defaultContentTypeEncoding.GetByteCount(content); using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, defaultContentTypeEncoding)) { await textWriter.WriteAsync(content); await textWriter.FlushAsync(); } } } } }
using System; namespace DesignPatterns.State.SystemPermissionExample { public class SystemProfile { public bool IsUnixPermissionRequired { get; set; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Nusstudios.Models; using Nusstudios.Common; namespace Nusstudios.Controllers { public class HomeController : Controller { [Route("{gb?}")] [Route("")] public IActionResult Index(bool? gb) { string val; return View(new HomeViewModel("Nusstudios", "https://nusstudios.com", true, false, false, false, false, false, false, gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val)))); } [Route("{controller}/{action}/{gb?}")] public IActionResult Blog(bool? gb) { string val; return View ( new ArticlesViewModel ( "Blog", "https://nusstudios.com/Home/Blog", false, true, false, false, false, false, false, gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? (bool)(gb = false) : (bool)(gb = bool.Parse(val))), new List<Article> { new Article("knuthmorrisspratt", (bool)gb ? "Knuth-Morris-Pratt algorithm" : "Knuth-Morris-Pratt algoritmus"), new Article("floydstortoiseandhare", (bool)gb ? "Floyd's tortoise and hare" : "Floyd teknős & nyúl algoritmusa"), new Article("mergesort", (bool)gb ? "Mergesort of Neummann János" : "Mergesort"), new Article("heapsort", (bool)gb ? "Heapsort of J.W.J Williams" : "Kupacrendezés"), new Article("dijkstra", (bool)gb ? "Dijkstra's shortest path" : "Dijkstra legrövidebb út kereső") }, new List<Article> { new Article("paradigms_brief_history", (bool)gb ? "History of programming paradigms" : "A programozási paradigmák története"), new Article("high_level_languages_behind_the_scenes", (bool)gb ? "High level languages: behind the scenes" : "Magas szintű nyelvek a kulisszák mögött") }, new List<Article> { new Article("transformers_game_configurations_low_level", (bool)gb ? "Transformers games INI/INT configurations low level" : "Transformeres játékok konfigurációi alacsony szinten"), new Article("youtube_ciphered_signatures", "Youtube ciphered signatures today"), new Article("graph_api_and_x_instagram_gis", "Graph API and X-Instagram-GIS") } ) ); } [Route("{controller}/{action}/{gb?}")] public IActionResult Projects(bool? gb) { string val; bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val)); return View( new ProjectsViewModel( isgb ? "Projects" : "Projektek", "https://nusstudios.com/Home/Projects", false, false, true, false, false, false, false, isgb, new List<Project> { new Project("nuss", "Nuss Youtube downloader"), new Project("nussdesktop_javafx", "Nuss Youtube downloader JavaFx"), new Project("nusstumblr", "Nusstmblr"), new Project("instarchiver", "Instagram archiver"), new Project("imagetopdfui", "Image to PDF UI"), new Project("gia", "Google Image Archiver") }, new List<Project> { new Project("cupmixer", "Cup Mixer") }, new List<Project> { new Project("torrentchk", "Torrentchk"), new Project("CPPO", "C++ object library"), new Project("pixie", "Pixie"), new Project("pixie_macos", "Pixie for macOS"), new Project("tfutilpp", "TF_games_Util++"), new Project("imgtopdf", "Image to PDF console"), new Project("stringmath", "StringMath library"), new Project("jcore", "JCore Library"), new Project("nusstudioscorecsharp", "Nusstudios.Core Library C#"), new Project("keylogger", "Key Logger"), new Project("lilcryptoc", "lilcryptoc"), new Project("lilcryptocpp", "lilcryptocpp"), new Project("swifflib", "SwiffLib"), new Project("hashcompare", "hashcompare"), new Project("equslvr", "equslvr") } ) ); } [Route("{controller}/{action}/{gb?}")] public IActionResult Reference(bool? gb) { string val; bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val)); return View(new HomeViewModel(isgb ? "Reference" : "Referenciáim", "https://nusstudios.com/Home/Reference", false, false, false, true, false, false, false, isgb)); } [Route("{controller}/{action}/{gb?}")] public IActionResult NussAPI(bool? gb) { string val; return View(new HomeViewModel("NussAPI", "https://nusstudios.com/Home/NussAPI", false, false, false, false, true, false, false, gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val)))); } /* public IActionResult PT4ZSB() { // ViewData["Message"] = "All Reference."; return View(); } */ [Route("{controller}/{action}/{gb?}")] public IActionResult Edu(bool? gb) { string val; bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val)); return View(new HomeViewModel(isgb ? "Private tutoring" : "Magántanítás", "https://nusstudios.com/Home/Edu", false, false, false, false, false, true, false, isgb)); } [Route("{controller}/{action}/{gb?}")] public IActionResult Contact(bool? gb) { string val; bool isgb = gb != null ? (bool)gb : ((val = Tools.GetCookieValue(Request, "gb")) == null ? false : bool.Parse(val)); return View(new HomeViewModel(isgb ? "Contact" : "Kapcsolat", "https://nusstudios.com/Home/Contact", false, false, false, false, false, false, true, isgb)); } } }
using University.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Configuration; using System.ComponentModel.DataAnnotations; namespace University.UI.Areas.Admin.Models { public class SubCategoryViewModel { string SubCategoryImagePath = WebConfigurationManager.AppSettings["SubCategoryImagePath"]; public Decimal Id { get; set; } // public Decimal CategoryId { get; set; } //[StringLength(50, ErrorMessage = "Do not enter more than 50 characters")] // [MaxLength(50)] public string Name { get; set; } public HttpPostedFileBase file { get; set; } public string ImageURL { get; set; } public string ImageALT { get; set; } public Nullable<bool> IsDeleted { get; set; } public Nullable<System.DateTime> CreatedDate { get; set; } public Nullable<Decimal> CreatedBy { get; set; } public Nullable<System.DateTime> DeletedDate { get; set; } public Nullable<Decimal> DeletedBy { get; set; } public Nullable<System.DateTime> UpdatedDate { get; set; } public Nullable<Decimal> UpdatedBy { get; set; } public virtual CategoryMaster CategoryMaster { get; set; } public string ImageFullPath { get { if (string.IsNullOrWhiteSpace(ImageURL)) { return null; } else { return SubCategoryImagePath.Replace("~", "") + ImageURL; } } } public Decimal AssocitedCustID { get; set; } } }
using System; using Android.App; using Android.Content; using Android.Gms.Maps; using Android.Gms.Maps.Model; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace Markers { [Activity(Label = "Markers", MainLauncher = true, Icon = "@drawable/icon", Theme = "@android:style/Theme.Holo.Light.DarkActionBar")] public class MainActivity : AbstractMapActivity, IOnMapReadyCallback { private bool needsInit = false; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource if (ReadyToGo()) { SetContentView(Resource.Layout.Main); MapFragment mapFrag = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map); if (bundle == null) { needsInit = true; } mapFrag.GetMapAsync(this); } } public void OnMapReady(GoogleMap map) { if (needsInit) { CameraUpdate center = CameraUpdateFactory.NewLatLng(new LatLng(40.76793169992044, -73.98180484771729)); CameraUpdate zoom = CameraUpdateFactory.ZoomTo(15); map.MoveCamera(center); map.AnimateCamera(zoom); } AddMarker(map, 40.748963847316034, -73.96807193756104, Resource.String.un, Resource.String.united_nations); AddMarker(map, 40.76866299974387, -73.98268461227417, Resource.String.lincoln_center, Resource.String.lincoln_center_snippet); AddMarker(map, 40.765136435316755, -73.97989511489868, Resource.String.carnegie_hall, Resource.String.practice_x3); AddMarker(map, 40.70686417491799, -74.01572942733765, Resource.String.downtown_club, Resource.String.heisman_trophy); } private void AddMarker(GoogleMap map, double lat, double lon, int title, int snippet) { MarkerOptions options = new MarkerOptions(); options.InvokePosition(new LatLng(lat, lon)); options.InvokeTitle(GetString(title)); options.InvokeSnippet(GetString(snippet)); map.AddMarker(options); } } }
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Zenworks.UI { [ContentProperty("SourceImage")] public class ImagePathExtension : IMarkupExtension<string?> { public string? Name { get; set; } public string? ProvideValue(IServiceProvider serviceProvider) { if (Name == null) { return null; } string imagePath; switch (Device.RuntimePlatform) { case Device.Android: imagePath = Name; break; case Device.iOS: imagePath = Name + ".png"; break; case Device.UWP: imagePath = "Icons/" + Name + ".png"; break; default: throw new PlatformNotSupportedException("Unsupported platform for loading images"); } return imagePath; } object? IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) { return ProvideValue(serviceProvider); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Windows_Project { public partial class Main : Form { public Main() { InitializeComponent(); } private void Main_Load(object sender, EventArgs e) { MessageBox.Show("Welcome"); } private void productsAndRelatedToolStripMenuItem_Click(object sender, EventArgs e) { } private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void usersToolStripMenuItem_Click(object sender, EventArgs e) { Users user = new Users(); user.WindowState = FormWindowState.Normal; user.StartPosition = FormStartPosition.CenterScreen; user.MdiParent = this; user.Show(); } private void suppliersToolStripMenuItem_Click(object sender, EventArgs e) { frmSuppliers supply = new frmSuppliers(); supply.WindowState = FormWindowState.Normal; supply.StartPosition = FormStartPosition.CenterScreen; supply.MdiParent = this; supply.Show(); } private void shippersToolStripMenuItem_Click(object sender, EventArgs e) { shippers ship = new shippers(); ship.WindowState = FormWindowState.Normal; ship.StartPosition = FormStartPosition.CenterScreen; ship.MdiParent = this; ship.Show(); } private void categoriesToolStripMenuItem_Click(object sender, EventArgs e) { Categories category = new Categories(); category.WindowState = FormWindowState.Normal; category.StartPosition = FormStartPosition.CenterScreen; category.MdiParent = this; category.Show(); } private void productsToolStripMenuItem_Click(object sender, EventArgs e) { Products product = new Products(); product.WindowState = FormWindowState.Normal; product.StartPosition = FormStartPosition.CenterScreen; product.MdiParent = this; product.Show(); } private void customersToolStripMenuItem_Click(object sender, EventArgs e) { Customers customer = new Customers(); customer.WindowState = FormWindowState.Normal; customer.StartPosition = FormStartPosition.CenterScreen; customer.MdiParent = this; customer.Show(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void toolStripButton1_Click(object sender, EventArgs e) { Users user = new Users(); user.WindowState = FormWindowState.Normal; user.StartPosition = FormStartPosition.CenterScreen; user.MdiParent = this; user.Show(); } private void toolStripButton2_Click(object sender, EventArgs e) { frmSuppliers supply = new frmSuppliers(); supply.WindowState = FormWindowState.Normal; supply.StartPosition = FormStartPosition.CenterScreen; supply.MdiParent = this; supply.Show(); } private void toolStripButton3_Click(object sender, EventArgs e) { shippers ship = new shippers(); ship.WindowState = FormWindowState.Normal; ship.StartPosition = FormStartPosition.CenterScreen; ship.MdiParent = this; ship.Show(); } private void toolStripButton4_Click(object sender, EventArgs e) { Categories category = new Categories(); category.WindowState = FormWindowState.Normal; category.StartPosition = FormStartPosition.CenterScreen; category.MdiParent = this; category.Show(); } private void toolStripButton5_Click(object sender, EventArgs e) { Products product = new Products(); product.WindowState = FormWindowState.Normal; product.StartPosition = FormStartPosition.CenterScreen; product.MdiParent = this; product.Show(); } private void toolStripButton6_Click(object sender, EventArgs e) { Customers customer = new Customers(); customer.WindowState = FormWindowState.Normal; customer.StartPosition = FormStartPosition.CenterScreen; customer.MdiParent = this; customer.Show(); } private void toolStripButton7_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections; using System.Globalization; using System.Reflection; using Phenix.Business; using Phenix.Core; using Phenix.Core.Cache; using Phenix.Core.Log; using Phenix.Core.Mapping; using Phenix.Core.Security; using Phenix.Services.Host.Core; namespace Phenix.Services.Host.Service { public sealed class DataPortal : MarshalByRefObject, Csla.Server.IDataPortalServer { #region 事件 //internal static event Action<DataSecurityEventArgs> DataSecurityChanged; //private static void OnDataSecurityChanged(DataSecurityEventArgs e) //{ // Action<DataSecurityEventArgs> action = DataSecurityChanged; // if (action != null) // action(e); //} #endregion #region 方法 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public Csla.Server.DataPortalResult Create(Type objectType, object criteria, Csla.Server.DataPortalContext context) { throw new NotSupportedException(MethodBase.GetCurrentMethod().Name); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public Csla.Server.DataPortalResult Fetch(Type objectType, object criteria, Csla.Server.DataPortalContext context) { ServiceManager.CheckIn(context.Principal); DataSecurityHub.CheckIn(objectType, ExecuteAction.Fetch, context.Principal); DateTime dt = DateTime.Now; Csla.Server.DataPortalResult result; DateTime? actionTime; object obj = ObjectCache.Find(objectType, criteria, out actionTime); if (obj != null) result = new Csla.Server.DataPortalResult(obj); else { Csla.Server.IDataPortalServer portal = new Csla.Server.DataPortal(); result = portal.Fetch(objectType, criteria, context); if (actionTime != null) ObjectCache.Add(criteria, result.ReturnObject, actionTime.Value); } //OnDataSecurityChanged(new DataSecurityEventArgs(context.Principal.Identity.Name)); //跟踪日志 if (AppConfig.Debugging) { int count = result.ReturnObject is IList ? ((IList)result.ReturnObject).Count : result.ReturnObject != null ? 1 : 0; Criterions criterions = criteria as Criterions; EventLog.SaveLocal(MethodBase.GetCurrentMethod().Name + ' ' + objectType.FullName + (criterions != null && criterions.Criteria != null ? " with " + criterions.Criteria.GetType().FullName : String.Empty) + " take " + DateTime.Now.Subtract(dt).TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + " millisecond," + " count = " + count); PerformanceAnalyse.Default.CheckFetchMaxCount(objectType.FullName, count, context.Principal); PerformanceAnalyse.Default.CheckFetchMaxElapsedTime(objectType.FullName, DateTime.Now.Subtract(dt).TotalSeconds, count, context.Principal); } return result; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public Csla.Server.DataPortalResult Update(object obj, Csla.Server.DataPortalContext context) { ServiceManager.CheckIn(context.Principal); DataSecurityHub.CheckIn(obj.GetType(), ExecuteAction.Update, context.Principal); DateTime dt = DateTime.Now; Csla.Server.IDataPortalServer portal = new Csla.Server.DataPortal(); //OnDataSecurityChanged(new DataSecurityEventArgs(context.Principal.Identity.Name)); Csla.Server.DataPortalResult result = portal.Update(obj, context); //跟踪日志 if (AppConfig.Debugging) PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(obj.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, obj is IList ? ((IList)obj).Count : 1, context.Principal); if (result.ReturnObject is Csla.Core.ICommandObject) return result; IBusiness business = result.ReturnObject as IBusiness; if (business != null && business.NeedRefresh) return result; return new Csla.Server.DataPortalResult(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public Csla.Server.DataPortalResult Delete(Type objectType, object criteria, Csla.Server.DataPortalContext context) { ServiceManager.CheckIn(context.Principal); DataSecurityHub.CheckIn(objectType, ExecuteAction.Delete, context.Principal); DateTime dt = DateTime.Now; Csla.Server.IDataPortalServer portal = new Csla.Server.DataPortal(); //OnDataSecurityChanged(new DataSecurityEventArgs(context.Principal.Identity.Name)); portal.Delete(objectType, criteria, context); //跟踪日志 if (AppConfig.Debugging) PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(objectType.FullName, DateTime.Now.Subtract(dt).TotalSeconds, -1, context.Principal); return new Csla.Server.DataPortalResult(); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace EQS.AccessControl.Application.ViewModels.Input { public class PersonInput { [Key] public int Id { get; set; } [Required(ErrorMessage = "Name is required")] public string Name { get; set; } public CredentialInput Credential { get; set; } public ICollection<int> Roles { get; set; } } }
using System; using System.Configuration; using System.Globalization; namespace Merchello.UkFest.Web { public static class AppSettings { #region App Settings public static object CropBackgroundColour { get { return Setting<string>("CropBackgroundColour"); } } #endregion #region Generic getter private static T Setting<T>(string name) { string value = ConfigurationManager.AppSettings[name]; if (value == null) { throw new Exception(String.Format("Could not find setting '{0}',", name)); } return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Uintra.Features.UserList.Models; namespace Uintra.Attributes { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] public class UIColumnAttribute : Attribute { public int Id { get; set; } public string Alias { get; set; } public string DisplayName { get; set; } public ColumnType Type { get; set; } public string PropertyName { get; set; } public bool SupportSorting { get; set; } public UIColumnAttribute(int order, string backofficeDisplayName, string propertyName, ColumnType type, bool supportSorting = false, string alias = null) { Id = order; DisplayName = backofficeDisplayName; Type = type; PropertyName = propertyName; SupportSorting = supportSorting; Alias = alias ?? DisplayName?.Replace(" ", string.Empty); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class TimeSet : MonoBehaviour { // UnityEngine.UIを読み込んでいるからPublic Textが許されるっっっっ public Text timeGUI; // シンキングタイムの制限時間 public float SetTime = 60.0f; // Use this for initialization void Start () { timeGUI.text = SetTime.ToString (); } // Update is called once per frame void Update () { // 時間を毎秒1ずつ減らし、UGUIに表示 SetTime -= -1.0f * Time.deltaTime; timeGUI.text = ((int)SetTime).ToString (); } }
using System.Linq; using System.Windows; using System.Windows.Controls; namespace Crystal.Plot2D.Charts { /// <summary> /// Represents a menu that appears in Debug version of Crystal.Plot2D. /// </summary> public class DebugMenu : IPlotterElement { /// <summary> /// Initializes a new instance of the <see cref="DebugMenu"/> class. /// </summary> public DebugMenu() { Panel.SetZIndex(Menu, 1); } public Menu Menu { get; } = new Menu { HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(3) }; public MenuItem TryFindMenuItem(string itemName) { return Menu.Items.OfType<MenuItem>().FirstOrDefault(item => item.Header.ToString() == itemName); } #region IPlotterElement Members public void OnPlotterAttached(PlotterBase plotter) { Plotter = plotter; plotter.CentralGrid.Children.Add(Menu); } public void OnPlotterDetaching(PlotterBase plotter) { plotter.CentralGrid.Children.Remove(Menu); Plotter = null; } public PlotterBase Plotter { get; private set; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Olive.Data; namespace Olive.Web.MVC.Areas.Administration.ViewModels { public class UnitsIndexViewModel { public IEnumerable<Unit> AllUnits{ get; set; } public Unit NewUnit { get; set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /** * @author Chris Foulston */ namespace Malee.Hive.Util.Display { public class Graphics { public enum DrawMode { Gizmos, Debug, GL } public DrawMode drawMode = DrawMode.Debug; public float duration = 0.0f; public bool draw2d = false; private int pen; private List<GraphicsCommand> commands; public Graphics() { commands = new List<GraphicsCommand>(); pen = 0; } public Color color { get { return Gizmos.color; } set { Gizmos.color = value; } } private GraphicsObject _graphicsObject; public GraphicsObject graphicsObject { get { if (_graphicsObject == null) { if (Camera.main == null) { _graphicsObject = new GameObject("GraphicsObject", typeof(GraphicsObject), typeof(Camera)).GetComponent<GraphicsObject>(); } else { _graphicsObject = Camera.main.gameObject.AddComponent<GraphicsObject>(); } } return _graphicsObject; } } public Vector3 penPosition { get { return commands[commands.Count - 1].v; } } public void Begin() { pen = 0; commands.Clear(); } public void MoveTo(Vector3 point) { commands.Add(new GraphicsCommand(GraphicCommand.Move, point)); } public void LineTo(Vector3 point) { if (commands.Count == 0) { MoveTo(Vector3.zero); } commands.Add(new GraphicsCommand(GraphicCommand.Line, point)); } public void End() { int len = commands.Count; GraphicsCommand curr; GraphicsCommand prev; for (; pen < len; pen++) { curr = commands[pen]; if (curr.type != GraphicCommand.Move) { prev = commands[pen - 1]; Vector3 v1 = prev.v; Vector3 v2 = curr.v; if (curr.type == GraphicCommand.Line) { switch (drawMode) { case DrawMode.Debug: DrawDebugLine(v1, v2); break; case DrawMode.Gizmos: DrawGizmosLine(v1, v2); break; case DrawMode.GL: DrawGLLine(v1, v2); break; } } } } } private void DrawGLLine(Vector3 v1, Vector3 v2) { if (duration > 0.0f) { graphicsObject.StartCoroutine(DelayGLLine(duration, v1, v2, draw2d)); } else { graphicsObject.GLLine(color, v1, v2, draw2d); } } private IEnumerator DelayGLLine(float duration, Vector3 v1, Vector3 v2, bool draw2d) { float st = Time.time; Color c = color; while (Time.time - st <= duration) { graphicsObject.GLLine(c, v1, v2, draw2d); yield return 0; } } private void DrawGizmosLine(Vector3 v1, Vector3 v2) { if (duration > 0.0f) { graphicsObject.StartCoroutine(DelayGizmosLine(duration, v1, v2)); } else { Gizmos.DrawLine(v1, v2); } } private IEnumerator DelayGizmosLine(float duration, Vector3 v1, Vector3 v2) { float st = Time.time; while (Time.time - st <= duration) { Gizmos.DrawLine(v1, v2); yield return 0; } } private void DrawDebugLine(Vector3 v1, Vector3 v2) { if (duration > 0.0f) { Debug.DrawLine(v1, v2, color, duration); } else { Debug.DrawLine(v1, v2, color); } } // // -- ENUMS -- // private enum GraphicCommand { Move, Line } // // -- STRUCTS -- // private struct GraphicsCommand { internal Vector3 v; internal GraphicCommand type; public GraphicsCommand(GraphicCommand type, Vector3 v) { this.v = v; this.type = type; } } } }
using System; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NHShareBack.Exceptions; using NHShareBack.Db; using Newtonsoft.Json; namespace NHShareBack { class Treatment { public static async Task Dispatch(HttpMessageEventArgs e) { await Task.Run(() => e.Request.HttpMethod switch { "GET" => GetCollection(e), "POST" => PostCollection(e), "PUT" => PutItem(e), "PATCH" => PatchItem(e), "DELETE" => DeleteItem(e), _ => UnsupportedException(e) }); } public static async Task GetCollection(HttpMessageEventArgs e) { string Author = e.Request.Cookies.GetCookie("Author"); if (await Globals.Db.GetCollectionAsync(Author) is not Collection coll) { await e.Response.SendHttpResponseAsync("Error: Either you've never uploaded, either there's a problem here"); return; } await e.Response.SendHttpResponseAsync($"Done: {coll.Name}"); } public static async Task PostCollection(HttpMessageEventArgs e) { try { JObject RequestData = await e.Request.GetRequestJObjectAsync(); User ToUploadUser = JsonConvert.DeserializeObject<User>($"{RequestData}"); if (await Globals.Db.InitUserAsync(ToUploadUser)) { await e.Response.SendHttpResponseAsync("Upload successeded"); } else { await e.Response.SendHttpResponseAsync("An error occured during the upload"); } } catch (Exception ex) when (ex is InvalidRequestJsonException) { await e.Response.SendHttpResponseAsync("Sent Json was invalid"); } } public static async Task PutItem(HttpMessageEventArgs e) { } public static async Task PatchItem(HttpMessageEventArgs e) { } public static async Task DeleteItem(HttpMessageEventArgs e) { } public static async Task UnsupportedException(HttpMessageEventArgs e) { } public static async Task GetAutorisations(HttpMessageEventArgs e) { } public static async Task UpdateAutorisations(HttpMessageEventArgs e) { } } }
//@Author Justin Scott Bieshaar. //For further questions please read comments or reach me via mail contact@justinbieshaar.com namespace Exam.Reference.Path{ public class ParticlePaths { /// <summary> /// Particle paths stored in ./Resources/ /// </summary> public static readonly string[] PARTICLES = { //initialize particle paths "Particles/Dash", "Particles/Dash", "Particles/Dash", "Particles/Dash", "Particles/Dash_Hit_Wall", "Particles/Walk", "Particles/Walk", "Particles/Walk", "Particles/Walk", "Particles/Stunned", "Particles/Stunned", "Particles/Stunned", "Particles/Stunned", "Particles/ObjectFinished", "Particles/ObjectVanished", "Particles/ObjectCreated", }; } } /// <summary> /// Particle type stored for reference and readability. /// </summary> public enum ParticleType { DASH = 0, DASH1 = 1, DASH2 = 2, DASH3 = 3, DASH_HIT_WALL = 4, WALK = 5, WALK1 = 6, WALK2 = 7, WALK3 = 8, STUNNED = 9, STUNNED1 = 10, STUNNED2 = 11, STUNNED3 = 12, OBJECT_FINISHED = 13, OBJECT_VANISHED = 14, OBJECT_CREATED = 15, }
using DamianTourBackend.Core.Entities; using FluentValidation; using System; using System.Linq; namespace DamianTourBackend.Application.RouteRegistration { public class RouteRegistrationValidator : AbstractValidator<RouteRegistrationDTO> { //private readonly string[] _sizes = new string[] { "s", "m", "l", "xl", "xxl" }; public RouteRegistrationValidator() { RuleFor(x => x.RouteId) .NotEmpty().WithMessage("Id cannot be null"); //RuleFor(x => x.OrderedShirt) // .NotEmpty().WithMessage("Must choose if you want a shirt"); RuleFor(x => x.ShirtSize) //.NotEmpty().WithMessage("Size of shirt cannot be empty") .Must(CheckSize) .MaximumLength(5).WithMessage("Size of shirt must be valid"); RuleFor(x => x.Privacy) //.NotEmpty().WithMessage("Size of privacy cannot be empty") .Must(CheckPrivacy) .MaximumLength(8).WithMessage("Size of privacy must be valid"); } private bool CheckSize(string shirtSize) { foreach (ShirtSize size in Enum.GetValues(typeof(ShirtSize))) if (shirtSize.ToLower().Equals(size.ToString().ToLower())) return true; return false; } private bool CheckPrivacy(string privacy) { foreach (Privacy enumPrivacy in Enum.GetValues(typeof(Privacy))) if (privacy.ToLower().Equals(enumPrivacy.ToString().ToLower())) return true; return false; } } }
using Client.Bussness; using Client.Helpers.Utils; using GalaSoft.MvvmLight; using System; using System.IO; using System.Windows; using System.Windows.Media.Imaging; using WPF.NewClientl.ViewModel; namespace WPF.NewClient.ViewModel { /// <summary> /// This class contains properties that a View can data bind to. /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public partial class WelcomeViewModel : ViewMeetingModelBase { private Window PageMainFrame = null; private Window PageNoteMain = null; private Window PageNoteMainTest = null; public string Password { get; set; } private string _errValidateMessage; public string ErrValidateMessage { get { return _errValidateMessage; } set { Set(ref _errValidateMessage, value); } } private Visibility _visible = Visibility.Visible; public Visibility Visible { get { return _visible; } set { Set(ref _visible, value); } } public BitmapImage SysLogoImage { get { Uri imageUi = new Uri("pack://application:,,,/Skins/Images/ui-logo.png", UriKind.Absolute); var fileName = string.Format(@"{0}\{1}", AppDomain.CurrentDomain.BaseDirectory, "SysMeetingLog.png"); if (File.Exists(fileName)) { return new BitmapImage(new Uri(fileName)); } return new BitmapImage(imageUi); } } private string _Name = string.Empty; public string Name { get { return _Name; } set { Set(ref _Name, value); } } private string _Department = string.Empty; public string Department { get { return _Department; } set { Set(ref _Department, value); } } private string _SiteNo = string.Empty; public string SiteNo { get { return _SiteNo; } set { Set(ref _SiteNo, value); } } private string _SystemName = string.Empty; public string SystemName { get { return _SystemName; } set { Set(ref _SystemName, value); } } private string _MeetingName = string.Empty; public string MeetingName { get { return _MeetingName; } set { Set(ref _MeetingName, value); } } public string CurrentTime { get { return new TimeInfo().TimeText; } } public string CurrentAmPm { get { return new TimeInfo().AmPmText; } } public string CurrentDate { get { return new TimeInfo().DateText; } } public string CurrentOldDate { get { var info = new TimeInfo(); return info.WeekText + " " + info.ChineseDate; } } /// <summary> /// Initializes a new instance of the WelcomeViewModel class. /// </summary> public WelcomeViewModel():base(AppClientContext.Context) { if(AppClientContext.Context!=null) { if (AppClientContext.Context.Meeting != null) { _MeetingName = AppClientContext.Context.Meeting.Name; _SystemName = AppClientContext.Context.SystemName; _SiteNo = AppClientContext.Context.Participant.SeatNo; _Name = AppClientContext.Context.Participant.Name; _Department = AppClientContext.Context.Participant.Department; } } } } }
using System; namespace com.Sconit.Entity.MD { public partial class SwitchTrading { } }
using System.Collections.Generic; using Alabo.Data.People.Users.Domain.Services; using Alabo.Domains.Entities; using Alabo.Domains.Query; using Alabo.Exceptions; using Alabo.Framework.Core.WebApis; using Alabo.Industry.Shop.Orders.Domain.Entities; using Alabo.Industry.Shop.Orders.Domain.Services; using Alabo.UI; using Alabo.UI.Design.AutoTables; namespace Alabo.Industry.Shop.Orders.PcDtos { /// <summary> /// 会员订单 /// 登录会员查看当前登录订单 /// </summary> public class UserApiOrderList : BaseApiOrderList, IAutoTable<UserApiOrderList> { public List<TableAction> Actions() { var list = new List<TableAction> { ToLinkAction("会员订单", "/Order/Index") }; return list; } public PageResult<UserApiOrderList> PageTable(object query, AutoBaseModel autoModel) { var model = ToQuery<PlatformApiOrderList>(); var user = Resolve<IUserService>().GetSingle(model.UserId); if (user == null) { throw new ValidException("您无权查看其他人订单"); } var expressionQuery = new ExpressionQuery<Order>(); if (model.UserId > 0) { expressionQuery.And(e => e.UserId == user.Id); } var list = Resolve<IOrderApiService>().GetPageList(query, expressionQuery); return ToPageResult<UserApiOrderList, ApiOrderListOutput>(list); } } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Tasks.Schedules.Domain.Enums { /// <summary> /// 分润结果类型 /// 分润执行类型 /// </summary> [ClassProperty(Name = "分润执行类型")] public enum FenRunResultType { /// <summary> /// 价格分润 /// 如果是分润方式时候,会显示分润比例 /// 分润方式 /// 价格分润表示会自动产生佣金,在分润规则设置中会显示分润比例,支持多个分润比例, 大部分的分润维度都是价格分润,比如裂变分佣 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "价格分润")] Price = 1, /// <summary> /// 队列方式执行 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "队列方式执行")] Queue = 2, /// <summary> /// 更新业绩 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "更新业绩")] Sales = 3 } }
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Xml.Linq; namespace DesignMaterial { /// <summary> /// Interação lógica para Registro.xam /// </summary> public partial class Registro : Page { public Registro() { InitializeComponent(); } private void AbrirMostrarTodos(object sender, RoutedEventArgs e) { XElement Cadastro = XElement.Load(@"Cadastro.xml"); Dados MeusDados = new Dados(); boxMostra.Text = String.Empty; var Consulta = from Registros in Cadastro.Elements("Registro") select new { Codigo = (string)Registros.Element("Codigo"), Data = (string)Registros.Element("Data"), Natureza = (string)Registros.Element("Natureza"), Descricao = (string)Registros.Element("Descricao"), Valor = (string)Registros.Element("Valor") }; //adicionar balanço no fim da consulta foreach (var x in Consulta) { boxMostra.Text += ($"Código => {x.Codigo} " + NL(1)); boxMostra.Text += ($"Data => {x.Data}" + NL(1)); boxMostra.Text += ($"Natureza => {x.Natureza}" + NL(1)); boxMostra.Text += ($"Descrição => {x.Descricao}" + NL(1)); boxMostra.Text += ($"Valor => {x.Valor}" + NL(1)); boxMostra.Text += ("--------------------------------" + NL(2)); } } private string NL(int TotalLinhas) // Para NewLine no TextBox { string Linha = ""; for (int i = 1; i <= TotalLinhas; i++) Linha += Environment.NewLine; return Linha; } private void Procurar(object sender, RoutedEventArgs e) { Operacoes NovaOperacao = new Operacoes(); boxMostra.Text = String.Empty; if (NovaOperacao.ValidarData(boxData1.Text) == true && NovaOperacao.ValidarData(boxData2.Text) == true) { XElement Cadastro = XElement.Load(@"Cadastro.xml"); Dados MeusDados = new Dados(); var Busca = from Registros in Cadastro.Elements("Registro") where DateTime.Parse((string)Registros.Element("Data")).Date >= DateTime.Parse(boxData1.Text).Date && DateTime.Parse((string)Registros.Element("Data")).Date <= DateTime.Parse(boxData2.Text).Date select new { Codigo = (string)Registros.Element("Codigo"), Data = (string)Registros.Element("Data"), Natureza = (string)Registros.Element("Natureza"), Descricao = (string)Registros.Element("Descricao"), Valor = (string)Registros.Element("Valor") };//Como adicionar um atributo derivado com o valor total de cada 4periodo? foreach (var x in Busca) { boxMostra.Text += ($"Código => {x.Codigo} " + NL(1)); boxMostra.Text += ($"Data => {x.Data}" + NL(1)); boxMostra.Text += ($"Natureza => {x.Natureza}" + NL(1)); boxMostra.Text += ($"Descrição => {x.Descricao}" + NL(1)); boxMostra.Text += ($"Valor => {x.Valor}" + NL(1)); boxMostra.Text += ("--------------------------------" + NL(2)); } } else { MessageBox.Show("Data incorreta! Por favor insira no formato DD/MM/AAAA", "Data incorreta", MessageBoxButton.OK); } } private void Excluir_Click(object sender, RoutedEventArgs e) { //Adicionar meio de testar o valor para que não seja um registro vazio XElement Cadastro = XElement.Load(@"Cadastro.xml"); var Remove = from Registros in Cadastro.Elements("Registro") where ((string)Registros.Element("Codigo")).Equals(boxCod.Text) select Registros; foreach (var x in Remove) { x.Element("Codigo").Parent.Remove(); } try { Cadastro.Save(@"Cadastro.xml"); } catch (UnauthorizedAccessException ex) { System.Windows.MessageBox.Show("Por favor, execute o programa como administrador para utilizar essa função!", ex.Message); System.Windows.Application.Current.Shutdown(); } MessageBox.Show("Registro excluído com sucesso!", "Aviso", MessageBoxButton.OK); } private void Limpar_Click(object sender, RoutedEventArgs e) { boxData1.Text = String.Empty; boxData2.Text = String.Empty; } private void TxtSaldo_Initialized(object sender, EventArgs e) { txtSaldo.Text = Convert.ToString(Math.Round(double.Parse(txtEntrada.Text) - double.Parse(txtSaida.Text),2)); } private void TxtSaida_Initialized(object sender, EventArgs e) { XElement Cadastro = XElement.Load(@"Cadastro.xml"); double ValSaida = 0; var PegaSaida = from Registros in Cadastro.Elements("Registro") where ((string)Registros.Element("Natureza")).Equals("Débito") select new { Codigo = (string)Registros.Element("Codigo"), Data = (string)Registros.Element("Data"), Natureza = (string)Registros.Element("Natureza"), Descricao = (string)Registros.Element("Descricao"), Valor = (double)Registros.Element("Valor") }; foreach (var x in PegaSaida) { ValSaida += x.Valor; } txtSaida.Text = ValSaida.ToString(); } private void TxtEntrada_Initialized(object sender, EventArgs e) { XElement Cadastro = XElement.Load(@"Cadastro.xml"); double ValEntrada = 0; var PegaEntrada = from Registros in Cadastro.Elements("Registro") where ((string)Registros.Element("Natureza")).Equals("Crédito") select new { Codigo = (string)Registros.Element("Codigo"), Data = (string)Registros.Element("Data"), Natureza = (string)Registros.Element("Natureza"), Descricao = (string)Registros.Element("Descricao"), Valor = (double)Registros.Element("Valor") }; foreach (var x in PegaEntrada) { ValEntrada += x.Valor; } txtEntrada.Text = ValEntrada.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; // public abstract class SegmentEditorSuperClass : MonoBehaviour { // private static List<SegmentEditorSuperClass> segmentEditors = new List<SegmentEditorSuperClass>(); // // TODO: make static? // // protected LevelPieceSuperClass currentSegment = null; // // TODO: separate editor super class for toggling objects without segments, such as ramps // protected abstract void ChildAwake(); // protected void Awake() { // segmentEditors.Add(this); // ChildAwake(); // } // protected void OnDestroy() { // segmentEditors.Remove(this); // } // public abstract void UpdateUI(); // public static void UpdateAllUI() { // foreach (var item in segmentEditors) // item.UpdateUI(); // } // public void SetSegment(LevelPieceSuperClass segment) { // // currentSegment = segment; // UpdateUI(); // } // public static void SetSegmentsOnAll(LevelPieceSuperClass segment) { // foreach (var editor in segmentEditors) // editor.SetSegment(segment); // } //}