text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCollider : MonoBehaviour
{
private Collider2D col2d;
void Awake()
{
col2d = transform.parent.GetComponent<Collider2D>();
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("Player") && col2d.enabled)
{
transform.parent.SendMessage("Hit", SendMessageOptions.DontRequireReceiver);
Destroy(gameObject);
}
}
}
|
using AtendimentoProntoSocorro.Data;
using AtendimentoProntoSocorro.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AtendimentoProntoSocorro.Repositories
{
public class PacienteRepository : BaseRepository<Paciente>, IPacienteRepository
{
public PacienteRepository(ApplicationDbContext context) : base(context)
{
}
public async Task<Paciente> GetPaciente(long cpf)
{
var paciente = await dbSet
.Where(p => p.CPF == cpf)
.SingleOrDefaultAsync();
if (paciente == null)
{
return paciente;
}
return paciente;
}
public async Task<IEnumerable<Paciente>> ListaPaciente(string nome)
{
if (!String.IsNullOrEmpty(nome))
{
var pacientes = await dbSet
.Where(p => p.Nome.ToUpper().Contains(nome.ToUpper())).ToListAsync();
return pacientes;
}
return null;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PlayFab;
[System.Serializable]
public class Computer
{
public string cpu;
public string memory;
public string hdd;
public string sdd;
public string ip;
public void Connect()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using CreamBell_DMS_WebApps.App_Code;
namespace CreamBell_DMS_WebApps
{
public partial class frmSalesOrderPreList : System.Web.UI.Page
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USERID"] == null || Session["USERID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx");
return;
}
if (!IsPostBack)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
string strQuery = " SELECT A.SO_NO,CONVERT(NVARCHAR, A.SO_DATE,106) AS SO_DATE,CONVERT(NVARCHAR, A.DELIVERY_DATE,106) AS DELIVERY_DATE, " +
" A.CUSTOMER_CODE+' / '+C.CUSTOMER_NAME AS CUSTOMER_CODE, " +
" ROUND(SUM(B.AMOUNT),2) AS AMOUNT FROM [ax].[ACXSALESHEADERPRE] A " +
" INNER JOIN [ax].[ACXSALESLINEPRE] B ON A.SO_NO=B.SO_NO AND A.SITEID = B.SITEID " +
" left Join ax.ACXCUSTMASTER c on A.CUSTOMER_CODE = C.CUSTOMER_CODE "+//and A.SITEID = C.SITE_CODE " +
" WHERE A.SITEID='" + Session["SiteCode"].ToString() + "' " +
" GROUP BY A.SO_NO,A.SO_DATE,A.DELIVERY_DATE,A.CUSTOMER_CODE,C.CUSTOMER_NAME ";
SqlCommand cmd = new SqlCommand(strQuery,conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GvSaleOrderPre.DataSource = ds;
GvSaleOrderPre.DataBind();
}
conn.Close();
conn.Dispose();
}
}
protected void lnkSONo_Click(object sender, EventArgs e)
{
string SONO = (sender as LinkButton).CommandArgument;
// Response.Redirect("frmCustomerPartyMasterNew.aspx?CustID=" + CustID);
Response.Redirect(String.Format("frmSaleOrder.aspx?SONO="+ SONO));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _3Layer.DTO
{
public class Question
{
public int Id { get; set; }
public string Content { get; set; }
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
public char Correct { get; set; }
public int Level { get; set; }
public int CatagoryId { get; set; }
}
}
|
using HiScoreWebApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
namespace HiScoreWebApp.Controllers
{
public class HiScoreController : Controller
{
private readonly HiScoreDBContext _context;
public HiScoreController(HiScoreDBContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await _context.HiScore.OrderByDescending(a => a.Score).ToListAsync());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.Utilities.Results
{
public class DataResult<T> : Result, IDataResult<T>
{
//Diğer Result tan farkı aynı zamanda data da var yani T data
public DataResult(T data, bool success, string message) : base(success, message)//base ile diyoruz ki sen base ye de success i ve message yi yolla
{
Data = data;
}
public DataResult(T data,bool success):base(success)//Mesaj göndermek istemediğimiz zaman bura çalışsın
{
Data = data;
}
public T Data { get; }
}
}
|
using log4net.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using com.Sconit.Entity.Exception;
using com.Sconit.Entity.PRD;
using com.Sconit.Entity;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.MRP.TRANS;
using com.Sconit.Entity.MRP.ORD;
using com.Sconit.Utility;
using com.Sconit.Entity.MRP.MD;
namespace com.Sconit.Service.MRP
{
public class BaseMgr
{
public IItemMgr itemMgr { get; set; }
public IBomMgr bomMgr { get; set; }
public IGenericMgr genericMgr { get; set; }
#region cacheLocation
private static IDictionary<string, Location> cachedAllLocation;
private static DateTime cacheDateTime;
protected IDictionary<string, Location> GetCacheAllLocation()
{
if (cachedAllLocation == null || cacheDateTime < DateTime.Now.AddMinutes(-10))
{
cacheDateTime = DateTime.Now;
var allLocation = this.genericMgr.FindAll<Location>();
cachedAllLocation = allLocation.ToDictionary(d => d.Code, d => d);
}
return cachedAllLocation;
}
protected Location GetCacheLocation(string locationCode)
{
Location location = null;
if (!GetCacheAllLocation().TryGetValue(locationCode, out location))
{
cachedAllLocation = null;
GetCacheAllLocation().TryGetValue(locationCode, out location);
};
return location;
}
#endregion
//得到基本单位用量
protected List<MrpBom> GetMrpBomList(string fgCode, string bomCode, DateTime effdate, BusinessException businessException, bool isOnlyNext = false)
{
var mrpBoms = new List<MrpBom>();
try
{
var bomMaster = this.bomMgr.GetCacheBomMaster(bomCode);
if (bomMaster != null)
{
var fgItem = this.itemMgr.GetCacheItem(fgCode);
IList<BomDetail> bomDetails = new List<BomDetail>();
if (isOnlyNext)
{
bomDetails = bomMgr.GetOnlyNextLevelBomDetail(bomCode, effdate, true);
}
else
{
bomDetails = bomMgr.GetFlatBomDetail(bomCode, effdate, true);
}
foreach (var bomDetail in bomDetails)
{
var item = this.itemMgr.GetCacheItem(bomDetail.Item);
double calculatedQty = 1;
//1.将bomMaster的单位转成基本单位
double fgQty = ConvertItemUomQty(fgItem.Code, bomMaster.Uom, 1, fgItem.Uom, businessException);
//2.将BomDetail的单位转成基本单位
double itemQty = ConvertItemUomQty(item.Code, bomDetail.Uom, (double)bomDetail.CalculatedQty, item.Uom, businessException);
//3.单位成品用量
calculatedQty = itemQty / fgQty;
var mrpBom = new MrpBom();
mrpBom.Bom = bomCode;
mrpBom.Item = bomDetail.Item;
mrpBom.Location = bomDetail.Location;
mrpBom.RateQty = calculatedQty;
mrpBom.IsSection = item.ItemCategory == "ZHDM";
mrpBom.ScrapPercentage = (double)bomDetail.ScrapPercentage;
//if (mrpBom.IsSection)
//{
// mrpBom.ScrapPercentage = fgItem.ScrapPercent;
//}
mrpBoms.Add(mrpBom);
}
}
}
catch (Exception ex)
{
businessException.AddMessage(new Message(CodeMaster.MessageType.Error, string.Format("BomCode {0} Error,{1}", bomCode, ex.Message)));
}
return mrpBoms;
}
protected double ConvertItemUomQty(string item, string sourceUom, double sourceQty, string targetUom, BusinessException businessException)
{
try
{
return (double)this.itemMgr.ConvertItemUomQty(item, sourceUom, (decimal)sourceQty, targetUom);
}
catch (Exception)
{
string message = string.Format("没有找到物料:{0}从单位:{1}到单位:{2}的转换", item, sourceUom, targetUom);
if (businessException != null)
{
businessException.AddMessage(new Message(CodeMaster.MessageType.Error, message));
}
return 1.0;
}
}
protected double ConvertItemUomQty(string item, string sourceUom, double sourceQty, string targetUom)
{
return ConvertItemUomQty(item, sourceUom, sourceQty, targetUom, null);
}
protected List<MrpShipPlan> GetProductPlanInList(DateTime planVersion, string flow)
{
var planInList = this.genericMgr.FindAllWithNativeSql<object[]>
("exec USP_Busi_MRP_GetPlanIn ?,?", new object[] { planVersion, flow },
new NHibernate.Type.IType[] { NHibernate.NHibernateUtil.DateTime, NHibernate.NHibernateUtil.String });
//[Flow] [varchar](50) NULL,
//[OrderType] [tinyint] NOT NULL,
//[Item] [varchar](50) NOT NULL,
//[StartTime] [datetime] NOT NULL,
//[WindowTime] [datetime] NOT NULL,
//[LocationFrom] [varchar](50) NULL,
//[LocationTo] [varchar](50) NULL,
//[Qty] [float] NOT NULL,
//[Bom] [varchar](50) NULL,
//[SourceType] [tinyint] NOT NULL,
//[SourceParty] [varchar](50) NULL,
var shipPlanList = planInList.Select(p =>
new MrpShipPlan
{
Flow = (string)p[0],
OrderType = (CodeMaster.OrderType)(int.Parse(p[1].ToString())),
Item = (string)p[2],
StartTime = (DateTime)p[3],
WindowTime = (DateTime)p[4],
LocationFrom = (string)p[5],
LocationTo = (string)p[6],
Qty = (double)p[7],
Bom = (string)p[8],
SourceType = (CodeMaster.MrpSourceType)(int.Parse(p[9].ToString())),
SourceParty = (string)p[10]
}).ToList();
return shipPlanList;
}
protected List<MrpShipPlan> GetProductPlanInList(MrpPlanMaster mrpPlanMaster, DateTime startTime, DateTime endTime, IList<MrpFlowDetail> mrpFlowDetailList = null)
{
var shipPlanList = new List<MrpShipPlan>();
//改成存储过程
shipPlanList = GetProductPlanInList(mrpPlanMaster.PlanVersion, null) ?? new List<MrpShipPlan>();
shipPlanList = shipPlanList.Where(p => p.StartTime >= startTime && p.StartTime < endTime).ToList();
return shipPlanList;
//订单 //todo 状态为Cancel的处理方法,订单类型为Production
var activeOrderDic = this.genericMgr.FindAll<ActiveOrder>
(@" from ActiveOrder where SnapTime =? and ResourceGroup =? and IsIndepentDemand=? ",
new object[] { mrpPlanMaster.SnapTime, mrpPlanMaster.ResourceGroup, false })
.GroupBy(p => p.Flow, (k, g) => new { k, g }).ToDictionary(d => d.k, d => d.g);
shipPlanList.AddRange(from p in activeOrderDic.SelectMany(p => p.Value)
select new MrpShipPlan
{
Flow = p.Flow,
Item = p.Item,
LocationFrom = p.LocationFrom,
LocationTo = p.LocationTo,
StartTime = p.StartTime,
WindowTime = p.WindowTime,
SourceId = p.OrderDetId,
SourceType = CodeMaster.MrpSourceType.Order,
OrderType = p.OrderType,
Qty = p.DemandQty,
SourceFlow = p.Flow,
SourceParty = p.PartyFrom,
ParentItem = p.Item
});
//计划,订单覆盖计划
if (mrpPlanMaster.ResourceGroup == CodeMaster.ResourceGroup.FI)
{
var shiftPlanList = this.genericMgr.FindAll<MrpFiShiftPlan>
(" from MrpFiShiftPlan where PlanVersion = ? and StartTime >=? and StartTime<=? ",
new object[] { mrpPlanMaster.PlanVersion, startTime, endTime });
foreach (var plan in shiftPlanList)
{
var activeOrderCount = (activeOrderDic.ValueOrDefault(plan.ProductLine) ?? new List<ActiveOrder>())
.Count(p => p.StartTime.Date == plan.PlanDate.Date && p.Shift == plan.Shift);
if (activeOrderCount == 0)
{
MrpShipPlan mrpShipPlan = new MrpShipPlan();
mrpShipPlan.Bom = plan.Bom;
mrpShipPlan.Flow = plan.ProductLine;
mrpShipPlan.Item = plan.Item;
mrpShipPlan.LocationFrom = plan.LocationFrom;
mrpShipPlan.LocationTo = plan.LocationTo;
mrpShipPlan.Bom = plan.Bom;
mrpShipPlan.StartTime = plan.StartTime;
mrpShipPlan.WindowTime = plan.WindowTime;
mrpShipPlan.SourceId = plan.Id;
mrpShipPlan.SourceType = CodeMaster.MrpSourceType.FiShift;
mrpShipPlan.OrderType = CodeMaster.OrderType.Production;
mrpShipPlan.Qty = plan.Qty;
mrpShipPlan.SourceFlow = plan.ProductLine;
mrpShipPlan.SourceParty = GetCacheLocation(mrpShipPlan.LocationFrom).Region;
mrpShipPlan.ParentItem = plan.Item;
shipPlanList.Add(mrpShipPlan);
}
}
}
else if (mrpPlanMaster.ResourceGroup == CodeMaster.ResourceGroup.EX)
{
var exShiftPlanList = this.genericMgr.FindAll<MrpExItemPlan>
(" from MrpExItemPlan where PlanVersion = ? and PlanDate >=? and PlanDate<=? ",
new object[] { mrpPlanMaster.PlanVersion, startTime, endTime });
var shipPlans = (from p in exShiftPlanList
group p by new
{
Flow = p.ProductLine,
Item = p.Item,
PlanDate = p.PlanDate,
} into g
select new MrpShipPlan
{
//Bom = g.Key.Bom,
Flow = g.Key.Flow,
Item = g.Key.Item,
//LocationFrom = g.Key.LocationFrom,
//LocationTo = g.Key.LocationTo,
StartTime = g.Key.PlanDate,
WindowTime = g.Key.PlanDate.AddDays(1),
SourceId = g.Min(q => q.Id),
SourceType = CodeMaster.MrpSourceType.ExDay,
OrderType = CodeMaster.OrderType.Production,
Qty = g.Sum(q => q.Qty),
SourceFlow = g.Key.Flow,
//SourceParty = GetCacheLocation(g.Key.LocationFrom).Region,
ParentItem = g.Key.Item
}).ToList();
var mrpFlowDetails = new List<MrpFlowDetail>();
if (mrpFlowDetailList == null)
{
mrpFlowDetails = this.genericMgr.FindAll<MrpFlowDetail>
(@" from MrpFlowDetail as m where m.SnapTime = ? and m.ResourceGroup=? ",
new object[] { mrpPlanMaster.SnapTime, mrpPlanMaster.ResourceGroup }).ToList();
}
else
{
mrpFlowDetails = mrpFlowDetailList.Where(p => p.ResourceGroup == mrpPlanMaster.ResourceGroup).ToList();
}
foreach (var shipPlan in shipPlans)
{
var flowDetail = mrpFlowDetails.FirstOrDefault(f => f.Flow == shipPlan.Flow && f.Item == shipPlan.Item
&& f.StartDate <= shipPlan.StartTime && f.EndDate > shipPlan.StartTime);
if (flowDetail == null)
{
flowDetail = mrpFlowDetails.FirstOrDefault(f => f.Flow == shipPlan.Flow);
}
shipPlan.Bom = flowDetail.Bom;
shipPlan.LocationFrom = flowDetail.LocationFrom;
shipPlan.LocationTo = flowDetail.LocationTo;
shipPlan.SourceParty = flowDetail.PartyFrom;
}
shipPlanList.AddRange(shipPlans);
}
else if (mrpPlanMaster.ResourceGroup == CodeMaster.ResourceGroup.MI)
{
var shiftPlanDic = this.genericMgr.FindEntityWithNativeSql<MrpMiShiftPlan>
(@"select a.* from MRP_MrpMiShiftPlan a join MRP_MrpMiDateIndex b
on a.CreateDate = b.CreateDate and a.ProductLine = b.ProductLine and a.PlanDate = b.PlanDate
where b.PlanDate >=? and b.PlanDate<=? and b.IsActive=? ", new object[] { startTime, endTime, true })
.GroupBy(p => p.PlanDate, (k, g) => new { k, g }).ToDictionary(d => d.k, d => d.g.ToList());
var mrpMiPlanDic = this.genericMgr.FindAll<MrpMiPlan>
(" from MrpMiPlan where PlanVersion = ? and PlanDate >=? and PlanDate<=? ",
new object[] { mrpPlanMaster.PlanVersion, startTime, endTime })
.GroupBy(p => p.PlanDate, (k, g) => new { k, g }).ToDictionary(d => d.k, d => d.g.ToList());
//优先级:订单>班产计划>日计划
DateTime currentDate = startTime;
while (currentDate < endTime)
{
currentDate = currentDate.AddDays(1);
var shiftPlans = shiftPlanDic.ValueOrDefault(currentDate);
if (shiftPlans != null)
{
foreach (var plan in shiftPlans)
{
var activeOrderCount = (activeOrderDic.ValueOrDefault(plan.ProductLine) ?? new List<ActiveOrder>())
.Count(p => p.StartTime.Date == plan.PlanDate.Date && p.Shift == plan.Shift);
if (activeOrderCount == 0)
{
MrpShipPlan mrpShipPlan = new MrpShipPlan();
mrpShipPlan.Bom = plan.Bom;
mrpShipPlan.Flow = plan.ProductLine;
mrpShipPlan.Item = plan.Item;
mrpShipPlan.LocationFrom = plan.LocationFrom;
mrpShipPlan.LocationTo = plan.LocationTo;
mrpShipPlan.StartTime = plan.StartTime;
mrpShipPlan.WindowTime = plan.WindowTime;
mrpShipPlan.SourceId = plan.Id;
mrpShipPlan.SourceType = CodeMaster.MrpSourceType.MiShift;
mrpShipPlan.OrderType = CodeMaster.OrderType.Production;
mrpShipPlan.Qty = plan.TotalQty;
mrpShipPlan.SourceFlow = plan.ProductLine;
mrpShipPlan.SourceParty = GetCacheLocation(mrpShipPlan.LocationFrom).Region;
mrpShipPlan.Item = plan.Item;
shipPlanList.Add(mrpShipPlan);
}
}
}
else
{
var miPlans = mrpMiPlanDic.ValueOrDefault(currentDate) ?? new List<MrpMiPlan>();
foreach (var plan in miPlans)
{
MrpShipPlan mrpShipPlan = new MrpShipPlan();
mrpShipPlan.Bom = plan.Bom;
mrpShipPlan.Flow = plan.ProductLine;
mrpShipPlan.Item = plan.Item;
mrpShipPlan.LocationFrom = plan.LocationFrom;
mrpShipPlan.LocationTo = plan.LocationTo;
mrpShipPlan.StartTime = plan.PlanDate;
mrpShipPlan.WindowTime = plan.PlanDate.AddDays(1);
mrpShipPlan.SourceId = plan.Id;
mrpShipPlan.SourceType = CodeMaster.MrpSourceType.MiShift;
mrpShipPlan.OrderType = CodeMaster.OrderType.Production;
mrpShipPlan.Qty = plan.TotalQty;
mrpShipPlan.SourceFlow = plan.ProductLine;
mrpShipPlan.SourceParty = GetCacheLocation(mrpShipPlan.LocationFrom).Region;
mrpShipPlan.Item = plan.Item;
shipPlanList.Add(mrpShipPlan);
}
}
}
}
return shipPlanList;
}
protected class MrpBom
{
public string Bom { get; set; }
public string Item { get; set; }
public string Location { get; set; }
/// <summary>
/// 断面的单位长度不包含废品率,其他的已包含废品率
/// </summary>
public Double RateQty { get; set; }
public bool IsSection { get; set; }
public Double ScrapPercentage { get; set; }
}
}
}
|
using System;
using System.IO;
using System.Reflection;
using System.Linq;
using Android.Widget;
using Android.OS;
using CC.Mobile.Services;
using Android.Content;
namespace CC.Mobile.Services
{
public class Messages : IMessages
{
Handler handler;
Context context;
public Messages(Context context){
this.context = context;
this.handler = new Handler (context.MainLooper);
}
public void ShowToast(string text, int timeout = 1000){
Toast.MakeText (context, text, GetToastLength (timeout)).Show ();
}
public void ShowMessage(string text)
{
Toast.MakeText (context, text, ToastLength.Long).Show ();
}
public void Dismiss()
{
}
public void ShowError(string text, int timeout = 1000)
{
handler.Post (() => {
Toast.MakeText (context, text, GetToastLength (timeout)).Show ();
});
}
public void ShowStatus(string text, int timeout)
{
Toast.MakeText (context, text, GetToastLength (timeout)).Show ();
}
public ToastLength GetToastLength(int duration){
return duration > 2500 ? ToastLength.Long : ToastLength.Short;
}
}
} |
namespace MathApplication.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class addDTB1 : DbMigration
{
public override void Up()
{
AddColumn("dbo.UserAccounts", "UserRole_ID", c => c.Int(nullable: false));
CreateIndex("dbo.UserAccounts", "UserRole_ID");
DropColumn("dbo.UserAccounts", "UserRole");
DropColumn("dbo.UserAccounts", "UserRank");
}
public override void Down()
{
AddColumn("dbo.UserAccounts", "UserRank", c => c.Int(nullable: false));
AddColumn("dbo.UserAccounts", "UserRole", c => c.Int(nullable: false));
DropIndex("dbo.UserAccounts", new[] { "UserRole_ID" });
DropColumn("dbo.UserAccounts", "UserRole_ID");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AspCoreBl.ModelDTO
{
public class DataSourceResult<T>
{
public List<T> Data { get; set; }
public int Total { get; set; }
public object Aggregates { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp7
{
public class MediaAdapter : IMediaPlayer
{
private IAdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(string audioType)
{
switch (audioType)
{
case "vlc":
advancedMediaPlayer = new VlcPlayer();
break;
case "mp4":
advancedMediaPlayer = new Mp4Player();
break;
default:
throw new NotImplementedException();
}
}
public void play(string audioType, string fileName)
{
switch (audioType)
{
case "vlc":
advancedMediaPlayer.playVlc(fileName);
break;
case "mp4":
advancedMediaPlayer.playMp4(fileName);
break;
default:
throw new NotImplementedException();
}
}
}
}
|
namespace BettingSystem.Infrastructure.Common
{
using System;
using System.Reflection;
using System.Text;
using Application.Common.Contracts;
using Application.Common.Settings;
using Domain.Common;
using Events;
using Extensions;
using GreenPipes;
using Hangfire;
using Hangfire.SqlServer;
using MassTransit;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Services;
public static class InfrastructureConfiguration
{
public static IServiceCollection AddCommonInfrastructure<TDbContext>(
this IServiceCollection services,
IConfiguration configuration,
Assembly assembly,
bool databaseHealthChecks = true,
bool messagingHealthChecks = true)
where TDbContext : DbContext
=> services
.AddDatabase<TDbContext>(configuration)
.AddTokenAuthentication(configuration)
.AddRepositories(assembly)
.AddHealth(
configuration,
databaseHealthChecks,
messagingHealthChecks);
public static IServiceCollection AddEvents(
this IServiceCollection services,
IConfiguration configuration,
bool usePolling = true,
params Type[] consumers)
{
var messageQueueSettings = configuration.GetMessageQueueSettings();
services
.AddMassTransit(mt =>
{
consumers.ForEach(consumer => mt.AddConsumer(consumer));
mt.AddBus(context => Bus.Factory.CreateUsingRabbitMq(rmq =>
{
rmq.Host(messageQueueSettings.Host, host =>
{
host.Username(messageQueueSettings.UserName);
host.Password(messageQueueSettings.Password);
});
consumers.ForEach(consumer => rmq.ReceiveEndpoint(consumer.FullName, endpoint =>
{
endpoint.PrefetchCount = 6;
endpoint.UseMessageRetry(retry => retry.Interval(5, 200));
endpoint.ConfigureConsumer(context, consumer);
}));
}));
})
.AddMassTransitHostedService()
.AddTransient<IEventPublisher, EventPublisher>();
if (usePolling)
{
services
.AddHangfireDatabase(configuration)
.AddHangfire(config => config
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(
configuration.GetCronJobsConnectionString(),
new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}))
.AddHangfireServer()
.AddHostedService<MessagesHostedService>();
}
return services;
}
private static IServiceCollection AddDatabase<TDbContext>(
this IServiceCollection services,
IConfiguration configuration)
where TDbContext : DbContext
=> services
.AddScoped<DbContext, TDbContext>()
.AddDbContext<TDbContext>(options => options
.UseSqlServer(
configuration.GetDefaultConnectionString(),
sqlOptions => sqlOptions
.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null)
.MigrationsAssembly(
typeof(TDbContext).Assembly.FullName)));
internal static IServiceCollection AddRepositories(
this IServiceCollection services,
Assembly assembly)
=> services
.Scan(scan => scan
.FromAssemblies(assembly)
.AddClasses(classes => classes
.AssignableTo(typeof(IDomainRepository<>))
.AssignableTo(typeof(IQueryRepository<>)))
.AsImplementedInterfaces()
.WithTransientLifetime());
private static IServiceCollection AddTokenAuthentication(
this IServiceCollection services,
IConfiguration configuration)
{
var secret = configuration
.GetSection(nameof(ApplicationSettings))
.GetValue<string>(nameof(ApplicationSettings.Secret));
var key = Encoding.ASCII.GetBytes(secret);
services
.AddAuthentication(authentication =>
{
authentication.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
authentication.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(bearer =>
{
bearer.RequireHttpsMetadata = false;
bearer.SaveToken = true;
bearer.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddHttpContextAccessor();
return services;
}
private static IServiceCollection AddHealth(
this IServiceCollection services,
IConfiguration configuration,
bool databaseHealthChecks = true,
bool messagingHealthChecks = true)
{
var healthChecks = services.AddHealthChecks();
if (databaseHealthChecks)
{
healthChecks
.AddSqlServer(configuration.GetDefaultConnectionString());
}
if (messagingHealthChecks)
{
var messageQueueSettings = configuration.GetMessageQueueSettings();
var messageQueueConnectionString =
$"amqp://{messageQueueSettings.UserName}:{messageQueueSettings.Password}@{messageQueueSettings.Host}/";
healthChecks
.AddRabbitMQ(rabbitConnectionString: messageQueueConnectionString);
}
return services;
}
private static IServiceCollection AddHangfireDatabase(
this IServiceCollection services,
IConfiguration configuration)
{
var connectionString = configuration.GetCronJobsConnectionString();
var dbName = connectionString
.Split(";")[1]
.Split("=")[1];
using var connection = new SqlConnection(connectionString.Replace(dbName, "master"));
connection.Open();
using var command = new SqlCommand(
$"IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'{dbName}') create database [{dbName}];",
connection);
command.ExecuteNonQuery();
return services;
}
}
}
|
using System;
namespace Uintra.Features.Subscribe.Models
{
public class SubscribeNotificationDisableUpdateModel
{
public Guid Id { get; set; }
public bool NewValue { get; set; }
public Guid ActivityId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PROYECTOFINAL.Models
{
public class compramodel
{
public int idcompra { get; set; }
public int idProvedor { get; set; }
public string Proveedor { get; set; }
public int idProducto { get; set; }
public string Product { get; set; }
public DateTime fecha { get; set; }
public int cantidad { get; set; }
public int costo { get; set; }
public int total { get; set; }
public int idLocal { get; set; }
}
} |
using EQS.AccessControl.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace EQS.AccessControl.Repository.Configurations
{
class RoleConfiguration : IEntityTypeConfiguration<Role>
{
public void Configure(EntityTypeBuilder<Role> builder)
{
builder.ToTable("Roles");
builder.HasKey(h => h.Id);
builder.Property(p => p.Name).IsRequired();
builder.Ignore(i => i.Validations);
}
}
}
|
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using Pe.Stracon.SGC.Presentacion.Recursos.Base;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.FlujoAprobacion
{
/// <summary>
/// Modelo de vista de flujo aprobacion formulario
/// </summary>
/// <remarks>
/// Creación: GMD 20150511
/// Modificación:
/// </remarks>
public class FlujoAprobacionEstadiosFormulario : GenericViewModel
{
/// <summary>
/// Constructor usado para el registro de datos
/// </summary>
public FlujoAprobacionEstadiosFormulario(/*List<CodigoValorResponse> listaOrdenFirmantes*/)
{
this.flujoAprobacionEstadioResponse = new FlujoAprobacionEstadioResponse();
this.flujoAprobacionEstadioResponse.ListaNombreInformado = new Dictionary<string, string>();
this.flujoAprobacionEstadioResponse.ListaNombreRepresentante = new Dictionary<string, string>();
this.flujoAprobacionEstadioResponse.ListaNombreResponsableVinculadas = new Dictionary<string, string>();
//this.ListaOrdenFirmantes = this.GenerarListadoOpcioneGenericoFormulario(listaOrdenFirmantes);
}
/// <summary>
/// Constructor usado para el registro de datos
/// </summary>
/// <param name="flujoAprobacionEstadio">Flujo aprobacion estadio</param>
public FlujoAprobacionEstadiosFormulario(FlujoAprobacionEstadioResponse flujoAprobacionEstadio)
{
this.flujoAprobacionEstadioResponse = flujoAprobacionEstadio;
}
#region Propiedades
/// <summary>
/// Objeto Flujo Aprobación Response
/// </summary>
public FlujoAprobacionEstadioResponse flujoAprobacionEstadioResponse { get; set; }
/// <summary>
/// Objeto Lista Orden de firmantes
/// </summary>
public List<SelectListItem> ListaOrdenFirmantes { get; set; }
#endregion
}
}
|
using System;
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// IPair of type `<Collider2D>`. Inherits from `IPair<Collider2D>`.
/// </summary>
[Serializable]
public struct Collider2DPair : IPair<Collider2D>
{
public Collider2D Item1 { get => _item1; set => _item1 = value; }
public Collider2D Item2 { get => _item2; set => _item2 = value; }
[SerializeField]
private Collider2D _item1;
[SerializeField]
private Collider2D _item2;
public void Deconstruct(out Collider2D item1, out Collider2D item2) { item1 = Item1; item2 = Item2; }
}
} |
using System.Collections.Generic;
using Airelax.Application.Comments.Dtos.Request;
using Airelax.Application.Comments.Dtos.Response;
namespace Airelax.Application.Comments
{
public interface ICommentService
{
void CreateOrUpdateComment(CreateOrUpdateCommentInput input);
IEnumerable<HouseCommentViewModel> GetHouseComments();
}
} |
using ecommerce.ecommerceClasses;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ecommerce
{
public partial class selectedProductRepartition : ecommerce.Form1
{
private string code;
public selectedProductRepartition()
{
InitializeComponent();
}
private void selectedProductRepartition_Load(object sender, EventArgs e)
{
TransactionDAO transactionDao = new TransactionDAO();
try
{
List<Transaction> transactions = transactionDao.getTransactionsListByProductID(Code);
this.statusLabel.Text = "Product Transaction Repartition";
this.statusStrip1.Refresh();
decimal total = 0;
if (transactions != null)
{
transactions.ForEach(item =>
{
total = total + (item.Product.PrixUnitaire * (1 + item.Product.Tva)) * item.Quantity;
});
productChart.Series["Repartition"].Points.AddXY("Total Transactions By Product", total);
}
else
{
throw new exceptions("There's currently no transaction for the selected product");
}
}catch(exceptions exception)
{
MessageBox.Show(exception.Message, "Exception", MessageBoxButtons.OK);
}
}
public string Code { get => code; set => code = value; }
private void chart1_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Автошкола
{
public class CarriersRepairsDA
{
private SqlDataAdapter dataAdapter;
// сохранить изменения строки
public void Save(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr)
{
dataAdapter = new SqlDataAdapter();
// на обновление
dataAdapter.UpdateCommand = new SqlCommand("UPDATE CarriersRepairs SET ID = @ID, Carrier = @Carrier, Master = @Master, " +
"Work = @Work, BeginDate = @BeginDate, EndDate = @EndDate " +
"WHERE ID = @OldID", conn.getConnection(), tr.getTransaction());
dataAdapter.UpdateCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID");
dataAdapter.UpdateCommand.Parameters.Add("@Carrier", System.Data.SqlDbType.Int, 255, "Carrier");
dataAdapter.UpdateCommand.Parameters.Add("@Master", System.Data.SqlDbType.Int, 255, "Master");
dataAdapter.UpdateCommand.Parameters.Add("@Work", System.Data.SqlDbType.Text, 255, "Work");
dataAdapter.UpdateCommand.Parameters.Add("@BeginDate", System.Data.SqlDbType.Date, 255, "BeginDate");
dataAdapter.UpdateCommand.Parameters.Add("@EndDate", System.Data.SqlDbType.Date, 255, "EndDate");
dataAdapter.UpdateCommand.Parameters.Add("@OldID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original;
// на вставку
dataAdapter.InsertCommand = new SqlCommand("INSERT INTO CarriersRepairs (ID, Carrier, Master, Work, " +
"BeginDate, EndDate) VALUES (@ID, @Carrier, @Master, @Work, @BeginDate, @EndDate)",
conn.getConnection(), tr.getTransaction());
dataAdapter.InsertCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID");
dataAdapter.InsertCommand.Parameters.Add("@Carrier", System.Data.SqlDbType.Int, 255, "Carrier");
dataAdapter.InsertCommand.Parameters.Add("@Master", System.Data.SqlDbType.Int, 255, "Master");
dataAdapter.InsertCommand.Parameters.Add("@Work", System.Data.SqlDbType.Text, 255, "Work");
dataAdapter.InsertCommand.Parameters.Add("@BeginDate", System.Data.SqlDbType.Date, 255, "BeginDate");
dataAdapter.InsertCommand.Parameters.Add("@EndDate", System.Data.SqlDbType.Date, 255, "EndDate");
// на удаление
dataAdapter.DeleteCommand = new SqlCommand("DELETE CarriersRepairs WHERE ID = @ID", conn.getConnection(), tr.getTransaction());
dataAdapter.DeleteCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original;
dataAdapter.Update(dataSet, "CarriersRepairs");
}
// прочитать таблицу
public void Read(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM CarriersRepairs", conn.getConnection(), tr.getTransaction());
dataAdapter.Fill(dataSet, "CarriersRepairs");
}
public void ReadByCarrierID(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int CarrierID)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM CarriersRepairs WHERE Carrier = @CarrierID", conn.getConnection(), tr.getTransaction());
dataAdapter.SelectCommand.Parameters.AddWithValue("@CarrierID", CarrierID);
dataAdapter.Fill(dataSet, "CarriersRepairs");
}
public void ReadByServiceMasterID(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int ServiceMasterID)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM CarriersRepairs WHERE Master = @ServiceMasterID", conn.getConnection(), tr.getTransaction());
dataAdapter.SelectCommand.Parameters.AddWithValue("@ServiceMasterID", ServiceMasterID);
dataAdapter.Fill(dataSet, "CarriersRepairs");
}
public void ReadByBeginEndDates(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, DateTime BeginDate, DateTime EndDate)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM CarriersRepairs WHERE BeginDate >= @BeginDate AND EndDate <= @EndDate", conn.getConnection(), tr.getTransaction());
dataAdapter.SelectCommand.Parameters.AddWithValue("@BeginDate", BeginDate);
dataAdapter.SelectCommand.Parameters.AddWithValue("@EndDate", EndDate);
dataAdapter.Fill(dataSet, "CarriersRepairs");
}
public void ReadByCarrierID_AND_LessonDate(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int CarrierID, DateTime LessonDate)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM CarriersRepairs WHERE Carrier = @CarrierID AND @LessonDate >= BeginDate AND @LessonDate <= EndDate", conn.getConnection(), tr.getTransaction());
dataAdapter.SelectCommand.Parameters.AddWithValue("@CarrierID", CarrierID);
dataAdapter.SelectCommand.Parameters.AddWithValue("@LessonDate", LessonDate);
dataAdapter.Fill(dataSet, "CarriersRepairs");
}
public void ReadByCarrierID_AND_CrossInBeginEndDates(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int CarrierID, DateTime BeginDate, DateTime EndDate)
{
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM CarriersRepairs WHERE Carrier = @CarrierID AND ((BeginDate <= @BeginDate AND @BeginDate <= EndDate) OR (EndDate >= @EndDate AND @EndDate >= BeginDate))", conn.getConnection(), tr.getTransaction());
dataAdapter.SelectCommand.Parameters.AddWithValue("@CarrierID", CarrierID);
dataAdapter.SelectCommand.Parameters.AddWithValue("@BeginDate", BeginDate);
dataAdapter.SelectCommand.Parameters.AddWithValue("@EndDate", EndDate);
dataAdapter.Fill(dataSet, "CarriersRepairs");
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using SendGrid.Helpers.Mail;
namespace Ajf.NugetWatcher
{
public class SendGridEmailAddressFactory : ISendGridEmailAddressFactory
{
public EmailAddress Create(string email, string name)
{
return new EmailAddress(email, name);
}
public EmailAddress CreateSingle(string mailAndName)
{
var strings = mailAndName.Split(';').ToArray();
return Create(strings[0], strings[1]);
}
public IEnumerable<EmailAddress> CreateMany(string[] mailAndName)
{
foreach (var s in mailAndName)
{
yield return CreateSingle(s);
}
}
}
} |
//-----------------------------------------------------------------------
// <copyright file="DocumentStrategy.cs" company="4Deep Technologies LLC">
// Copyright (c) 4Deep Technologies LLC. All rights reserved.
// <author>Darren Ford</author>
// <date>Thursday, April 30, 2015 3:00:44 PM</date>
// </copyright>
//-----------------------------------------------------------------------
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace Dizzle.Cqrs.Core.Storage
{
static class NameCache<T>
{
// ReSharper disable StaticFieldInGenericType
public static readonly string Name;
public static readonly string Namespace;
// ReSharper restore StaticFieldInGenericType
static NameCache()
{
var type = typeof(T);
Name = new string(Splice(type.Name).ToArray()).TrimStart('-');
var dcs = type.GetTypeInfo().CustomAttributes.OfType<DataContractAttribute>().ToArray();
if (dcs.Length <= 0) return;
var attribute = dcs.First();
if (!string.IsNullOrEmpty(attribute.Name))
{
Name = attribute.Name;
}
if (!string.IsNullOrEmpty(attribute.Namespace))
{
Namespace = attribute.Namespace;
}
}
static IEnumerable<char> Splice(string source)
{
foreach (var c in source)
{
if (char.IsUpper(c))
{
yield return '-';
}
yield return char.ToLower(c);
}
}
}
public sealed class ViewStrategy : IDocumentStrategy
{
public string GetEntityBucket<TEntity>()
{
return Conventions.ViewsFolder + "\\" + NameCache<TEntity>.Name;
}
public string GetEntityLocation<TEntity>(object key)
{
if (key is unit)
return NameCache<TEntity>.Name + ".json";
var hashed = key as IIdentity;
if (hashed != null)
{
var stableHashCode = hashed.GetStableHashCode();
var b = (byte)((uint)stableHashCode % 251);
return b + "\\" + hashed.GetTag() + "-" + hashed.GetId() + ".json";
}
if (key is Guid)
{
var b = (byte)((uint)((Guid)key).GetHashCode() % 251);
return b + "\\" + key.ToString().ToLowerInvariant() + ".json";
}
if (key is string)
{
var corrected = ((string)key).ToLowerInvariant().Trim();
var b = (byte)((uint)CalculateStringHash(corrected) % 251);
return b + "\\" + corrected + ".json";
}
return key.ToString().ToLowerInvariant() + ".json";
}
static int CalculateStringHash(string value)
{
if (value == null) return 42;
unchecked
{
var hash = 23;
foreach (var c in value)
{
hash = hash * 31 + c;
}
return hash;
}
}
public void Serialize<TEntity>(TEntity entity, Stream stream)
{
// ProtoBuf must have non-zero files
stream.WriteByte(42);
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
JsonSerializer ser = new JsonSerializer();
ser.NullValueHandling = NullValueHandling.Ignore;
ser.Formatting = Formatting.Indented;
ser.Serialize(jsonWriter, entity);
jsonWriter.Flush();
}
public TEntity Deserialize<TEntity>(Stream stream)
{
var signature = stream.ReadByte();
if (signature != 42)
throw new InvalidOperationException("Unknown view format");
StreamReader reader = new StreamReader(stream);
JsonTextReader jsonReader = new JsonTextReader(reader);
JsonSerializer ser = new JsonSerializer();
return ser.Deserialize<TEntity>(jsonReader);
}
}
public sealed class DocumentStrategy : IDocumentStrategy
{
public void Serialize<TEntity>(TEntity entity, Stream stream)
{
// ProtoBuf must have non-zero files
stream.WriteByte(42);
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jsonWriter, entity);
jsonWriter.Flush();
}
public TEntity Deserialize<TEntity>(Stream stream)
{
var signature = stream.ReadByte();
if (signature != 42)
throw new InvalidOperationException("Unknown view format");
StreamReader reader = new StreamReader(stream);
JsonTextReader jsonReader = new JsonTextReader(reader);
JsonSerializer ser = new JsonSerializer();
return ser.Deserialize<TEntity>(jsonReader);
}
public string GetEntityBucket<TEntity>()
{
return Conventions.DocsFolder + "/" + NameCache<TEntity>.Name;
}
public string GetEntityLocation<TEntity>(object key)
{
if (key is unit)
return NameCache<TEntity>.Name + ".json";
return key.ToString().ToLowerInvariant() + ".json";
}
}
}
|
namespace NumberConverter.Services
{
public interface IConverterService
{
string NumberToWords(decimal number);
}
}
|
namespace Uintra.Features.Media.Strategies.Preset
{
public class MemberProfilePresetStrategy : IPresetStrategy
{
public string ThumbnailPreset { get; } = "preset=profile";
public string PreviewPreset { get; } = "preset=preview";
public string PreviewTwoPreset { get; } = "preset=previewTwo";
public int MediaFilesToDisplay { get; } = int.MaxValue; //Means that all files should render
}
} |
using GameManager;
using UnityEngine;
public class hasAbility : MonoBehaviour
{
private bool crouch;
private bool sprint;
private bool attack;
private allowAbility ability;
private void Start()
{
ability = GetComponentInChildren<allowAbility>();
crouch = ability.crouching;
sprint = ability.sprinting;
attack = ability.attack;
if (crouch && GameManager_Master.Instance.hasCrouch)
{
this.gameObject.SetActive(false);
}
else if (sprint && GameManager_Master.Instance.hasSprint)
{
this.gameObject.SetActive(false);
}
else if (attack && GameManager_Master.Instance.hasAttack)
{
this.gameObject.SetActive(false);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
[RequireComponent(typeof(TMP_Text))]
public class LapCounterUIScript : MonoBehaviour, IObserver<int> {
TMP_Text text;
private static LapCounterUIScript mainInstance;
private void Awake() {
mainInstance = this;
}
public static void SetCar() {
if (mainInstance)
SteeringScript.MainInstance.LapCompletedObservers.Add(mainInstance);
}
// bool init = false;
private void Start() {
// SteeringScript.MainInstance.LapCompletedObservers.Add(this);
// Debug.LogWarning("lap steering: " + SteeringScript.MainInstance.gameObject.name);
text = GetComponent<TMP_Text>();
}
// private void Update() {
// if (init) {
// return;
// }
// SteeringScript.MainInstance.LapCompletedObservers.Add(this);
// init = true;
// }
// when car completes a lap
public void Notify(int lapNumber) {
text.text = lapNumber.ToString();
}
}
|
using System.IO;
using OfficeOpenXml;
namespace FIMMonitoring.Domain.Repositories
{
public class ReportRepository
{
private SoftLogsContext context;
public ReportRepository(SoftLogsContext context)
{
this.context = context;
}
public byte[] GenerateValidationErrorsReport(int importId)
{
var rows = context.GetValidationErrors(importId);
using (var excel = new ExcelPackage())
{
var ws = excel.Workbook.Worksheets.Add("ValidationResults");
ws.Cells["A1"].LoadFromDataTable(rows, true);
using (var ms = new MemoryStream())
{
excel.SaveAs(ms);
return ms.ToArray();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Threading;
using System.Xml;
namespace winFormArduino2web
{
public struct sensorDataField
{
public string fieldName;
public double fieldValue;
}
public partial class Form1 : Form
{
bool startStop = true;
bool sendTestString = false;
string testString = "<tblData><field1>13</field1><field2>26</field2><field3>30</field3></tblData>";
static SerialPort _serialPort;
StreamWriter sw;
string portName;
XmlDocument xmlDoc; XmlNode rootNode;
int numOfFields = 1;
sensorDataField[] FieldsArray;
string tag1 = "<tblData>";
string tag2 = "</tblData>";
string tag3 = "field";
string tag4 = "field";
string outFileName="./data_from_arduino.txt";
public Form1()
{
InitializeComponent();
listBox1.SelectedIndex = 2;
xmlDoc = new XmlDocument(); // Create the XmlDocument.
rootNode = xmlDoc.CreateElement("data");
xmlDoc.AppendChild(rootNode);
}
private void butt_Start_Click(object sender, EventArgs e)
{
if (startStop)//start was clicked
{
_serialPort = new SerialPort();
_serialPort.PortName = portName;// "COM3";//Set your board COM
_serialPort.BaudRate = 9600;
try
{
_serialPort.Open();
butt_Start.Text = "Stop";
startStop = !startStop;
bool append = true;
sw = new StreamWriter("../../data_from_arduino.txt", append);
timer1.Interval = 200;
timer1.Enabled = true;
label_messages.Text = "";
}
catch (Exception ex)
{
// Handle exception
label_messages.Text = ex.Message;
_serialPort.Close();
}
}
else //Stop was clicked
{
butt_Start.Text = "Start";
startStop = !startStop;
timer1.Enabled = false;
_serialPort.Close();
sw.Flush();
sw.Close();
label_messages.Text = "";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
string a = _serialPort.ReadExisting();
textBox1.Text = a;
sw.WriteLine(a);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the currently selected item in the ListBox.
portName = listBox1.SelectedItem.ToString();
//textBox1.Text = portName;
}
private void butOnce_Click(object sender, EventArgs e)
{
if (!int.TryParse(textBox_fields_numbers.Text,out numOfFields))
{
MessageBox.Show("The number of fields must be a number", "Error Detected in Input", MessageBoxButtons.OK);
textBox_fields_numbers.Text = "1";
return;
}
if (numOfFields < 1)
{ MessageBox.Show("The number of fields must be >0", "Error Detected in Input", MessageBoxButtons.OK);
textBox_fields_numbers.Text = "1";
return;
}
FieldsArray = new sensorDataField[numOfFields];// creating array of fields names and values
_serialPort = new SerialPort();
_serialPort.PortName = portName;// "COM3";//Set your board COM
_serialPort.BaudRate = 9600;
try
{
string a;
if (!sendTestString)
{
_serialPort.Open();
a = _serialPort.ReadExisting(); // get string from COM
}
else
a = textBox1.Text;
string pa="";
pa = ParseXml(a); // string that starts and ends with <tbl>
//string parsedTag = ParseXmlTag(ref a);
//LoadXml(pa); // עדיין צריך לפתור עניין אוביקט
textBox1.Text = pa;
Write2File(outFileName,pa);
_serialPort.Close();
if (checkBox1.Checked) // sending to Thingspeak
{
while (pa.Length != 0)
{
string tagString = ParseXmlTag(ref pa); // get first <tblData> xml node
if (!LoadXml2Array(tagString, FieldsArray)) continue; // array faild
label_messages.Text = "Thingspeak: opening web request";
openWebThingspeak(FieldsArray);
label_messages.Text = "finished web request";
}
}
if (checkBox2.Checked) // sending to Bigbangs
{
label_messages.Text = "Bigbangs: opening web request";
openWebBigbangs(pa);
label_messages.Text = "finished web request";
}
}
catch (Exception ex)
{
// Handle exception
label_messages.Text = ex.Message;
_serialPort.Close();
}
}
private void Write2File(string fileName,string str)
{
bool append = true;
sw = new StreamWriter(fileName, append);
sw.WriteLine(str);
sw.Flush();
sw.Close();
}
/// <summary>
/// input a parsed string with correct tags in the begining and end
/// the fuction trys to load it into a sensorDataField array
/// </summary>
/// <param name="pa"></param>
private bool LoadXml2Array(string tagString,sensorDataField[] tbl)
{
for (int i = 1; i <= numOfFields; i++)
{
string openTag = "<"+tag3 + i.ToString() + ">";
string closeTag = "</"+ tag3 + i.ToString() + ">";
string fieldVal = ParseXmlTag(ref tagString, openTag, closeTag);
tbl[i - 1].fieldName = tag3 + i.ToString();
if (!double.TryParse(fieldVal,out tbl[i-1].fieldValue))
{ return false;} //field value failed. skipping the whole <tbl> string
}
//try
//{
// xmlDoc.LoadXml(tagString);
//}
//catch (XmlException e)
//{ }
return true;
}
/// <summary>
/// input a parsed string with correct tags in the begining and end
/// the fuction trys to load it into an XML doc
/// </summary>
/// <param name="pa"></param>
private void LoadXml(string pa)
{
while (pa.Length != 0)
{
string tagString = ParseXmlTag(ref pa);
try
{
xmlDoc.LoadXml(tagString);
}
catch (XmlException e)
{ }
}
}
/// <summary>
/// gets a string, parses tags and load into an XML doc type
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private XmlDocument ParseLoadXml(string str)
{
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
return doc;
}
/// <summary>
/// parses and returns first tag1 to tag2 from string
/// the original string is reducted from the parsed tag string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string ParseXmlTag(ref string str)
{
string st;
int i = str.IndexOf(tag1);
int j = str.IndexOf(tag2);
if (i > j) // first </> tag is before the <> tag
{
str = str.Substring(j + tag2.Length + 1);
i = str.IndexOf(tag1);
j = str.IndexOf(tag2);
}
if (!str.Contains(tag1) || !str.Contains(tag2))
return (string.Empty);
st = str.Substring(i, (j - i + tag2.Length));
if ((j - i + tag2.Length) + 1 >= str.Length)
str = "";
else
str = str.Substring((j - i + tag2.Length) + 1);
return st;
}
/// <summary>
/// parses and returns value of first tag from string
/// the original string is reducted from the parsed tag string
/// </summary>
/// <param name="str"></param><param name="openTag"></param><param name="closeTag"></param>
/// <returns>string</returns>
private string ParseXmlTag(ref string str,string openTag,string closeTag)
{
string st;
int i = str.IndexOf(openTag);
int j = str.IndexOf(closeTag);
if (i > j) // first </> tag is before the <> tag
{
str = str.Substring(j + closeTag.Length + 1); // cut the damaged string
i = str.IndexOf(openTag); // find new indexes
j = str.IndexOf(closeTag);
}
if (!str.Contains(openTag) || !str.Contains(closeTag))
return (string.Empty);
//st = str.Substring(i, (j - i + closeTag.Length)); // get the string with tags
st = str.Substring(i + openTag.Length, (j - i - openTag.Length)); // get the value without tags
str = str.Substring((j - i + closeTag.Length) + 1); // reduce the original string
return st;
}
/// <summary>
/// returns a string that begins and ends with XML tag
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string ParseXml(string str)
{
string tag1="<tblData>";
string tag2 = "</tblData>";
string st;
if (!str.Contains(tag1)||!str.Contains(tag2))
return ("");
int i=str.IndexOf(tag1);
int j = str.LastIndexOf(tag2);
return str.Substring(i, (j - i + tag2.Length));
}
private void openWebThingspeak(sensorDataField[] FieldsArray)
{
string WRITEKEY = textBox2.Text;
//string WRITEKEY = "DC10XQ6LEHXOOAHZ"; // https://thingspeak.com/channels/656336/private_show
string strUpdateBase = "http://api.thingspeak.com/update";
string strUpdateURI = strUpdateBase + "?key=" + WRITEKEY;
for (int i = 0; i < FieldsArray.Length; i++)
{
strUpdateURI += "&" + FieldsArray[i].fieldName + "=" + FieldsArray[i].fieldValue.ToString();
}
try
{
//string strField1 = "20";
//string strField2 = "40";
////HttpWebRequest ThingsSpeakReq;
////HttpWebResponse ThingsSpeakResp;
//strUpdateURI += "&field1=" + strField1;
//strUpdateURI += "&field2=" + strField2;
// ThingsSpeakReq = (HttpWebRequest)WebRequest.Create(strUpdateURI);
WebRequest request = WebRequest.Create(strUpdateURI);//
WebResponse response = request.GetResponse();
//ThingsSpeakResp = (HttpWebResponse)ThingsSpeakReq.GetResponse();
//if (!(string.Equals(ThingsSpeakResp.StatusDescription, "OK")))
//{
// Exception exData = new Exception(ThingsSpeakResp.StatusDescription);
// throw exData;
//}
}
catch (Exception ex)
{
textBox3.Text = ex.Message;
throw;
}
}
private void openWebThingspeakTest()
{
try
{
string WRITEKEY = textBox2.Text;
//string WRITEKEY = "DC10XQ6LEHXOOAHZ"; // https://thingspeak.com/channels/656336/private_show
string strUpdateBase = "http://api.thingspeak.com/update";
string strUpdateURI = strUpdateBase + "?key=" + WRITEKEY;
string strField1 = "20";
string strField2 = "40";
//HttpWebRequest ThingsSpeakReq;
//HttpWebResponse ThingsSpeakResp;
strUpdateURI += "&field1=" + strField1;
strUpdateURI += "&field2=" + strField2;
// ThingsSpeakReq = (HttpWebRequest)WebRequest.Create(strUpdateURI);
WebRequest request = WebRequest.Create(strUpdateURI);//
WebResponse response = request.GetResponse();
//ThingsSpeakResp = (HttpWebResponse)ThingsSpeakReq.GetResponse();
//if (!(string.Equals(ThingsSpeakResp.StatusDescription, "OK")))
//{
// Exception exData = new Exception(ThingsSpeakResp.StatusDescription);
// throw exData;
//}
}
catch (Exception ex)
{
textBox3.Text = ex.Message;
throw;
}
}
private void openWebBigbangs(string pa)
{
try
{
string FOLDER = textBox4.Text;
string strUpdateBase = "http://bigbangs.work/";
string strUpdateURI = strUpdateBase + FOLDER+"/index.php/" + "?data=";
strUpdateURI += pa;
WebRequest request = WebRequest.Create(strUpdateURI);//
WebResponse response = request.GetResponse();
textBox3.Text = ((HttpWebResponse)response).StatusDescription;
response.Close();
//if (!(string.Equals(ThingsSpeakResp.StatusDescription, "OK")))
//{
// Exception exData = new Exception(ThingsSpeakResp.StatusDescription);
// throw exData;
//}
}
catch (Exception ex)
{
textBox3.Text = ex.Message;
throw;
}
}
private void button1_Click(object sender, EventArgs e) // Opens txt file location
{
if (File.Exists(outFileName))
{
string absPath = Path.GetFullPath(outFileName);
System.Diagnostics.Process.Start("explorer.exe", " /select, " + absPath);
}
}
private void checkBoxTest_CheckedChanged(object sender, EventArgs e)
{
if (!checkBoxTest.Checked)
{
checkBoxTest.Text = "Check to send test String";
textBox1.ReadOnly = true;
textBox1.Text = "";
sendTestString = false;
}
else
{
checkBoxTest.Text = "Write in text box string to send";
textBox1.ReadOnly = false;
textBox1.Text = testString;
sendTestString = true;
}
}
}
}
|
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Base;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.Core.Base
{
/// <summary>
/// Servicio que representa los Proveedores
/// </summary>
/// <remarks>
/// Creación: GMD 20150602 <br />
/// Modificación: <br />
/// </remarks>
public interface IProveedorService : IGenericService
{
/// <summary>
/// Realiza la búsqueda de Proveedores del Servicio Web
/// </summary>
/// <param name="filtro">Filtro de búsqueda</param>
/// <returns>Lista de Proveedores del Servicio Web</returns>
ProcessResult<List<ProveedorResponse>> BuscarProveedorOracle(ProveedorRequest filtro);
/// <summary>
/// Realiza la búsqueda de Proveedores del Servicio Web -SAP
/// </summary>
/// <param name="filtro">Filtro de búsqueda</param>
/// <returns>Lista de Proveedores del Servicio Web - SAP</returns>
ProcessResult<List<ProveedorResponse>> BuscarProveedorSAP(ProveedorRequest filtro);
/// <summary>
/// Realiza la búsqueda de un Proveedor y si no existe lo registra
/// </summary>
/// <param name="filtro">Filtro de búsqueda</param>
/// <returns>Registro de Proveedor encontrado o registrado</returns>
ProcessResult<List<ProveedorResponse>> BuscarRegistrarProveedorContrato(ProveedorRequest filtro);
/// <summary>
/// Realiza la búsqueda de Proveedores
/// </summary>
/// <param name="filtro">Filtro de búsqueda</param>
/// <returns>Lista de Proveedores</returns>
ProcessResult<List<ProveedorResponse>> BuscarProveedor(ProveedorRequest filtro);
/// <summary>
/// Realiza la búsqueda de Proveedores
/// </summary>
/// <param name="filtro">Filtro de búsqueda</param>
/// <returns>Lista de Proveedores</returns>
ProcessResult<List<ProveedorResponse>> BuscarProveedorNombreRuc(ProveedorRequest filtro);
}
}
|
using System.Collections;
using System.Collections.Generic;
using DChild.Gameplay.Combat.StatusEffects;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Objects.Characters
{
[System.Serializable]
public class StatusResistances
{
[System.Serializable]
public struct Resistance
{
[SerializeField]
[ReadOnly]
private string m_statusName;
[SerializeField]
public bool isImmune;
public Resistance(string status)
{
m_statusName = status;
isImmune = true;
}
public string statusName
{
get
{
return m_statusName;
}
}
}
[SerializeField]
[ListDrawerSettings(HideAddButton = true, NumberOfItemsPerPage = 5, ShowItemCount = true, ShowPaging = true)]
private Resistance[] m_resistances;
public bool IsImmune<T>() where T : IStatusEffect
{
var typeString = typeof(T).Name;
for (int i = 0; i < m_resistances.Length; i++)
{
if (typeString == m_resistances[i].statusName)
{
return m_resistances[i].isImmune;
}
}
return false;
}
#region Editor
#if UNITY_EDITOR
public void AddStatusResistance(params Resistance[] statusResistances)
{
List<Resistance> statusList = new List<Resistance>(m_resistances);
for (int i = 0; i < statusResistances.Length; i++)
{
statusList.Add(statusResistances[i]);
}
m_resistances = statusList.ToArray();
}
[Button("Initalize")]
private void Initalize()
{
var statusString = Reflection.GetDerivedClassesName(typeof(IStatusEffect));
var statusReferences = new Resistance[statusString.Length];
CopyValues(statusString, ref statusReferences);
m_resistances = statusReferences;
}
private void CopyValues(string[] status,ref Resistance[] resistance)
{
List<Resistance> statusList = new List<Resistance>(m_resistances);
for (int i = 0; i < resistance.Length; i++)
{
resistance[i] = new Resistance(status[i]);
for (int j = 0; j < statusList.Count; j++)
{
if (statusList[j].statusName == resistance[i].statusName)
{
resistance[i].isImmune = statusList[j].isImmune;
statusList.RemoveAt(j);
break;
}
}
}
}
#endif
#endregion
}
} |
using System;
using System.Collections.Generic;
using EasyDev.PL;
using WebCaching = System.Web.Caching;
using System.Web;
using EasyDev.EPS.Attributes;
using System.Threading;
namespace EasyDev.EPS.BusinessObject
{
/// <summary>
/// 业务对象的抽象基类
/// </summary>
public abstract class AbstractBO : IBO
{
private static readonly string DEFAULT_SESSION = "DEFAULT_SESSION";
protected virtual string KeyField
{
get;
set;
}
/// <summary>
/// SESSION集合同时也作为SESSION对象的缓存对象,用于多数据库环境
/// </summary>
private WebCaching.Cache SessionCache { get; set; }
/// <summary>
/// 业务对象所引用的数据模型
/// </summary>
public virtual IModel Model { get; set; }
/// <summary>
/// 默认SESSION对象
/// </summary>
public virtual GenericDBSession DefaultSession
{
get
{
//先从缓存中取Session
GenericDBSession session = SessionCache.Get(DEFAULT_SESSION) as GenericDBSession;
if (session == null)
{
try
{
if (Monitor.TryEnter(SessionCache, 100))
{
if (session == null)
{
session = DBSessionManager.CreateDBSession(DataSourceManager.CreateDefaultDataSource());
SessionCache.Insert(DEFAULT_SESSION, session);
}
}
}
catch (ArgumentException e)
{
throw e;
}
finally
{
Monitor.Exit(SessionCache);
}
}
return session;
}
}
/// <summary>
/// 根据SESSION名称取得会话对象
/// SESSION名称与数据源配置文件中的数据源配置名称对应
/// </summary>
/// <param name="sessionName">会话名称</param>
/// <returns></returns>
public virtual IGenericDBSession GetSessionByName(string sessionName)
{
GenericDBSession session = SessionCache.Get(sessionName) as GenericDBSession;
if (session == null)
{
try
{
if (Monitor.TryEnter(SessionCache, 100))
{
if (session == null)
{
session = DBSessionManager.CreateDBSession(DataSourceManager.CreateDefaultDataSource());
SessionCache.Insert(sessionName, session);
}
}
}
catch (ArgumentException e)
{
throw e;
}
finally
{
Monitor.Exit(SessionCache);
}
}
return session;
}
/// <summary>
/// 初始化方法
/// </summary>
protected virtual void Initialize()
{
//初始化缓存
SessionCache = HttpRuntime.Cache;
}
/// <summary>
/// 构造方法
/// </summary>
protected AbstractBO()
{
Initialize();
}
/// <summary>
/// 取得当前最大的SQU值,用于ORACLE数据库,ORACLE数据库中的SEQUENCE对象必须以SEQ_{表名}命名
/// </summary>
/// <returns></returns>
public virtual string GetNextSequenceId(string tableName)
{
try
{
return Convert.ToString(
DefaultSession.GetScalarObjectFromCommand(
string.Format(@"SELECT SEQ_{0}.nextval FROM dual", tableName)));
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// 取得当前最大的SQU值,用于ORACLE数据库,ORACLE数据库中的SEQUENCE对象必须以SEQ_{表名}命名
/// 此方法会根据Model类的自定义属性来判断模型用于哪个数据库,并根据数据库类型获取序列值
/// </summary>
/// <returns></returns>
public virtual string GetNextSequenceId<TModel>()
{
object[] attr = typeof(TModel).GetCustomAttributes(false);
string dbName = DBName.ORACLE;
if (attr != null && attr.Length > 0 && attr[0].GetType() == typeof(DatabaseNameAttribute))
{
dbName = ((DatabaseNameAttribute)attr[0]).DatabaseName;
}
if (dbName.Equals(DBName.ORACLE, StringComparison.CurrentCultureIgnoreCase))
{
return GetNextSequenceId(typeof(TModel).Name);
}
else
{
return Guid.NewGuid().ToString();
}
}
#region IBO 成员
public virtual bool Save(IModel entity)
{
throw new NotSupportedException();
}
public virtual bool Delete(IModel entity)
{
throw new NotSupportedException();
}
public virtual bool Update(IModel entity)
{
throw new NotSupportedException();
}
public virtual IModel FindByInstance(IModel instance)
{
throw new NotSupportedException();
}
public virtual IList<IModel> FindAllInstance()
{
throw new NotSupportedException();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Usererro 的摘要说明
/// </summary>
public class Usererro
{
public Usererro()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public string shixiao(Object user)
{
if (user == null)
{
return "<script>alert('账号已失效,请重新登录!');top.location.href = 'login.aspx';</script>";
}
else
{
return "";
}
}
} |
using System;
namespace C__Project
{
class Input_Enum
{
enum Months
{
None,
January, // 1
February, // 2
March, // 3
April, // 4
May, // 5
June, // 6
July, // 7
August,
September,
October,
November,
December
}
static void Tenth(string[] args)
{
Console.WriteLine("Enter number from 1-12.");
string mnum;
mnum = Console.ReadLine();
var int1 = int.Parse(mnum);
var output = (Months)int1;
Console.WriteLine(output);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Model.APIModels.Parameter
{
/// <summary>
/// 公共参数
/// </summary>
public class E_BasePara
{
/// <summary>
/// 请求时间
/// </summary>
public DateTime? d { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawn : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
if(_player == null)
{
_player = GameObject.FindGameObjectWithTag("Player");
}
}
public static GameObject _player = null;
public GameObject _enemyPrefab;
public GameObject spawn(Room room)
{
GameObject enemy = GameObject.Instantiate(_enemyPrefab, transform.position, _enemyPrefab.transform.rotation);
EnemyBase ebase = enemy.GetComponent<EnemyBase>();
ebase._player = _player.transform;
ebase._Room = room;
return enemy;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterRespawn : MonoBehaviour
{
private Transform monsterGroup;
public GameObject[] monsterObjects;
public Transform[] instantiatePositions;
[SerializeField]
public int monsterCount = 3;
[SerializeField]
public int remainingMonster = 3;
public int xPos;
public int zPos;
private string[] monsters = { "Kiwi", "Chili", "Eggy" };
// Start is called before the first frame update
void Start()
{
monsterGroup = gameObject.transform;
}
// Update is called once per frame
void Update()
{
if (remainingMonster == 0)
{
StartCoroutine(monsterRespawn());
}
//if (remainingMonster < monsterCount) {
// print("respawn");
// StartCoroutine(monsterRespawn());
//}
}
IEnumerator monsterRespawn()
{
monsterCount++;
//while (remainingMonster < monsterCount)
//{
// xPos = Random.Range(-50,60);
// zPos = Random.Range(163,230);
// monster = GameObject.FindGameObjectWithTag(monsters[Random.Range(0, monsters.Length-1)]);
// Instantiate(monster, new Vector3(xPos, 0.625015f, zPos), Quaternion.identity);
// monster.SetActive(true);
// remainingMonster++;
// yield return new WaitForSeconds(0.1f);
//}
while (remainingMonster < monsterCount)
{
int respawnPosIndex = Random.Range(0, instantiatePositions.Length);
int monsterIndex = Random.Range(0,monsterObjects.Length);
GameObject newMonster = Instantiate(monsterObjects[monsterIndex], monsterGroup);
newMonster.transform.position = instantiatePositions[respawnPosIndex].transform.position;
newMonster.SetActive(true);
//monster = GameObject.FindGameObjectWithTag(monsters[Random.Range(0, monsters.Length - 1)]);
//Instantiate(monster, new Vector3(xPos, 0.625015f, zPos), Quaternion.identity);
//monster.SetActive(true);
remainingMonster++;
yield return new WaitForSeconds(0.1f);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using System.Diagnostics;
namespace goodmatch
{
class Program
{
private static List<string> fline = new List<string>();
private static List<string> males = new List<string>();
private static List<string> females = new List<string>();
private static List<string> flogs = new List<string>();
static void Main(string[] args)
{
var watch = new Stopwatch();
watch.Start();
try
{
using (StreamReader fRead = new StreamReader("C:/Users/User/Desktop/derivco/goodmatch/goodmatch/file.csv"))
{
while (!fRead.EndOfStream)
{
String line = fRead.ReadLine();
String[] names = line.Split(',');
if (names[1].ToLower().Equals("m"))
{
if (!males.Contains(names[0]))
{
males.Add(names[0]);
}
}
else
{
if (!females.Contains(names[0]))
{
females.Add(names[0]);
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The File could not be read:");
Console.WriteLine(e.Message);
}
matchNames(males, females);
_ = writeToFile1();
matchNames(females, males);
_ = writeToFile2();
matchName();
watch.Stop();
flogs.Add($"Execution Time : {watch.ElapsedMilliseconds} ms");
_ = saveLogs();
}
public static void matchName() {
try
{
Console.WriteLine("Enter name 1 : "); var name1 = Console.ReadLine();
Console.WriteLine("Enter name 2 : "); var name2 = Console.ReadLine();
if (isLetter(name1) && isLetter(name2))
{
var sentence = name1 + "matches" + name2;
var num = countLetters(sentence);
var lines = "";
if (Convert.ToInt32(num) >= 80)
{
lines = name1 + " matches " + name2 + " " + num + "%, good match";
Console.WriteLine(lines);
}
else
{
lines = name1 + " matches " + name2 + " " + num + "%";
Console.WriteLine(lines);
}
}
else
{
Console.WriteLine("Enter a string containing only alphabet.");
flogs.Add(name1 + " " + name2);
matchName();
}
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
}
public static async Task saveLogs() {
try
{
using StreamWriter file = new("C:/Users/User/Desktop/derivco/goodmatch/goodmatch/logs.txt", append: true);
foreach (string lines in flogs)
{
await file.WriteLineAsync(lines);
}
Console.WriteLine("Logs have been saved to logs.txt file");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static void matchNames(List<string> male, List<string> female) {
foreach (string name1 in male)
{
foreach (string name2 in female)
{
try
{
if (isLetter(name1) && isLetter(name2))
{
var sentence = name1 + "matches" + name2;
var num = countLetters(sentence);
var lines = "";
if (Convert.ToInt32(num) >= 80)
{
lines = name1 + " matches " + name2 + " " + num + "%, good match";
fline.Add(lines);
}
else
{
lines = name1 + " matches " + name2 + " " + num + "%";
fline.Add(lines);
}
}
else
{
Console.WriteLine("Enter a string containing only alphabet.");
flogs.Add(name1 + " " + name2);
}
}
catch(ArgumentOutOfRangeException e) {
Console.WriteLine(e.Message);
}
}
}
}
public static async Task writeToFile1()
{
try
{
fline.Sort();
using StreamWriter file = new("C:/Users/User/Desktop/derivco/goodmatch/goodmatch/output.txt", append: true);
foreach (string lines in fline)
{
await file.WriteLineAsync(lines);
}
fline.Clear();
Console.WriteLine("Results have been printed on the file called output.txt.");
}catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
public static async Task writeToFile2()
{
try
{
fline.Sort();
using StreamWriter file = new("C:/Users/User/Desktop/derivco/goodmatch/goodmatch/output2.txt", append: true);
foreach (string lines in fline)
{
await file.WriteLineAsync(lines);
}
fline.Clear();
Console.WriteLine("Results for a reverse combination have been printed to output2.txt.");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static bool isLetter(string name)
{
foreach (char c in name)
{
if (!Char.IsLetter(c))
return false;
}
return true;
}
public static string countLetters(string sentence) {
var nums = "";
var cchar = new List<Char>();
var schar = sentence.ToLower().ToCharArray();
int count = 0;
for (int i=0;i<schar.Length;i++) {
if (!cchar.Contains(schar[i]))
{
for (int j=0;j<schar.Length;j++) {
if (schar[i] == schar[j]) {
count++;
}
}
cchar.Add(schar[i]);
nums += Convert.ToString(count);
count = 0;
}
}
cchar.Clear();
List<int> nm = getPercentage(nums);
string vb = "";
for (int i=0;i<nm.Count();i++) {
vb += nm[i];
}
return vb;
}
public static List<int> getPercentage(string nums) {
char[] nc = nums.ToCharArray();
List<int> ll = new List<int>();
int per = 0;
if (nc.Length < 3) {
foreach (char c in nc) {
ll.Add(Convert.ToInt32(char.GetNumericValue(c)));
}
return ll;
}else {
int fCount = 0;
int bCount = nc.Length-1;
var numss = "";
while (fCount <= bCount)
{
if (fCount != bCount)
{
per = int.Parse(nc[fCount].ToString()) + int.Parse(nc[bCount].ToString());
numss += Convert.ToString(per);
ll.Add(per);
fCount++;
bCount--;
}
else
{
per = int.Parse(nc[fCount].ToString());
numss += Convert.ToString(per);
ll.Add(per);
break;
}
}
return getPercentage(numss);
}
}
}
}
|
namespace XH.Commands.Projects
{
public class CreateProjectCommand : CreateOrUpdateProjectCommand
{
}
} |
#if !UNITY_2018_3_OR_NEWER
using UnityEditor;
using UnityEngine;
namespace PumpEditor
{
public class ProjectSettingsSelectEditorWindow : EditorWindow
{
private bool showSettingsInspector;
private Vector2 windowScrollPosition;
private Vector2 buttonsScrollPosition;
private Vector2 inspectorScrollPosition;
[MenuItem("Window/Pump Editor/Project Settings Select")]
private static void Init()
{
var window = EditorWindow.GetWindow<ProjectSettingsSelectEditorWindow>();
var icon = EditorGUIUtility.Load("SettingsIcon") as Texture2D;
window.titleContent = new GUIContent("Project", icon);
window.Show();
}
private static void DrawProjectSettingsButton(string menuItemName)
{
if (GUILayout.Button(menuItemName, GUILayout.MinWidth(150)))
{
var menuItemPath = "Edit/Project Settings/" + menuItemName;
EditorApplication.ExecuteMenuItem(menuItemPath);
}
}
private static void DrawTargetTitle(string title)
{
EditorGUILayout.BeginHorizontal(GUI.skin.box);
EditorGUILayout.LabelField(title);
EditorGUILayout.EndHorizontal();
}
private void OnGUI()
{
windowScrollPosition = EditorGUILayout.BeginScrollView(windowScrollPosition);
EditorGUILayout.BeginHorizontal();
ProjectSettingsButtonsGUI();
ProjectSettingsInspectorGUI();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
}
private void OnSelectionChange()
{
Repaint();
}
private void ProjectSettingsButtonsGUI()
{
EditorGUILayout.BeginVertical();
EditorGUILayout.Space();
showSettingsInspector = EditorGUILayout.Toggle("Show Settings Inspector", showSettingsInspector);
EditorGUILayout.Space();
buttonsScrollPosition = EditorGUILayout.BeginScrollView(buttonsScrollPosition);
EditorGUILayout.BeginVertical(GUI.skin.box);
DrawProjectSettingsButton("Input");
DrawProjectSettingsButton("Tags and Layers");
DrawProjectSettingsButton("Audio");
DrawProjectSettingsButton("Time");
DrawProjectSettingsButton("Player");
DrawProjectSettingsButton("Physics");
DrawProjectSettingsButton("Physics 2D");
DrawProjectSettingsButton("Quality");
DrawProjectSettingsButton("Graphics");
DrawProjectSettingsButton("Network");
DrawProjectSettingsButton("Editor");
DrawProjectSettingsButton("Script Execution Order");
DrawProjectSettingsButton("Preset Manager");
EditorGUILayout.EndVertical();
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
private void ProjectSettingsInspectorGUI()
{
if (!showSettingsInspector)
{
return;
}
var selectedObject = Selection.activeObject;
if (selectedObject == null
|| !ProjectSettingsTypeHelper.IsProjectSettingsType(selectedObject))
{
EditorGUILayout.BeginVertical();
EditorGUILayout.Space();
EditorGUILayout.HelpBox("No project settings to inspect.", MessageType.Info);
EditorGUILayout.EndVertical();
return;
}
inspectorScrollPosition = EditorGUILayout.BeginScrollView(inspectorScrollPosition);
EditorGUILayout.Space();
var targetTitle = ProjectSettingsTypeHelper.GetProjectSettingsTargetTitle(selectedObject);
DrawTargetTitle(targetTitle);
EditorGUILayout.BeginVertical();
Editor editor = Editor.CreateEditor(selectedObject);
editor.OnInspectorGUI();
EditorGUILayout.EndVertical();
EditorGUILayout.EndScrollView();
}
}
}
#endif
|
public enum Abilities {None = 0, Shield = 1, Boost = 2};
|
using Register.DataManager;
using Register.Model.DatabaseModel;
using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Register.Common.Helper;
using Register.Repository;
namespace Register.Controllers
{
//[RoutePrefix("register")]
public class RegisterController : BaseController
{
// GET: Register
[Route("")]
public ActionResult List()
{
var studentList = _dataManager.List<Student>();
var studentViewModelList = Mapper.MapStudentStudentViewModel(studentList.ToList());
return View(studentViewModelList);
}
[Route("detail/{id}")]
public ActionResult Details(int id)
{
return View();
}
[Route("create")]
[HttpGet]
public ActionResult Create()
{
var student = new Student();
LoadCityDropDownViewBag();
return View(student);
}
[Route("create/{collection?}")]
[HttpPost]
public ActionResult Create(Student collection)
{
try
{
if (ModelState.IsValid)
{
// var student = new Student();
collection.City = _dataManager.GetById<City>((int)collection.City.Id);
collection.District = _dataManager.GetById<District>((int)collection.District.Id);
_dataManager.SaveOrChange(collection);
return RedirectToAction("List");
}
else
{
LoadCityDropDownViewBag();
return View(collection);
}
}
catch
{
LoadCityDropDownViewBag();
return View(collection);
}
}
[Route("edit/{id}")]
public ActionResult Edit(int id)
{
var student = _dataManager.GetById<Student>(id); //context.Student.Where(x=>x.Id == id).FirstOrDefault();
LoadCityDropDownViewBag();
LoadDistrictDropDownViewBag(student.City.Id);
return View(student);
}
[Route("edit/{id?}/{collection?}")]
[HttpPost]
public ActionResult Edit(int id, Student collection)
{
try
{
if (ModelState.IsValid)
{
// var student = new Student();
collection.City = _dataManager.GetById<City>((int)collection.City.Id);
collection.District = _dataManager.GetById<District>((int)collection.District.Id);
_dataManager.SaveOrChange(collection);
return RedirectToAction("List");
}
else
{
LoadCityDropDownViewBag();
return View(collection);
}
}
catch
{
LoadCityDropDownViewBag();
return View(collection);
}
}
// GET: Deneme/Delete/5
[Route("delete/{id}")]
public ActionResult Delete(int id)
{
var student = _dataManager.GetById<Student>(id);
return View(student);
}
[Route("delete/{id?}/{collection?}")]
[HttpPost]
public ActionResult Delete(int id, Student collection)
{
try
{
var student = _dataManager.GetById<Student>(id);
_dataManager.Delete(student);
return RedirectToAction("List");
}
catch
{
return View();
}
}
[Route("districts/{id?}")]
[HttpPost]
public JsonResult GetDistricts(int id)
{
if (id == default(int))
{
return null;
}
try
{
var districts = _dataManager.FindBy<District>(x => x.City.Id == id);//context.District.Where(x => x.City_Id == id).ToList();
var list = districts.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name }).ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
return null; //ThrowJSONError(exception);
}
}
}
} |
using System;
using IrsMonkeyApi.Models.DB;
using Microsoft.AspNetCore.Mvc;
namespace IrsMonkeyApi.Models.DAL
{
public class MemberDal : IMemberDal
{
private readonly IRSMonkeyContext _context;
public MemberDal(IRSMonkeyContext context)
{
_context = context;
}
public Member GetMember(Guid memberId)
{
try
{
var member = _context.Member.Find(memberId);
return member;
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public Member CreateMember(Member member)
{
try
{
_context.Member.Add(member);
var newMember = _context.SaveChanges();
return newMember > 0 ? member : null;
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public Member UpdateMember(Member member)
{
try
{
_context.Update(member);
var updatedMember = _context.SaveChanges();
return updatedMember > 0 ? member : null;
}
catch (Exception)
{
throw;
}
}
}
} |
using UnityEngine;
using System.Collections;
public class StateMachine<T>
{
private State<T> currentState;
private State<T> previousState;
public StateMachine(State<T> _startState)
{
ChangeState(_startState);
}
public void ChangeState(State<T> _nextState)
{
if(currentState != null)
{
currentState.Exit();
}
previousState = currentState;
currentState = _nextState;
if(currentState != null)
{
currentState.sm = this;
currentState.Enter();
}
}
public void RevertState()
{
ChangeState(previousState);
}
public void Update()
{
if (currentState != null)
{
currentState.Update();
}
}
}
|
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Autofac.Integration.WebApi;
namespace AspNetMvcSample.Capsule.Modules
{
public class ControllerCapsuleModule: Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
// Register the MVC Controllers
//builder.RegisterControllers(Assembly.Load("KiksApp.Web"));
// Register the Web API Controllers
//builder.RegisterApiControllers(Assembly.GetCallingAssembly());
builder.RegisterApiControllers(Assembly.Load("AspNetMvcSample"));
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Plugins.Messenger;
using Cirrious.MvvmCross.ViewModels;
using ResidentAppCross.ServiceClient;
namespace ResidentAppCross
{
public class App : MvxApplication
{
public App()
{
//Mvx.RegisterType<ICalculation, Calculation>();
Mvx.RegisterSingleton<IMvxAppStart>(new MvxAppStart<LoginViewModel>());
Mvx.RegisterSingleton(new ApplicationContext());
Mvx.RegisterSingleton<IRestClient>(new RestClient());
Mvx.RegisterType<ILoginManager,LoginService>();
}
}
public interface IQueryMenuItems
{
}
public class ApplicationContext
{
public string LoginId;
public string Username;
}
public class LoginViewModel : MvxViewModel
{
public ILoginManager LoginManager { get; }
private string _username;
public string Username
{
get { return _username; }
set { _username = value;
SetProperty(ref _username, value, "Username");
}
}
private string _password;
public string Password
{
get { return _password; }
set { SetProperty(ref _password, value, "Password"); }
}
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set { SetProperty(ref _errorMessage, value, "ErrorMessage"); }
}
public LoginViewModel(ILoginManager loginManager)
{
LoginManager = loginManager;
}
public ICommand LoginCommand
{
get
{
return new MvxCommand(async () =>
{
var result = await LoginManager.Login(Username, Password);
if (result == null)
{
ShowViewModel<HomeViewModel>();
}
else
{
ErrorMessage = result;
}
//ShowViewModel<HomeViewModel>()
}, () => true);
}
}
}
public class HomeViewModel : MvxViewModel
{
public HomeViewModel()
{
MenuItems.Add(new MenuItemViewModel()
{
Name = "Home"
});
MenuItems.Add(new MenuItemViewModel()
{
Name = "Maitenance Request"
});
MenuItems.Add(new MenuItemViewModel()
{
Name = "Request Courtest Officer"
});
MenuItems.Add(new MenuItemViewModel()
{
Name = "Pay Rent"
});
MenuItems.Add(new MenuItemViewModel()
{
Name = "Community Partners"
});
}
private ObservableCollection<MenuItemViewModel> _menuItems = new ObservableCollection<MenuItemViewModel>();
public ObservableCollection<MenuItemViewModel> MenuItems
{
get { return _menuItems; }
set { _menuItems = value; RaisePropertyChanged("MenuItems"); }
}
}
public class MenuItemViewModel : MvxViewModel
{
public string Name { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TimeAttack : MonoBehaviour
{
public float timer;
public LifeGauge lifeGauge;
public Text text;
const string FORMATTER = "Time Attack: {0:F2}";
// Start is called before the first frame update
void Start()
{
timer = 0;
text.text = string.Format(FORMATTER, timer);
}
// Update is called once per frame
void Update()
{
if (lifeGauge.life > 0)
{
timer += Time.deltaTime;
}
text.text = string.Format(FORMATTER, timer);
}
}
|
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace powerDg.KMS.Data
{
/* This is used if database provider does't define
* IKMSDbSchemaMigrator implementation.
*/
public class NullKMSDbSchemaMigrator : IKMSDbSchemaMigrator, ITransientDependency
{
public Task MigrateAsync()
{
return Task.CompletedTask;
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7DRL_2021
{
static class InputUtil
{
public static Dictionary<Keys, Point> NumpadKeys = new Dictionary<Keys, Point>()
{
{ Keys.NumPad1, new Point(-1, +1) },
{ Keys.NumPad2, new Point(0, +1) },
{ Keys.NumPad3, new Point(+1, +1) },
{ Keys.NumPad4, new Point(-1, 0) },
//Numpad5 is no direction
{ Keys.NumPad6, new Point(+1, 0) },
{ Keys.NumPad7, new Point(-1, -1) },
{ Keys.NumPad8, new Point(0, -1) },
{ Keys.NumPad9, new Point(+1, -1) },
};
public static Dictionary<Keys, Point> WASDKeys = new Dictionary<Keys, Point>()
{
{ Keys.W, new Point(0, -1) },
{ Keys.A, new Point(-1, 0) },
{ Keys.S, new Point(0, +1) },
{ Keys.D, new Point(+1, 0) },
};
public static Dictionary<Keys, Point> ArrowKeys = new Dictionary<Keys, Point>()
{
{ Keys.Up, new Point(0, -1) },
{ Keys.Left, new Point(-1, 0) },
{ Keys.Down, new Point(0, +1) },
{ Keys.Right, new Point(+1, 0) },
};
public static Dictionary<Keys, int> NumberKeys = new Dictionary<Keys, int>()
{
{ Keys.D0, 0 },
{ Keys.D1, 1 },
{ Keys.D2, 2 },
{ Keys.D3, 3 },
{ Keys.D4, 4 },
{ Keys.D5, 5 },
{ Keys.D6, 6 },
{ Keys.D7, 7 },
{ Keys.D8, 8 },
{ Keys.D9, 9 },
};
public static Point? GetDirectionNumpadDown(InputTwinState state)
{
var result = NumpadKeys.Where(x => state.IsKeyDown(x.Key)).Select(x => x.Value);
if (result.Count() == 1)
return result.Single();
return null;
}
public static Point? GetDirectionNumpadPressed(InputTwinState state, int repeatStart, int repeatStep)
{
var result = NumpadKeys.Where(x => state.IsKeyPressed(x.Key, repeatStart, repeatStep)).Select(x => x.Value);
if (result.Count() == 1)
return result.Single();
return null;
}
public static Point? GetDirectionDown(this IDictionary<Keys, Point> map, InputTwinState state)
{
var shift = state.IsKeyDown(Keys.LeftShift);
var result = map.Where(x => state.IsKeyDown(x.Key)).Select(x => x.Value);
if (result.Count() < 2 && shift)
return null;
var direction = result.Aggregate(Point.Zero, (a, b) => a + b);
if (direction == Point.Zero)
return null;
return direction;
}
public static Point? GetDirectionPressed(this IDictionary<Keys, Point> map, InputTwinState state, int repeatStart, int repeatStep)
{
if (map.Any(x => state.IsKeyPressed(x.Key, repeatStart, repeatStep)))
return GetDirectionDown(map, state);
return null;
}
public static int? GetNumberDown(this IDictionary<Keys, int> map, InputTwinState state)
{
var result = map.Where(x => state.IsKeyDown(x.Key)).Select(x => x.Value);
if (result.Count() == 1)
return result.Single();
return null;
}
public static int? GetNumberPressed(this IDictionary<Keys, int> map, InputTwinState state)
{
var result = map.Where(x => state.IsKeyPressed(x.Key)).Select(x => x.Value);
if (result.Count() == 1)
return result.Single();
return null;
}
public static int? GetNumberPressed(this IDictionary<Keys, int> map, InputTwinState state, int repeatStart, int repeatStep)
{
var result = map.Where(x => state.IsKeyPressed(x.Key, repeatStart, repeatStep)).Select(x => x.Value);
if (result.Count() == 1)
return result.Single();
return null;
}
}
}
|
using System;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace StarlightRiver.Projectiles
{
public class GlassSpike : ModProjectile
{
public override void SetDefaults()
{
projectile.hostile = true;
projectile.width = 22;
projectile.height = 22;
projectile.penetrate = 1;
projectile.timeLeft = 180;
projectile.tileCollide = true;
projectile.ignoreWater = true;
projectile.damage = 5;
}
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Glass Spike");
}
public override void AI()
{
for (int k = 0; k <= 1; k++)
{
Dust.NewDustPerfect(projectile.Center + projectile.velocity * 3, ModContent.DustType<Dusts.Air>(), (projectile.velocity * (Main.rand.NextFloat(-0.25f, -0.05f))).RotatedBy((k == 0) ? 0.4f : - 0.4f), 0, default, 0.5f);
}
projectile.rotation = projectile.velocity.ToRotation() + (3.14f / 4);
}
public override void ModifyHitPlayer(Player target, ref int damage, ref bool crit)
{
target.AddBuff(BuffID.Bleeding, 300);
}
public override void Kill(int timeLeft)
{
for (int k = 0; k <= 10; k++)
{
Dust.NewDust(projectile.position, 22, 22, ModContent.DustType<Dusts.Glass2>(), projectile.velocity.X * 0.5f, projectile.velocity.Y * 0.5f);
Dust.NewDust(projectile.position, 22, 22, ModContent.DustType<Dusts.Air>());
}
Main.PlaySound(SoundID.Shatter, projectile.Center);
}
}
} |
namespace Linq.Range.Tests
{
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class SliceTests
{
[TestMethod]
public void NonEmptySourceTests()
{
int[] source = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Multiple elements in the middle.
Assert.IsTrue(source.Slice(^9..5).ToArray().SequenceEqual(source[^9..5]));
Assert.IsTrue(source.Slice(2..7).ToArray().SequenceEqual(source[2..7]));
Assert.IsTrue(source.Slice(2..^4).ToArray().SequenceEqual(source[2..^4]));
Assert.IsTrue(source.Slice(^7..^4).ToArray().SequenceEqual(source[^7..^4]));
Assert.IsTrue(source.Hide().Slice(^9..5).ToArray().SequenceEqual(source[^9..5]));
Assert.IsTrue(source.Hide().Slice(2..7).ToArray().SequenceEqual(source[2..7]));
Assert.IsTrue(source.Hide().Slice(2..^4).ToArray().SequenceEqual(source[2..^4]));
Assert.IsTrue(source.Hide().Slice(^7..^4).ToArray().SequenceEqual(source[^7..^4]));
// Rang with one index.
Assert.IsTrue(source.Slice(^9..).ToArray().SequenceEqual(source[^9..]));
Assert.IsTrue(source.Slice(2..).ToArray().SequenceEqual(source[2..]));
Assert.IsTrue(source.Slice(..^4).ToArray().SequenceEqual(source[..^4]));
Assert.IsTrue(source.Slice(..6).ToArray().SequenceEqual(source[..6]));
Assert.IsTrue(source.Hide().Slice(^9..).ToArray().SequenceEqual(source[^9..]));
Assert.IsTrue(source.Hide().Slice(2..).ToArray().SequenceEqual(source[2..]));
Assert.IsTrue(source.Hide().Slice(..^4).ToArray().SequenceEqual(source[..^4]));
Assert.IsTrue(source.Hide().Slice(..6).ToArray().SequenceEqual(source[..6]));
// All.
Assert.IsTrue(source.Slice(..).ToArray().SequenceEqual(source[..]));
Assert.IsTrue(source.Hide().Slice(..).ToArray().SequenceEqual(source[..]));
// Single element in the middle.
Assert.IsTrue(source.Slice(^9..2).ToArray().SequenceEqual(source[^9..2]));
Assert.IsTrue(source.Slice(2..3).ToArray().SequenceEqual(source[2..3]));
Assert.IsTrue(source.Slice(2..^7).ToArray().SequenceEqual(source[2..^7]));
Assert.IsTrue(source.Slice(^5..^4).ToArray().SequenceEqual(source[^5..^4]));
Assert.IsTrue(source.Hide().Slice(^9..2).ToArray().SequenceEqual(source[^9..2]));
Assert.IsTrue(source.Hide().Slice(2..3).ToArray().SequenceEqual(source[2..3]));
Assert.IsTrue(source.Hide().Slice(2..^7).ToArray().SequenceEqual(source[2..^7]));
Assert.IsTrue(source.Hide().Slice(^5..^4).ToArray().SequenceEqual(source[^5..^4]));
// Single element at start.
Assert.IsTrue(source.Slice(^10..1).ToArray().SequenceEqual(source[^10..1]));
Assert.IsTrue(source.Slice(0..1).ToArray().SequenceEqual(source[0..1]));
Assert.IsTrue(source.Slice(0..^9).ToArray().SequenceEqual(source[0..^9]));
Assert.IsTrue(source.Slice(^10..^9).ToArray().SequenceEqual(source[^10..^9]));
Assert.IsTrue(source.Hide().Slice(^10..1).ToArray().SequenceEqual(source[^10..1]));
Assert.IsTrue(source.Hide().Slice(0..1).ToArray().SequenceEqual(source[0..1]));
Assert.IsTrue(source.Hide().Slice(0..^9).ToArray().SequenceEqual(source[0..^9]));
Assert.IsTrue(source.Hide().Slice(^10..^9).ToArray().SequenceEqual(source[^10..^9]));
// Single element at end.
Assert.IsTrue(source.Slice(^1..10).ToArray().SequenceEqual(source[^1..10]));
Assert.IsTrue(source.Slice(9..10).ToArray().SequenceEqual(source[9..10]));
Assert.IsTrue(source.Slice(9..^0).ToArray().SequenceEqual(source[9..^0]));
Assert.IsTrue(source.Slice(^1..^0).ToArray().SequenceEqual(source[^1..^0]));
Assert.IsTrue(source.Hide().Slice(^1..10).ToArray().SequenceEqual(source[^1..10]));
Assert.IsTrue(source.Hide().Slice(9..10).ToArray().SequenceEqual(source[9..10]));
Assert.IsTrue(source.Hide().Slice(9..^0).ToArray().SequenceEqual(source[9..^0]));
Assert.IsTrue(source.Hide().Slice(^1..^0).ToArray().SequenceEqual(source[^1..^0]));
// No element.
Assert.IsTrue(source.Slice(3..3).ToArray().SequenceEqual(source[3..3]));
Assert.IsTrue(source.Slice(6..^4).ToArray().SequenceEqual(source[6..^4]));
Assert.IsTrue(source.Slice(3..^7).ToArray().SequenceEqual(source[3..^7]));
Assert.IsTrue(source.Slice(^3..7).ToArray().SequenceEqual(source[^3..7]));
Assert.IsTrue(source.Slice(^6..^6).ToArray().SequenceEqual(source[^6..^6]));
Assert.IsTrue(source.Hide().Slice(3..3).ToArray().SequenceEqual(source[3..3]));
Assert.IsTrue(source.Hide().Slice(6..^4).ToArray().SequenceEqual(source[6..^4]));
Assert.IsTrue(source.Hide().Slice(3..^7).ToArray().SequenceEqual(source[3..^7]));
Assert.IsTrue(source.Hide().Slice(^3..7).ToArray().SequenceEqual(source[^3..7]));
Assert.IsTrue(source.Hide().Slice(^6..^6).ToArray().SequenceEqual(source[^6..^6]));
// Invalid range.
Assert.ThrowsException<OverflowException>(() => source[3..2].ToArray());
Assert.IsFalse(source.Slice(3..2).Any());
Assert.ThrowsException<OverflowException>(() => source[6..^5].ToArray());
Assert.IsFalse(source.Slice(6..^5).Any());
Assert.ThrowsException<OverflowException>(() => source[3..^8].ToArray());
Assert.IsFalse(source.Slice(3..^8).Any());
Assert.ThrowsException<OverflowException>(() => source[^6..^7].ToArray());
Assert.IsFalse(source.Slice(^6..^7).Any());
Assert.ThrowsException<OverflowException>(() => source[3..2].ToArray());
Assert.IsFalse(source.Hide().Slice(3..2).Any());
Assert.ThrowsException<OverflowException>(() => source[6..^5].ToArray());
Assert.IsFalse(source.Hide().Slice(6..^5).Any());
Assert.ThrowsException<OverflowException>(() => source[3..^8].ToArray());
Assert.IsFalse(source.Hide().Slice(3..^8).Any());
Assert.ThrowsException<OverflowException>(() => source[^6..^7].ToArray());
Assert.IsFalse(source.Hide().Slice(^6..^7).Any());
}
[TestMethod]
public void EmptySourceTests()
{
int[] source = { };
// Multiple elements in the middle.
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^9..5].ToArray());
Assert.IsFalse(source.Slice(^9..5).Any());
Assert.ThrowsException<ArgumentException>(() => source[2..7].ToArray());
Assert.IsFalse(source.Slice(2..7).Any());
Assert.ThrowsException<OverflowException>(() => source[2..^4].ToArray());
Assert.IsFalse(source.Slice(2..^4).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^7..^4].ToArray());
Assert.IsFalse(source.Slice(^7..^4).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^9..5].ToArray());
Assert.IsFalse(source.Hide().Slice(^9..5).Any());
Assert.ThrowsException<ArgumentException>(() => source[2..7].ToArray());
Assert.IsFalse(source.Hide().Slice(2..7).Any());
Assert.ThrowsException<OverflowException>(() => source[2..^4].ToArray());
Assert.IsFalse(source.Hide().Slice(2..^4).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^7..^4].ToArray());
Assert.IsFalse(source.Hide().Slice(^7..^4).Any());
// Rang with one index.
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^9..].ToArray());
Assert.IsFalse(source.Slice(^9..).Any());
Assert.ThrowsException<OverflowException>(() => source[2..].ToArray());
Assert.IsFalse(source.Slice(2..).Any());
Assert.ThrowsException<OverflowException>(() => source[..^4].ToArray());
Assert.IsFalse(source.Slice(..^4).Any());
Assert.ThrowsException<ArgumentException>(() => source[..6].ToArray());
Assert.IsFalse(source.Slice(..6).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^9..].ToArray());
Assert.IsFalse(source.Hide().Slice(^9..).Any());
Assert.ThrowsException<OverflowException>(() => source[2..].ToArray());
Assert.IsFalse(source.Hide().Slice(2..).Any());
Assert.ThrowsException<OverflowException>(() => source[..^4].ToArray());
Assert.IsFalse(source.Hide().Slice(..^4).Any());
Assert.ThrowsException<ArgumentException>(() => source[..6].ToArray());
Assert.IsFalse(source.Hide().Slice(..6).Any());
// All.
var xx = source[..];
Assert.IsTrue(source.Slice(..).ToArray().SequenceEqual(source[..]));
Assert.IsTrue(source.Hide().Slice(..).ToArray().SequenceEqual(source[..]));
// Single element in the middle.
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^9..2].ToArray());
Assert.IsFalse(source.Slice(^9..2).Any());
Assert.ThrowsException<ArgumentException>(() => source[2..3].ToArray());
Assert.IsFalse(source.Slice(2..3).Any());
Assert.ThrowsException<OverflowException>(() => source[2..^7].ToArray());
Assert.IsFalse(source.Slice(2..^7).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^5..^4].ToArray());
Assert.IsFalse(source.Slice(^5..^4).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^9..2].ToArray());
Assert.IsFalse(source.Hide().Slice(^9..2).Any());
Assert.ThrowsException<ArgumentException>(() => source[2..3].ToArray());
Assert.IsFalse(source.Hide().Slice(2..3).Any());
Assert.ThrowsException<OverflowException>(() => source[2..^7].ToArray());
Assert.IsFalse(source.Hide().Slice(2..^7).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^5..^4].ToArray());
Assert.IsFalse(source.Hide().Slice(^5..^4).Any());
// Single element at start.
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^10..1].ToArray());
Assert.IsFalse(source.Slice(^10..1).Any());
Assert.ThrowsException<ArgumentException>(() => source[0..1].ToArray());
Assert.IsFalse(source.Slice(0..1).Any());
Assert.ThrowsException<OverflowException>(() => source[0..^9].ToArray());
Assert.IsFalse(source.Slice(0..^9).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^10..^9].ToArray());
Assert.IsFalse(source.Slice(^10..^9).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^10..1].ToArray());
Assert.IsFalse(source.Hide().Slice(^10..1).Any());
Assert.ThrowsException<ArgumentException>(() => source[0..1].ToArray());
Assert.IsFalse(source.Hide().Slice(0..1).Any());
Assert.ThrowsException<OverflowException>(() => source[0..^9].ToArray());
Assert.IsFalse(source.Hide().Slice(0..^9).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^10..^9].ToArray());
Assert.IsFalse(source.Hide().Slice(^10..^9).Any());
// Single element at end.
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^1..10].ToArray());
Assert.IsFalse(source.Slice(^1..^10).Any());
Assert.ThrowsException<ArgumentException>(() => source[9..10].ToArray());
Assert.IsFalse(source.Slice(9..10).Any());
Assert.ThrowsException<OverflowException>(() => source[9..^0].ToArray());
Assert.IsFalse(source.Slice(9..^9).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^1..^0].ToArray());
Assert.IsFalse(source.Slice(^1..^9).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^1..10].ToArray());
Assert.IsFalse(source.Hide().Slice(^1..^10).Any());
Assert.ThrowsException<ArgumentException>(() => source[9..10].ToArray());
Assert.IsFalse(source.Hide().Slice(9..10).Any());
Assert.ThrowsException<OverflowException>(() => source[9..^0].ToArray());
Assert.IsFalse(source.Hide().Slice(9..^9).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^1..^0].ToArray());
Assert.IsFalse(source.Hide().Slice(^1..^9).Any());
// No element.
Assert.ThrowsException<ArgumentException>(() => source[3..3].ToArray());
Assert.IsFalse(source.Slice(3..3).Any());
Assert.ThrowsException<OverflowException>(() => source[6..^4].ToArray());
Assert.IsFalse(source.Slice(6..^4).Any());
Assert.ThrowsException<OverflowException>(() => source[3..^7].ToArray());
Assert.IsFalse(source.Slice(3..^7).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^3..7].ToArray());
Assert.IsFalse(source.Slice(^3..7).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^6..^6].ToArray());
Assert.IsFalse(source.Slice(^6..^6).Any());
Assert.ThrowsException<ArgumentException>(() => source[3..3].ToArray());
Assert.IsFalse(source.Hide().Slice(3..3).Any());
Assert.ThrowsException<OverflowException>(() => source[6..^4].ToArray());
Assert.IsFalse(source.Hide().Slice(6..^4).Any());
Assert.ThrowsException<OverflowException>(() => source[3..^7].ToArray());
Assert.IsFalse(source.Hide().Slice(3..^7).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^3..7].ToArray());
Assert.IsFalse(source.Hide().Slice(^3..7).Any());
Assert.ThrowsException<ArgumentOutOfRangeException>(() => source[^6..^6].ToArray());
Assert.IsFalse(source.Hide().Slice(^6..^6).Any());
// Invalid range.
Assert.ThrowsException<OverflowException>(() => source[3..2].ToArray());
Assert.IsFalse(source.Slice(3..2).Any());
Assert.ThrowsException<OverflowException>(() => source[6..^5].ToArray());
Assert.IsFalse(source.Slice(6..^5).Any());
Assert.ThrowsException<OverflowException>(() => source[3..^8].ToArray());
Assert.IsFalse(source.Slice(3..^8).Any());
Assert.ThrowsException<OverflowException>(() => source[^6..^7].ToArray());
Assert.IsFalse(source.Slice(^6..^7).Any());
Assert.ThrowsException<OverflowException>(() => source[3..2].ToArray());
Assert.IsFalse(source.Hide().Slice(3..2).Any());
Assert.ThrowsException<OverflowException>(() => source[6..^5].ToArray());
Assert.IsFalse(source.Hide().Slice(6..^5).Any());
Assert.ThrowsException<OverflowException>(() => source[3..^8].ToArray());
Assert.IsFalse(source.Hide().Slice(3..^8).Any());
Assert.ThrowsException<OverflowException>(() => source[^6..^7].ToArray());
Assert.IsFalse(source.Hide().Slice(^6..^7).Any());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Middleware.Data
{
public class Device
{
public int Id { get; set; }
public string DeviceId { get; set; }
public string DeviceName { get; set; }
public bool? SatelliteCapable { get; set; }
public double SequenceNumber { get; set; }
public double LastCom { get; set; }
public int State { get; set; }
public int ComState { get; set; }
public string Pac { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
public string DeviceTypeId { get; set; }
public string GroupId { get; set; }
public int Lqi { get; set; }
public double ActivationTime { get; set; }
public int TokenState { get; set; }
public string TokenDetailMessage { get; set; }
public int TokenEnd { get; set; }
public string ContractId { get; set; }
public double CreationTime { get; set; }
public string ModemCertificateId { get; set; }
public bool? Prototype { get; set; }
public string ProductCertificateId { get; set; }
public bool? AutomaticRenewal { get; set; }
public int AutomaticRenewalStatus { get; set; }
public string CreatedBy { get; set; }
public double LastEditionTime { get; set; }
public string LastEditedBy { get; set; }
public bool? Activable { get; set; }
public byte[] Payload { get; set; }
public string DateReceived { get; set; }
public string RequestOrigin { get; set; }
public int Type { get; set; }
public string Data { get; set; }
public double SeqNumber { get; set; }
public string SigfoxDeviceTypeId { get; set; }
public string Acknowledgment { get; set; }
public string LongPolling { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class BPRegistration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SendMail()
{
try
{
MailMessage mail = new MailMessage();
mail.To.Add("mudrameri@gmail.com");
mail.From = new MailAddress("newleadgenerated@gmail.com");
mail.Subject = "New BP Registration For MM";
string Body = "Name:-" + txtBPName.Text + Environment.NewLine + "Mobile:-" + txtBPNumber.Text + Environment.NewLine + "Email:-" + txtBPEmail.Text + Environment.NewLine + "PAN:-" + txtBPPAN.Text + Environment.NewLine + "Aadhar:-" + txtBPAadhar.Text + Environment.NewLine + "Company:-" + txtBPCompany.Text + Environment.NewLine + "City:-" + txtBPCity.Text;
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("newleadgenerated@gmail.com", "@789!@emw!");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
lblMsg.Text = "MMBP Registration Successful.";
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
}
}
protected void btnBPSubmit_Click(object sender, EventArgs e)
{
SendMail();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Command.Piekarnia
{
public class ChlebJasny : IPrzepis
{
public void PodajPrzepis()
{
Console.WriteLine("Piekę chleb jasny!");
}
}
}
|
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Formatter;
using MQTTnet.Client;
namespace MQTTnet.Tests.Server
{
[TestClass]
public sealed class Retain_As_Published_Tests : BaseTestClass
{
[TestMethod]
public Task Subscribe_With_Retain_As_Published()
{
return ExecuteTest(true);
}
[TestMethod]
public Task Subscribe_Without_Retain_As_Published()
{
return ExecuteTest(false);
}
async Task ExecuteTest(bool retainAsPublished)
{
using (var testEnvironment = CreateTestEnvironment(MqttProtocolVersion.V500))
{
await testEnvironment.StartServer();
var client1 = await testEnvironment.ConnectClient();
var applicationMessageHandler = testEnvironment.CreateApplicationMessageHandler(client1);
var topicFilter = testEnvironment.Factory.CreateTopicFilterBuilder().WithTopic("Topic").WithRetainAsPublished(retainAsPublished).Build();
await client1.SubscribeAsync(topicFilter);
await LongTestDelay();
// The client will publish a message where it is itself subscribing to.
await client1.PublishAsync("Topic", "Payload", true);
await LongTestDelay();
applicationMessageHandler.AssertReceivedCountEquals(1);
Assert.AreEqual(retainAsPublished, applicationMessageHandler.ReceivedApplicationMessages[0].Retain);
}
}
}
} |
using StardewModdingAPI;
namespace UnlimitedPlayers
{
/// <summary>The mod entry point.</summary>
public class ModEntry : Mod
{
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides simplified APIs for writing mods.</param>
public override void Entry(IModHelper helper)
{
ConfigParser parser = helper.ReadConfig<ConfigParser>();
parser.Store(); // Now we can access the config from every class without helper or passing the instance
LazyHelper.ModHelper = helper; // And here I am just absolutly lazy - terribly sorry >.<
LazyHelper.ModEntry = this; // There will always only be one valid instance + see above
helper.Events.GameLoop.GameLaunched += Events.GameEvents_FirstUpdateTick;
//GameEvents.FirstUpdateTick += Events.GameEvents_FirstUpdateTick;
helper.Events.Display.MenuChanged += Events.MenuEvents_MenuChanged;
// Overwrite the player limit in Stardew Valley source code
LazyHelper.OverwritePlayerLimit();
LazyHelper.ModEntry.Monitor.Log("Player limit set to " + LazyHelper.PlayerLimit + " players.", LogLevel.Info);
}
}
}
|
using SampleProject.Models;
using System.Collections.Generic;
namespace SampleProject.Repository
{
public interface IUserRepository
{
List<Data> GetUsers();
Data GetUserById(int id);
Data CreateUser(Data userModel, string password);
Data EditUser(Data userModel);
void DeleteUser(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JDWinService.Model
{
//采购订单 物料日志表
public class JD_OrderListApply_Log
{
/// <summary>
///
/// </summary>
public int ItemID { get; set; }
/// <summary>
///
/// </summary>
public int TaskID { get; set; }
/// <summary>
///
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
///
/// </summary>
public DateTime UpdateTime { get; set; }
/// <summary>
///
/// </summary>
public string SupplierName { get; set; }
/// <summary>
///
/// </summary>
public string SupplierCode { get; set; }
/// <summary>
///
/// </summary>
public string PlanType { get; set; }
/// <summary>
///
/// </summary>
public string PlanTypeCode { get; set; }
/// <summary>
///
/// </summary>
public string CoinType { get; set; }
/// <summary>
///
/// </summary>
public string CoinTypeCode { get; set; }
/// <summary>
///
/// </summary>
public string Rate { get; set; }
/// <summary>
///
/// </summary>
public string RateType { get; set; }
/// <summary>
///
/// </summary>
public string RateTypeCode { get; set; }
/// <summary>
///
/// </summary>
public string OrderMode { get; set; }
/// <summary>
///
/// </summary>
public string OrderModeCode { get; set; }
/// <summary>
///
/// </summary>
public string OrderType { get; set; }
/// <summary>
///
/// </summary>
public string OrderTypeCode { get; set; }
/// <summary>
///
/// </summary>
public string OrderRange { get; set; }
/// <summary>
///
/// </summary>
public string OrderRangeCode { get; set; }
/// <summary>
///
/// </summary>
public string BalanceType { get; set; }
/// <summary>
///
/// </summary>
public string BalanceTypeCode { get; set; }
/// <summary>
///
/// </summary>
public string BU { get; set; }
/// <summary>
///
/// </summary>
public string BUCode { get; set; }
/// <summary>
///
/// </summary>
public decimal FAllPrice { get; set; }
/// <summary>
///
/// </summary>
public decimal FAllTaxPrice { get; set; }
/// <summary>
///
/// </summary>
public string FBillNo { get; set; }
/// <summary>
///
/// </summary>
public int FInterID { get; set; }
/// <summary>
///
/// </summary>
public int FEntryID { get; set; }
/// <summary>
///
/// </summary>
public string FNumber { get; set; }
/// <summary>
///
/// </summary>
public string FName { get; set; }
/// <summary>
///
/// </summary>
public string FModel { get; set; }
/// <summary>
///
/// </summary>
public decimal FQtyMin { get; set; }
/// <summary>
///
/// </summary>
public decimal FBatchAppendQty { get; set; }
/// <summary>
///
/// </summary>
public string WuLiaoCode { get; set; }
/// <summary>
///
/// </summary>
public string WuLiaoSupplier { get; set; }
/// <summary>
///
/// </summary>
public string EnginCRName { get; set; }
/// <summary>
///
/// </summary>
public string EnginCRCode { get; set; }
/// <summary>
///
/// </summary>
public double PriceXiShu { get; set; }
/// <summary>
///
/// </summary>
public string SupplierVersion { get; set; }
/// <summary>
///
/// </summary>
public string funit { get; set; }
/// <summary>
///
/// </summary>
public string funitID { get; set; }
/// <summary>
///
/// </summary>
public decimal FQty { get; set; }
/// <summary>
///
/// </summary>
public decimal FCommitQty { get; set; }
/// <summary>
///
/// </summary>
public decimal FpoNum { get; set; }
/// <summary>
///
/// </summary>
public DateTime FFetchTime { get; set; }
/// <summary>
///
/// </summary>
public string FSupplyID { get; set; }
/// <summary>
///
/// </summary>
public string fsupNo { get; set; }
/// <summary>
///
/// </summary>
public string fsupname { get; set; }
/// <summary>
///
/// </summary>
public decimal FAuxPrice { get; set; }
/// <summary>
///
/// </summary>
public decimal FAuxTaxPrice { get; set; }
/// <summary>
///
/// </summary>
public decimal FAmount { get; set; }
/// <summary>
///
/// </summary>
public decimal FTaxAmount { get; set; }
/// <summary>
///
/// </summary>
public string Remarks { get; set; }
/// <summary>
///
/// </summary>
public decimal FCess { get; set; }
/// <summary>
///
/// </summary>
public decimal POHightPrice { get; set; }
/// <summary>
///
/// </summary>
public string IsUpdate { get; set; }
/// <summary>
///
/// </summary>
public DateTime FDate { get; set; }
/// <summary>
///
/// </summary>
public string DeptID { get; set; }
/// <summary>
///
/// </summary>
public string DeptIDCode { get; set; }
/// <summary>
///
/// </summary>
public string FEmpID { get; set; }
/// <summary>
///
/// </summary>
public string FEmpIDCode { get; set; }
/// <summary>
///
/// </summary>
public string FManageID { get; set; }
/// <summary>
///
/// </summary>
public string FManageIDCode { get; set; }
/// <summary>
///
/// </summary>
public string FBillerID { get; set; }
/// <summary>
///
/// </summary>
public DateTime FDate1 { get; set; }
public string ordernum { get; set; }
public string REQType { get; set; }
public int IsPart { get; set; }
public string ExtraInfo { get; set; }
public string HeadRemarks { get; set; }
public int FFixLeadTime { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AdventOfCode2020
{
// https://adventofcode.com/2020/day/11
public class Day11
{
private List<Location> layout = new List<Location>();
private List<Location> priorLayout = new List<Location>();
private int MaxXcord => this.layout.Max(x => x.Xcord);
private int MaxYcord => this.layout.Max(x => x.Ycord);
public string Run()
{
var fullInput = InputHelper.ReadOutEachLine("Day11Input");
for (int row = 0; row < fullInput.Count(); row++)
{
for (int item = 0; item < fullInput[row].Length; item++)
{
var location = new Location { Xcord = item , Ycord = row };
var charToAdd = fullInput[row][item];
switch (charToAdd)
{
case ('L'):
location.Occupied = false;
break;
case ('#'):
location.Occupied = true;
break;
case ('.'): // not really needed...
location.Occupied = null;
break;
}
layout.Add(location);
}
}
//this.Print();
do
{
this.UpdateSeats();
this.Print();
//Console.ReadLine();
} while (!this.Compare(priorLayout));
//Console.WriteLine("************************");
Console.WriteLine();
return $"Part 1: { this.priorLayout.Count(x => x.Occupied == true) }, Part 2: {"TBD"}";
}
private bool Compare(IList<Location> loctions)
{
var string1 = string.Join("", loctions.OrderBy(x => x.Ycord).ThenBy(x => x.Xcord));
var string2 = string.Join("", this.layout.OrderBy(x => x.Ycord).ThenBy(x => x.Xcord));
var same = string1 == string2;
return same;
}
private void Print()
{
//for(int counter = 0; counter <= this.MaxXcord; counter++)
//{
// var row = "";
// var priorRowItems = this.FindRow(this.priorLayout, counter);
// row += string.Join("", priorRowItems);
// row += " ";
// var rowItems = this.FindRow(this.layout, counter);
// row += string.Join("", rowItems);
// Console.WriteLine(row);
//}
//Console.WriteLine("");
//for (int counter = 0; counter <= this.MaxXcord; counter++)
//{
// var row = "";
// var priorRowItems = this.FindRow(this.priorLayout, counter);
// foreach (var item in priorRowItems)
// {
// row += CountSeats(item, this.priorLayout);
// }
// row += " ";
// var rowItems = this.FindRow(this.layout, counter);
// foreach (var item in rowItems)
// {
// row += CountSeats(item, this.layout);
// }
// Console.WriteLine(row);
//}
Console.WriteLine("************************");
Console.WriteLine(this.layout.Count(x => x.Occupied == true));
Console.WriteLine("************************");
}
private IList<Location> FindRow(IList<Location> locations, int row) => locations.Where(item => item.Ycord == row).OrderBy(x => x.Xcord).ToList();
private void UpdateSeats()
{
this.priorLayout = new List<Location>();
foreach (var item in this.layout)
{
this.priorLayout.Add(new Location { Xcord = item.Xcord, Ycord = item.Ycord, Occupied = item.Occupied });
}
this.layout = new List<Location>();
foreach (var location in this.priorLayout)
{
var seatCount = this.CountSeats(location, this.priorLayout);
if (location.Occupied == true && seatCount >= 4)
{
this.layout.Add(new Location { Xcord = location.Xcord, Ycord = location.Ycord, Occupied = false });
}
else if(location.Occupied == false && seatCount == 0)
{
this.layout.Add(new Location { Xcord = location.Xcord, Ycord = location.Ycord, Occupied = true });
}
else // if no change or empty spot
{
this.layout.Add(new Location { Xcord = location.Xcord, Ycord = location.Ycord, Occupied = location.Occupied });
}
}
}
private int CountSeats(Location location, IList<Location> locationToCheckAgainst)
{
if(location.Occupied == null)
{
return 0;
}
// the names are wrong...
var topLeft = this.CountIfOccupied(locationToCheckAgainst, location.Xcord - 1, location.Ycord - 1); // top Left
var topCenter = this.CountIfOccupied(locationToCheckAgainst, location.Xcord - 1, location.Ycord + 0); // top center
var topRight = this.CountIfOccupied(locationToCheckAgainst, location.Xcord - 1, location.Ycord + 1); // top right
var centerLeft = this.CountIfOccupied(locationToCheckAgainst, location.Xcord + 0, location.Ycord - 1); // center right
var centerRight = this.CountIfOccupied(locationToCheckAgainst, location.Xcord + 0, location.Ycord + 1); // center left
var bottomLeft = this.CountIfOccupied(locationToCheckAgainst, location.Xcord + 1, location.Ycord - 1); // bottom left
var bottomCenter = this.CountIfOccupied(locationToCheckAgainst, location.Xcord + 1, location.Ycord + 0); // top center
var bottomRight = this.CountIfOccupied(locationToCheckAgainst, location.Xcord + 1, location.Ycord + 1); // bottom right
var occupied = topLeft + topCenter + topRight + centerLeft + centerRight + bottomLeft + bottomCenter + bottomRight;
//if(occupied >=3)
//{
// _ = "breakhere";
//}
return occupied;
}
private int CountIfOccupied(IList<Location> locationToCheckAgainst, int xcord, int ycord)
{
var location = locationToCheckAgainst.FirstOrDefault(x => x.Xcord == xcord && x.Ycord == ycord);
if(location == null)
{
return 0;
}
return location.Occupied == true ? 1 : 0;
}
private class Location
{
public int Xcord { get; set; }
public int Ycord { get; set; }
// Null means floor
public bool? Occupied { get; set; }
public override string ToString()
{
if (Occupied == true)
{
return "#";
}
if (Occupied == false)
{
return "L";
}
return ".";
}
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SuperMario.Collision;
namespace SuperMario.Entities.Mario.MarioCondition
{
public abstract class StarMario : MarioConditionState
{
protected StarMario(IPlayerTexturePack playerTexturePack) : base(playerTexturePack) {}
Entity CrouchLeft;
Entity CrouchRight;
Entity JumpLeft;
Entity JumpRight;
Entity StandLeft;
Entity StandRight;
protected override Entity CrouchingLeft
{
get
{
if (CrouchLeft == null)
CrouchLeft = new StaticTintableMarioEntity(ScreenLocation, TexturePack.CrouchingLeft, new Rectangle(0, 0, TexturePack.CrouchingLeft.Width, TexturePack.CrouchingLeft.Height));
CrouchLeft.SetScreenLocation(ScreenLocation);
return CrouchLeft;
}
}
protected override Entity CrouchingRight
{
get
{
if (CrouchRight == null)
CrouchRight = new StaticTintableMarioEntity(ScreenLocation, TexturePack.CrouchingRight, new Rectangle(0, 0, TexturePack.CrouchingRight.Width, TexturePack.CrouchingRight.Height));
CrouchRight.SetScreenLocation(ScreenLocation);
return CrouchRight;
}
}
protected override Entity JumpingLeft
{
get
{
if (JumpLeft == null)
JumpLeft = new StaticTintableMarioEntity(ScreenLocation, TexturePack.JumpingLeft, new Rectangle(0, 0, TexturePack.JumpingLeft.Width, TexturePack.JumpingLeft.Height));
JumpLeft.SetScreenLocation(ScreenLocation);
return JumpLeft;
}
}
protected override Entity JumpingRight
{
get
{
if (JumpRight == null)
JumpRight = new StaticTintableMarioEntity(ScreenLocation, TexturePack.JumpingRight, new Rectangle(0, 0, TexturePack.JumpingRight.Width, TexturePack.JumpingRight.Height));
JumpRight.SetScreenLocation(ScreenLocation);
return JumpRight;
}
}
protected override Entity RunningLeft
{
get
{
if (RunningLeftValue == null)
RunningLeftValue = new RunningTintedMario(ScreenLocation, TexturePack.RunningLeft);
RunningLeftValue.SetScreenLocation(ScreenLocation);
return RunningLeftValue;
}
}
protected override Entity RunningRight
{
get
{
if (RunningRightValue == null)
RunningRightValue = new RunningTintedMario(ScreenLocation, TexturePack.RunningRight);
RunningRightValue.SetScreenLocation(ScreenLocation);
return RunningRightValue;
}
}
protected override Entity StandingLeft
{
get
{
if (StandLeft == null)
StandLeft = new StaticTintableMarioEntity(ScreenLocation, TexturePack.FacingLeft, new Rectangle(0, 0, TexturePack.FacingLeft.Width, TexturePack.FacingLeft.Height));
StandLeft.SetScreenLocation(ScreenLocation);
return StandLeft;
}
}
protected override Entity StandingRight
{
get
{
if (StandRight == null)
StandRight = new StaticTintableMarioEntity(ScreenLocation, TexturePack.FacingRight, new Rectangle(0, 0, TexturePack.FacingRight.Width, TexturePack.FacingRight.Height));
StandRight.SetScreenLocation(ScreenLocation);
return StandRight;
}
}
}
public class RunningTintedMario : TintableAnimatedEntity
{
Texture2D texture;
Rectangle currentAnimationRectangle;
int numberOfFrames = 3;
public RunningTintedMario(Vector2 screenLocation, Texture2D texture) : base(screenLocation, 2000000)
{
this.texture = texture;
currentAnimationRectangle = new Rectangle(0, 0, texture.Width / numberOfFrames, texture.Height);
}
public override ISprite FirstSprite => new TintableSprite(texture, new Rectangle(0, 0, texture.Width / numberOfFrames, texture.Height));
public override ISprite NextSprite
{
get
{
currentAnimationRectangle.X += texture.Width / numberOfFrames;
if (currentAnimationRectangle.X == texture.Width)
currentAnimationRectangle.X = 0;
return new TintableSprite(texture, currentAnimationRectangle);
}
}
public override void Collide(Entity entity, RectangleCollisions collisions)
{
}
}
}
|
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.DataAccess.Object;
using Anywhere2Go.Library;
using OfficeOpenXml;
using System.IO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using Anywhere2Go.DataAccess.AccountObject;
using Anywhere2Go.AccountingLogic;
namespace Claimdi.Web.TH.UploadFile
{
/// <summary>
/// Summary description for UploadFileInspection
/// </summary>
public class UploadFileInspection : IHttpHandler, System.Web.SessionState.IReadOnlySessionState
{
public bool IsReusable
{
get
{
return false;
}
}
public class Result
{
public long importId { get; set; }
public List<ImportCheckBilling> dataImport { get; set; }
}
public void ProcessRequest(HttpContext context)
{
BaseResult<Result> resultObj = new BaseResult<Result>();
try
{
var files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
//int recordCount = 0;
HttpPostedFile file = context.Request.Files[i];
if (file.ContentLength > 0)
{
string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
string temp = "ImportFile/FileUpload/" + fileName;
string directoryPath = context.Server.MapPath("~/ImportFile/FileUpload");
string path = Path.Combine(directoryPath, fileName);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
file.SaveAs(path);
ExcelPackage package = new ExcelPackage(file.InputStream);
DataTable t = package.ToDataTable();
resultObj.Result = new Result();
resultObj.Result.dataImport = new List<ImportCheckBilling>();
BillingLogic bill = new BillingLogic();
foreach (DataRow row in t.Rows)
{
var data = new ImportCheckBilling();
data.TaskID = Convert.ToString(row[0]);
data.InvoiceID = Convert.ToString(row[1]);
data.InvoiceProvID = Convert.ToString(row[2]);
data.CustomerPay = Convert.ToString(row[3]);
if (string.IsNullOrEmpty(data.TaskID) && string.IsNullOrEmpty(data.InvoiceID) && string.IsNullOrEmpty(data.InvoiceProvID))
{
continue;
}
else
{
data = bill.CheckBilling(data);
resultObj.Result.dataImport.Add(data);
}
}
}
}
}
catch (Exception ex)
{
resultObj.StatusCode = "500";
resultObj.Message = ex.Message;
}
var serializer = new JavaScriptSerializer();
context.Response.ContentType = "application/json";
context.Response.Write(serializer.Serialize(resultObj));
}
public class ResultValidate
{
public bool result { get; set; }
public string message { get; set; }
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
using System;
using Hakaima;
//using NendUnityPlugin.AD;
using GoogleMobileAds.Api;
using NCMB;
public class TitleManager : MonoBehaviour
{
public enum State
{
Menu,
Ranking,
Record,
Help,
End,
Extra,
}
public class Catalog
{
public int pageNum { get; private set; }
public float positionX { get; private set; }
public int nowPageIndex { get; private set; }
public int prePageIndex { get; private set; }
public bool isMove { get; private set; }
public bool isArrowRight { get; private set; }
public bool isArrowLeft { get; private set; }
private float moveTime;
public void Init (int pageNum)
{
this.pageNum = pageNum;
this.positionX = 0;
this.nowPageIndex = 0;
this.prePageIndex = 0;
this.isMove = false;
this.isArrowRight = true;
this.isArrowLeft = false;
}
public void Move (float deltaTime, int frameRate)
{
if (this.isMove) {
this.moveTime += deltaTime * 2.5f;
this.positionX = -(-(this.nowPageIndex - this.prePageIndex) * this.moveTime * (this.moveTime - 2) + this.prePageIndex) * Data.SCREEN_WIDTH;
if (this.moveTime >= 1) {
this.isMove = false;
}
}
}
public void Next ()
{
if (!this.isMove) {
if (this.nowPageIndex < this.pageNum - 1) {
this.prePageIndex = this.nowPageIndex;
this.nowPageIndex++;
this.isMove = true;
this.moveTime = 0;
this.isArrowRight = this.nowPageIndex < this.pageNum - 1;
this.isArrowLeft = true;
}
}
}
public void Prev ()
{
if (!this.isMove) {
if (this.nowPageIndex > 0) {
this.prePageIndex = this.nowPageIndex;
this.nowPageIndex--;
this.isMove = true;
this.moveTime = 0;
this.isArrowRight = true;
this.isArrowLeft = this.nowPageIndex > 0;
}
}
}
}
private class Bird
{
public enum State
{
Wait,
Fly,
}
public const int IMAGE_0 = 0;
public const int IMAGE_1 = 1;
public State state { get; private set; }
public float time { get; private set; }
public float positionX { get; private set; }
public float positionY { get; private set; }
public float scaleX { get; private set; }
public float scaleY { get; private set; }
public bool visible { get; private set; }
public int imageIndex { get; private set; }
private float speedX;
private float speedY;
private float imageTime;
private float sidePositionX;
public void Init (float sidePositionX)
{
this.sidePositionX = sidePositionX;
this.Wait ();
}
public void Move (float deltaTime, int frameRate)
{
switch (this.state) {
case State.Wait:
{
}
break;
case State.Fly:
{
this.positionX += this.speedX * deltaTime * frameRate;
this.positionY += this.speedY * deltaTime * frameRate;
if (Math.Abs (this.positionX) >= this.sidePositionX) {
this.Wait ();
}
int index = (int)this.imageTime % 2;
switch (index) {
case 0:
this.imageIndex = IMAGE_0;
break;
case 1:
this.imageIndex = IMAGE_1;
break;
}
this.imageTime += 0.1f * deltaTime * frameRate;
}
break;
}
}
public void Wait ()
{
this.state = State.Wait;
this.time = 0;
this.visible = false;
}
public void Fly ()
{
this.state = State.Fly;
this.time = 0;
this.imageIndex = 0;
this.imageTime = 0;
this.visible = true;
int distance = UnityEngine.Random.value * 2 < 1 ? 1 : -1;
this.positionX = -this.sidePositionX * distance;
this.positionY = 0 + UnityEngine.Random.value * 600;
this.scaleX = distance;
this.scaleY = 1;
this.speedX = 4 * distance;
this.speedY = 1;
}
}
public class Cover
{
public bool visible { get; set; }
public Color color { get; private set; }
public Cover ()
{
this.visible = true;
this.color = Color.black;
}
public void SetAlpha (float alpha)
{
Color color = Color.black;
color.a = alpha;
this.color = color;
}
}
private class Ranking
{
public enum State
{
Fetch, // サーバーからハイスコアを取得.
Save, // サーバーにハイスコアを保存.
Goto, // サーバーからTop10を取得へ.
FetchRank, // 現プレイヤーのハイスコアを受けとってランクを取得.
TopRank, // サーバーからTop10を取得.
Finish, // 処理終了.
}
public State state { get; set; }
private NCMB.HighScore hiscore;
private LeaderBoard leaderBoard;
public void Init()
{
if (leaderBoard == null) {
leaderBoard = new LeaderBoard ();
}
if (hiscore == null) {
hiscore = new NCMB.HighScore (0, 0, "");
}
state = State.Fetch;
if (hiscore != null) {
hiscore.isCorrect = false;
hiscore.isCorrectFinish = false;
}
}
public void Fetch(string name)
{
if (!hiscore.isCorrect) {
hiscore = new NCMB.HighScore (0, 0, name);
hiscore.fetch ();
}
}
public void Save(int score, int stage)
{
if (!hiscore.isCorrect) {
if (hiscore.score < score) {
hiscore.score = score;
hiscore.stage = stage;
hiscore.save ();
} else {
hiscore.isCorrectFinish = true;
}
}
}
public void FetchRank()
{
if (!leaderBoard.isCorrect) {
leaderBoard.fetchRank (hiscore.score);
}
}
public void FetchTopRank()
{
if (!leaderBoard.isCorrect) {
leaderBoard.fetchTopRankers ();
}
}
public void Next(State state)
{
if (hiscore.isCorrectFinish) {
this.state = state;
hiscore.isCorrect = false;
hiscore.isCorrectFinish = false;
}
}
public void NextLeaderBoard(State state)
{
if (leaderBoard.isfetchRankFinish) {
this.state = state;
leaderBoard.isCorrect = false;
leaderBoard.isfetchRankFinish = false;
}
if (leaderBoard.isfetchTopRankersFinish) {
if (leaderBoard.currentRank > 0 ) {
MainManager.Instance.loginInfo.SetMyRankInfo(leaderBoard.currentRank, leaderBoard.topRankers[leaderBoard.currentRank-1].score);
for(int i = 0; i < leaderBoard.topRankers.Count; i++ )
{
MainManager.Instance.loginInfo.SetUserName(leaderBoard.topRankers [i].name);
MainManager.Instance.loginInfo.SetUserScore(leaderBoard.topRankers [i].score);
}
}
this.state = state;
leaderBoard.isCorrect = false;
leaderBoard.isfetchTopRankersFinish = false;
}
}
public void debug()
{
//Debug.Log ("score = " + hiscore.score + ", stage = " + hiscore.stage+", name = "+hiscore.name+", rank = "+leaderBoard.currentRank);
}
}
private class Gacha
{
public float y { get; set; }
public float timer { get; set; }
public float gachabarSet { get; set; }
public float gachabarAngle { get; set; }
public int gachaMode { get; set; }
public int selectedGachaNumber { get; set; }
public void keepY( float y )
{
this.y = y;
}
public void clear()
{
timer = 0;
gachaMode = 0;
gachabarSet = 0;
gachabarAngle = 0;
selectedGachaNumber = 0;
}
public void lottery(int n)
{
UnityEngine.Random.InitState ((int)Time.time);
int start = UnityEngine.Random.Range (0, n - 20);
int randomNum = UnityEngine.Random.Range (0, n);
int hit = n / (n / 20);
//Debug.Log ("Gacha Resut : " + start + " < " + randomNum+" < "+(start+hit));
// あたり.
if (randomNum >= start && randomNum < start + hit) {
//Debug.Log ("HIT");
selectedGachaNumber = UnityEngine.Random.Range (1, Data.CHARACTER_MAX);
} else {
// -1 = life 1up.
selectedGachaNumber = -1;
}
}
}
public const int RANKING_PAGE_NUM = 2;
public const int RECORD_PAGE_NUM = 3;
public const int HELP_PAGE_NUM = 10;
private const int EXCHANGE_CODE = 0x10101010;
private State state;
private float time;
private GameObject goMenu;
private GameObject goRanking;
private GameObject goRecord;
private GameObject goHelp;
private GameObject goEnd;
private GameObject goExtra;
private GameObject goCover;
private GameObject goConceal;
private GameObject goSelectCharacter;
private GameObject goGacha;
private GameObject goGachaStart;
private GameObject goGachaResult;
private GameObject goInformation;
private GameObject goMenuLogo;
private GameObject goMenuJapaneseTitle;
private GameObject goMenuButtonStart;
private GameObject goMenuButtonContinue;
private GameObject goMenuButtonRanking;
private GameObject goMenuButtonRecord;
private GameObject goMenuButtonHelp;
private GameObject goMenuButtonExtra;
private GameObject goMenuVolumeOn;
private GameObject goMenuVolumeOff;
private GameObject goMenuBird;
private GameObject goMenuTwitter;
private GameObject goMenuLoginBonus;
private GameObject goMenuLoginBonusButtonOk;
private GameObject goMenuHiscore;
private GameObject goRankingMe;
private GameObject goRankingPage;
private GameObject goRankingConnecting;
private GameObject goRankingPoint;
private GameObject goRankingSwipe;
private GameObject goRankingArrowRight;
private GameObject goRankingArrowLeft;
private GameObject goRankingButtonLogout;
private GameObject goRankingButtonChangeUserName;
private GameObject goRankingButtonBack;
private GameObject goRankingExplanation;
private GameObject goLogin;
private GameObject goSignup;
private GameObject goLoginButton;
private GameObject goSignupButton;
private GameObject goRegistButton;
private GameObject goLoginDescription;
private GameObject goSignupDescription;
private GameObject goSignupButtonRanking;
private GameObject goChagne;
private GameObject goChagneButtonUserName;
private GameObject goChagneButtonUserPassword;
private GameObject goChangeResultUserName;
private GameObject goLoginFirst;
private GameObject goLoginFirstExplanation;
private GameObject goSignupFinish;
private GameObject goSignupRegistedExplanation;
private GameObject goRecordPage;
private GameObject goRecordPoint;
private GameObject goRecordSwipe;
private GameObject goRecordArrowRight;
private GameObject goRecordArrowLeft;
private GameObject goRecordButtonBack;
private GameObject goHelpPage;
private GameObject goHelpPoint;
private GameObject goHelpSwipe;
private GameObject goHelpArrowRight;
private GameObject goHelpArrowLeft;
private GameObject goHelpButtonBack;
private GameObject goHelpButtonPrivacy;
private GameObject goCatalogPage;
private GameObject goCatalogPoint;
private GameObject goCatalogArrowRight;
private GameObject goCatalogArrowLeft;
private GameObject goCaution;
private GameObject goCautionButtonYes;
private GameObject goCautionButtonNo;
private GameObject goEndDescription;
private GameObject goEndButtonYes;
private GameObject goEndButtonNo;
private GameObject goExtraDescription;
private GameObject goExtraButtonBack;
private GameObject goExtraItemTitle;
private GameObject goExtraItemDescription;
private GameObject goExtraItemButtonMovie;
private GameObject goExtraLifeTitle;
private GameObject goExtraLifeDescription;
private GameObject goExtraLifeButtonMovie;
private GameObject goExtraLifeNow;
private GameObject goExtraRecommendedTitle;
private GameObject goExtraRecommendedButtonMoreGame;
private GameObject goSelectCharacterGachaTicketText;
private GameObject goSelectCharacterGachaTicket;
private GameObject goSelectCharacterFrame;
private GameObject goSelectCharacterButtonStart;
private GameObject goSelectCharacterButtonGacha;
private GameObject goSelectCharacterButtonPlayAds;
private GameObject goSelectCharacterButtonBack;
private List<GameObject> goCharacter;
private GameObject goGachaBar;
private GameObject goGachaCupsule;
private GameObject goGachaResultChara;
private GameObject goGachaResultGachaTicketText;
private GameObject goGachaResultGachaTicket;
private GameObject goGachaResultButtonGacha;
private GameObject goGachaResultButtonPlayAds;
private GameObject goGachaResultButtonBack;
private GameObject goGachaResultGotText;
private GameObject goGachaLotteryChara;
private GameObject goGachaLotteryLife;
private GameObject goInformationButton;
private GameObject goVersion;
private Catalog catalog;
private Bird bird;
private Cover cover;
private UserAuth user;
private Ranking ranking;
private float birdIndex;
//private int bookedSelectCharacter;
public Sprite spriteLogo;
public Sprite spriteLogoEn;
private List<Sprite> spriteBirdList;
[SerializeField]
private Sprite spriteBird0;
[SerializeField]
private Sprite spriteBird1;
[SerializeField]
private Sprite spriteDragonFly0;
[SerializeField]
private Sprite spriteDragonFly1;
private static bool isCoverOnce = true;
private string connectingText;
private Gacha gacha;
private LoginBonus loginBonus;
private void Awake ()
{
Init ();
this.state = State.Menu;
Create ();
}
private void Update ()
{
Run ();
Draw ();
}
private void Init ()
{
string path = Application.systemLanguage == SystemLanguage.Japanese ? Data.HELP_PATH_JAPANESE : Data.HELP_PATH_ENGLISH;
goMenu = transform.Find ("UI/Menu").gameObject;
goRanking = transform.Find ("UI/Ranking").gameObject;
goRecord = transform.Find ("UI/Record").gameObject;
goHelp = Instantiate (Resources.Load<GameObject> (path));
goHelp .transform.SetParent (transform.Find ("UI"));
goCaution = transform.Find ("UI/Caution").gameObject;
goEnd = transform.Find ("UI/End").gameObject;
goExtra = transform.Find ("UI/Extra").gameObject;
goCover = transform.Find ("UI/Cover").gameObject;
goConceal = transform.Find ("UI/Conceal").gameObject;
goSelectCharacter = transform.Find ("UI/SelectCharacter").gameObject;
goGacha = transform.Find ("UI/Gacha").gameObject;
goGachaStart = transform.Find ("UI/Gacha/Playing").gameObject;
goGachaResult = transform.Find ("UI/Gacha/Result").gameObject;
goInformation = transform.Find ("UI/Information").gameObject;
goMenuLogo = goMenu.transform.Find ("Logo").gameObject;
goMenuJapaneseTitle = goMenu.transform.Find ("JapaneseTitle").gameObject;
goMenuButtonStart = goMenu.transform.Find ("ButtonStart").gameObject;
goMenuButtonContinue = goMenu.transform.Find ("ButtonContinue").gameObject;
goMenuButtonRanking = goMenu.transform.Find ("ButtonRanking").gameObject;
goMenuButtonRecord = goMenu.transform.Find ("ButtonRecord").gameObject;
goMenuButtonHelp = goMenu.transform.Find ("ButtonHelp").gameObject;
goMenuButtonExtra = goMenu.transform.Find ("ButtonExtra").gameObject;
goMenuVolumeOn = goMenu.transform.Find ("Volume/On").gameObject;
goMenuVolumeOff = goMenu.transform.Find ("Volume/Off").gameObject;
goMenuBird = goMenu.transform.Find ("Bird").gameObject;
goMenuTwitter = goMenu.transform.Find ("Twitter").gameObject;
goMenuLoginBonus = goMenu.transform.Find ("LoginBonus").gameObject;
goMenuLoginBonusButtonOk = goMenu.transform.Find ("LoginBonus/ButtonOk").gameObject;
goMenuHiscore = goMenu.transform.Find ("Hiscore").gameObject;
goRankingMe = goRanking.transform.Find ("Me").gameObject;
goRankingPage = goRanking.transform.Find ("Page").gameObject;
goRankingConnecting = goRanking.transform.Find ("Connecting").gameObject;
goRankingPoint = goRanking.transform.Find ("Point").gameObject;
goRankingSwipe = goRanking.transform.Find ("Swipe").gameObject;
goRankingArrowRight = goRanking.transform.Find ("ArrowRight").gameObject;
goRankingArrowLeft = goRanking.transform.Find ("ArrowLeft").gameObject;
goRankingButtonChangeUserName = goRanking.transform.Find ("ButtonChangeUserName").gameObject;
goRankingButtonBack = goRanking.transform.Find ("ButtonBack").gameObject;
goRankingButtonLogout = goRanking.transform.Find ("ButtonLogout").gameObject;
goRankingExplanation = goRanking.transform.Find ("Explanation").gameObject;
goLogin = goRanking.transform.Find ("Login").gameObject;
goSignup = goRanking.transform.Find ("Signup").gameObject;
goLoginButton = goLogin.transform.Find ("ButtonLogin").gameObject;
goSignupButton = goLogin.transform.Find ("ButtonSignup").gameObject;
goRegistButton = goSignup.transform.Find ("ButtonRegist").gameObject;
goLoginDescription = goLogin.transform.Find ("Description").gameObject;
goSignupDescription = goSignup.transform.Find ("Description").gameObject;
goSignupButtonRanking = goSignup.transform.Find ("ButtonRanking").gameObject;
goChagne = goRanking.transform.Find ("Change").gameObject;
goChagneButtonUserName = goChagne.transform.Find ("ButtonChangeId").gameObject;
goChagneButtonUserPassword = goChagne.transform.Find ("ButtonChangePassword").gameObject;
goChangeResultUserName = goChagne.transform.Find ("DescriptionId").gameObject;
goLoginFirst = goLogin.transform.Find ("FirstMember").gameObject;
goLoginFirstExplanation = goLogin.transform.Find ("FirstMemberExplanation").gameObject;
goSignupFinish = goSignup.transform.Find ("Finish").gameObject;
goSignupRegistedExplanation = goSignup.transform.Find ("RegistedExplanation").gameObject;
goRecordPage = goRecord.transform.Find ("Page").gameObject;
goRecordPoint = goRecord.transform.Find ("Point").gameObject;
goRecordSwipe = goRecord.transform.Find ("Swipe").gameObject;
goRecordArrowRight = goRecord.transform.Find ("ArrowRight").gameObject;
goRecordArrowLeft = goRecord.transform.Find ("ArrowLeft").gameObject;
goRecordButtonBack = goRecord.transform.Find ("ButtonBack").gameObject;
goHelpPage = goHelp.transform.Find ("Page").gameObject;
goHelpPoint = goHelp.transform.Find ("Point").gameObject;
goHelpSwipe = goHelp.transform.Find ("Swipe").gameObject;
goHelpArrowRight = goHelp.transform.Find ("ArrowRight").gameObject;
goHelpArrowLeft = goHelp.transform.Find ("ArrowLeft").gameObject;
goHelpButtonBack = goHelp.transform.Find ("ButtonBack").gameObject;
goHelpButtonPrivacy = goHelp.transform.Find ("ButtonPrivacy").gameObject;
Destroy (goHelp.transform.Find ("Attention").gameObject);
goCautionButtonYes = goCaution.transform.Find ("ButtonYes").gameObject;
goCautionButtonNo = goCaution.transform.Find ("ButtonNo").gameObject;
goEndDescription = goEnd.transform.Find ("Description").gameObject;
goEndButtonYes = goEnd.transform.Find ("ButtonYes").gameObject;
goEndButtonNo = goEnd.transform.Find ("ButtonNo").gameObject;
goExtraDescription = goExtra.transform.Find ("Description").gameObject;
goExtraButtonBack = goExtra.transform.Find ("ButtonBack").gameObject;
goExtraItemTitle = goExtra.transform.Find ("Item/Title").gameObject;
goExtraItemDescription = goExtra.transform.Find ("Item/Description").gameObject;
goExtraItemButtonMovie = goExtra.transform.Find ("Item/ButtonMovie").gameObject;
goExtraLifeTitle = goExtra.transform.Find ("Life/Title").gameObject;
goExtraLifeDescription = goExtra.transform.Find ("Life/Description").gameObject;
goExtraLifeButtonMovie = goExtra.transform.Find ("Life/ButtonMovie").gameObject;
goExtraLifeNow = goExtra.transform.Find ("Life/Now").gameObject;
goExtraRecommendedTitle = goExtra.transform.Find ("Recommended/Title").gameObject;
goExtraRecommendedButtonMoreGame= goExtra.transform.Find ("Recommended/ButtonMoreGame").gameObject;
goSelectCharacterGachaTicketText= goSelectCharacter.transform.Find ("GachaTicketText").gameObject;
goSelectCharacterGachaTicket = goSelectCharacter.transform.Find ("GachaTicket").gameObject;
goSelectCharacterFrame = goSelectCharacter.transform.Find ("Frame").gameObject;
goSelectCharacterFrame.GetComponent<Animation> ().wrapMode = WrapMode.Loop;
goSelectCharacterButtonStart = goSelectCharacter.transform.Find ("ButtonStart").gameObject;
goSelectCharacterButtonGacha = goSelectCharacter.transform.Find ("ButtonGacha").gameObject;
goSelectCharacterButtonPlayAds = goSelectCharacter.transform.Find ("ButtonPlayAds").gameObject;
goSelectCharacterButtonBack = goSelectCharacter.transform.Find ("ButtonBack").gameObject;
goGachaBar = goGachaStart.transform.Find ("GachaBar").gameObject;
goGachaCupsule = goGachaStart.transform.Find ("Cupsule").gameObject;
goGachaResultChara = goGachaResult.transform.Find ("Chara").gameObject;
goGachaResultGachaTicketText = goGachaResult.transform.Find ("GachaTicketText").gameObject;
goGachaResultGachaTicket = goGachaResult.transform.Find ("GachaTicket").gameObject;
goGachaResultButtonGacha = goGachaResult.transform.Find ("ButtonGacha").gameObject;
goGachaResultButtonPlayAds = goGachaResult.transform.Find ("ButtonPlayAds").gameObject;
goGachaResultButtonBack = goGachaResult.transform.Find ("ButtonBack").gameObject;
goGachaResultGotText = goGachaResult.transform.Find ("GotText").gameObject;
goGachaLotteryChara = goGachaStart.transform.Find ("LotteryChara").gameObject;
goGachaLotteryLife = goGachaStart.transform.Find ("LotteryLife").gameObject;
goInformationButton = goInformation.transform.Find ("ButtonOk").gameObject;
goVersion = goMenu.transform.Find ("Version").gameObject;
goVersion.GetComponent<Text> ().text = "Ver." + Application.version;
goMenuLogo .GetComponent<Image> ().sprite = Language.sentence == Language.sentenceEn ? spriteLogoEn : spriteLogoEn;
goMenuLogo .GetComponent<Image> ().SetNativeSize ();
goMenuJapaneseTitle .SetActive (Language.sentence == Language.sentenceJa);
goMenuButtonStart .GetComponent<Button> ().onClick.AddListener (() => OnMenuButtonStartSelectCharacter ());
goMenuButtonContinue .GetComponent<Button> ().onClick.AddListener (() => OnMenuButtonContinue ());
goMenuButtonRanking .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Ranking));
goMenuButtonRecord .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Record));
goMenuButtonHelp .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Help));
goMenuButtonExtra .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Extra));
goMenuVolumeOn .GetComponent<Button> ().onClick.AddListener (() => OnVolume (true));
goMenuVolumeOff .GetComponent<Button> ().onClick.AddListener (() => OnVolume (false));
goMenuTwitter .GetComponent<Button> ().onClick.AddListener (() => OnTwitter ());
goMenuLoginBonusButtonOk .GetComponent<Button> ().onClick.AddListener (() => OnButtonLoginBonusClose ());
if (MainManager.Instance.isTutorial) {
goMenuButtonStart.transform.localPosition = goMenuButtonContinue.transform.localPosition;
goMenuButtonContinue.SetActive (false);
}
goMenuHiscore.GetComponent<Text> ().text = "HISCORE " + MainManager.Instance.scoreHigh.ToString ("D7");
goLoginButton .GetComponent<Button> ().onClick.AddListener (() => OnLogin ());
goSignupButton .GetComponent<Button> ().onClick.AddListener (() => OnButtonRegist ());
goRegistButton .GetComponent<Button> ().onClick.AddListener (() => OnButtonRegist ());
goRankingButtonChangeUserName .GetComponent<Button> ().onClick.AddListener (() => OnChange ());
goRankingButtonBack .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Menu, false));
goRankingButtonLogout .GetComponent<Button> ().onClick.AddListener (() => OnLogout ());
goRankingArrowRight .GetComponent<Button> ().onClick.AddListener (() => OnCatalogNextPage ());
goRankingArrowLeft .GetComponent<Button> ().onClick.AddListener (() => OnCatalogPrevPage ());
goChagneButtonUserName .GetComponent<Button> ().onClick.AddListener (() => OnChangeUserName ());
goChagneButtonUserPassword .GetComponent<Button> ().onClick.AddListener (() => OnChangeUserPassword ());
goSignupButtonRanking .GetComponent<Button> ().onClick.AddListener (() => OnRanking ());
goRecordButtonBack .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Menu, false));
goRecordArrowRight .GetComponent<Button> ().onClick.AddListener (() => OnCatalogNextPage ());
goRecordArrowLeft .GetComponent<Button> ().onClick.AddListener (() => OnCatalogPrevPage ());
goHelpButtonBack .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Menu, false));
goHelpButtonPrivacy .GetComponent<Button> ().onClick.AddListener (() => OnPrivacyPorisy ());
goHelpArrowRight .GetComponent<Button> ().onClick.AddListener (() => OnCatalogNextPage ());
goHelpArrowLeft .GetComponent<Button> ().onClick.AddListener (() => OnCatalogPrevPage ());
goRankingSwipe .GetComponent<EventTrigger> ().triggers.Find (obj => obj.eventID == EventTriggerType.Drag).callback.AddListener (eventData => OnSwipe ((PointerEventData)eventData));
goRecordSwipe .GetComponent<EventTrigger> ().triggers.Find (obj => obj.eventID == EventTriggerType.Drag).callback.AddListener (eventData => OnSwipe ((PointerEventData)eventData));
goHelpSwipe .GetComponent<EventTrigger> ().triggers.Find (obj => obj.eventID == EventTriggerType.Drag).callback.AddListener (eventData => OnSwipe ((PointerEventData)eventData));
goCaution .transform.Find ("Text").GetComponent<Text> ().text = Language.sentence [Language.START_CAUTION];
goCautionButtonYes .GetComponent<Button> ().onClick.AddListener (() => OnMenuButtonStart ());
goCautionButtonNo .GetComponent<Button> ().onClick.AddListener (() => OnMenuButtonCaution (false));
goEndDescription .GetComponent<Text> ().text = Language.sentence [Language.APPLICATION_QUIT];
goEndDescription .GetComponent<Text> ().fontSize = Language.sentence == Language.sentenceJa ? 50 : 70;
goEndButtonYes .GetComponent<Button> ().onClick.AddListener (() => OnEnd ());
goEndButtonNo .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Menu, false));
goExtraDescription .GetComponent<Text> ().text = Language.sentence [Language.EXTRA_DESCRIPTION];
goExtraItemTitle .GetComponent<Text> ().text = Language.sentence [Language.EXTRA_ITEM_TITLE];
goExtraItemDescription .GetComponent<Text> ().text = Language.sentence [Language.EXTRA_ITEM_DESCRIPTION];
goExtraLifeTitle .GetComponent<Text> ().text = Language.sentence [Language.EXTRA_LIFE_TITLE];
goExtraLifeDescription .GetComponent<Text> ().text = Language.sentence [Language.EXTRA_LIFE_DESCRIPTION];
goExtraRecommendedTitle .GetComponent<Text> ().text = Language.sentence [Language.EXTRA_RECOMMENDED_TITLE];
goExtraButtonBack .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Menu, false));
goExtraItemButtonMovie .GetComponent<Button> ().onClick.AddListener (() => OnExtraItemButtonMovie ());
goExtraLifeButtonMovie .GetComponent<Button> ().onClick.AddListener (() => OnExtraLifeButtonMovie ());
goExtraLifeNow .GetComponent<Text> ().text = MainManager.Instance.life.ToString ();
goExtraRecommendedButtonMoreGame.GetComponent<Button> ().onClick.AddListener (() => OnExtraButtonMoreGame ());
if (MainManager.Instance.isTutorial) {
goSelectCharacterButtonStart .GetComponent<Button> ().onClick.AddListener (() => OnMenuButtonStart ());
} else {
goSelectCharacterButtonStart .GetComponent<Button> ().onClick.AddListener (() => OnMenuButtonCaution (true));
}
goSelectCharacterButtonGacha .GetComponent<Button> ().onClick.AddListener (() => OnGacha ());
goSelectCharacterButtonPlayAds .GetComponent<Button> ().onClick.AddListener (() => ShowAdsMovie ());
goSelectCharacterButtonBack .GetComponent<Button> ().onClick.AddListener (() => OnButton (State.Menu, false));
goGachaResultButtonGacha .GetComponent<Button> ().onClick.AddListener (() => OnGacha ());
goGachaResultButtonPlayAds .GetComponent<Button> ().onClick.AddListener (() => ShowAdsMovie ());
goGachaResultButtonBack .GetComponent<Button> ().onClick.AddListener (() => OnGachaResultBackButton ());
goGachaLotteryChara .GetComponent<Text> ().text = Language.sentence [Language.GACHA_LOTTERY_CHARA];
goGachaLotteryLife .GetComponent<Text> ().text = Language.sentence [Language.GACHA_LOTTERY_LIFE];
goInformationButton .GetComponent<Button> ().onClick.AddListener (() => OnButtonInformationClose ());
goCharacter = new List<GameObject> ();
for (int i = 0; i < Data.CHARACTER_MAX; i++) {
goCharacter.Add (goSelectCharacter.transform.Find ("Character/Chara" + i).gameObject);
}
for (int i = 0; i < Data.CHARACTER_MAX; i++) {
GameObject obj = goSelectCharacter.transform.Find ("Character/Chara" + i).gameObject;
goCharacter [i].GetComponent<SelectCharacter> ().buttonNumber = i;
goCharacter [i].GetComponent<Button> ().onClick.AddListener (() => obj.GetComponent<SelectCharacter>().OnSelectCharacter ());
}
gacha = new Gacha ();
gacha.clear ();
gacha.keepY (goGachaCupsule.transform.localPosition.y);
InitSelectCharacterFrame ();
loginBonus = new LoginBonus ();
loginBonus.LoadLoginTime ();
loginBonus.prevGachaTicket = MainManager.Instance.gachaTicket;
// ログインボーナス.
if (!IsOffline()) {
StartCoroutine (loginBonus.GetLoginBonus());
}
bird = new Bird ();
catalog = new Catalog ();
cover = new Cover ();
user = new UserAuth ();
ranking = new Ranking ();
SoundManager.Instance.PlaySe (SoundManager.SeName.JINGLE_TITLE);
OnVolume (PlayerPrefs.GetInt (Data.SOUND_MUTE) == 1);
spriteBirdList = new List<Sprite> (){
spriteDragonFly0,
spriteDragonFly1,
};
goConceal.SetActive (true);
goCover.SetActive (isCoverOnce);
isCoverOnce = false;
// ランキングアクセス時に毎回通信しないためにここで初期化。
// もし毎回させたい場合は、Create()の中で呼ぶ。
ranking.Init ();
// Add 2017.11.7
#if UNITY_IOS
goExtraRecommendedButtonMoreGame.transform.Find("Image/Text").GetComponent<Text>().text = "App Store";
#endif
}
private void Create ()
{
goMenu.SetActive (false);
goRanking.SetActive (false);
goRecord.SetActive (false);
goHelp.SetActive (false);
goCaution.SetActive (false);
goEnd.SetActive (false);
goExtra.SetActive (false);
//MainManager.Instance.nendAdIcon.Hide ();
MainManager.Instance.bannerView.Hide ();
switch (this.state) {
case State.Menu:
{
goMenu.SetActive (true);
goSelectCharacter.SetActive (false);
//SetInformation (); // 2019.4.9 Ver.1.2.9はちょっとした不具合修正のため表示しない
SetLoginBonus ();
time = 0;
birdIndex = 0;
bird.Init (800);
//if (MainManager.Instance.isAdvertise)
// MainManager.Instance.nendAdIcon.Show ();
//goMenu.transform.Find ("PrivateAds").gameObject.SetActive (IsOffline ()); // オフラインの時のみプライベート広告.
MainManager.Instance.bannerView.Show ();
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_MENU);
}
break;
case State.Ranking:
{
goRanking.SetActive (true);
goLoginDescription.SetActive (false);
goSignupDescription.SetActive (false);
goRankingConnecting.SetActive (false);
goLogin.SetActive (false);
goSignup.SetActive (false);
goChagne.SetActive (false);
goRankingMe.SetActive (false);
goRankingPage.SetActive (false);
goRankingPoint.SetActive (false);
goRankingSwipe.SetActive (false);
goRankingArrowLeft.SetActive (false);
goRankingArrowRight.SetActive (false);
goRankingButtonChangeUserName.SetActive (false);
goRankingButtonBack.SetActive (true);
goRankingButtonLogout.SetActive (false);
goLogin.transform.Find ("Id/TextId").GetComponent<Text> ().text = Language.sentence [Language.RANKING_NAME];
goLogin.transform.Find ("Password/TextPassword").GetComponent<Text> ().text = Language.sentence [Language.RANKING_PASSWORD];
goSignup.transform.Find ("Id/TextId").GetComponent<Text> ().text = Language.sentence [Language.RANKING_NAME];
goSignup.transform.Find ("Password/TextPassword").GetComponent<Text> ().text = Language.sentence [Language.RANKING_PASSWORD];
goSignup.transform.Find ("RePassword/TextPassword").GetComponent<Text> ().text = Language.sentence [Language.RANKING_PASSWORD_CONFIRM];
goSignup.transform.Find ("Id/InputField/Placeholder").GetComponent<Text> ().text = Language.sentence [Language.RANKING_NAME_FORM];
goSignup.transform.Find ("Password/InputField/Placeholder").GetComponent<Text> ().text = Language.sentence [Language.RANKING_PASSWORD_FORM];
goRankingExplanation.GetComponent<Text> ().text = Language.sentence [Language.RANKING_THISSYSTEM];
goLoginFirst.GetComponent<Text>().text = Language.sentence [Language.LOGIN_BIGINNER];
goLoginFirstExplanation.GetComponent<Text>().text = Language.sentence [Language.RANKING_FIRST_EXPLANATION];
goSignupFinish.GetComponent<Text>().text = Language.sentence [Language.LOGIN_FINISH];
goSignupRegistedExplanation.GetComponent<Text>().text = Language.sentence [Language.RANKING_REGISTED_EXPLANATION];
goChagne.transform.Find ("Id/TextId").GetComponent<Text> ().text = Language.sentence [Language.RANKING_NAME];
goChagne.transform.Find ("ButtonChangeId/Image/Text").GetComponent<Text> ().text = Language.sentence [Language.RANKING_NAME_CHANGE];
// 8/19 エラーの原因は、毎回TitleManagerを削除しているので、未ログイン扱いになってしまう、ゲーム終了後は毎回ランキングデータを持ってこないといけない
// もしくはローカルに保存してそれを表示する こっちのほうが現実的
if (IsOffline ()) {
SetConnecting (false);
goRankingConnecting.SetActive (true);
goRankingButtonBack.SetActive (true);
//goRankingConnecting.GetComponent<Text> ().color = new Color (1, 0, 0, 0);
connectingText = Language.sentence [Language.OFFLINE];
goRankingConnecting.GetComponent<Text> ().text = connectingText;
} else {
// 未ログイン
if (!MainManager.Instance.isLogin) {
goLogin.SetActive (true);
// 以前ログインしていればストレージから情報を得て自動ログイン
AutoLogin ();
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_RANKING);
// ログイン済み
} else {
goRankingButtonChangeUserName.SetActive (true);
OnRanking ();
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_RANKING);
}
}
}
break;
case State.Record:
{
goRecord.SetActive (true);
string text = null;
text += Language.sentence [Language.RECORD_ENEMY_DIE_TO_TOMB] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_ENEMY_DIE_TO_TOMB)) + "\n";
text += Language.sentence [Language.RECORD_ENEMY_DIE_TO_HOLE] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_ENEMY_DIE_TO_HOLE)) + "\n";
text += Language.sentence [Language.RECORD_TOMB_COLLAPSE] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_TOMB_COLLAPSE)) + "\n";
text += Language.sentence [Language.RECORD_HOLE_OPEN] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_HOLE_OPEN)) + "\n";
text += Language.sentence [Language.RECORD_HOLE_CLOSE] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_HOLE_CLOSE)) + "\n";
text += Language.sentence [Language.RECORD_HOLE_FALL] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_HOLE_FALL)) + "\n";
text += Language.sentence [Language.RECORD_BONUS_APPEAR] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_BONUS_APPEAR)) + "\n";
text += Language.sentence [Language.RECORD_BONUS_GET] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_BONUS_GET)) + "\n";
text += Language.sentence [Language.RECORD_ITEM_GET] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_ITEM_GET)) + "\n";
text += Language.sentence [Language.RECORD_DAMAGE] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_DAMAGE)) + "\n";
text += Language.sentence [Language.RECORD_ESCAPE] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_ESCAPE)) + "\n";
text += Language.sentence [Language.RECORD_MAX_TOMB_COLLAPSE] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_MAX_TOMB_COLLAPSE)) + "\n";
text += Language.sentence [Language.RECORD_SCORE_ALL] + string.Format ("{0,5}", PlayerPrefs.GetInt (Data.RECORD_SCORE_ALL));
goRecordPage.transform.Find ("Page0").GetComponent<Text> ().text = text;
if (Language.sentence == Language.sentenceEn) {
goRecordPage.transform.Find ("Page0").GetComponent<RectTransform> ().sizeDelta = new Vector2 (925, 1000);
}
string text0 = null;
string text1 = null;
for (int i = 0; i < 20; i++) {
TimeSpan span = TimeSpan.FromSeconds (Data.GetStageData (i).limitTime - PlayerPrefs.GetFloat (Data.RECORD_CLEAR_TIME + i));
string record = string.Format (Language.sentence [Language.RECORD_CLEAR_TIME] + "\t{1:00}:{2:00}:{3}\n", i + 1, span.Minutes, span.Seconds, span.Milliseconds.ToString ("000").Substring (0, 2));
if (PlayerPrefs.GetInt (Data.RECORD_CLEAR + i) == 0) {
record = string.Format (Language.sentence [Language.RECORD_CLEAR_TIME] + "\t--:--:--\n", i + 1);
}
if (i < 10) {
text0 += record;
} else {
text1 += record;
}
}
goRecordPage.transform.Find ("Page1").GetComponent<Text> ().text = text0;
goRecordPage.transform.Find ("Page2").GetComponent<Text> ().text = text1;
catalog.Init (RECORD_PAGE_NUM);
goCatalogPage = goRecordPage;
goCatalogPoint = goRecordPoint;
goCatalogArrowRight = goRecordArrowRight;
goCatalogArrowLeft = goRecordArrowLeft;
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_RECORD);
}
break;
case State.Help:
{
goHelp.SetActive (true);
catalog.Init (HELP_PAGE_NUM);
goCatalogPage = goHelpPage;
goCatalogPoint = goHelpPoint;
goCatalogArrowRight = goHelpArrowRight;
goCatalogArrowLeft = goHelpArrowLeft;
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_HELP);
}
break;
case State.End:
{
goEnd.SetActive (true);
}
break;
case State.Extra:
{
goExtra.SetActive (true);
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_EXTRA);
if (MainManager.Instance.isExtraItemSandal)
if (MainManager.Instance.isExtraItemHoe)
if (MainManager.Instance.isExtraItemStone)
if (MainManager.Instance.isExtraItemParasol)
goExtraItemDescription.GetComponent<Text> ().text = Language.sentence [Language.EXTRA_ITEM_DESCRIPTION_HAVE];
}
break;
}
}
private void Run ()
{
CheckBackKey ();
switch (this.state) {
case State.Menu:
{
if (time >= 0.05f)
cover.visible = false;
if (time >= birdIndex * 10) {
birdIndex++;
bird.Fly ();
}
bird.Move (Time.deltaTime, Data.TARGET_FRAME_RATE);
time += Time.deltaTime;
ProcGacha ();
}
break;
case State.Ranking:
{
if (Logined()) {
//MainManager.Instance.isDebug = true;
if (Ranking.State.Fetch == ranking.state) {
//goRankingButtonChangeUserName.SetActive (true);
goRankingButtonBack.SetActive (true);
}
HighScoreData ();
RankingData ();
}
Connecting ();
if ( goRankingPoint.activeSelf ) {
catalog.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE);
}
}
break;
case State.Record:
case State.Help:
{
catalog.Move (Data.DELTA_TIME, Data.TARGET_FRAME_RATE);
}
break;
}
}
private void Draw ()
{
switch (this.state) {
case State.Menu:
{
if (goCover.activeSelf != cover.visible) {
goCover.SetActive (cover.visible);
}
if (cover.visible) {
if (goCover.GetComponent<Image> ().color != cover.color) {
goCover.GetComponent<Image> ().color = cover.color;
}
}
if (goMenuBird.activeSelf != bird.visible) {
goMenuBird.SetActive (bird.visible);
}
if (bird.visible) {
if (goMenuBird.transform.localPosition.x != bird.positionX || goMenuBird.transform.localPosition.y != bird.positionY) {
goMenuBird.transform.localPosition = new Vector3 (bird.positionX, bird.positionY);
}
if (goMenuBird.transform.localScale.x != bird.scaleX || goMenuBird.transform.localScale.y != bird.scaleY) {
goMenuBird.transform.localScale = new Vector3 (bird.scaleX, bird.scaleY);
}
if (goMenuBird.GetComponent<Image> ().sprite != spriteBirdList [bird.imageIndex]) {
goMenuBird.GetComponent<Image> ().sprite = spriteBirdList [bird.imageIndex];
}
}
}
break;
case State.Ranking:
{
if ( goRankingPoint.activeSelf ) {
if (goCatalogPage.transform.localPosition.x != catalog.positionX) {
goCatalogPage.transform.localPosition = new Vector3 (catalog.positionX, goCatalogPage.transform.localPosition.y);
}
if (goCatalogArrowRight.activeSelf != catalog.isArrowRight) {
goCatalogArrowRight.SetActive (catalog.isArrowRight);
}
if (goCatalogArrowLeft.activeSelf != catalog.isArrowLeft) {
goCatalogArrowLeft.SetActive (catalog.isArrowLeft);
}
goCatalogPoint.transform.Find ("PointNow").localPosition = goCatalogPoint.transform.Find ("Point" + catalog.nowPageIndex).localPosition;
}
}
break;
case State.Record:
case State.Help:
{
if (goCatalogPage.transform.localPosition.x != catalog.positionX) {
goCatalogPage.transform.localPosition = new Vector3 (catalog.positionX, goCatalogPage.transform.localPosition.y);
}
if (goCatalogArrowRight.activeSelf != catalog.isArrowRight) {
goCatalogArrowRight.SetActive (catalog.isArrowRight);
}
if (goCatalogArrowLeft.activeSelf != catalog.isArrowLeft) {
goCatalogArrowLeft.SetActive (catalog.isArrowLeft);
}
goCatalogPoint.transform.Find ("PointNow").localPosition = goCatalogPoint.transform.Find ("Point" + catalog.nowPageIndex).localPosition;
}
break;
}
}
private void OnMenuButtonStart ()
{
//MainManager.Instance.selectCharacter = bookedSelectCharacter; // 2019.4.9 iwasaki 予約しておいた番号を代入 => 廃止
//MainManager.Instance.SaveCharacter ();
MainManager.Instance.StoryPrologue ();
MainManager.Instance.RecordSave ();
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK);
//MainManager.Instance.nendAdIcon.Hide ();
MainManager.Instance.bannerView.Hide ();
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_START);
}
private void OnMenuButtonStartSelectCharacter()
{
goSelectCharacter.SetActive (true);
ReflashGachaTicket ();
ShowCharacter ();
ChangeCharacterName ();
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK);
//MainManager.Instance.nendAdIcon.Hide ();
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_SELECT_CHARACTER);
}
private void OnMenuButtonCaution (bool active)
{
goCaution.SetActive (active);
SoundManager.Instance.PlaySe (active ? SoundManager.SeName.SE_OK : SoundManager.SeName.SE_CANCEL);
}
private void OnMenuButtonContinue ()
{
MainManager.Instance.CurrentStage (MainManager.Instance.life, MainManager.Instance.weapon);
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK);
//MainManager.Instance.nendAdIcon.Hide ();
MainManager.Instance.bannerView.Hide ();
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_CONTINUE);
}
private void OnSwipe (PointerEventData eventData)
{
float ratio = 1.0f * Screen.width / Data.SCREEN_WIDTH;
Vector2 delta = eventData.delta / ratio;
if (delta.x < -5) {
OnCatalogNextPage ();
} else if (delta.x > 5) {
OnCatalogPrevPage ();
}
}
private void OnCatalogNextPage ()
{
if (!catalog.isMove) {
catalog.Next ();
if (catalog.isMove)
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_MOVE);
}
}
private void OnCatalogPrevPage ()
{
if (!catalog.isMove) {
catalog.Prev ();
if (catalog.isMove)
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_MOVE);
}
}
private void OnButton (State state, bool ok = true)
{
this.state = state;
Create ();
SoundManager.Instance.PlaySe (ok ? SoundManager.SeName.SE_OK : SoundManager.SeName.SE_CANCEL);
}
private void OnPrivacyPorisy()
{
string url = Data.PRIVACY_POLICY_URL;
Application.OpenURL(url);
}
private void OnVolume (bool isMute)
{
SoundManager.Instance.SetMute (isMute);
goMenuVolumeOn.SetActive (!isMute);
goMenuVolumeOff.SetActive (isMute);
PlayerPrefs.SetInt (Data.SOUND_MUTE, isMute ? 1 : 0);
}
private void OnTwitter ()
{
// Add 2017.11.7
#if UNITY_ANDROID
SocialConnector.SocialConnector.Share (Language.sentence [Language.TWITTER], Data.URL, null);
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_TWITTER);
#elif UNITY_IOS
SocialConnector.SocialConnector.Share (Language.sentence [Language.TWITTER], Data.URL_IOS, null);
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_TWITTER);
#endif
}
private void OnEnd ()
{
Application.Quit ();
}
private void OnExtraItemButtonMovie ()
{
MainManager.Instance.ShowInterstitial (() => {
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_EXTRA_ITEM);
MainManager.Instance.isExtraItemSandal = true;
MainManager.Instance.isExtraItemHoe = true;
MainManager.Instance.isExtraItemStone = true;
MainManager.Instance.isExtraItemParasol = true;
Create ();
});
}
private void OnExtraLifeButtonMovie ()
{
MainManager.Instance.ShowInterstitial (() => {
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_EXTRA_LIFE);
MainManager.Instance.life += 5;
goExtraLifeNow.GetComponent<Text> ().text = MainManager.Instance.life.ToString ();
});
}
// アプリ紹介
private void OnExtraButtonMoreGame ()
{
#if UNITY_ANDROID
// market://details?id=パッケージ名
Application.OpenURL (Data.MORE_GAME_PACKAGENAME_ANDROID);
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_EXTRA_MOREGAME);
#elif UNITY_IOS
// http://appstore.com/アプリ名
Application.OpenURL (Data.MORE_GAME_PACKAGENAME_IOS);
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_EXTRA_MOREGAME);
#endif
}
// ガチャ.
private void OnGacha()
{
if (MainManager.Instance.gachaTicket <= 0) {
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_CANCEL);
return;
}
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_GACHA_PLAY);
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK);
MainManager.Instance.gachaTicket--;
ReflashGachaTicket ();
gacha.clear ();
goGachaCupsule.transform.localPosition = new Vector3 (goGachaCupsule.transform.localPosition.x, gacha.y, goGachaCupsule.transform.localPosition.z);
gacha.gachaMode = 1;
goGacha.SetActive (true);
goGachaStart.SetActive (true);
goGachaResult.SetActive (false);
goSelectCharacter.SetActive (false);
}
private void OnGachaResultBackButton()
{
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_CANCEL);
ShowCharacter ();
goGacha.SetActive (false);
goGachaStart.SetActive (false);
goGachaResult.SetActive (false);
goSelectCharacter.SetActive (true);
}
public void OnSelectCharacter(int number)
{
if (MainManager.Instance.IsCharacter (number)) {
float x = goCharacter [number].transform.localPosition.x;
float y = goCharacter [number].transform.localPosition.y + 22;
goSelectCharacterFrame.transform.localPosition = new Vector3 (x, y, 0);
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_OK);
//bookedSelectCharacter = number; // 2019.4.9 iwasaki 予約のみ => 廃止
MainManager.Instance.selectCharacter = number;
MainManager.Instance.SaveCharacter ();
} else {
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_CANCEL);
}
}
private void InitSelectCharacterFrame()
{
float x = goCharacter [MainManager.Instance.selectCharacter].transform.localPosition.x;
float y = goCharacter [MainManager.Instance.selectCharacter].transform.localPosition.y + 22;
goSelectCharacterFrame.transform.localPosition = new Vector3 (x, y, 0);
}
// ガチャ結果で表示するキャラクター or ハート.
private void ChangeSprite()
{
//Debug.Log (gacha.selectedGachaNumber);
if (gacha.selectedGachaNumber == -1) {
string uri = "Textures/hart";
//Debug.Log (uri);
Sprite spt = Resources.Load<Sprite> (uri) as Sprite;
goGachaResultChara.GetComponent<Image> ().sprite = spt;
goGachaResultChara.GetComponent<Image> ().SetNativeSize ();
//goGachaResultChara.transform.localScale = new Vector3 (2, 2, 2);
} else {
string uri = "Textures/player" + gacha.selectedGachaNumber + "_bottom_0";
Sprite spt = Resources.Load<Sprite> (uri) as Sprite;
//Debug.Log (uri);
goGachaResultChara.GetComponent<Image> ().sprite = spt;
goGachaResultChara.GetComponent<Image> ().SetNativeSize ();
goGachaResultChara.transform.localScale = new Vector3 (2, 2, 2);
}
}
// ガチャ演出と抽選.
private void ProcGacha()
{
// ガチャチケット獲得.
if (MainManager.Instance.isInterstitialClose) {
MainManager.Instance.gachaTicket += 1;
ReflashGachaTicket();
MainManager.Instance.isInterstitialClose = false;
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_GACHA_BANNER_ADS);
}
if (gacha.gachaMode > 0) {
// 演出スキップ.
bool isSkip = false;
if (Input.GetMouseButton (0)) {
gacha.gachaMode = 8;
isSkip = true;
}
// カプセルが転がる.
if (gacha.gachaMode == 8) {
goGachaCupsule.SetActive (true);
}
// ガチャアプセルのアニメスタート.
if (goGachaCupsule.activeSelf) {
if (goGachaCupsule.transform.localPosition.y <= -599 || isSkip) {
gacha.lottery (100);
ChangeSprite();
MainManager.Instance.SaveCharacter ();
if (gacha.selectedGachaNumber == -1) {
goGachaResultGotText.GetComponent<Text> ().text = Language.sentence [Language.LIFEIS1UP];
MainManager.Instance.life++;
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_GACHA_LIFE);
} else {
goGachaResultGotText.GetComponent<Text> ().text = Language.sentence [Language.YOUGOTCHARA];
MainManager.Instance.GetCharacter (gacha.selectedGachaNumber);
string chara = Data.FIREBASE_EVENT_GACHA_KUNOICHI;
if (gacha.selectedGachaNumber == Data.CHARACTER_MIKO)
chara = Data.FIREBASE_EVENT_GACHA_MIKO;
if (gacha.selectedGachaNumber == Data.CHARACTER_NINJA)
chara = Data.FIREBASE_EVENT_GACHA_MIKO;
if (gacha.selectedGachaNumber == Data.CHARACTER_MATIMUSUME)
chara = Data.FIREBASE_EVENT_GACHA_MACHIMUSUME;
if (gacha.selectedGachaNumber == Data.CHARACTER_HACHI)
chara = Data.FIREBASE_EVENT_GACHA_HACHI;
FirebaseAnalyticsManager.Instance.LogEvent (chara);
}
// 結果へ.
ShowAdsBanner();
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_RESULT);
goGachaResult.SetActive (true);
goGachaStart.SetActive (!goGachaResult.activeSelf);
goGachaCupsule.SetActive(!goGachaResult.activeSelf);
gacha.clear ();
goGachaCupsule.transform.localPosition = new Vector3 (goGachaCupsule.transform.localPosition.x, gacha.y, goGachaCupsule.transform.localPosition.z);
}
return;
}
// 回転処理.
if (gacha.gachaMode % 2 == 1) {
gacha.timer = Time.time;
gacha.gachabarAngle = 0;
gacha.gachabarSet = (20 + UnityEngine.Random.Range (10, 30));
gacha.gachaMode++;
}
if (gacha.gachaMode % 2 == 0) {
if (Time.time >= gacha.timer + UnityEngine.Random.Range (0.5f, 1.25f)) {
SoundManager.Instance.PlaySe (SoundManager.SeName.SE_GACHA);
gacha.gachabarAngle += 10;
if (gacha.gachabarAngle >= gacha.gachabarSet) {
gacha.gachaMode++;
}
goGachaBar.transform.localEulerAngles += new Vector3 (0, 0, -(gacha.gachabarAngle % 360));
}
}
}
}
// キャラクター選択でキャラクター表示.
private void ShowCharacter()
{
for (int i = 0; i < Data.CHARACTER_MAX; i++) {
if (MainManager.Instance.IsCharacter (i)) {
goCharacter [i].GetComponent<Image> ().color = new Color (1, 1, 1, 1);
}
}
}
// キャラクター名、日本語 or 英語.
private void ChangeCharacterName()
{
for (int i = 0; i < Data.CHARACTER_MAX; i++) {
goSelectCharacter.transform.Find ("Character/Chara" + i + "Name").GetComponent<Text> ().text = Language.sentence [Language.CHARANAME_SAMURAI + i];
}
}
// チケット数を更新.
private void ReflashGachaTicket()
{
goSelectCharacterGachaTicketText.GetComponent<Text> ().text = Language.sentence [Language.GACHA_RESULT_GACHATICKETTEXT];
goSelectCharacterGachaTicket.GetComponent<Text> ().text = MainManager.Instance.gachaTicket.ToString();
goGachaResultGachaTicketText.GetComponent<Text> ().text = Language.sentence [Language.GACHA_RESULT_GACHATICKETTEXT];
goGachaResultGachaTicket.GetComponent<Text> ().text = MainManager.Instance.gachaTicket.ToString();
}
// ガチャチケットを獲得するための動画視聴.
private void ShowAdsMovie()
{
UnityEngine.Random.InitState ((int)Time.time);
MainManager.Instance.ShowInterstitial (() => {
MainManager.Instance.gachaTicket += 5;
ReflashGachaTicket();
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_EVENT_GACHA_ADS);
});
}
// バナーが出たらガチャチケット1枚.
private void ShowAdsBanner()
{
UnityEngine.Random.InitState ((int)Time.time);
if (UnityEngine.Random.Range (0, 100) < 20) {
MainManager.Instance.ShowInterstitialNoMovie ();
}
}
// 起動時に出すポップアップインフォ.
private void SetInformation()
{
if (MainManager.Instance.IsInformation ()) {
if (Language.sentence == Language.sentenceEn) {
goInformation.transform.Find ("Title").GetComponent<Text> ().fontSize = 32;
goInformation.transform.Find ("Explanation").GetComponent<Text> ().fontSize = 30;
} else {
goInformation.transform.Find ("Title").GetComponent<Text> ().fontSize = 30;
goInformation.transform.Find ("Explanation").GetComponent<Text> ().fontSize = 26;
}
goInformation.transform.Find ("Title").GetComponent<Text> ().text = Language.sentence [Language.INFORMATION_TITLE];
goInformation.transform.Find ("Explanation").GetComponent<Text> ().text = Language.sentence [Language.INFORMATION_EXPLANATION];
goInformation.SetActive (true);
FirebaseAnalyticsManager.Instance.LogEvent (Data.FIREBASE_SCREEN_INFORMATION);
}
}
// ガチャチケットを獲得した時に出すポップアップ.
public void SetLoginBonus()
{
if (loginBonus.prevGachaTicket < MainManager.Instance.gachaTicket) {
goMenuLoginBonus.transform.Find ("Text").GetComponent<Text> ().text = Language.sentence [Language.LOGIN_BONUS_TEXT];
goMenuLoginBonus.SetActive (true);
loginBonus.prevGachaTicket = MainManager.Instance.gachaTicket;
FirebaseAnalyticsManager.Instance.LogScreen (Data.FIREBASE_SCREEN_BONUS);
}
}
// ポップアップインフォを非表示.
private void OnButtonInformationClose()
{
MainManager.Instance.SaveInformation ();
goInformation.SetActive (false);
}
// ログインボーナスのポップアップを非表示.
private void OnButtonLoginBonusClose()
{
goMenuLoginBonus.SetActive (false);
}
private void CheckBackKey ()
{
if (Input.GetKeyDown (KeyCode.Escape)) {
switch (this.state) {
case State.Menu:
if (goGacha.activeSelf) {
OnGachaResultBackButton ();
} else if (goCaution.activeSelf) {
OnMenuButtonCaution (false);
} else if (goSelectCharacter.activeSelf) {
OnButton (State.Menu, false);
} else {
OnButton (State.End);
}
break;
default:
OnButton (State.Menu, false);
break;
}
}
}
// ========================================
// 以下、ランキング関連.
// ========================================
private void OnLogin()
{
string id = goLogin.transform.Find("Id/InputField/Text").GetComponent<Text>().text;
string password = goLogin.transform.Find("Password/InputField/Text").GetComponent<Text>().text;
//Debug mode.
//id = "Cookie";
//password = "1111";
bool flg = ErrorUserAuth(goLoginDescription, id, password);
if (flg) {
return;
}
ranking.Init ();
MainManager.Instance.loginInfo.Reset ();
SetConnecting (true);
user.logIn (id, password);
}
// ログアウト.
// 未使用予定.
private void OnLogout()
{
SetPreparationLogout ();
user.logOut ();
}
// 登録後の表示.
private void OnSignup()
{
goSignup.SetActive (true);
goLogin.SetActive (false);
goSignup.transform.Find ("Description").gameObject.SetActive(false);
goRankingConnecting.GetComponent<Text> ().text = Language.sentence [Language.SIGNUP];
goRankingConnecting.SetActive(false);
goSignup.transform.Find ("UserName").GetComponent<Text> ().text = user.userName;
goSignup.transform.Find ("UserPassword").GetComponent<Text> ().text = user.password;
}
// 登録処理.
private void OnButtonRegist()
{
string name = goSignup.transform.Find("Id/InputField/Text").GetComponent<Text>().text;
string password = goSignup.transform.Find("Password/InputField/Text").GetComponent<Text>().text;
string rePassword = goSignup.transform.Find("RePassword/InputField/Text").GetComponent<Text>().text;
string mail = null; // No nessesary this time.
name = AutoGenerateUserName ();
password = AutoGenerateUserPassword ();
rePassword = password;
//Debug mode.
//id = "Cookie";
//password = "1111";
//rePassword = "1111";
bool flg = ErrorUserAuth(goSignupDescription, name, password, rePassword);
if (flg) {
return;
}
ranking.Init ();
MainManager.Instance.loginInfo.Reset ();
SetConnecting (false);
user.signUp (name, mail, password);
}
// ランキング表示へ.
private void OnRanking()
{
if (IsOffline ()) {
return;
}
SetRanking (false);
string textRank = null;
string textName = null;
string textScore = null;
// No.1 - 10をセット
int max = MainManager.Instance.loginInfo.GetRankMax ();
int count = (max > (HighScore.RANKING_MAX >> 1)) ? HighScore.RANKING_MAX >> 1 : max;
for (int i = 0; i < count; i++) {
textRank += "No." + (i + 1) + "\n";
textName += MainManager.Instance.loginInfo.GetUserName (i) + "\n";
textScore += MainManager.Instance.loginInfo.GetUserScore (i) + "\n";
}
string text = null;
text = "My Rank.\n";
text += "No." + MainManager.Instance.loginInfo.GetRank () + " " + MainManager.Instance.loginInfo.GetName () + " " + MainManager.Instance.loginInfo.GetScore () + "点\n";
goRankingPage.SetActive (true);
goRankingMe.SetActive (true);
goRankingPage.transform.Find ("Page0/Rank").GetComponent<Text> ().text = textRank;
goRankingPage.transform.Find ("Page0/Name").GetComponent<Text> ().text = textName;
goRankingPage.transform.Find ("Page0/Score").GetComponent<Text> ().text = textScore;
goRankingMe.GetComponent<Text> ().text = text;
if (Language.sentence == Language.sentenceEn) {
goRankingPage.transform.Find ("Page0").GetComponent<RectTransform> ().sizeDelta = new Vector2 (925, 1000);
}
// No.11 - 20までをセット
count = max - (HighScore.RANKING_MAX >> 1);
if (max >= HighScore.RANKING_MAX)
count = HighScore.RANKING_MAX >> 1;
//Debug.Log (max+", count = "+count);
if (count > 0) {
SetRanking (true);
textRank = null;
textName = null;
textScore = null;
// For debug.
/*for (int i = 0; i < 10; i++) {
textRank += "No."+(10+i+1)+"\n";
textName += "user name "+i+"\n";
textScore += ((i+1)*1000)+"\n";
}*/
for (int i = 0; i < count; i++) {
textRank += "No." + (10 + i + 1) + "\n";
textName += MainManager.Instance.loginInfo.GetUserName ((HighScore.RANKING_MAX >> 1) + i) + "\n";
textScore += MainManager.Instance.loginInfo.GetUserScore ((HighScore.RANKING_MAX >> 1) + i) + "\n";
}
goRankingPage.transform.Find ("Page1/Rank").GetComponent<Text> ().text = textRank;
goRankingPage.transform.Find ("Page1/Name").GetComponent<Text> ().text = textName;
goRankingPage.transform.Find ("Page1/Score").GetComponent<Text> ().text = textScore;
catalog.Init (RANKING_PAGE_NUM);
goCatalogPage = goRankingPage;
goCatalogPoint = goRankingPoint;
goCatalogArrowRight = goRankingArrowRight;
goCatalogArrowLeft = goRankingArrowLeft;
}
goRankingButtonChangeUserName.SetActive (true);
goRankingButtonBack.SetActive (true);
goRankingConnecting.SetActive (false);
goSignup.SetActive (false);
}
private void SetRanking( bool flg )
{
goRankingPoint.SetActive (flg);
goRankingSwipe.SetActive (flg);
goRankingArrowLeft.SetActive (flg);
goRankingArrowRight.SetActive (flg);
//goRankingButtonLogout.SetActive (flg);
}
private void OnChange()
{
goChangeResultUserName.SetActive (false);
goRankingPage.SetActive (false);
goRankingMe.SetActive (false);
goRankingButtonChangeUserName.SetActive (false);
goChagne.SetActive (true);
SetRanking (false);
}
private void OnChangeUserName()
{
NCMBUser.CurrentUser.UserName = goChagne.transform.Find("Id/InputField/Text").GetComponent<Text>().text;
NCMBUser.CurrentUser.SignUpAsync ( (NCMBException e) => {
if( e == null ){
PlayerPrefs.SetString (Data.LOGIN_NAME, goChagne.transform.Find("Id/InputField/Text").GetComponent<Text>().text);
goChangeResultUserName.GetComponent<Text> ().color = new Color (1, 1, 1, 1);
goChangeResultUserName.GetComponent<Text>().text = Language.sentence [Language.RANKING_NAME_CHANGE_CORRECT];
goChangeResultUserName.SetActive(true);
goSignupButtonRanking.SetActive (false);
goRankingButtonBack.SetActive(true);
}
else{
// Error.
goChangeResultUserName.GetComponent<Text> ().color = new Color (1, 0, 0, 0);
goChangeResultUserName.GetComponent<Text>().text = Language.sentence [Language.RANKING_NAME_CHANGE_INCORRECT];
goChangeResultUserName.SetActive(true);
goRankingButtonBack.SetActive(true);
}
});
}
// 未対応.
private void OnChangeUserPassword()
{
}
private bool isLogin;
private bool isLogout;
private bool isConnecting;
private void SetConnecting( bool isLogin )
{
this.isLogin = isLogin;
this.isLogout = false;
this.isConnecting = true;
goRankingConnecting.SetActive (true);
goRankingButtonChangeUserName.SetActive (false);
goRankingButtonBack.SetActive (false);
goLogin.SetActive (false);
goSignup.SetActive (false);
goRankingConnecting.GetComponent<Text> ().color = new Color (1, 1, 1, 1);
connectingText = Language.sentence [Language.CONNECTING];
}
private void SetPreparationLogout()
{
this.isLogin = false;
this.isLogout = true;
this.isConnecting = true;
goRankingConnecting.SetActive (true);
goRankingMe.SetActive(false);
goRankingPage.SetActive(false);
goRankingPoint.SetActive(false);
goRankingSwipe.SetActive(false);
goRankingArrowLeft.SetActive(false);
goRankingArrowRight.SetActive(false);
goRankingButtonLogout.SetActive(false);
goRankingButtonChangeUserName.SetActive (false);
goRankingButtonBack.SetActive (false);
goRankingConnecting.GetComponent<Text> ().color = new Color (1, 1, 1, 1);
connectingText = Language.sentence [Language.CONNECTING];
}
private void Connecting()
{
if (IsOffline ()) {
return;
}
// 接続中...
if (goRankingConnecting.activeSelf) {
// エラーコードなし
if (user.errorCode == null) {
// 正常ログアウト
if (MainManager.Instance.isLogin == false && isLogout ) {
isConnecting = false;
this.isLogout = false;
goRankingConnecting.GetComponent<Text> ().text = Language.sentence [Language.LOGOUT];
goRankingButtonBack.SetActive (true);
}
// 未ログイン = 接続中アニメ
if (isConnecting) {
float i = Time.time % 3;
goRankingConnecting.GetComponent<Text> ().text = connectingText.Substring (0, connectingText.Length - 2 + (int)i);
}
// 正常ログイン
if (Logined()) {
isConnecting = false;
if (isAutoLogin) {
if (Ranking.State.Finish == ranking.state) {
OnRanking ();
goRankingConnecting.SetActive (false);
}
}
else
OnSignup ();
}
}
// ログイン、サインインに失敗
if (user.errorCode != null) {
// テキストの設定
if (!goRankingButtonBack.activeSelf) {
goRankingConnecting.GetComponent<Text> ().color = new Color (1, 0, 0, 1);
// 名前とパスワードが不一致
if (user.errorCode == NCMBException.INCORRECT_PASSWORD ||
user.errorCode == NCMBException.INCORRECT_HEADER ||
user.errorCode == NCMBException.OAUTH_ERROR
) {
goRankingConnecting.GetComponent<Text> ().text = Language.sentence [Language.ERROR_LOGIN_INCORRECT];
}
// すでに名前が使われている.
if (user.errorCode == NCMBException.DUPPLICATION_ERROR) {
goRankingConnecting.GetComponent<Text> ().text = Language.sentence [Language.ERROR_SIGNUP_INCORRECT];
}
// 使用制限(APIコール数、PUSH通知数、ストレージ容量)超過エラーです.
if (user.errorCode == NCMBException.DUPPLICATION_ERROR) {
goRankingConnecting.GetComponent<Text> ().text = Language.sentence [Language.REQUEST_OVERLOAD];
}
// 戻るボタンを表示
goRankingButtonBack.SetActive (true);
}
}
}
}
private bool Logined()
{
return (user.currentPlayer () != null && !isLogout);
}
private bool isAutoLogin;
private void AutoLogin()
{
if (IsOffline ()) {
return;
}
// Read them from strage.
string name = PlayerPrefs.GetString (Data.LOGIN_NAME);
string password = PlayerPrefs.GetString (Data.LOGIN_PASSWORD);
isAutoLogin = false;
//Debug.Log (name + ", " + password);
if (!(name.Equals ("") && password.Equals (""))) {
SetConnecting (true);
user.logIn (name, password);
isAutoLogin = true;
}
}
private bool IsOffline()
{
if (Application.internetReachability == NetworkReachability.NotReachable) {
return true;
}
return false;
}
// user name.
private string AutoGenerateUserName()
{
int name = int.Parse (DateTime.Now.ToString ("MMddHHmmss"));
name ^= EXCHANGE_CODE;
return name.ToString();
}
// user password.
private string AutoGenerateUserPassword()
{
int pass = int.Parse (DateTime.Now.ToString ("MMddHHmmss"));
pass ^= EXCHANGE_CODE;
return pass.ToString();
}
private bool ErrorUserAuth(GameObject obj, string id, string password, string repassword = null)
{
bool error = false;
string text = null;
// Incorrect name.
if (id.Equals ("") || id.Length >= 14) {
error = true;
text = Language.sentence [Language.ERROR_NONAME];
// Incorrect password.
} else if (password.Equals ("")) {
error = true;
text = Language.sentence [Language.ERROR_NOPASSWORD];
}
// Incorrect password and confirmatioin password.
if (repassword != null) {
if (!password.Equals (repassword)) {
error = true;
text = Language.sentence [Language.ERROR_SIGNUP_NOMATCH_PASSWORD];
}
}
// Draw error message.
if (error) {
obj.SetActive (true);
obj.GetComponent<Text> ().text = text;
goRankingButtonBack.SetActive (true);
}
return error;
}
private void HighScoreData()
{
switch (ranking.state) {
case Ranking.State.Fetch:
{
ranking.Fetch (user.currentPlayer());
ranking.Next (Ranking.State.Save);
}
break;
case Ranking.State.Save:
{
int score = 0;
int stage = 0;
if (PlayerPrefs.HasKey (Data.RECORD_SCORE_HIGH)) {
score = PlayerPrefs.GetInt (Data.RECORD_SCORE_HIGH);
int present = PlayerPrefs.GetInt (Data.RECORD_SCORE);
if (present < 10000)
score = present;
}
ranking.Save (score, stage);
ranking.Next (Ranking.State.Goto);
}
break;
case Ranking.State.Goto:
ranking.state = Ranking.State.FetchRank;
ranking.debug ();
break;
}
}
private void RankingData()
{
switch (ranking.state) {
case Ranking.State.FetchRank:
{
ranking.FetchRank ();
ranking.NextLeaderBoard (Ranking.State.TopRank);
}
break;
case Ranking.State.TopRank:
{
ranking.FetchTopRank ();
ranking.NextLeaderBoard (Ranking.State.Finish);
}
break;
case Ranking.State.Finish:
ranking.debug ();
break;
}
}
public class UserAuth {
public string userName;
public string password;
public string errorCode;
private string currentPlayerName;
// mobile backendに接続してログイン ------------------------
public void logIn( string id, string pw ) {
errorCode = null;
NCMBUser.LogInAsync (id, pw, (NCMBException e) => {
// 接続成功したら
if( e == null ){
currentPlayerName = id;
userName = id;
password = pw;
MainManager.Instance.isLogin = true;
MainManager.Instance.loginInfo.SetLoginInfo(userName,password);
PlayerPrefs.SetString (Data.LOGIN_NAME, userName);
PlayerPrefs.SetString (Data.LOGIN_PASSWORD, password);
FirebaseAnalyticsManager.Instance.LogEvent(Data.FIREBASE_EVENT_RANKING_LOGIN);
}
else {
errorCode = e.ErrorCode;
}
});
}
// mobile backendに接続して新規会員登録 ------------------------
public void signUp( string id, string mail, string pw ) {
NCMBUser user = new NCMBUser();
user.UserName = id;
user.Email = mail;
user.Password = pw;
errorCode = null;
user.SignUpAsync((NCMBException e) => {
if( e == null ){
user.ACL = new NCMBACL(NCMBUser.CurrentUser.ObjectId);
user.SaveAsync();
currentPlayerName = id;
userName = id;
password = pw;
MainManager.Instance.isLogin = true;
MainManager.Instance.loginInfo.SetLoginInfo(userName,password);
PlayerPrefs.SetString (Data.LOGIN_NAME, userName);
PlayerPrefs.SetString (Data.LOGIN_PASSWORD, password);
FirebaseAnalyticsManager.Instance.LogEvent(Data.FIREBASE_EVENT_RANKING_SIGNIN);
//Debug.Log ("### name = " + userName + ", pass = " + password);
}
else {
errorCode = e.ErrorCode;
}
});
}
// mobile backendに接続してログアウト ------------------------
public void logOut() {
errorCode = null;
NCMBUser.LogOutAsync ( (NCMBException e) => {
if( e == null ){
currentPlayerName = null;
MainManager.Instance.isLogin = false;
}
});
}
// 現在のプレイヤー名を返す --------------------
public string currentPlayer()
{
return currentPlayerName;
}
}
}
|
using DigitalFormsSteamLeak.Entity.IModels;
using DigitalFormsSteamLeak.Entity.Models;
using DigitalFormsSteamLeak.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalFormsSteamLeak.Business
{
public class LeakTypeFactory : ILeakFactory<ILeakType>
{
protected LeakDbHelper leakDB { get; set; }
public LeakTypeFactory()
{
leakDB = new LeakDbHelper();
}
public int Create(ILeakType entity)
{
return leakDB.Save<LeakType>((LeakType)entity);
}
public int Update(ILeakType entity)
{
return leakDB.Update<LeakType>((LeakType)entity);
}
public IQueryable<ILeakType> GetAll()
{
return leakDB.GetDetails<LeakType>();
}
public IQueryable<ILeakType> GetById(Guid? id)
{
return GetAll().Where(lt => lt.LeakTypeId == id);
}
}
} |
using Microsoft.Extensions.Configuration;
namespace M220NLessons
{
public static class Constants
{
//public static string MongoDbConnectionUri = "mongodb+srv://m220student:m220password@mflix-0s7fk.mongodb.net/";
public static string BadMongoDbConnectionUri = "mongodb://localhost:27011/"; // Used only to force a timeout
public static string LocalMongoDbConnectionUri = "mongodb://localhost:27017/"; // Used only to force a timeout
public static string MongoDbConnectionUri()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();
return configuration.GetValue<string>("MongoUri");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace prueba18032015
{
interface IFigura
{
abstract public void pintar();
abstract public void calcularArea();
abstract public void calcularVolumen();
abstract public void cmbiarTexto();
}
}
|
public class Solution {
public IList<int> MajorityElement(int[] nums) {
int candidate1 = int.MinValue, candidate2 = int.MinValue, cnt1 = 0, cnt2 = 0;
foreach (int num in nums) {
if (num == candidate1) cnt1++;
else if (num == candidate2) cnt2++;
else if (cnt1 == 0) {
candidate1 = num;
cnt1 = 1;
}
else if (cnt2 == 0) {
candidate2 = num;
cnt2 = 1;
}
else {
cnt1 --;
cnt2 --;
}
}
cnt1 = 0;
cnt2 = 0;
foreach (int num in nums) {
if (num == candidate1) cnt1 ++;
else if (num == candidate2) cnt2 ++;
}
var res = new List<int>();
if (cnt1 > nums.Length / 3) res.Add(candidate1);
if (cnt2 > nums.Length / 3) res.Add(candidate2);
return res;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Highscores : MonoBehaviour {
public Text container;
// Use this for initialization
void Start () {
container.text = "";
PlayerPrefs.SetInt("highScore1score", 12309129);
PlayerPrefs.SetInt("highScore2score", 3211233);
PlayerPrefs.SetInt("highScore3score", 123121);
PlayerPrefs.SetInt("highScore4score", 12123);
PlayerPrefs.SetInt("highScore5score", 1233);
PlayerPrefs.SetInt("highScore6score", 123);
PlayerPrefs.SetInt("highScore7score", 12);
PlayerPrefs.SetInt("highScore8score", 1);
PlayerPrefs.SetInt("highScore9score", -3);
PlayerPrefs.SetInt("highScore10score", -19);
PlayerPrefs.SetString("highScore1pseudo", "gaspar");
PlayerPrefs.SetString("highScore2pseudo", "toto");
PlayerPrefs.SetString("highScore3pseudo", "ttit");
PlayerPrefs.SetString("highScore4pseudo", "kazji");
PlayerPrefs.SetString("highScore5pseudo", "pazlsmqd");
PlayerPrefs.SetString("highScore6pseudo", "ezpoids");
PlayerPrefs.SetString("highScore7pseudo", "ezpfoizefpoxc");
PlayerPrefs.SetString("highScore8pseudo", "ocnref");
PlayerPrefs.SetString("highScore9pseudo", "ioccdjsknezui");
PlayerPrefs.SetString("highScore10pseudo", "pokcdkeo");
for (int highnum = 1; highnum <= 10; ++highnum)
{
string score = "highScore" + highnum.ToString() + "score";
string pseudo = "highScore" + highnum.ToString() + "pseudo";
Debug.Log("Pseudo: " + pseudo);
Debug.Log("Score: " + score.ToString());
if (!PlayerPrefs.HasKey(pseudo) || !PlayerPrefs.HasKey(score))
return;
container.text += PlayerPrefs.GetString(pseudo) + ": " + PlayerPrefs.GetInt(score).ToString() + "\n";
}
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text.RegularExpressions;
namespace NStandard.Runtime
{
public class AssemblyContext : AssemblyLoadContext
{
private static readonly string ProgramFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
#if NET35
private static readonly string UserProfileFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "..");
#else
private static readonly string UserProfileFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
#endif
public Assembly MainAssembly { get; private set; }
public List<string> Directories = new();
public List<string> LoadedSdks = new();
public List<Assembly> LoadedAssemblies = new();
public List<AssemblyName> LoadedAssemblyNames = new();
public readonly DotNetFramework Framework;
public readonly DotNetFramework[] CompatibilityFrameworks;
public AssemblyContext(DotNetFramework framework, string sdkType)
{
Framework = framework;
CompatibilityFrameworks = framework.CompatibilityFrameworks.OrderByDescending(x => x.Order).ToArray();
LoadSdk(sdkType);
}
public void LoadMain(string assemblyFile)
{
if (MainAssembly is not null) throw new InvalidOperationException("Main assembly has been loaded.");
var assembly = LoadFromAssemblyPath(assemblyFile);
LoadedAssemblies.Add(assembly);
LoadedAssemblyNames.Add(assembly.GetName());
Directories.Add(Path.GetDirectoryName(assemblyFile));
MainAssembly = assembly;
foreach (var refAsseblyName in MainAssembly.GetReferencedAssemblies())
{
Load(refAsseblyName);
}
}
private void AddToDirectories(string packageDir)
{
if (Directory.Exists(packageDir))
{
var verPairs = (
from nuVersion in Directory.GetDirectories(packageDir).Select(x => Path.GetFileName(x))
let ver = GetVersionFromNuVersion(nuVersion)
where ver >= Framework.Version
orderby ver
select new { NuVersion = nuVersion, Version = ver }
).ToArray();
if (verPairs.Any())
{
Directories.Add($"{packageDir}/{verPairs[0].NuVersion}");
}
}
}
private void LoadSdk(string sdkType)
{
if (LoadedSdks.Contains(sdkType)) return;
if (!new[] { SdkType.Legacy, SdkType.Core, SdkType.Web }.Contains(sdkType)) throw new ArgumentException($"Unkown sdk type. ({sdkType})", nameof(sdkType));
if (sdkType == SdkType.Legacy) throw new NotSupportedException(".NET Framework is not supported.");
if (sdkType == SdkType.Core || sdkType == SdkType.Web)
{
LoadedSdks.Add(SdkType.Core);
AddToDirectories($"{ProgramFilesFolder}/dotnet/shared/Microsoft.NETCore.App");
}
if (sdkType == SdkType.Web)
{
LoadedSdks.Add(SdkType.Web);
AddToDirectories($"{ProgramFilesFolder}/dotnet/shared/Microsoft.AspNetCore.App");
AddToDirectories($"{ProgramFilesFolder}/dotnet/shared/Microsoft.AspNetCore.All");
}
}
public string GetNuVersion(Version version)
{
return version.MinorRevision <= 0
? $"{version.Major}.{version.Minor}.{version.Build}"
: $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}";
}
private readonly Regex NuVersionRegex = new(@"(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:-\w+)?", RegexOptions.Singleline);
public Version GetVersionFromNuVersion(string nuVersion)
{
var match = NuVersionRegex.Match(nuVersion);
if (!match.Success) return default;
var groups = match.Groups;
var major = int.Parse(groups[1].Value);
var minor = int.Parse(groups[2].Value);
var build = int.Parse(groups[3].Value);
var revision = groups[4];
return new Version(major, minor, build, revision.Success ? int.Parse(revision.Value) : 0);
}
public string GetFileFromNugetCache(AssemblyName asmName)
{
var packageDir = $"{UserProfileFolder}/.nuget/packages/{asmName.Name.ToLower()}";
if (!Directory.Exists(packageDir)) return null;
var verPairs = (from nuVersion in Directory.GetDirectories(packageDir)
let ver = GetVersionFromNuVersion(nuVersion)
where ver >= asmName.Version
orderby ver
select new { NuVersion = nuVersion, Version = ver }).ToArray();
if (verPairs.Length == 0) return null;
foreach (var pair in verPairs)
{
var libDir = $"{packageDir}/{pair.NuVersion}/lib";
if (!Directory.Exists(libDir)) continue;
var tfms = Directory.GetDirectories(libDir);
var selectTfm = CompatibilityFrameworks.FirstOrDefault(framework => tfms.Contains(framework.TFM));
if (selectTfm != null)
{
var file = $"{libDir}/{selectTfm.TFM}/{asmName.Name}.dll";
if (File.Exists(file)) return file;
}
}
return null;
}
public string GetFileFromSdkNuGetFallbackFolder(AssemblyName asmName)
{
var packageDir = $"{ProgramFilesFolder}/dotnet/sdk/NuGetFallbackFolder/{asmName.Name.ToLower()}";
if (!Directory.Exists(packageDir)) return null;
var verPairs = (from nuVersion in Directory.GetDirectories(packageDir)
let ver = GetVersionFromNuVersion(nuVersion)
where ver >= asmName.Version
orderby ver
select new { NuVersion = nuVersion, Version = ver }).ToArray();
if (verPairs.Length == 0) return null;
foreach (var pair in verPairs)
{
var libDir = $"{packageDir}/{pair.NuVersion}/lib";
if (!Directory.Exists(libDir)) continue;
var tfms = Directory.GetDirectories(libDir);
var selectTfm = CompatibilityFrameworks.FirstOrDefault(framework => tfms.Contains(framework.TFM));
if (selectTfm != null)
{
var file = $"{libDir}/{selectTfm.TFM}/{asmName.Name}.dll";
if (File.Exists(file)) return file;
}
}
return null;
}
public virtual Type GetType(string name)
{
if (name.Count(',') == 1)
{
var parts = name.Split(',');
var typeName = parts[0];
var assemblyName = parts[1];
return LoadedAssemblies.FirstOrDefault(x => x.GetName().Name == assemblyName)?.GetType(typeName);
}
else return MainAssembly.GetType(name);
}
public virtual Type[] GetTypes() => MainAssembly.GetTypes();
protected override Assembly Load(AssemblyName assemblyName)
{
var found = LoadedAssemblies.FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
if (found is not null) return found;
foreach (var directory in Directories)
{
var dll = Directory.EnumerateFiles(directory, $"{assemblyName.Name}.dll").FirstOrDefault()
?? GetFileFromSdkNuGetFallbackFolder(assemblyName)
?? GetFileFromNugetCache(assemblyName);
if (dll is not null)
{
var assembly = LoadFromAssemblyPath(dll);
LoadedAssemblies.Add(assembly);
LoadedAssemblyNames.Add(assembly.GetName());
return assembly;
}
}
throw new FileNotFoundException($"Can not find {assemblyName}.dll");
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Throw : EntityBehavior {
public float shootDelay = .5f;
public List<GameObject> projectiles;
public Vector2 firePosition = Vector2.zero;
public Color debugColor = Color.yellow;
public float debugRadius = 3f;
public bool throwing;
private float timeElapsed = 0f;
void Update() {
if (projectiles != null) {
var canFire = inputState.GetButtonValue(inputButtons[0]);
if (canFire && timeElapsed > shootDelay) {
OnThrow(true);
}
else if (throwing && !canFire) {
OnThrow(false);
}
timeElapsed += Time.deltaTime;
}
}
protected virtual void OnThrow(bool value) {
throwing = value;
if (throwing) {
CreateProjectile(CalculateFirePosition());
timeElapsed = 0;
}
}
public void CreateProjectile(Vector2 pos) {
for (int i = 0; i < projectiles.Count; i++) {
var clone = Instantiate(projectiles[i], pos, Quaternion.identity) as GameObject;
clone.transform.localScale = transform.localScale;
}
}
Vector2 CalculateFirePosition() {
var pos = firePosition;
pos.x *= (float)inputState.direction;
pos.x += transform.position.x;
pos.y += transform.position.y;
return pos;
}
void OnDrawGizmos() {
Gizmos.color = debugColor;
var pos = firePosition;
if (inputState != null)
pos.x *= (float)inputState.direction;
pos.x += transform.position.x;
pos.y += transform.position.y;
Gizmos.DrawWireSphere(pos, debugRadius);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using WordTree.Service;
namespace APP_Form
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TrialMain());
//Application.Run(new SelectWordsForm());
//WordAndDicManager wordAndDicManager = WordAndDicManager.getInstance();
//WordTree.Model.Word word = wordAndDicManager.getWord("access");
//SpellingCheckForm spellingCheckForm = new SpellingCheckForm(word);
//spellingCheckForm.SetValue(word);
//Application.Run(spellingCheckForm);
//WordTree.Model.Word word1 = wordAndDicManager.getWord("adorn");
//WordTree.Model.Word word2 = wordAndDicManager.getWord("signal");
//WordTree.Model.Word word3 = wordAndDicManager.getWord("intention");
//Application.Run(new ExplanationCheckForm(word, word1, word2, word3));
}
}
}
|
using EddiDataDefinitions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using Utilities;
namespace EddiNavigationService
{
public static class EDAstro
{
private const string GalacticPOI_URI = "https://edastro.com/poi/json/combined";
public static ObservableCollection<NavBookmark> GetPOIs()
{
var galacticPOIs = new ObservableCollection<NavBookmark>();
var jsonString = Net.DownloadString(GalacticPOI_URI);
if (!string.IsNullOrEmpty(jsonString))
{
var jArray = JArray.Parse(jsonString);
// Iterate in reverse order to remove any duplicate entries which appear on both GEC and GMP lists
var unique = jArray
.OrderBy(y => y["source"]) // Order alphabetically by source ("GEC" before "GMP")
.GroupBy(x => x["galMapSearch"]) // Group POIs by system name
.Select(x => x.First()) // Select only the GEC POI if both GEC and GMP POIs exist within the same group
.ToList();
for (var i = jArray.Count - 1; i >= 0; i--)
{
var token = jArray[i];
if (!unique.Contains(token))
{
token.Remove();
}
}
foreach (JToken jToken in jArray)
{
try
{
var obj = jToken.ToObject<JObject>();
if ( obj[ "id64" ] is null ) { continue; }
var systemName = obj["galMapSearch"].ToString();
var systemAddress = obj["id64"].ToObject<ulong>();
var poiName = WebUtility.HtmlDecode(obj["name"].ToString());
// Skip any items without a system name
if (string.IsNullOrEmpty(systemName))
{
continue;
}
// Coordinates
var coordinates = obj["coordinates"].ToObject<JArray>();
var x = coordinates[0]?.ToObject<decimal>();
var y = coordinates[1]?.ToObject<decimal>();
var z = coordinates[2]?.ToObject<decimal>();
var poiBookmark = new NavBookmark(systemName, systemAddress, x, y, z, "", poiName, false, null,
null, false)
{
descriptionMarkdown = obj["descriptionMardown"].ToString()
};
if (obj["source"].ToString() == "GEC")
{
poiBookmark.comment = obj["summary"].ToString();
poiBookmark.url = obj["poiUrl"].ToString();
}
else if (obj["source"].ToString() == "GMP")
{
poiBookmark.url = obj["galMapUrl"].ToString();
}
galacticPOIs.Add(poiBookmark);
}
catch (Exception e)
{
Logging.Error("Failed to parse Galactic POI: " + JsonConvert.SerializeObject(jToken), e);
}
}
}
return galacticPOIs;
}
}
} |
#version 430 core
layout(local_size_x = 1024) in;
uint maxNumVerts;
layout(binding = 0, offset = 0) uniform atomic_uint ac;
// this is the buffer vec4 vec4 vec4 [vert conf][norm rad][col time dev] from the current depth frame from the previous depth to buffer call
layout(std430, binding = 0) buffer feedbackBuffer
{
vec4 interleavedData [];
};
//layout(std430, binding = 1) buffer updateIndexMapBuffer
//{
// vec4 outputUpdateIndexInterleaved [];
//};
layout(std430, binding = 1) buffer indexMatchingBuffer
{
int outputIndexMatchingBuffer [];
};
layout (binding = 0) uniform usampler2D indexSampler; // 4x
layout (binding = 1) uniform sampler2D vertConfSampler; // 4x
layout (binding = 2) uniform sampler2D normRadiSampler; // 4x
layout (binding = 3) uniform sampler2D colTimDevSampler; // 4x
layout(binding = 0, rgba32f) uniform image2D outImagePC;
uniform vec4 camPam; //cx, cy, fx, fy
uniform float scale; // index map scale = 4.0f
uniform mat4 pose[4];
uniform float maxDepth;
uniform float time;
uniform float weighting;
vec2 imSize;
vec3 getVert(sampler2DArray depthTex, vec3 textureCoord, ivec3 texelCoord)
{
float z = float(textureLod(depthTex, textureCoord, 0.0f).x); // SINGLE CAMERA MODE
return vec3((texelCoord.x - camPam.x) * z * camPam.z,
(texelCoord.y - camPam.y) * z * camPam.w,
z);
}
vec3 getNorm(sampler2DArray depthTex, vec4 centreVertexPosition, vec3 textureCoord, vec3 textureShift, ivec3 texelCoord)
{
vec3 posXF = getVert(depthTex, textureCoord + vec3(textureShift.x, 0, 0), texelCoord + ivec3(1, 0, 0));
vec3 posXB = getVert(depthTex, textureCoord - vec3(textureShift.x, 0, 0), texelCoord - ivec3(1, 0, 0));
vec3 posYF = getVert(depthTex, textureCoord + vec3(0, textureShift.y, 0), texelCoord + ivec3(0, 1, 0));
vec3 posYB = getVert(depthTex, textureCoord - vec3(0, textureShift.y, 0), texelCoord - ivec3(0, 1, 0));
vec3 dX = ((posXB + centreVertexPosition.xyz) / 2.0) - ((posXF + centreVertexPosition.xyz) / 2.0);
vec3 dY = ((posYB + centreVertexPosition.xyz) / 2.0) - ((posYF + centreVertexPosition.xyz) / 2.0);
return normalize(cross(dX, dY));
}
float getRadi(float depth, float normZ, int camNumber)
{
float meanFocal = ((1.0 / abs(camPam.z)) + (1.0 / abs(camPam.w))) / 2.0;
const float sqrt2 = 1.41421356237f;
float radius = (depth / meanFocal) * sqrt2;
float radius_n = radius;
radius_n = radius_n / abs(normZ);
radius_n = min(2.0f * radius, radius_n);
return radius_n;
}
float getConf(vec3 texelCoord, float weighting)
{
const float maxRadDist = 400; //sqrt((width * 0.5)^2 + (height * 0.5)^2)
const float twoSigmaSquared = 0.72; //2*(0.6^2) from paper
vec2 pixelPosCentered = texelCoord.xy - camPam.xy;
float radialDist = sqrt(dot(pixelPosCentered, pixelPosCentered)) / maxRadDist;
return exp((-(radialDist * radialDist) / twoSigmaSquared)) * weighting;
}
bool checkNeighbours(vec3 texCoord, sampler2DArray depth)
{
float z = float(textureLod(depth, vec3(texCoord.x - (1.0 / imSize.x), texCoord.y, texCoord.z), 0.0));
if(z == 0)
return false;
z = float(textureLod(depth, vec3(texCoord.x, texCoord.y - (1.0 / imSize.y), texCoord.z), 0.0));
if(z == 0)
return false;
z = float(textureLod(depth, vec3(texCoord.x + (1.0 / imSize.x), texCoord.y, texCoord.z), 0.0));
if(z == 0)
return false;
z = float(textureLod(depth, vec3(texCoord.x, texCoord.y + (1.0 / imSize.y), texCoord.z), 0.0));
if(z == 0)
return false;
return true;
}
bool checkNeighboursFIXME(int someNumber)
{
return true;
}
float angleBetween(vec3 a, vec3 b)
{
return acos(dot(a, b) / (length(a) * length(b)));
}
float encodeColor(vec3 c)
{
int rgb = int(round(c.x * 255.0f));
rgb = (rgb << 8) + int(round(c.y * 255.0f));
rgb = (rgb << 8) + int(round(c.z * 255.0f));
return float(rgb);
}
vec3 decodeColor(float c)
{
vec3 col;
col.x = float(int(c) >> 16 & 0xFF) / 255.0f;
col.y = float(int(c) >> 8 & 0xFF) / 255.0f;
col.z = float(int(c) & 0xFF) / 255.0f;
return col;
}
vec3 projectPoint(vec3 p)
{
return vec3(((((camPam.z * p.x) / p.z) + camPam.x) - (imSize.x * 0.5)) / (imSize.x * 0.5),
((((camPam.w * p.y) / p.z) + camPam.y) - (imSize.y * 0.5)) / (imSize.y * 0.5),
p.z / maxDepth);
}
vec3 projectPointImage(vec3 p)
{
return vec3(((camPam.z * p.x) / p.z) + camPam.x,
((camPam.w * p.y) / p.z) + camPam.y,
p.z);
}
// this gets run for every valid depth vertex from the depth TFO
void main()
{
ivec2 bigTexSize = textureSize(vertConfSampler, 0); // this is the 4x size
imSize = vec2(bigTexSize).xy / 4.0f;
int vertID = int(gl_GlobalInvocationID.x); // 0 to max number of valid depth verts
//ivec2 texelCoord = ivec2(vertID % texSize.x, (vertID / texSize.x) % texSize.y);
//vec2 textureCoord = vec2(float(texelCoord.x + 0.5f) / float(texSize.x), float(texelCoord.y + 0.5) / float(texSize.y));
//Vertex position integrated into model transformed to global coords
vec4 vPosLocal = interleavedData[(vertID * 3)];
vec4 geoVertPosConf = pose[0] * vec4(vPosLocal.xyz, 1);
geoVertPosConf.w = vPosLocal.w;
//Normal and radius computed with filtered position / depth map transformed to global coords
//vec3 vNormLocal = getNorm(depthSampler, geoVertPosConf, textureCoord, 1.0f / vec3(texSize.xyz), texelCoord);
vec4 vNormLocal = interleavedData[(vertID * 3) + 1];// vec4(mat3(pose) * vNormLocal, getRadi(geoVertPosConf.z, vNormLocal.z, texelCoord.z));
vec4 geoVertNormRadi = vec4(mat3(pose[0]) * vNormLocal.xyz, vNormLocal.w);
vec4 geoColTimDev = interleavedData[(vertID * 3) + 2];
vec4 geoVertColTimDev;
int updateId = 0;
uint best = 0U;
//If this point is actually a valid vertex (i.e. has depth)
// this should now be valid depth since we TFBO'd it previously
//if(texelCoord.x % 2 == int(time) % 2 && texelCoord.y % 2 == int(time) % 2 &&
// checkNeighboursFIXME(1) &&
if (vPosLocal.z > 0 && vPosLocal.z <= maxDepth) // only proceed if every other pixel, and every other frame, for some reason
{
///// outputUpdateIndexInterleaved[(vertID * 3)] = interleavedData[(vertID * 3)];
///// outputUpdateIndexInterleaved[(vertID * 3) + 1] = interleavedData[(vertID * 3) + 1];
// project to 1x image space
vec3 pix = projectPointImage(geoVertPosConf.xyz);
//imageStore(outImagePC, ivec2(pix.xy), vec4(geoVertPosConf.xyz, 2.0f));
int counter = 0;
float bestDist = 1000;
float windowMultiplier = 2;
// find the ray in the 1x image
float xl = ((pix.x - camPam.x) / camPam.z);
float yl = ((pix.y - camPam.y) / camPam.w);
float lambda = sqrt(xl * xl + yl * yl + 1);
//imageStore(outImagePC, ivec2(pix.xy), vec4(1, 0, 0, 1));
vec3 ray = vec3(xl, yl, 1);
// ray is direction of ray in pixel space out from each pixel from camera centre
// find best
for (int i = int((pix.x * 4) - 2); i < int((pix.x * 4) + 2); i += 1)
{
for (int j = int((pix.y * 4) - 2); j < int((pix.y * 4) + 2); j += 1)
{
uint current = uint(texelFetch(indexSampler, ivec2(i, j), 0));
if (current > 0U)
{
vec4 vertConf = texelFetch(vertConfSampler, ivec2(i, j), 0);
//imageStore(outImagePC, ivec2(i / 4, j / 4), vec4((vertConf.z * lambda) - (vPosLocal.z * lambda), 0, 0, 1));
// check to see if the camera space pixel ray that goes between each potential global pixel (vertConf) is in range of the current depth map (vposlocal)
if (abs((vertConf.z * lambda) - (vPosLocal.z * lambda)) < 0.05)
{
//imageStore(outImagePC, ivec2(i / 4, j / 4), vec4(vertConf.z, vPosLocal.z, 0, 1));
float dist = length(cross(ray, vertConf.xyz)) / length(ray);
vec4 normRad = texelFetch(normRadiSampler, ivec2(i, j), 0);
if (dist < bestDist && (abs(normRad.z) < 0.75f || abs(angleBetween(normRad.xyz, vNormLocal.xyz)) < 0.5f))
{
//imageStore(outImagePC, ivec2(i / 4, j / 4), vec4(dist, vertConf.z, vPosLocal.z, 1));
counter++;
bestDist = dist;
best = current;
}
}
}
}
}
//We found a point to merge with
if (counter > 0)
{
updateId = 1;
geoVertColTimDev.w = -1;
}
else
{
//New unstable vertex
updateId = 2;
geoVertColTimDev.w = -2;
}
}
//Emit a vertex if either we have an update to store, or a new unstable vertex to store
//if (updateId == 1) //!!!!! USE THIS
// {
// we want to store the stable vertices in some buffer/image
// old way is to add the vert info to a large sparse texture
// we would have to use glClearTexImage after every frame, or directly set the value back to zeros after its used in the next shader! ooo efficient maybe otherwise we would have historics
// we dont actually need the 3x buffers here, all we need is an index buffer matching the size of the global buffer which tells us for each vertex in the global model should be updated with what index in the new depth fram edata
//outputUpdateIndexInterleaved[vertID * 3] = geoVertPosConf;
//outputUpdateIndexInterleaved[(vertID * 3) + 1] = geoVertNormRadi;
//outputUpdateIndexInterleaved[(vertID * 3) + 2] = vec4(geoVertColTimDev.xy, vertID, -1);
if (updateId > 0)
{
if (updateId == 1)
{
outputIndexMatchingBuffer[best] = vertID;
}
else
{
uint appendedPosition = atomicCounterIncrement(ac);
outputIndexMatchingBuffer[appendedPosition] = -vertID;
}
}
// output the vertID of the new depth vert data in a buffer of size of the global array buffer at the index point of the vert where it matches
// or set a flag showing the vertID of the new depth vert in the global buffer itself, if space is available
// }
//else
// {
// unstable vertex doesnt get passed to the ICP algorithm, but it is not deleted from the global vbo
// we can append unstable to the end of the vbo, since we know the county offset from the current global vert size
// how about
// index = county + current vertID (from depth ID, not global ID)
// this will contain blanks for sure, but will pass all info without overwriting
// outputUpdateIndexInterleaved[vertID * 3] = vec4(0);
// outputUpdateIndexInterleaved[(vertID * 3) + 1] = vec4(0);
// outputUpdateIndexInterleaved[(vertID * 3) + 2] = vec4(0.8);
// }
} |
using HttpCookie = System.Web.HttpCookie;
namespace Sentry.AspNet.Tests;
public class HttpContextExtensionsTests
{
[Fact]
public void StartSentryTransaction_CreatesValidTransaction()
{
// Arrange
var context = HttpContextBuilder.Build();
// Act
var transaction = context.StartSentryTransaction();
// Assert
transaction.Name.Should().Be("GET /the/path");
transaction.Operation.Should().Be("http.server");
((IHasTransactionNameSource)transaction).NameSource.Should().Be(TransactionNameSource.Url);
}
[Fact]
public void StartSentryTransaction_BindsToScope()
{
// Arrange
using var _ = SentrySdk.UseHub(new Hub(
new SentryOptions
{
Dsn = ValidDsn
},
Substitute.For<ISentryClient>()
));
var context = HttpContextBuilder.Build();
// Act
var transaction = context.StartSentryTransaction();
var transactionFromScope = SentrySdk.GetSpan();
// Assert
transactionFromScope.Should().BeSameAs(transaction);
}
[Fact]
public void FinishSentryTransaction_FinishesTransaction()
{
// Arrange
using var _ = SentrySdk.UseHub(new Hub(
new SentryOptions
{
Dsn = ValidDsn
},
Substitute.For<ISentryClient>()
));
var context = HttpContextBuilder.Build(404);
// Act
var transaction = context.StartSentryTransaction();
context.FinishSentryTransaction();
// Assert
transaction.IsFinished.Should().BeTrue();
transaction.Status.Should().Be(SpanStatus.NotFound);
}
[Fact]
public void StartSentryTransaction_SendDefaultPii_set_to_true_sets_cookies()
{
// Arrange
var context = HttpContextBuilder.BuildWithCookies(new []{ new HttpCookie("foo", "bar") });
SentryClientExtensions.SentryOptionsForTestingOnly = new SentryOptions
{
SendDefaultPii = true
};
// Act
var transaction = context.StartSentryTransaction();
// Assert
transaction.Request.Cookies.Should().Be("foo=bar");
}
[Fact]
public void StartSentryTransaction_SendDefaultPii_set_to_true_does_not_set_cookies_if_none_found()
{
// Arrange
var context = HttpContextBuilder.BuildWithCookies(new HttpCookie[] { });
SentryClientExtensions.SentryOptionsForTestingOnly = new SentryOptions
{
SendDefaultPii = true
};
// Act
var transaction = context.StartSentryTransaction();
// Assert
transaction.Request.Cookies.Should().BeEmpty();
}
[Fact]
public void StartSentryTransaction_SendDefaultPii_set_to_false_does_not_set_cookies()
{
// Arrange
var context = HttpContextBuilder.BuildWithCookies(new []{ new HttpCookie("foo", "bar") });
SentryClientExtensions.SentryOptionsForTestingOnly = new SentryOptions
{
SendDefaultPii = false
};
// Act
var transaction = context.StartSentryTransaction();
// Assert
transaction.Request.Cookies.Should().BeNull();
}
[Fact]
public void StartSentryTransaction_missing_options_does_not_set_cookies()
{
// Arrange
var context = HttpContextBuilder.BuildWithCookies(new []{ new HttpCookie("foo", "bar") });
// Act
var transaction = context.StartSentryTransaction();
// Assert
transaction.Request.Cookies.Should().BeNull();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossCameraPoint : MonoBehaviour
{
public float size = 15;
public CameraFollow CF;
public CubeKingBoss cubeKingBoss;
void Switch(int value)
{
if (value == 0)
{
CF.CameraPoint(transform, size, true);
if(!CubeKingBoss.isRaiding)
cubeKingBoss.GameStart();
}
else if (value == 1)
CF.CameraPoint(transform, size, false);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CrackingHackerRank
{
class Programs
{
public static void callPoints() {
int[,] points = { {5, 6, 7 },
{ 3, 6, 10 } };
int [] res = AwardedPoints.points(points[0,0],points[0,1],points[0,2],
points[1, 0], points[1, 1], points[1, 2]
);
Console.WriteLine(string.Join(" ",res));
}
public static void callBalanced() {
string[] expressions = { "{[()]}",
"{[(])}",
"{{[[(())]]}}"
};
BalancedBrackets.run(expressions);
}
public static void callRansomeTests() {
string[,] tests = {
{ "hello world", "hello"},
{ "hello World", "hello world"},
{ "give me one grand today night", "give one grand today"},
{ "two times three is not four", "two times two is four"},
};
string[] results = { "Y","N","Y","N"};
for (int i = 0; i<tests.GetLength(0);i++) {
string a = (tests[i,0]);
string b = (tests[i, 1]);
string r = callRansom(a,b);
Tests.Equal(r, results[i]);
}
}
public static string callRansom(string magazine, string note) {
//Console.WriteLine("Calling with {0} {1}",magazine,note);
if (Ransome.canMakeNote(magazine, note))
{
return "Y";
}
else {
return "N";
}
}
public static void callAnagramMaker()
{
string a = "";
string b = "";
//List<List<string>> cases = new List<List<string>>();
a = "imkhnpqnhlvaxlmrsskbyyrhwfvgteubrelgubvdmrdmesfxkpykprunzpustowmvhupkqsyjxmnptkcilmzcinbzjwvxshubeln";
b = "wfnfdassvfugqjfuruwrdumdmvxpbjcxorettxmpcivurcolxmeagsdundjronoehtyaskpwumqmpgzmtdmbvsykxhblxspgnpgfzydukvizbhlwmaajuytrhxeepvmcltjmroibjsdkbqjnqjwmhsfopjvehhiuctgthrxqjaclqnyjwxxfpdueorkvaspdnywupvmy";
//a = "aabcc";
//b = "abbcd";
//a = "abc";
//b = "cde";
a = "abfgh";
b = "fg";
int removals = AnagramMaker.removals(a, b);
Console.WriteLine("removals returned "+removals);
}
public static void callLeftRotation()
{
int[] a = { 1, 2, 3, 4, 5 };
Console.WriteLine(string.Join(",", a));
a = LeftRotationPartition.leftRotation(a, 2);
Console.WriteLine(string.Join(",", a));
}
}
}
|
using System;
using System.Linq.Expressions;
using Fingo.Auth.DbAccess.Models.CustomData;
using Fingo.Auth.DbAccess.Repository.Interfaces.CustomData;
using Fingo.Auth.Domain.CustomData.ConfigurationClasses.User;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Implementation;
using Fingo.Auth.Domain.CustomData.Services.Interfaces;
using Moq;
using Xunit;
namespace Fingo.Auth.Domain.CustomData.Tests.Factories.Actions.Implementation
{
public class SaveUserCustomDataTest
{
[Fact]
public void Can_Save_Boolean_User_Custom_Data()
{
// Arrange
var booleanConfiguration = new BooleanUserConfiguration {Value = true};
var result = new UserCustomData
{
Id = 1 ,
ProjectCustomData = new ProjectCustomData
{
ConfigurationName = "firstConfiguration"
}
};
var customServiceMock = new Mock<ICustomDataJsonConvertService>();
customServiceMock.Setup(m => m.Serialize(booleanConfiguration)).Returns(booleanConfiguration.Value.ToString);
var userCustomDataRepository = new Mock<IUserCustomDataRepository>();
userCustomDataRepository.Setup(m => m.FindBy(It.IsAny<Expression<Func<UserCustomData , bool>>>())).Returns(
new[]
{
result
});
// Act
var target = new SaveUserCustomData(userCustomDataRepository.Object , customServiceMock.Object);
target.Invoke(1 , 1 , "name" , booleanConfiguration);
// Assert
Assert.True(result.ModificationDate.Date == DateTime.UtcNow.Date);
Assert.True(result.SerializedConfiguration == true.ToString());
userCustomDataRepository.Verify(m => m.Edit(result));
}
[Fact]
public void Can_Save_Number_User_Custom_Data()
{
// Arrange
var numberUserConfiguration = new NumberUserConfiguration {Value = 10};
var result = new UserCustomData
{
Id = 1 ,
ProjectCustomData = new ProjectCustomData
{
ConfigurationName = "firstConfiguration"
}
};
var customServiceMock = new Mock<ICustomDataJsonConvertService>();
customServiceMock.Setup(m => m.Serialize(numberUserConfiguration))
.Returns(numberUserConfiguration.Value.ToString);
var userCustomDataRepository = new Mock<IUserCustomDataRepository>();
userCustomDataRepository.Setup(m => m.FindBy(It.IsAny<Expression<Func<UserCustomData , bool>>>())).Returns(
new[]
{
result
});
// Act
var target = new SaveUserCustomData(userCustomDataRepository.Object , customServiceMock.Object);
target.Invoke(1 , 1 , "name" , numberUserConfiguration);
// Assert
Assert.True(result.ModificationDate.Date == DateTime.UtcNow.Date);
Assert.True(result.SerializedConfiguration == 10.ToString());
userCustomDataRepository.Verify(m => m.Edit(result));
}
[Fact]
public void Can_Save_Text_User_Custom_Data()
{
// Arrange
var textUserConfiguration = new TextUserConfiguration {Value = "test"};
var result = new UserCustomData
{
Id = 1 ,
ProjectCustomData = new ProjectCustomData
{
ConfigurationName = "firstConfiguration"
}
};
var customServiceMock = new Mock<ICustomDataJsonConvertService>();
customServiceMock.Setup(m => m.Serialize(textUserConfiguration))
.Returns(textUserConfiguration.Value.ToString);
var userCustomDataRepository = new Mock<IUserCustomDataRepository>();
userCustomDataRepository.Setup(m => m.FindBy(It.IsAny<Expression<Func<UserCustomData , bool>>>())).Returns(
new[]
{
result
});
// Act
var target = new SaveUserCustomData(userCustomDataRepository.Object , customServiceMock.Object);
target.Invoke(1 , 1 , "name" , textUserConfiguration);
// Assert
Assert.True(result.ModificationDate.Date == DateTime.UtcNow.Date);
Assert.True(result.SerializedConfiguration == "test");
userCustomDataRepository.Verify(m => m.Edit(result));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Вообще не поняла эти задания. Нашла в интернете. Из всего ниже написанного понимаю процентов 70 из первого и процентов 30 из второго. Сделала все, что могла. Понять и простить
namespace Homework
{
class Homework
{
static void quickSort(int[] a, int l, int r)
{
Console.WriteLine("\n***************************************");
Console.WriteLine("\n***************************************");
int temp;
int x = a[l + (r - l) / 2];
//запись эквивалентна (l+r)/2,
//но не вызввает переполнения на больших данных
int i = l;
int j = r;
while (i <= j)
{
while (a[i] < x) i++;
while (a[j] > x) j--;
if (i <= j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
if (i < r)
quickSort(a, i, r);
if (l < j)
quickSort(a, l, j);
}
static void Main(string[] args)
{
int size;
size = Convert.ToInt32(Console.ReadLine());
string str = Console.ReadLine();
string[] mas = str.Split(' ');
int[] a = new int[size];
for (int i = 0; i < size; i++)
{
a[i] = int.Parse(mas[i]);
}
quickSort(a, 0, size - 1);
for (int i = 0; i < size; i++)
{
Console.Write(a[i]);
Console.Write(' ');
}
Console.WriteLine("\n***************************************");
Console.WriteLine("\n***************************************");
int verticesCount = 10;
int[,] adjacency = new int[verticesCount, verticesCount];
Random rnd = new Random();
// Псевдослучайное заполнение матрицы смежности
for (int row = 0; row < verticesCount - 1; row++)
for (int col = row + 1; col < verticesCount; col++)
if (rnd.Next(3) < 1)
{
adjacency[row, col] = 1;
adjacency[col, row] = 1;
}
Console.WriteLine("\n***************************************");
Console.WriteLine("Обход графа в глубину с печатью вершин.");
PrintDeep(adjacency);
Console.WriteLine("\n***************************************");
Console.WriteLine("Обход графа в ширину с печатью вершин.");
PrintWidth(adjacency);
Console.ReadKey();
}
static bool IsVerifyGraf(int[,] adjacency)
{
int verticesCount = adjacency.GetLength(0);
if (verticesCount != adjacency.GetLength(1))
{
Console.WriteLine("Ошибка! Матрица смежности неверной размерности!");
return false;
}
bool error = false;
for (int row = 0; row < verticesCount; row++)
{
if (adjacency[row, row] != 0)
error = true;
for (int col = row + 1; col < verticesCount; col++)
if (adjacency[row, col] != adjacency[col, row])
{
error = true;
break;
}
if (error)
break;
}
if (error)
{
Console.WriteLine("Ошибка! Матрица смежности ошибочна!");
return false;
}
return true;
}
static void PrintVert(int Vert, int[,] adjacency)
{
if (!IsVerifyGraf(adjacency))
return;
Console.Write($"Вершина {Vert}. Смежна с вершинами:");
int verticesCount = adjacency.GetLength(0);
for (int col = 0; col < verticesCount; col++)
if (adjacency[Vert, col] != 0)
Console.Write($" {col}");
}
static void PrintDeep(int[,] adjacency)
{
if (!IsVerifyGraf(adjacency))
return;
int verticesCount = adjacency.GetLength(0);
List<int> vertList = new List<int>();
Stack<int> vertStack = new Stack<int>();
for (int vert = 0; vert < verticesCount; vert++)
{
//if (vertList.IndexOf(vert) >= 0)
// continue;
int vertCurr = vert;
while (true)
{
if (vertList.IndexOf(vertCurr) < 0)
{
PrintVert(vertCurr, adjacency);
Console.WriteLine();
vertList.Add(vertCurr);
for (int col = 0; col < verticesCount; col++)
if (adjacency[vertCurr, col] != 0 && vertList.IndexOf(col) < 0)
vertStack.Push(col);
}
if (vertStack.Count == 0)
break;
vertCurr = vertStack.Pop();
}
}
}
static void PrintWidth(int[,] adjacency)
{
if (!IsVerifyGraf(adjacency))
return;
int verticesCount = adjacency.GetLength(0);
List<int> vertList = new List<int>();
Queue<int> vertQueue = new Queue<int>();
for (int vert = 0; vert < verticesCount; vert++)
{
//if (vertList.IndexOf(vert) >= 0)
// continue;
int vertCurr = vert;
while (true)
{
if (vertList.IndexOf(vertCurr) < 0)
{
PrintVert(vertCurr, adjacency);
Console.WriteLine();
vertList.Add(vertCurr);
for (int col = 0; col < verticesCount; col++)
if (adjacency[vertCurr, col] != 0 && vertList.IndexOf(col) < 0)
vertQueue.Enqueue(col);
}
if (vertQueue.Count == 0)
break;
vertCurr = vertQueue.Dequeue();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using System.Globalization;
namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual
{
/// <summary>
/// Implementacion del adaptador de Bien
/// </summary>
public sealed class BienAdapter
{
/// <summary>
/// Obtiene la entidad response de una entidad Logic
/// </summary>
/// <param name="objLogic">objeto logic</param>
/// <param name="lstTipoBien">lista con los tipos de bien</param>
/// <param name="lstTipoTarifa">lista tipos de tarifa</param>
/// <param name="lstMoneda">listas de moneda</param>
/// <returns>Entidad Response de entidad Logic</returns>
public static BienResponse ObtenerBienResponseDeLogic(BienLogic objLogic,List<CodigoValorResponse> lstTipoBien = null,
List<CodigoValorResponse> lstTipoTarifa = null,
List<CodigoValorResponse> lstMoneda = null,
List<CodigoValorResponse> lstPeriodoAl = null)
{
int li_index = -1;
BienResponse objRpta = new BienResponse();
objRpta.CodigoBien = objLogic.CodigoBien.ToString();
objRpta.CodigoTipoBien = objLogic.CodigoTipoBien;
objRpta.CodigoIdentificacion = objLogic.CodigoIdentificacion;
objRpta.NumeroSerie = objLogic.NumeroSerie;
objRpta.Descripcion = objLogic.Descripcion;
objRpta.Marca = objLogic.Marca;
objRpta.Modelo = objLogic.Modelo;
objRpta.FechaAdquisicion = objLogic.FechaAdquisicion.Value.ToString(DatosConstantes.Formato.FormatoFecha);
objRpta.TiempoVidaString = objLogic.TiempoVida.ToString(DatosConstantes.Formato.FormatoNumeroDecimal);
objRpta.ValorResidualString = objLogic.ValorResidual.ToString(DatosConstantes.Formato.FormatoNumeroDecimal);
objRpta.CodigoTipoTarifa = objLogic.CodigoTipoTarifa;
objRpta.CodigoPeriodoAlquiler = objLogic.CodigoPeriodoAlquiler;
objRpta.ValorAlquilerString = objLogic.ValorAlquiler.HasValue ? objLogic.ValorAlquiler.Value.ToString(DatosConstantes.Formato.FormatoNumeroDecimal) : null;
objRpta.CodigoMoneda = objLogic.CodigoMoneda;
objRpta.MesInicioAlquiler = objLogic.MesInicioAlquiler;
if (objRpta.MesInicioAlquiler > 0)
{
objRpta.DescripcionMesInicioAlquiler = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int.Parse(objRpta.MesInicioAlquiler.ToString())));
}
objRpta.AnioInicioAlquiler = objLogic.AnioInicioAlquiler;
if (objRpta.AnioInicioAlquiler > 0)
{
objRpta.MesAnioInicioAlquiler = objRpta.DescripcionMesInicioAlquiler + " - " + objRpta.AnioInicioAlquiler;
}
if (lstTipoBien != null && lstTipoBien.Count > 0)
{
li_index = lstTipoBien.FindIndex(x => x.Codigo.ToString() == objLogic.CodigoTipoBien);
if (li_index > -1)
{
objRpta.NombreTipoBien = lstTipoBien[li_index].Valor.ToString();
}
}
li_index = -1;
if (lstTipoTarifa != null && lstTipoTarifa.Count > 0)
{
li_index = lstTipoTarifa.FindIndex(x => x.Codigo.ToString() == objLogic.CodigoTipoTarifa);
if (li_index > -1)
{
objRpta.NombreTipoTarifa = lstTipoTarifa[li_index].Valor.ToString();
}
}
li_index = -1;
if (lstMoneda != null && lstMoneda.Count > 0)
{
li_index = lstMoneda.FindIndex(x => x.Codigo.ToString() == objLogic.CodigoMoneda);
if (li_index > -1)
{
objRpta.NombreMoneda = lstMoneda[li_index].Valor.ToString();
}
}
li_index = -1;
if (lstPeriodoAl != null && lstPeriodoAl.Count > 0)
{
li_index = lstPeriodoAl.FindIndex(x => x.Codigo.ToString() == objLogic.CodigoPeriodoAlquiler);
if (li_index > -1)
{
objRpta.NombrePeriodoAlquiler = lstPeriodoAl[li_index].Valor.ToString();
}
}
return objRpta;
}
/// <summary>
/// Obtiene la entidad de una entidad request
/// </summary>
/// <param name="objRqst">objeto request</param>
/// <returns>Entidad de objeto Bien</returns>
public static BienEntity ObtenerBienEntityDeRequest(BienRequest objRqst)
{
BienEntity rpta = new BienEntity();
NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
numberFormatInfo.NumberDecimalSeparator = ".";
numberFormatInfo.NumberGroupSeparator = ",";
if (objRqst.CodigoBien == null)
{
objRqst.CodigoBien = Guid.Empty;
}
rpta.CodigoBien = (Guid)objRqst.CodigoBien;
rpta.CodigoTipoBien = objRqst.CodigoTipoBien;
rpta.CodigoIdentificacion = objRqst.CodigoIdentificacion;
rpta.NumeroSerie = objRqst.NumeroSerie;
rpta.Descripcion = objRqst.Descripcion.ToUpper();
rpta.Marca = objRqst.Marca.ToUpper();
rpta.Modelo = objRqst.Modelo.ToUpper();
rpta.FechaAdquisicion = DateTime.ParseExact(objRqst.FechaAdquisicionString, DatosConstantes.Formato.FormatoFecha, System.Globalization.CultureInfo.InvariantCulture);
rpta.TiempoVida = Decimal.Parse(objRqst.TiempoVidaString, numberFormatInfo);
rpta.ValorResidual = Decimal.Parse(objRqst.ValorResidualString, numberFormatInfo);
rpta.CodigoTipoTarifa = objRqst.CodigoTipoTarifa;
rpta.CodigoPeriodoAlquiler = objRqst.CodigoPeriodoAlquiler;
if (!string.IsNullOrWhiteSpace(objRqst.ValorAlquilerString))
{
rpta.ValorAlquiler = Decimal.Parse(objRqst.ValorAlquilerString, numberFormatInfo);
}
rpta.CodigoMoneda = objRqst.CodigoMoneda;
rpta.MesInicioAlquiler = Byte.Parse(objRqst.MesInicioAlquiler.ToString());
rpta.AnioInicioAlquiler = Int16.Parse(objRqst.AnioInicioAlquiler.ToString());
return rpta;
}
/// <summary>
/// Obtiene el responde Bien de una entidad Bien
/// </summary>
/// <param name="objEnt">Objeti entidad</param>
/// <returns>Entidad Response de objeto Bien</returns>
public static BienResponse ObtenerBienResponseDeEntity(BienEntity objEnt)
{
BienResponse rpta = new BienResponse();
rpta.CodigoBien = objEnt.CodigoBien.ToString();
rpta.CodigoTipoBien = objEnt.CodigoTipoBien;
rpta.CodigoIdentificacion = objEnt.CodigoIdentificacion;
rpta.NumeroSerie = objEnt.NumeroSerie;
rpta.Descripcion = objEnt.Descripcion;
rpta.Marca = objEnt.Marca;
rpta.Modelo = objEnt.Modelo;
rpta.FechaAdquisicion = objEnt.FechaAdquisicion.ToString(DatosConstantes.Formato.FormatoFecha);
rpta.TiempoVida = objEnt.TiempoVida;
rpta.TiempoVidaString = objEnt.TiempoVida.ToString(DatosConstantes.Formato.FormatoNumeroDecimal);
rpta.ValorResidual = objEnt.ValorResidual;
rpta.ValorResidualString = objEnt.ValorResidual.ToString(DatosConstantes.Formato.FormatoNumeroDecimal);
rpta.CodigoTipoTarifa = objEnt.CodigoTipoTarifa;
rpta.CodigoPeriodoAlquiler = objEnt.CodigoPeriodoAlquiler;
rpta.ValorAlquiler = objEnt.ValorAlquiler;
rpta.ValorAlquilerString = objEnt.ValorAlquiler.HasValue ? objEnt.ValorAlquiler.Value.ToString(DatosConstantes.Formato.FormatoNumeroDecimal) : null;
rpta.CodigoMoneda = objEnt.CodigoMoneda;
rpta.MesInicioAlquiler = objEnt.MesInicioAlquiler;
rpta.AnioInicioAlquiler = objEnt.AnioInicioAlquiler;
return rpta;
}
/// <summary>
/// Obtiene el responde Bien de una entidad Bien
/// </summary>
/// <param name="objEnt">Objeti entidad</param>
/// <returns>Entidad Response de objeto Bien Alquiler</returns>
public static BienAlquilerResponse ObtenerBienAlquilerResponseDeEntity(BienAlquilerEntity objEnt)
{
BienAlquilerResponse rpta = new BienAlquilerResponse();
rpta.CodigoBienAlquiler = objEnt.CodigoBienAlquiler.ToString();
rpta.CodigoBien = objEnt.CodigoBien.ToString();
rpta.IndicadorSinLimite = objEnt.IndicadorSinLimite;
rpta.CantidadLimite = objEnt.CantidadLimite;
rpta.CantidadLimiteString = objEnt.CantidadLimite.HasValue ? objEnt.CantidadLimite.Value.ToString(DatosConstantes.Formato.FormatoNumeroDecimal) : null;
rpta.Monto = objEnt.Monto;
rpta.MontoString = objEnt.Monto.ToString(DatosConstantes.Formato.FormatoNumeroDecimal);
return rpta;
}
/// <summary>
/// Obtiene el responde Bien de una entidad Bien
/// </summary>
/// <param name="objEnt">Objeti entidad</param>
/// <returns>Entidad Response de objeto Bien Alquiler</returns>
public static BienAlquilerResponse ObtenerBienAlquilerResponseDeLogic(BienAlquilerLogic objLogic)
{
BienAlquilerResponse rpta = new BienAlquilerResponse();
rpta.CodigoBienAlquiler = objLogic.CodigoBienAlquiler.ToString();
rpta.CodigoBien = objLogic.CodigoBien.ToString();
rpta.IndicadorSinLimite = objLogic.IndicadorSinLimite;
rpta.CantidadLimite = objLogic.CantidadLimite;
rpta.CantidadLimiteString = objLogic.CantidadLimite.HasValue ? objLogic.CantidadLimite.Value.ToString(DatosConstantes.Formato.FormatoNumeroDecimal) : null;
rpta.Monto = objLogic.Monto;
rpta.MontoString = objLogic.Monto.ToString(DatosConstantes.Formato.FormatoNumeroDecimal);
return rpta;
}
/// <summary>
/// Obtiene la entidad BienAlquiler de una entidad request
/// </summary>
/// <param name="objRqst">objeto request bienAlquiler</param>
/// <returns>Entidad de objeto Bien Alquiler</returns>
public static BienAlquilerEntity ObtenerBienAlquilerEntityDeRequest(BienAlquilerRequest objRqst)
{
BienAlquilerEntity rpta = new BienAlquilerEntity();
NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
numberFormatInfo.NumberDecimalSeparator = ".";
numberFormatInfo.NumberGroupSeparator = ",";
if (objRqst.CodigoBienAlquiler == null)
{
objRqst.CodigoBienAlquiler = Guid.Empty;
}
if (objRqst.CodigoBien == null)
{
objRqst.CodigoBien = Guid.Empty;
}
rpta.CodigoBienAlquiler = (Guid)objRqst.CodigoBienAlquiler;
rpta.CodigoBien = (Guid)objRqst.CodigoBien;
rpta.IndicadorSinLimite = objRqst.IndicadorSinLimite;
if (!rpta.IndicadorSinLimite)
{
rpta.CantidadLimite = Decimal.Parse(objRqst.CantidadLimiteString, numberFormatInfo);
}
rpta.Monto = Decimal.Parse(objRqst.MontoString, numberFormatInfo);
return rpta;
}
/// <summary>
/// Obtiene la entidad Bien Registro response de una entidad logic
/// </summary>
/// <param name="objRqst">objeto Response bienRegistro</param>
/// <returns>Entidad BienRegistroResponse</returns>
public static BienRegistroResponse ObtenerBienRegistroResponseDeLogic(BienRegistroLogic objRqst)
{
BienRegistroResponse rpta = new BienRegistroResponse();
rpta.Tipo = objRqst.CodigoTipoContenido;
rpta.Valor = objRqst.Contenido;
return rpta;
}
/// <summary>
/// Realiza la adaptación de campos para la búsqueda
/// </summary>
/// <param name="bienLogic">Entidad Lógica Bien</param>
/// <returns>Clase Bien Response con los datos de búsqueda</returns>
public static BienResponse ObtenerDescripcionCompletaBien(BienLogic bienLogic, List<BienAlquilerResponse> listaAlquiler, List<CodigoValorResponse> listaPeriodoAlquilerBien)
{
var bienResponse = new BienResponse();
bienResponse.CodigoBien = bienLogic.CodigoBien.ToString();
bienResponse.CodigoIdentificacion = bienLogic.CodigoIdentificacion;
bienResponse.NumeroSerie = bienLogic.NumeroSerie;
bienResponse.Descripcion = bienLogic.Descripcion;
bienResponse.Marca = bienLogic.Marca;
bienResponse.Modelo = bienLogic.Modelo;
bienResponse.CodigoMoneda = bienLogic.CodigoMoneda;
if (bienLogic.FechaAdquisicion != null)
{
bienResponse.FechaAdquisicion = Convert.ToDateTime(bienLogic.FechaAdquisicion).ToString(DatosConstantes.Formato.FormatoFecha);
}
bienResponse.MesInicioAlquiler = bienLogic.MesInicioAlquiler;
bienResponse.AnioInicioAlquiler = bienLogic.AnioInicioAlquiler;
bienResponse.DescripcionMesInicioAlquiler = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int.Parse(bienResponse.MesInicioAlquiler.ToString())));
if (listaAlquiler != null && listaAlquiler.Count > 0)
{
bienResponse.ValorAlquilerString = string.Empty;
decimal limiteInferiorActual = 0.01M;
var alquilerSinLimite = listaAlquiler.Where(item => item.IndicadorSinLimite).FirstOrDefault();
var periodoAlquilerBien = listaPeriodoAlquilerBien.Where(itemWhere => itemWhere.Codigo.ToString() == bienLogic.CodigoPeriodoAlquiler).FirstOrDefault().Valor;
foreach (var item in listaAlquiler.Where(item => !item.IndicadorSinLimite).ToList())
{
bienResponse.ValorAlquilerString += limiteInferiorActual + " - " + item.CantidadLimiteString + " " + periodoAlquilerBien + " " + bienLogic.CodigoMoneda + " " + item.MontoString + "<br></br>";
limiteInferiorActual = Convert.ToDecimal(item.CantidadLimite) + 0.01M;
}
}
else
{
bienResponse.ValorAlquilerString = bienLogic.ValorAlquiler.HasValue ? bienLogic.ValorAlquiler.Value.ToString(DatosConstantes.Formato.FormatoNumeroDecimal) : null;
}
bienResponse.DescripcionCompleta = bienLogic.CodigoIdentificacion + " - " + bienLogic.NumeroSerie + " - " + bienLogic.Descripcion + " - " + bienLogic.Marca + " - " + bienLogic.Modelo + " - " + bienResponse.FechaAdquisicion + " - " + bienResponse.DescripcionMesInicioAlquiler + " " + bienResponse.AnioInicioAlquiler;
return bienResponse;
}
}
} |
using DomainEventsExemplo.Domain.Entites;
using DomainEventsExemplo.Domain.Handles;
using System;
namespace DomainEventsExemplo.Domain.Events
{
public class SalvarPedidoEcomenda : IHandle<EncomendaRealizada>
{
public void Handle(EncomendaRealizada args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Encomenda {args.ObjetoId} do cliente {args.ClientId}");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Example
{
public int minHp;
public int maxHp;
}
|
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base;
using System.Collections.Generic;
using System.Web.Mvc;
namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.Plantilla
{
/// <summary>
/// Modelo de vista de plantilla
/// </summary>
/// <remarks>
/// Creación: GMD 20150519 </br>
/// Modificación: </br>
/// </remarks>
public class PlantillaFormulario : GenericViewModel
{
/// <summary>
/// Constructor usado para el registro de datos
/// </summary>
/// <param name="tipoServicio">Lista de Tipos de Servicios</param>
/// <param name="tipoRequerimiento">Lista de Tipos de Requerimientos</param>
/// <param name="tipoDocumentoContrato">Lista de Tipos de Documentos</param>
/// <param name="estadoVigencia">Lista de Estados de Vigencia</param>
public PlantillaFormulario(List<CodigoValorResponse> tipoServicio, List<CodigoValorResponse> tipoRequerimiento, List<CodigoValorResponse> tipoDocumentoContrato, List<CodigoValorResponse> estadoVigencia, string indicadorCopia, bool? esmayormenor)
{
this.TipoServicio = this.GenerarListadoOpcioneGenericoFormulario(tipoServicio);
this.TipoDocumentoContrato = this.GenerarListadoOpcioneGenericoFormulario(tipoDocumentoContrato);
this.EstadoVigencia = this.GenerarListadoOpcioneGenericoFormulario(estadoVigencia);
this.IndicadorCopia = indicadorCopia;
this.Plantilla = new PlantillaResponse();
//INICIO: Julio Carrera
if (esmayormenor != null)
{
this.Plantilla.EsMayorMenor = (bool)esmayormenor;
}
//FIN: Julio Carrera
}
/// <summary>
/// Constructor usado para el registro de datos
/// </summary>
/// <param name="tipoServicio">Lista de Tipos de Servicios</param>
/// <param name="tipoRequerimiento">Lista de Tipos de Requerimientos</param>
/// <param name="tipoDocumentoContrato">Lista de Tipos de Documentos</param>
/// <param name="estadoVigencia">Lista de Estados de Vigencia</param>
/// <param name="plantilla">Clase Response de Plantilla</param>
public PlantillaFormulario(List<CodigoValorResponse> tipoServicio, List<CodigoValorResponse> tipoRequerimiento, List<CodigoValorResponse> tipoDocumentoContrato, List<CodigoValorResponse> estadoVigencia, PlantillaResponse plantilla)
{
this.TipoServicio = this.GenerarListadoOpcioneGenericoFormulario(tipoServicio, plantilla.CodigoTipoContrato);
this.TipoDocumentoContrato = this.GenerarListadoOpcioneGenericoFormulario(tipoDocumentoContrato, plantilla.CodigoTipoDocumentoContrato);
this.EstadoVigencia = this.GenerarListadoOpcioneGenericoFormulario(estadoVigencia, plantilla.CodigoEstadoVigencia);
//INICIO: Julio Carrera
//this.EsMayorMenor = plantilla.EsMayorMenor;
//FIN: Julio Carrera
this.Plantilla = plantilla;
}
#region Propiedades
/// <summary>
/// Lista de Tipos de Servicios
/// </summary>
public List<SelectListItem> TipoServicio { get; set; }
/// <summary>
/// Lista de Tipos de Documentos de Contratos
/// </summary>
public List<SelectListItem> TipoDocumentoContrato { get; set; }
/// <summary>
/// Lista de Estados de Vigencia
/// </summary>
public List<SelectListItem> EstadoVigencia { get; set; }
/// <summary>
/// Clase Response de Plantilla
/// </summary>
public PlantillaResponse Plantilla { get; set; }
/// <summary>
/// Indica si el formulario nuevo es copia o no
/// </summary>
public string IndicadorCopia { get; set; }
//INICIO: Julio Carrera
/// <summary>
/// Indica si el formulario nuevo es copia o no
/// </summary>
public bool EsMayorMenor { get; set; }
//FIN: Julio Carrera
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using DevTools.WinForms.Metro.Design.Converters;
using DevTools.WinForms.Metro.Framework.Themes;
namespace DevTools.WinForms.Metro.Design.Editors
{
public class PaletteColorEditor : ColorEditor
{
private static Color[] Colors;
static PaletteColorEditor()
{
Colors = PaletteColorConverter.Colors.OfType<Color>().ToArray();
}
public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value)
{
var colorEditorObject = this;
Type colorUiType = typeof(ColorEditor).GetNestedType("ColorUI", BindingFlags.NonPublic);
var colorUiConstructor = colorUiType.GetConstructors()[0];
var colorUiField = typeof(ColorEditor).GetField("colorUI", BindingFlags.Instance | BindingFlags.NonPublic);
var colorUiObject = colorUiConstructor.Invoke(new[] { colorEditorObject });
colorUiField.SetValue(colorEditorObject, colorUiObject);
var palField = colorUiObject.GetType().GetField("pal", BindingFlags.Instance | BindingFlags.NonPublic);
var palObject = palField.GetValue(colorUiObject);
var palCustomColorsField = palObject.GetType().GetField("customColors", BindingFlags.Instance | BindingFlags.NonPublic);
palCustomColorsField.SetValue(palObject, Colors);
var selectedValue = base.EditValue(context, provider, value);
Colors = palCustomColorsField.GetValue(palObject) as Color[];
return selectedValue;
}
}
}
|
using System.ComponentModel.Composition;
using System.Web;
using System.Web.Mvc;
using DemoWebApp.Models;
using SqlMapper;
namespace DemoWebApp.Controllers
{
public class DemoController : Controller
{
//
// GET: /Demo/
public ActionResult Index(string demoName)
{
var demoService = new DemoSystem();
var errorMessages = demoService.RunDemo(demoName);
TempData["errorMessages"] = errorMessages;
return RedirectToRoute("DumpUrl");
}
}
}
|
namespace BettingSystem.Application.Games.Matches.Commands.Create
{
using System.Threading;
using System.Threading.Tasks;
using Application.Common.Contracts;
using Application.Common.Exceptions;
using Common;
using Domain.Games.Factories.Matches;
using Domain.Games.Repositories;
using MediatR;
public class CreateMatchCommand : MatchCommand<CreateMatchCommand>, IRequest<CreateMatchResponseModel>
{
public class CreateMatchCommandHandler : IRequestHandler<CreateMatchCommand, CreateMatchResponseModel>
{
private readonly IMatchFactory matchFactory;
private readonly IMatchDomainRepository matchRepository;
private readonly ITeamDomainRepository teamRepository;
private readonly IImageService imageService;
public CreateMatchCommandHandler(
IMatchFactory matchFactory,
IMatchDomainRepository matchRepository,
ITeamDomainRepository teamRepository,
IImageService imageService)
{
this.matchFactory = matchFactory;
this.matchRepository = matchRepository;
this.teamRepository = teamRepository;
this.imageService = imageService;
}
public async Task<CreateMatchResponseModel> Handle(
CreateMatchCommand request,
CancellationToken cancellationToken)
{
var homeTeam = await this.teamRepository.Find(
request.HomeTeam,
cancellationToken);
if (homeTeam == null)
{
throw new NotFoundException(nameof(homeTeam), request.HomeTeam);
}
var awayTeam = await this.teamRepository.Find(
request.AwayTeam,
cancellationToken);
if (awayTeam == null)
{
throw new NotFoundException(nameof(awayTeam), request.AwayTeam);
}
var stadium = await this.matchRepository.GetStadium(
request.StadiumName,
cancellationToken);
var factory = this.matchFactory.WithStartDate(request.StartDate);
if (stadium == null)
{
var image = await this.imageService.Process(request.StadiumImage);
factory = factory.WithStadium(
request.StadiumName,
image.OriginalContent,
image.ThumbnailContent);
}
else
{
factory = factory.WithStadium(stadium);
}
var match = factory
.WithHomeTeam(homeTeam)
.WithAwayTeam(awayTeam)
.Build();
await this.matchRepository.Save(match, cancellationToken);
return new CreateMatchResponseModel(match.Id);
}
}
}
}
|
using ClaimDi.DataAccess;
using System;
using System.Resources;
using System.ServiceModel.Activation;
using System.Web.Routing;
namespace Claimdi.WCF.Consumer
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Configurator.Initialize();
Anywhere2Go.DataAccess.Object.Configurator.Initialize();
RouteTable.Routes.Add(new ServiceRoute("master", new WebServiceHostFactory(), typeof(Master)));
RouteTable.Routes.Add(new ServiceRoute("authentication", new WebServiceHostFactory(), typeof(Authentication)));
RouteTable.Routes.Add(new ServiceRoute("user", new WebServiceHostFactory(), typeof(Account)));
RouteTable.Routes.Add(new ServiceRoute("carinfo", new WebServiceHostFactory(), typeof(CarInfo)));
RouteTable.Routes.Add(new ServiceRoute("k4k", new WebServiceHostFactory(), typeof(TaskK4K)));
RouteTable.Routes.Add(new ServiceRoute("na", new WebServiceHostFactory(), typeof(TaskNA)));
RouteTable.Routes.Add(new ServiceRoute("inspection", new WebServiceHostFactory(), typeof(TaskInspection)));
RouteTable.Routes.Add(new ServiceRoute("taskinfo", new WebServiceHostFactory(), typeof(TaskInfo)));
RouteTable.Routes.Add(new ServiceRoute("ilertu", new WebServiceHostFactory(), typeof(ILertU)));
RouteTable.Routes.Add(new ServiceRoute("mtiintergration", new WebServiceHostFactory(), typeof(MTIIntergration)));
RouteTable.Routes.Add(new ServiceRoute("taskbikeinfo", new WebServiceHostFactory(), typeof(TaskBikeInfo)));
log4net.Config.XmlConfigurator.Configure();
}
protected void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
string sessionId = Session.SessionID;
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Assistenza.BufDalsi.Data;
using Assistenza.BufDalsi.Web.Models.GenericoViewModels;
using Assistenza.BufDalsi.Data.Models;
using Microsoft.AspNetCore.Authorization;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Assistenza.BufDalsi.Web.Controllers
{
public class GenericoController : Controller
{
ITicketData _data;
public GenericoController(ITicketData dat)
{
_data = dat;
}
[Authorize(Roles = "Admin,Operator")]
[HttpGet]
public IActionResult InsertGenerico(int clt_Id, int ipt_Id)
{
InsertGenericoViewModel model = new InsertGenericoViewModel();
model.clt_Id = clt_Id;
model.ipt_Id = ipt_Id;
model.gnr_Impianto = ipt_Id;
return PartialView("InsertGenerico", model);
}
[Authorize(Roles = "Admin,Operator")]
[HttpPost]
public IActionResult InsertGenerico(InsertGenericoViewModel model)
{
Generico help = new Generico();
help.gnr_Descrizione= model.gnr_Descrizione;
help.gnr_Impianto= model.gnr_Impianto;
help.gnr_Marca= model.gnr_Marca;
help.gnr_Modello= model.gnr_Modello;
help.gnr_Nome= model.gnr_Nome;
help.gnr_OreUltimoIntervento= model.gnr_OreUltimoIntervento;
help.gnr_Rimosso= model.gnr_Rimosso;
help.gnr_Serie= model.gnr_Serie;
help.gnr_UltimaInstallazione= model.gnr_UltimaInstallazione;
help.gnr_UltimoIntervento= model.gnr_UltimoIntervento;
_data.InsertGenerico(help);
return RedirectToAction("ImpiantoFullInfo", "Impianto", new { ipt_Id = model.ipt_Id, clt_Id = model.clt_Id });
}
[Authorize(Roles = "Admin,Operator")]
[HttpGet]
public ActionResult DeleteGenerico(int Id, int ipt_Id, int clt_Id)
{
DeleteGenericoViewModel model = new DeleteGenericoViewModel();
model.Id = Id;
model.clt_Id = clt_Id;
model.ipt_Id = ipt_Id;
return PartialView("DeleteGenerico", model);
}
[Authorize(Roles = "Admin,Operator")]
[HttpPost]
public ActionResult DeleteGenerico(DeleteGenericoViewModel model)
{
_data.DeleteGenerico(model.Id);
return RedirectToAction("ImpiantoFullInfo", "Impianto", new { ipt_Id = model.ipt_Id, clt_Id = model.clt_Id });
}
[Authorize(Roles = "Admin,Operator")]
[HttpGet]
public IActionResult UpdateGenerico(int gnr_Id, int ipt_Id, int clt_Id)
{
var gener = this._data.GetGenerico(gnr_Id);
if (gener == null)
return NotFound();
var model = new UpdateGenericoViewModel( gener.gnr_Id,
gener.gnr_Nome,
gener.gnr_UltimaInstallazione,
gener.gnr_UltimoIntervento,
gener.gnr_OreUltimoIntervento,
gener.gnr_Marca,
gener.gnr_Modello,
gener.gnr_Serie,
gener.gnr_Rimosso,
gener.gnr_Descrizione,
gener.gnr_Impianto
);
model.ipt_Id = ipt_Id;
model.clt_Id = clt_Id;
return PartialView(model);
}
[Authorize(Roles = "Admin,Operator")]
[HttpPost]
public ActionResult UpdateGenerico(UpdateGenericoViewModel Model)
{
Generico gen = new Generico(
Model.gnr_Id,
Model.gnr_Nome,
Model.gnr_UltimaInstallazione,
Model.gnr_UltimoIntervento,
Model.gnr_OreUltimoIntervento,
Model.gnr_Marca,
Model.gnr_Modello,
Model.gnr_Serie,
Model.gnr_Rimosso,
Model.gnr_Descrizione,
Model.gnr_Impianto
);
this._data.UpdateGenerico(gen);
return RedirectToAction("ImpiantoFullInfo", "Impianto", new { ipt_Id = Model.ipt_Id, clt_Id = Model.clt_Id });
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GunMovment : MonoBehaviour {
public Rigidbody rocketPrefab;
public Transform barrelEnd;
public float damage = 10f;
public float range = 100f;
public Text ammoLeft;
public Text txtLathedAmmo;
public Text txtLathedExperience;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
private int shotGunAmmo = 20;
private int lathedAmmo = 0;
private int lathedExperience = 0;
//private float verticalMouseAxis = 0.0f;
// Use this for initialization
void Start () {
PlayerPrefs.SetInt("ShotGunAmmo", shotGunAmmo);
PlayerPrefs.SetInt("lathedAmmo", 0);
shotGunAmmo = PlayerPrefs.GetInt("ShotGunAmmo");
lathedAmmo = PlayerPrefs.GetInt("lathedAmmo");
lathedAmmo = PlayerPrefs.GetInt("lathedAmmo");
ammoLeft.text = shotGunAmmo.ToString();
txtLathedAmmo.text = lathedAmmo.ToString();
txtLathedExperience.text = lathedExperience.ToString();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
//Debug.Log(hit.transform.name);
}
shotGunAmmo = PlayerPrefs.GetInt("ShotGunAmmo");
if (shotGunAmmo == 0)
{
print("No more bullets");
}
else
{
// Play sound
AudioSource shoot = GetComponent<AudioSource>();
shoot.Play();
// Everything else
muzzleFlash.Play();
Rigidbody rocketInstance;
rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
rocketInstance.AddForce(barrelEnd.forward * 20000);
shotGunAmmo = shotGunAmmo - 1;
PlayerPrefs.SetInt("ShotGunAmmo", shotGunAmmo);
ammoLeft.text = shotGunAmmo.ToString();
// print("You have " + shotGunAmmo + " shotgun shells left!");
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Carie : MonoBehaviour
{
public float movimento = 8;
public Rigidbody2D rigidbody2d;
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
void Update()
{
andar();
}
void andar()
{
rigidbody2d.velocity = new Vector2(movimento, rigidbody2d.velocity.y);
if (movimento < 0)
{
GetComponent<SpriteRenderer>().flipX = true;
}
else if (movimento > 0)
{
GetComponent<SpriteRenderer>().flipX = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Xml;
public class M_Users
{
public M_Users()
{
}
public M_Users(DataRow dr)
{
UserId = Convert.ToInt32(dr["UserId"]);
RoleId = dr["RoleId"].ToString();
Name = dr["Name"].ToString();
Email = dr["Email"].ToString();
Password = dr["Password"].ToString();
Active = Convert.ToByte(dr["Active"]);
}
#region Properties
public int UserId { get; set; }
public string RoleId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public int Active { get; set; }
#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 System.Threading;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
using Form1.Properties;
using enem;
namespace Form1
{
public partial class Form2 : Form
{
Bitmap image;
Rectangle rect;
private int matches;
private int players;
private int enemys;
enemy oponent = new enemy();
public bool IsEven(int a)
{
return (a % 2) == 0;
}
private void Reset()
{
matches = 25;
players = 0;
enemys = 0;
textBox2.Text = "25";
textBox1.Text = "0";
// oponent.allscore = matches;
// oponent.enemyscore = players;
//oponent.myscore = enemys;
oponent.getinfo(enemys, players, matches);
}
private void victory()
{
if (matches <= 0)
{
if (IsEven(players) == true)
{
MessageBox.Show("You won!");
}
else
{
MessageBox.Show("You lose");
}
}
}
private void drawmatch()
{
Bitmap image = new Bitmap(@"H:\Match.png");
Graphics x = this.CreateGraphics();
x.Clear(Color.Transparent);
for (int i = 0; i < matches; i++)
{
rect = new Rectangle(0 + i * 15, 50, image.Width, image.Height);
x.DrawImage(image, rect);
}
}
public Form2()
{
InitializeComponent();
// image = Properties.Resources.matchIMG;
// rect = new Rectangle(400, 300, image.Width, image.Height);
}
/* private void Form_paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawImage(image, rect);
}*/
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("3 matchs taken");
matches = matches - 1;
players = players + 1;
victory();
oponent.getinfo(enemys, players, matches);
var exitTurple = oponent.myturn(enemys, players, matches);
enemys = exitTurple.Item1;
players = exitTurple.Item2;
matches = exitTurple.Item3;
textBox3.Text = enemys.ToString();
textBox2.Text = matches.ToString();
textBox1.Text = players.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("2 matchs taken");
matches = matches - 2;
players = players + 2;
victory();
oponent.getinfo(enemys, players, matches);
var exitTurple = oponent.myturn(enemys, players, matches);
enemys = exitTurple.Item1;
players = exitTurple.Item2;
matches = exitTurple.Item3;
textBox3.Text = enemys.ToString();
textBox2.Text = matches.ToString();
textBox1.Text = players.ToString();
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("3 matchs taken");
matches = matches - 3;
players = players + 3;
victory();
oponent.getinfo(enemys, players, matches);
var exitTurple = oponent.myturn(enemys, players, matches);
enemys = exitTurple.Item1;
players = exitTurple.Item2;
matches = exitTurple.Item3;
textBox3.Text = enemys.ToString();
textBox2.Text = matches.ToString();
textBox1.Text = players.ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
/* Bitmap image = new Bitmap(@"H:\Match.png");
Graphics x = this.CreateGraphics();
x.Clear(Color.Transparent);
for (int i = 0; i < matches; i++)
{
rect = new Rectangle(0+i*15, 50, image.Width, image.Height);
x.DrawImage(image, rect);
}*/
drawmatch();
if (matches < 3) button3.Enabled = false;
if (matches < 2) button2.Enabled = false;
if (matches < 1) button1.Enabled = false;
if (matches <= 0)
{
if (IsEven(players) == true)
{
MessageBox.Show("You won!");
}
else
{
MessageBox.Show("You lose");
}
Form4 newForm = new Form4(enemys,players);
newForm.Show();
// Application.Exit();
}
}
private void label3_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button4_Click_1(object sender, EventArgs e)
{
Reset();
drawmatch();
button3.Enabled = true;
button2.Enabled = true;
button1.Enabled = true;
var exitTurple = oponent.myturn(enemys, players, matches);
enemys = exitTurple.Item1;
players = exitTurple.Item2;
matches = exitTurple.Item3;
textBox3.Text = enemys.ToString();
textBox2.Text = matches.ToString();
textBox1.Text = players.ToString();
}
private void button1_Click_1(object sender, EventArgs e)
{
MessageBox.Show("1 matchs taken");
matches = matches - 1;
players = players + 1;
victory();
oponent.getinfo(enemys, players, matches);
var exitTurple = oponent.myturn(enemys, players, matches);
enemys = exitTurple.Item1;
players = exitTurple.Item2;
matches = exitTurple.Item3;
textBox3.Text = enemys.ToString();
textBox2.Text = matches.ToString();
textBox1.Text = players.ToString();
}
private void button2_Click_1(object sender, EventArgs e)
{
MessageBox.Show("2 matchs taken");
matches = matches - 2;
players = players + 2;
victory();
oponent.getinfo(enemys, players, matches);
var exitTurple = oponent.myturn(enemys, players, matches);
enemys = exitTurple.Item1;
players = exitTurple.Item2;
matches = exitTurple.Item3;
textBox3.Text = enemys.ToString();
textBox2.Text = matches.ToString();
textBox1.Text = players.ToString();
}
private void button3_Click_1(object sender, EventArgs e)
{
MessageBox.Show("3 matchs taken");
matches = matches - 3;
players = players + 3;
victory();
oponent.getinfo(enemys, players, matches);
var exitTurple = oponent.myturn(enemys, players, matches);
enemys = exitTurple.Item1;
players = exitTurple.Item2;
matches = exitTurple.Item3;
textBox3.Text = enemys.ToString();
textBox2.Text = matches.ToString();
textBox1.Text = players.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
using Project.Game;
namespace Project.Interactables
{
public class ChestInteractable : Interactable
{
public Interactable content;
public Animator anim;
private int openHash = Animator.StringToHash("OpenTrigger");
public void AnimationCompleted()
{
if (debug)
{
Debug.Log("Animation Completed");
}
if (content != null)
{
/*.inventory.AddItem("keys");
Destroy(content);*/
}
}
private void Start()
{
SM = new StateMachine(
new List<Action> { Closed, Opened, Searched },
Closed,
Opened
);
SM.AddTransition(Closed, ItemAction.USE, Opened);
SM.AddTransition(Opened, ItemAction.USE, Searched);
CurrentState = SM.CurrentState.Method.Name;
}
private void Searched()
{
if (content != null)
{
content.Interact();
}
}
private void Closed()
{
if (debug)
Debug.Log(gameObject.name + " is Closed.");
}
private void Opened()
{
if (debug)
Debug.Log(gameObject.name + " is Opened.");
anim.SetTrigger(openHash);
}
}
} |
namespace myface
{
public partial class NoIdController
{
public class NoidResultInput
{
public string businessnumber { get; set; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using HealthVault.Sample.Xamarin.Core.Models;
using HealthVault.Sample.Xamarin.Core.Services;
using HealthVault.Sample.Xamarin.Core.ViewModels.ViewRows;
using HealthVault.Sample.Xamarin.Core.Views;
using Microsoft.HealthVault.Clients;
using Microsoft.HealthVault.Connection;
using Microsoft.HealthVault.ItemTypes;
using Microsoft.HealthVault.Record;
using Xamarin.Forms;
namespace HealthVault.Sample.Xamarin.Core.ViewModels
{
public class WeightViewModel : ViewModel
{
private readonly IHealthVaultConnection _connection;
public const double KgToLbsFactor = 2.20462;
public WeightViewModel(
IHealthVaultConnection connection,
INavigationService navigationService) : base(navigationService)
{
_connection = connection;
AddCommand = new Command(async () => await GoToAddWeightPageAsync());
LoadState = LoadState.Loading;
}
private void RefreshPage(IEnumerable<Weight> weights)
{
List<Weight> weightList = weights.ToList();
WeightValue weightValue = weightList.FirstOrDefault()?.Value;
if (weightValue != null)
{
double pounds = weightValue.Kilograms * KgToLbsFactor;
LastWeightValue = pounds.ToString("N0");
LastWeightUnit = "lbs";
}
else
{
LastWeightValue = string.Empty;
LastWeightUnit = string.Empty;
}
HistoricWeightValues = weightList.Skip(1).Select(w => new WeightViewRow(w)).ToList();
}
public override async Task OnNavigateToAsync()
{
await LoadAsync(async () =>
{
await RefreshAsync();
await base.OnNavigateToAsync();
});
}
public override async Task OnNavigateBackAsync()
{
await LoadAsync(async () =>
{
await RefreshAsync();
await base.OnNavigateBackAsync();
});
}
private async Task RefreshAsync()
{
var person = await _connection.GetPersonInfoAsync();
IThingClient thingClient = _connection.CreateThingClient();
HealthRecordInfo record = person.SelectedRecord;
IReadOnlyCollection<Weight> items = await thingClient.GetThingsAsync<Weight>(record.Id);
RefreshPage(items);
}
private IEnumerable<WeightViewRow> _historicWeightValues;
public IEnumerable<WeightViewRow> HistoricWeightValues
{
get { return _historicWeightValues; }
set
{
_historicWeightValues = value;
OnPropertyChanged();
}
}
public ICommand AddCommand { get; }
private string _lastWeightValue;
public string LastWeightValue
{
get { return _lastWeightValue; }
set
{
_lastWeightValue = value;
OnPropertyChanged();
}
}
private string _lastWeightUnit;
public string LastWeightUnit
{
get { return _lastWeightUnit; }
set
{
_lastWeightUnit = value;
OnPropertyChanged();
}
}
private async Task GoToAddWeightPageAsync()
{
var viewModel = new WeightAddViewModel(_connection, NavigationService);
var medicationsMainPage = new WeightAddPage
{
BindingContext = viewModel,
};
await NavigationService.NavigateAsync(medicationsMainPage);
}
}
}
|
namespace MeeToo.Security.Options
{
public class UserIdentityOptions
{
public string DbName { get; set; }
public string CollectionName { get; set; }
}
}
|
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using Witsml;
using Witsml.Data;
using Witsml.Data.Measures;
using Witsml.ServiceReference;
using WitsmlExplorer.Api.Jobs;
using WitsmlExplorer.Api.Jobs.Common;
using WitsmlExplorer.Api.Services;
using WitsmlExplorer.Api.Workers;
using Xunit;
namespace WitsmlExplorer.Api.Tests.Workers
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class CopyTrajectoryWorkerTests
{
private readonly CopyTrajectoryWorker copyTrajectoryWorker;
private readonly Mock<IWitsmlClient> witsmlClient;
private const string WellUid = "wellUid";
private const string SourceWellboreUid = "sourceWellboreUid";
private const string TargetWellboreUid = "targetWellboreUid";
private const string TrajectoryUid = "trajectoryUid";
public CopyTrajectoryWorkerTests()
{
var witsmlClientProvider = new Mock<IWitsmlClientProvider>();
witsmlClient = new Mock<IWitsmlClient>();
witsmlClientProvider.Setup(provider => provider.GetClient()).Returns(witsmlClient.Object);
copyTrajectoryWorker = new CopyTrajectoryWorker(witsmlClientProvider.Object);
}
[Fact]
public async Task CopyTrajectory_OK()
{
var copyTrajectoryJob = CreateJobTemplate();
witsmlClient.Setup(client =>
client.GetFromStoreAsync(It.Is<WitsmlTrajectories>(WitsmlTrajectories => WitsmlTrajectories.Trajectories.First().Uid == TrajectoryUid), new OptionsIn(ReturnElements.All, null)))
.ReturnsAsync(GetSourceTrajectories());
SetupGetWellbore();
var copyTrajectoryQuery = SetupAddInStoreAsync();
var result = await copyTrajectoryWorker.Execute(copyTrajectoryJob);
var trajectory = copyTrajectoryQuery.First().Trajectories.First();
Assert.True(result.Item1.IsSuccess);
Assert.NotEmpty(trajectory.TrajectoryStations);
}
private void SetupGetWellbore()
{
witsmlClient.Setup(client =>
client.GetFromStoreAsync(It.IsAny<WitsmlWellbores>(), new OptionsIn(ReturnElements.Requested, null)))
.ReturnsAsync(new WitsmlWellbores
{
Wellbores = new List<WitsmlWellbore>
{
new WitsmlWellbore
{
UidWell = "Well1",
Uid = "wellbore1",
Name = "Wellbore 1",
NameWell = "Well 1"
}
}
});
}
private List<WitsmlTrajectories> SetupAddInStoreAsync()
{
var addedTrajectory = new List<WitsmlTrajectories>();
witsmlClient.Setup(client => client.AddToStoreAsync(It.IsAny<WitsmlTrajectories>()))
.Callback<WitsmlTrajectories>(witsmlTrajectories => addedTrajectory.Add(witsmlTrajectories))
.ReturnsAsync(new QueryResult(true));
return addedTrajectory;
}
private CopyTrajectoryJob CreateJobTemplate(string targetWellboreUid = TargetWellboreUid)
{
return new CopyTrajectoryJob
{
Source = new TrajectoryReference
{
WellUid = WellUid,
WellboreUid = SourceWellboreUid,
TrajectoryUid = TrajectoryUid
},
Target = new WellboreReference
{
WellUid = WellUid,
WellboreUid = targetWellboreUid
}
};
}
private WitsmlTrajectories GetSourceTrajectories()
{
var witsmlTrajectory = new WitsmlTrajectory
{
UidWell = WellUid,
UidWellbore = SourceWellboreUid,
Uid = TrajectoryUid,
NameWell = "",
NameWellbore = "",
Name = "",
ObjectGrowing = null,
ParentTrajectory = new WitsmlWellboreTrajectory
{
TrajectoryReference = "",
WellboreParent = ""
},
DTimTrajStart = "",
DTimTrajEnd = "",
MdMin = new WitsmlMeasuredDepthCoord(),
MdMax = new WitsmlMeasuredDepthCoord(),
ServiceCompany = "",
MagDeclUsed = new WitsmlPlaneAngleMeasure(),
GridCorUsed = new WitsmlPlaneAngleMeasure(),
GridConUsed = new WitsmlPlaneAngleMeasure(),
AziVertSect = new WitsmlPlaneAngleMeasure(),
DispNsVertSectOrig = new WitsmlLengthMeasure(),
DispEwVertSectOrig = new WitsmlLengthMeasure(),
Definitive = "",
Memory = "",
FinalTraj = "",
AziRef = "",
TrajectoryStations = new List<WitsmlTrajectoryStation>
{
new WitsmlTrajectoryStation()
},
CommonData = new WitsmlCommonData(),
CustomData = new WitsmlCustomData()
};
return new WitsmlTrajectories
{
Trajectories = new List<WitsmlTrajectory> {witsmlTrajectory}
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//**********************************************************************
//
// 文件名称(File Name):LoadTaskExecuteLogRequest.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-04-21 10:12:53
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-04-21 10:12:53
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.Model.request
{
public class LoadTaskExecuteLogRequest : PageRequestBase
{
/// <summary>
/// 任务编号
/// </summary>
public int TaskId { get; set; }
/// <summary>
/// 任务日志创建起始时间
/// </summary>
public string TaskLogCreateTimeRange { get; set; }
/// <summary>
/// 节点id
/// </summary>
public int NodeId { get; set; }
/// <summary>
/// 任务执行状态
/// </summary>
public int TaskExecuteStatus { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.IL2CPU.API
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Field, AllowMultiple = true)]
public sealed class AsmMarkerAttribute : AsmLabelAttribute
{
private static string[] mAsmMarkers = new string[]
{
};
public AsmMarkerAttribute(AsmMarkerType aMarkerType) : base(mAsmMarkers[(int)aMarkerType])
{
}
}
public enum AsmMarkerType
{
}
}
|
using Terraria.ID;
using Terraria.ModLoader;
namespace DuckingAround.Items.Placeable
{
public class HephaestusForge : ModItem
{
public override void SetStaticDefaults()
{
Tooltip.SetDefault("Powers of an ancient Greek god have been channeled into this forge...");
DisplayName.SetDefault("Hephaestus' Forge");
}
public override void SetDefaults()
{
item.width = 48;
item.height = 34;
item.maxStack = 99;
item.useTurn = true;
item.autoReuse = true;
item.useAnimation = 15;
item.useTime = 10;
item.useStyle = ItemUseStyleID.SwingThrow;
item.consumable = true;
item.value = 150000;
item.createTile = ModContent.TileType<Tiles.HephaestusForge>();
}
}
} |
using Discord.WebSocket;
using OrbCore.ContentStructures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrbCore.Interfaces.Receivers {
public interface IUserBannedReceiver {
Task OnUserBanned(GuildUserEventContent guildUserEvent);
}
}
|
using System;
namespace DelftTools.Utils.PropertyBag
{
/// <summary>
/// Represents a single property in a PropertySpec.
/// </summary>
public class PropertySpec
{
private Attribute[] attributes;
private string category;
private object defaultValue;
private string description;
private string editor;
private string name;
private string type;
private string typeConverter;
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
public PropertySpec(string name, string type) : this(name, type, null, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
public PropertySpec(string name, Type type)
:
this(name, type.AssemblyQualifiedName, null, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
public PropertySpec(string name, string type, string category) : this(name, type, category, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category"></param>
public PropertySpec(string name, Type type, string category)
:
this(name, type.AssemblyQualifiedName, category, null, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
public PropertySpec(string name, string type, string category, string description)
:
this(name, type, category, description, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
public PropertySpec(string name, Type type, string category, string description)
:
this(name, type.AssemblyQualifiedName, category, description, null) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue)
{
this.name = name;
this.type = type;
this.category = category;
this.description = description;
this.defaultValue = defaultValue;
attributes = null;
}
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue)
:
this(name, type.AssemblyQualifiedName, category, description, defaultValue) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
string editor, string typeConverter)
: this(name, type, category, description, defaultValue)
{
this.editor = editor;
this.typeConverter = typeConverter;
}
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
string editor, string typeConverter)
:
this(name, type.AssemblyQualifiedName, category, description, defaultValue, editor, typeConverter) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
Type editor, string typeConverter)
:
this(name, type, category, description, defaultValue, editor.AssemblyQualifiedName,
typeConverter) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The fully qualified name of the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
Type editor, string typeConverter)
:
this(name, type.AssemblyQualifiedName, category, description, defaultValue,
editor.AssemblyQualifiedName, typeConverter) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
string editor, Type typeConverter)
:
this(name, type, category, description, defaultValue, editor, typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The fully qualified name of the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
string editor, Type typeConverter)
:
this(name, type.AssemblyQualifiedName, category, description, defaultValue, editor,
typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">The fully qualified name of the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, string type, string category, string description, object defaultValue,
Type editor, Type typeConverter)
:
this(name, type, category, description, defaultValue, editor.AssemblyQualifiedName,
typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Initializes a new instance of the PropertySpec class.
/// </summary>
/// <param name="name">The name of the property displayed in the property grid.</param>
/// <param name="type">A Type that represents the type of the property.</param>
/// <param name="category">The category under which the property is displayed in the
/// property grid.</param>
/// <param name="description">A string that is displayed in the help area of the
/// property grid.</param>
/// <param name="defaultValue">The default value of the property, or null if there is
/// no default value.</param>
/// <param name="editor">The Type that represents the type of the editor for this
/// property. This type must derive from UITypeEditor.</param>
/// <param name="typeConverter">The Type that represents the type of the type
/// converter for this property. This type must derive from TypeConverter.</param>
public PropertySpec(string name, Type type, string category, string description, object defaultValue,
Type editor, Type typeConverter)
:
this(name, type.AssemblyQualifiedName, category, description, defaultValue,
editor.AssemblyQualifiedName, typeConverter.AssemblyQualifiedName) { }
/// <summary>
/// Gets or sets a collection of additional Attributes for this property. This can
/// be used to specify attributes beyond those supported intrinsically by the
/// PropertySpec class, such as ReadOnly and Browsable.
/// </summary>
public Attribute[] Attributes
{
get { return attributes; }
set { attributes = value; }
}
/// <summary>
/// Gets or sets the category name of this property.
/// </summary>
public string Category
{
get { return category; }
set { category = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the type converter
/// type for this property.
/// </summary>
public string ConverterTypeName
{
get { return typeConverter; }
set { typeConverter = value; }
}
/// <summary>
/// Gets or sets the default value of this property.
/// </summary>
public object DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; }
}
/// <summary>
/// Gets or sets the help text description of this property.
/// </summary>
public string Description
{
get { return description; }
set { description = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the editor type for
/// this property.
/// </summary>
public string EditorTypeName
{
get { return editor; }
set { editor = value; }
}
/// <summary>
/// Gets or sets the name of this property.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets or sets the fully qualfied name of the type of this
/// property.
/// </summary>
public string TypeName
{
get { return type; }
set { type = value; }
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.