text
stringlengths 13
6.01M
|
|---|
using UnityEngine;
using System.Collections;
namespace ComLib.Unity.Extensions
{
public static class GameObjectExtensions
{
/// <summary>
/// Sets the layer of this gameobject, and all of its children
/// </summary>
/// <param name="go">root gameObject</param>
/// <param name="newLayer">new Layer</param>
public static void SetLayerRecursively(this GameObject go, LayerMask newLayer)
{
go.layer = newLayer;
for (int i = 0; i < go.transform.childCount; i++)
{
go.transform.GetChild(i).gameObject.SetLayerRecursively(newLayer);
}
}
/// <summary>
/// Sets the tag of this gameobject, and all of its children
/// </summary>
/// <param name="go">root gameObject</param>
/// <param name="newTag">new Tag</param>
public static void SetTagRecursively(this GameObject go, string newTag)
{
go.tag = newTag;
foreach (GameObject child in go.transform)
{
child.SetTagRecursively(newTag);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace pair_Programming
{
class Program
{
static SqlConnection conn;
static string str1 = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Elhanan\Documents\pairprogramming.mdf;Integrated Security=True;Connect Timeout=30";
static void Main(string[] args)
{
int choise;
Console.WriteLine("Menu:");
Console.WriteLine("Please enter 1 to work on auther:");
Console.WriteLine("Please enter 2 to work on article:");
choise = Convert.ToInt32(Console.ReadLine());
if (choise == 1)
{
int choi;
Console.WriteLine("Menu:");
Console.WriteLine("Please enter 3 to add auther:");
Console.WriteLine("Please enter 4 to update auther email:");
Console.WriteLine("Please enter 5 to delete auther:");
Console.WriteLine("Please enter 6 to see all auther record:");
choi = Convert.ToInt32(Console.ReadLine());
if (choi == 3)
{
Add_auther();
}
else if (choi == 4)
{
update_auther();
}
else if (choi == 5)
{
delete_auther();
}
else if (choi == 6)
{
read_auther();
}
else
{
Console.WriteLine("Wrong choise please see the menu:");
}
}
else if (choise == 2)
{
int choi;
Console.WriteLine("Menu:");
Console.WriteLine("Please enter 7 to add article:");
Console.WriteLine("Please enter 8 to update article:");
Console.WriteLine("Please enter 9 to delete article:");
Console.WriteLine("Please enter 10 to see all article record:");
choi = Convert.ToInt32(Console.ReadLine());
if (choi == 7)
{
Add_article();
}
else if (choi == 8)
{
//update_article();
}
else if (choi == 9)
{
//delete_article();
}
else if (choi == 10)
{
// read_article();
}
else
{
Console.WriteLine("Wrong choise please see the menu:");
}
}
}
public static void Add_auther()
{
string name;
string email;
Console.WriteLine("Enter auther name");
name = Console.ReadLine();
Console.WriteLine("Enter auther email");
email = Console.ReadLine();
try
{
conn = new SqlConnection(str1);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("INSERT INTO auther (name,email) values(@name,@email)", conn);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@email", email);
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Auther data saved to database");
}
}
catch(Exception ex)
{
Console.WriteLine("something wrong."+ex);
}
Console.ReadLine();
}
public static void read_auther()
{
try
{
conn = new SqlConnection(str1);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM auther", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("something wrong." + ex);
}
Console.ReadLine();
}
public static void update_auther()
{
string name;
string email;
Console.WriteLine("Enter auther name to change his/her email");
name = Console.ReadLine();
Console.WriteLine("Enter new email");
email = Console.ReadLine();
try
{
conn = new SqlConnection(str1);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("update auther set email = @email Where name='" + name + "'", conn);
cmd.Parameters.AddWithValue("@email", email);
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Auther email successfully updated");
}
}
catch (Exception ex)
{
Console.WriteLine("something wrong." + ex);
}
}
public static void delete_auther()
{
string name;
Console.WriteLine("Enter auther name to be deleted");
name = Console.ReadLine();
try
{
conn = new SqlConnection(str1);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("Delete from auther where name='" + name + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Auther successfully deleted!");
}
}
catch (Exception ex)
{
Console.WriteLine("something wrong." + ex);
}
}
public static void Add_article()
{
string article;
string body;
string auterid;
Console.WriteLine("Enter article name");
article = Console.ReadLine();
Console.WriteLine("Enter article body");
body = Console.ReadLine();
Console.WriteLine("Enter article body");
auterid = Console.ReadLine();
try
{
conn = new SqlConnection(str1);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("INSERT INTO article (article,body,autherid) values(@article,@body,@auterid)", conn);
cmd.Parameters.AddWithValue("@article", article);
cmd.Parameters.AddWithValue("@body", body);
cmd.Parameters.AddWithValue("@auterid", auterid);
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("The article successfully saved to database");
}
}
catch (Exception ex)
{
Console.WriteLine("Something wrong." + ex);
}
Console.ReadLine();
}
public static void update_article()
{
string article;
string body;
Console.WriteLine("Enter article to update its body");
article = Console.ReadLine();
Console.WriteLine("Enter new atricle body");
body = Console.ReadLine();
try
{
conn = new SqlConnection(str1);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("update article set body = @body Where article='" + article + "'", conn);
cmd.Parameters.AddWithValue("@body", body);
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Atricle successfully updated");
}
}
catch (Exception ex)
{
Console.WriteLine("something wrong." + ex);
}
}
public static void delete_article()
{
string article;
Console.WriteLine("Enter article to be deleted");
article = Console.ReadLine();
try
{
conn = new SqlConnection(str1);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("Delete from article where name='" + article + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Article successfully deleted!");
}
}
catch (Exception ex)
{
Console.WriteLine("something wrong." + ex);
}
}
}
}
|
using University.Data;
using University.Repository;
using University.Repository.Interface;
using University.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace University.Service
{
public class FeedbackService: IFeedbackService
{
private readonly IFeedbackRepository _feedbackRepository;
public FeedbackService(IFeedbackRepository feedbackRepository)
{
_feedbackRepository = feedbackRepository;
}
public bool SaveFeedback(ProductFeedback productFeedback)
{
return _feedbackRepository.SaveFeedback(productFeedback);
}
public bool SaveGeneralFeedback(GeneralFeedback generalFeedback)
{
return _feedbackRepository.SaveGeneralFeedback(generalFeedback);
}
public List<GeneralFeedback> GetGeneralFeedback()
{
return _feedbackRepository.GetGeneralFeedback();
}
}
}
|
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DemoApp.Profiles
{
public class CentreProfile : Profile
{
public CentreProfile()
{
//listing of centres
CreateMap<Entities.Centres, Models.CentresDto>()
.ForMember(
dest => dest.CentreNumber,
opt => opt.MapFrom(src => src.CentreNo)
)
//.ForMember(
// dest => dest.SchoolCategory,
// opt =>
// {
// opt.PreCondition(src => src.SchoolCategory != null);
// opt.MapFrom(src => src.SchoolCategory);
// }
//)
.ForMember(
dest => dest.CentreSanctions,
opt =>
{
opt.PreCondition(src => src.CentreSanctions != null);
opt.MapFrom(src => src.CentreSanctions.ToList());
}
);
//create a new centre mapping
CreateMap<Models.CentreCreateDto, Entities.Centres>()
.ForMember(
dest => dest.CentreNo,
opt => opt.MapFrom(src => src.CentreNumber)
);
//update an existing centre
CreateMap<Models.CentreUpdateDto, Entities.Centres>()
.ForMember(
dest => dest.CentreNo,
opt => opt.MapFrom(src => src.CentreNumber)
);
}
}
}
|
using EddiCompanionAppService.Exceptions;
using Newtonsoft.Json.Linq;
using System;
using Utilities;
namespace EddiCompanionAppService.Endpoints
{
public class FleetCarrierEndpoint : Endpoint
{
private const string FLEETCARRIER_URL = "/fleetcarrier";
// We cache data to avoid spamming the service
private JObject cachedFleetCarrierJson;
private DateTime cachedFleetCarrierTimeStamp;
private DateTime cachedFleetCarrierExpires => cachedFleetCarrierTimeStamp.AddSeconds(30);
// Set up an event handler for data changes
public event EndpointEventHandler FleetCarrierUpdatedEvent;
/// <summary>
/// Contains information about the player's fleet carrier (if any)
/// </summary>
/// <param name="forceRefresh"></param>
/// <returns></returns>
public JObject GetFleetCarrier(bool forceRefresh = false)
{
if ((!forceRefresh) && cachedFleetCarrierExpires > DateTime.UtcNow)
{
// return the cached version
Logging.Debug($"{FLEETCARRIER_URL} endpoint queried too often. Returning cached data: ", cachedFleetCarrierJson);
return cachedFleetCarrierJson;
}
try
{
Logging.Debug($"Getting {FLEETCARRIER_URL} data");
var result = GetEndpoint(FLEETCARRIER_URL);
if ( result is null )
{
return null;
}
if (!result.DeepEquals(cachedFleetCarrierJson))
{
cachedFleetCarrierJson = result;
cachedFleetCarrierTimeStamp = result["timestamp"]?.ToObject<DateTime?>() ?? DateTime.MinValue;
Logging.Debug($"{FLEETCARRIER_URL} returned: ", cachedFleetCarrierJson);
FleetCarrierUpdatedEvent?.Invoke(this, new CompanionApiEndpointEventArgs(CompanionAppService.Instance.ServerURL(), null, null, null, cachedFleetCarrierJson));
}
else
{
Logging.Debug($"{FLEETCARRIER_URL} returned, no change from prior cached data.");
}
}
catch (EliteDangerousCompanionAppException ex)
{
// not Logging.Error as telemetry is getting spammed when the server is down
Logging.Warn(ex.Message);
}
return cachedFleetCarrierJson;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace UserDetailsClient.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
// To get SSO with a UWP app, you'll need to register the following
// redirect URI for your application
Uri redirectURIForSsoWithoutBroker = Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
// To have WAM working you need to register the following redirect URI for your application
string sid = redirectURIForSsoWithoutBroker.Host.ToUpper();
// only used in the .WithBroker scenario.
string redirectUriWithWAM = $"ms-appx-web://microsoft.aad.brokerplugin/{sid}";
// Then use the following:
LoadApplication(new UserDetailsClient.App(redirectURIForSsoWithoutBroker.AbsoluteUri));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GatewayEDI.Logging;
namespace LoggingTestConsole
{
class Program
{
private static ILog primaryLog = LogManager.GetLog(typeof(Program));
private static ILog secondaryLog = LogManager.GetLog(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
Program.primaryLog.Debug("primaryLog Debug Message");
Program.primaryLog.Info("primaryLog Info Message");
Program.primaryLog.Warn("primaryLog Warn Message");
Program.primaryLog.Error("primaryLog Error Message");
Program.primaryLog.Fatal("primaryLog Fatal Message");
Program.secondaryLog.Debug("secondaryLog Debug Message");
Program.secondaryLog.Info("secondaryLog Info Message");
Program.secondaryLog.Warn("secondaryLog Warn Message");
Program.secondaryLog.Error("secondaryLog Error Message");
Program.secondaryLog.Fatal("secondaryLog Fatal Message");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApiBluesea.Utils;
namespace WebApiBluesea
{
public partial class WapCharging : System.Web.UI.Page
{
readonly log4net.ILog log = log4net.LogManager.GetLogger("request_response");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Label1.Text = "Clicked at " + DateTime.Now.ToString();
Crypto crypto = new Crypto();
string id = DateTime.UtcNow.ToString("yyyyMMddHHmmssfffffff",
CultureInfo.InvariantCulture);
String returnurl = "http://112.213.86.104:8088/returnurl.aspx|" + id + "|6|1000";
log.Info("returnurl before encrypted :" + returnurl);
String encrypted = crypto.encrypt(returnurl);
String returnurlencode = HttpUtility.UrlEncode(encrypted);
String urlcheckout = "http://3g.topteen.vn/dt/dungfmc/?k=" + returnurlencode;
log.Info("urlcheckout :" + urlcheckout);
Response.Redirect(urlcheckout);
}
}
}
|
using System;
using System.Linq;
using MassEffect.Exceptions;
namespace MassEffect.Engine.Commands
{
using MassEffect.Interfaces;
public class AttackCommand : Command
{
public AttackCommand(IGameEngine gameEngine)
: base(gameEngine)
{
}
private string PrintMethod(string msg)
{
return msg;
}
public override void Execute(string[] commandArgs)
{
string attackingShipName = commandArgs[1];
string defendingShipName = commandArgs[2];
var attackingShip = this.GameEngine.Starships.FirstOrDefault(st => st.Name == attackingShipName);
var defendingShip = this.GameEngine.Starships.FirstOrDefault(st => st.Name == defendingShipName);
this.ValidateAlive(attackingShip);
this.ValidateAlive(defendingShip);
var attack = attackingShip.ProduceAttack();
defendingShip.RespondToAttack(attack);
PrintMethod(String.Format("{0} attacked {1}", attackingShip, defendingShip));
if (defendingShip.Shields < 0)
{
defendingShip.Shields = 0;
}
if (defendingShip.Health <= 0)
{
defendingShip.Health = 0;
Console.WriteLine(Messages.ShipDestroyed,defendingShipName);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PPesoIdeal
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
double peso, altura, pesoIdeal;
if ((double.TryParse(txtPesoAtual.Text, out peso) &&
double.TryParse(txtAltura.Text, out altura)))
{
if (rbMasculino.Checked)
{
pesoIdeal = (72.7 * altura) - 58;
pesoIdeal = Math.Round(pesoIdeal, 2);
txtPesoIdeal.Text = pesoIdeal.ToString("N2");
if (peso > pesoIdeal)
{
txtSituacao.Text = "Regime Obrigatório Já!!";
}
else if(peso < pesoIdeal)
{
txtSituacao.Text = "Coma Bastante Massas e Doces!!";
}
else
{
txtSituacao.Text = "Você está no peso Ideal!!";
}
}
else if (rbFeminino.Checked)
{
pesoIdeal = (62.1 * altura) - 58;
pesoIdeal = Math.Round(pesoIdeal, 2);
txtPesoIdeal.Text = pesoIdeal.ToString("N2");
if (peso > pesoIdeal)
{
txtSituacao.Text = "Regime Obrigatório Já!!";
}
else if (peso < pesoIdeal)
{
txtSituacao.Text = "Coma Bastante Massas e Doces!!";
}
else
{
txtSituacao.Text = "Você está no peso Ideal!!";
}
}
else
{
MessageBox.Show("INFORME O SEXO!");
}
}
else
{
MessageBox.Show("Informe uma altura e/ou peso válidos");
}
}
private void btnLimpar_Click(object sender, EventArgs e)
{
txtAltura.Clear();
txtPesoAtual.Clear();
txtPesoIdeal.Clear();
txtSituacao.Clear();
rbMasculino.Checked = false;
rbFeminino.Checked = false;
}
}
}
|
namespace P08MilitaryElite.Interfaces.Factories
{
public interface IEngineerFactory : IAbstractFactory<IEngineer>
{
}
}
|
namespace gView.Framework.Symbology
{
[global::System.AttributeUsageAttribute(global::System.AttributeTargets.Property)]
public class UseLineSymbolPicker : global::System.Attribute
{
public UseLineSymbolPicker()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.DataVisualization.Charting;
public partial class UserHistory : System.Web.UI.Page
{
string userId;
protected void Page_Load(object sender, EventArgs e)
{
//get the user id, the range of 7 previous dates for chart select statements
userId = Session["UserId"].ToString();
Session["Date"] = DateTime.Today.ToShortDateString();
Session["Date2"] = DateTime.Today.AddDays(-7).ToShortDateString();
}
protected void btnST_Click(object sender, EventArgs e)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ffff99");
Label1.Text = "Your Screen Time Statistics in the last few days";
Label2.Text = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterationConnectionString"].ConnectionString);
conn.Open();
DateTime lastTime;
string strSTAmount;
int ST_Amount=0;
DateTime currentDate = DateTime.Today.AddDays(-5);
DateTime currentDate2 = DateTime.Today.AddDays(-5).AddHours(23).AddMinutes(59);
string checkLastTime;
for (int i = 1; i <= 5; i++)
{
//select the last time in date column that match the current session user id and a specific date
checkLastTime = "select Max(Date) from ScreenTimeData where UserID= '"+ userId+"' AND Date between CONVERT(datetime,'"+currentDate+"',103) AND CONVERT(datetime,'"+currentDate2+"',103)";
SqlCommand command1 = new SqlCommand(checkLastTime, conn);
if ((command1.ExecuteScalar() != DBNull.Value))
{
SqlCommand tempCommand = new SqlCommand(checkLastTime, conn);
lastTime = Convert.ToDateTime(tempCommand.ExecuteScalar());
//get the screen time amount of the last update
string checkScreenTime = "select UserScreenDailyAmnt from ScreenTimeData where UserID = '" + userId + "' AND Date > Convert(datetime,'" + lastTime + "',103) AND Date <= DATEADD(s,1, Convert(datetime,'" + lastTime + "',103))";
SqlCommand command2 = new SqlCommand(checkScreenTime, conn);
strSTAmount = command2.ExecuteScalar().ToString().Replace(" ","");
ST_Amount = Convert.ToInt32(strSTAmount);
//add data to chart
ScreenTimeChart.Series["UserScreenTime"].Points.AddXY(lastTime.Date,ST_Amount);
ScreenTimeChart.Series["ScreenTimeLimit"].Points.AddXY(lastTime.Date, 3);
}
Label2.Text= Label2.Text+"<br/>"+"On "+currentDate.ToShortDateString()+" your screen time amount was "+ ST_Amount+" hours";
ST_Amount = 0;
currentDate = currentDate.AddDays(1);
currentDate2 = currentDate.AddHours(23).AddMinutes(59);
}
conn.Close();
double startDate = DateTime.Today.AddDays(-5).ToOADate();
double endDate = DateTime.Today.ToOADate();
//limit the values that appear in x axis
ScreenTimeChart.ChartAreas["ChartArea1"].AxisX.Minimum = startDate;
ScreenTimeChart.ChartAreas["ChartArea1"].AxisX.Maximum = endDate;
//to show each single day in x axis
ScreenTimeChart.ChartAreas["ChartArea1"].AxisX.Interval = 1;
//to show the x axis labels vertically
ScreenTimeChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.Angle = 90;
//set the width of series column in the char
ScreenTimeChart.Series["ScreenTimeLimit"]["PixelPointWidth"] = "25";
ScreenTimeChart.Series["UserScreenTime"]["PixelPointWidth"] = "25";
//show the chart
ScreenTimeChart.Visible = true;
}
protected void btnPA_Click(object sender, EventArgs e)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ffcccc");
Label1.Text = "Your Exercise Performance Statistics in the last few days";
Label2.Text = "";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterationConnectionString"].ConnectionString);
conn.Open();
DateTime lastTime;
string strDailySteps;
int dailySteps=0;
DateTime currentDate = DateTime.Today.AddDays(-5);
DateTime currentDate2 = DateTime.Today.AddDays(-5).AddHours(23).AddMinutes(59);
string checkLastTime;
for (int i = 1; i <= 5; i++)
{
//select the last time in date column that match the current session user id and a specific date
checkLastTime = "select Max(DateAndTime) from PhysicalActivityData where UserID= '" + userId + "' AND DateAndTime between CONVERT(datetime,'" + currentDate + "',103) AND CONVERT(datetime,'" + currentDate2 + "',103)";
SqlCommand command1 = new SqlCommand(checkLastTime, conn);
if ((command1.ExecuteScalar() != DBNull.Value))
{
// SqlCommand tempCommand = new SqlCommand(checkLastTime, conn);
//lastTime = Convert.ToDateTime(tempCommand.ExecuteScalar());
lastTime = Convert.ToDateTime(command1.ExecuteScalar());
//get the last updated number of steps
string checkDailySteps = "select DailySteps from PhysicalActivityData where UserID = '" + userId + "' AND DateAndTime > Convert(datetime,'" + lastTime + "',103) AND DateAndTime <= DATEADD(s,1, Convert(datetime,'" + lastTime + "',103))";
SqlCommand command2 = new SqlCommand(checkDailySteps, conn);
strDailySteps = command2.ExecuteScalar().ToString().Replace(" ", "");
dailySteps = Convert.ToInt32(strDailySteps);
//add data to chart
PhysicalActivityChart.Series["UserPhysicalSteps"].Points.AddXY(lastTime.Date, dailySteps);
PhysicalActivityChart.Series["RecommendedStepsBoys"].Points.AddXY(lastTime.Date, 13000);
PhysicalActivityChart.Series["RecommendedStepsGirls"].Points.AddXY(lastTime.Date, 11000);
}
Label2.Text = Label2.Text + "<br/>" + "On " + currentDate.ToShortDateString() + " your steps amount was " + dailySteps + " steps";
dailySteps = 0;
currentDate = currentDate.AddDays(1);
currentDate2 = currentDate.AddHours(23).AddMinutes(59);
}
conn.Close();
double startDate = DateTime.Today.AddDays(-5).ToOADate();
double endDate = DateTime.Today.ToOADate();
//limit the values that appear in x axis
PhysicalActivityChart.ChartAreas["ChartArea1"].AxisX.Minimum = startDate;
PhysicalActivityChart.ChartAreas["ChartArea1"].AxisX.Maximum = endDate;
//to show each single day in x axis
PhysicalActivityChart.ChartAreas["ChartArea1"].AxisX.Interval = 1;
//to show the x axis labels vertically
PhysicalActivityChart.ChartAreas["ChartArea1"].AxisX.LabelStyle.Angle = 90;
//set the width of series column in the char
PhysicalActivityChart.Series["UserPhysicalSteps"]["PixelPointWidth"] = "25";
PhysicalActivityChart.Series["RecommendedStepsBoys"]["PixelPointWidth"] = "25";
PhysicalActivityChart.Series["RecommendedStepsGirls"]["PixelPointWidth"] = "25";
//show the chart
PhysicalActivityChart.Visible = true;
}
}
|
using System;
namespace OccuranceOfMaxNumbers
{
class Program
{
static void Main(string[] args)
{
int numberMax = 0;
int maxOccurances = 0;
bool cond = true;
do
{
Console.Write("Enter number : ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine();
if (number > numberMax)
{
numberMax = number;
maxOccurances = 1;
}
else if (number == numberMax) maxOccurances++;
else if (number < numberMax && number != 0) { }
else
{
cond = false;
Console.WriteLine($"Max number is {numberMax} and number of occurances is {maxOccurances}");
}
} while (cond);
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
using System.Collections.Generic;
using System.Linq;
using E_ShopDomainModel.Interfaces;
namespace E_ShopDomainModel.Tests
{
[TestClass]
public class DiscountPolicyTests
{
[TestMethod]
public void When_lower_or_equal_than_minSumForDiscount_and_minForDiscountCoefficient()
{
//arrange
List<ItemEntity> items = new List<ItemEntity>();
items.Add(
new ItemEntity
{
ItemId = Guid.NewGuid(),
Name = "carrot",
Description = "delicious",
Price = (decimal)2.5,
Count = 5
}
);
DiscountPolicy discount = new DiscountPolicy();
var sum = items.Sum<ItemEntity>(x => x.Price * x.Count);
//act
var result = discount.PriceCalculation(items);
//assert
Assert.AreEqual(sum , result);
}
[TestMethod]
public void When_greater_than_minSumForDiscount_but_lower_minForDiscountCoefficient()
{
//arrange
List<ItemEntity> items = new List<ItemEntity>();
items.Add(
new ItemEntity
{
ItemId = Guid.NewGuid(),
Name = "carrot",
Description = "delicious",
Price = (decimal)5.5,
Count = 300
}
);
DiscountPolicy discount = new DiscountPolicy();
decimal sum = items.Sum<ItemEntity>(x => x.Price * x.Count) * (decimal)0.3;
//act
decimal result = discount.PriceCalculation(items);
//assert
Assert.AreEqual(sum, result);
}
[TestMethod]
public void When_greater_than_minSumForDiscount_and_minForDiscountCoefficient()
{
//arrange
List<ItemEntity> items = new List<ItemEntity>();
items.Add(
new ItemEntity
{
ItemId = Guid.NewGuid(),
Name = "carrot",
Description = "delicious",
Price = (decimal)5.5,
Count = 300
}
);
items.Add(
new ItemEntity
{
ItemId = Guid.NewGuid(),
Name = "tomatoes",
Description = "delicious",
Price = (decimal)10,
Count = 10
}
);
items.Add(
new ItemEntity
{
ItemId = Guid.NewGuid(),
Name = "green onion",
Description = "delicious",
Price = (decimal)5,
Count = 100
}
);
DiscountPolicy discount = new DiscountPolicy(30,2);
decimal sum = items.Sum<ItemEntity>(x => x.Price * x.Count) * (decimal)0.3 * (decimal)1.67;
//act
decimal result = discount.PriceCalculation(items);
//assert
Assert.AreEqual(sum, result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void When_null_argument_come()
{
//arrange
List<ItemEntity> items = null;
DiscountPolicy discount = new DiscountPolicy(30, 2);
//act
decimal result = discount.PriceCalculation(items);
}
}
}
|
using System;
using Xunit;
namespace LoggingKata.Test
{
public class TacoParserTests
{
[Fact]
public void ShouldDoSomething()
{
// TODO: Complete Something, if anything
//Arrange
var tacoParser = new TacoParser();
//Act
var actual = tacoParser.Parse("34.073638, -84.677017, Taco Bell Acwort...");
//Assert
Assert.NotNull(actual);
}
[Theory]
[InlineData("Example")]
public void ShouldParse(string str)
{
// TODO: Complete Should Parse
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void ShouldFailParse(string str)
{
// TODO: Complete Should Fail Parse
}
}
}
|
using DChild.Gameplay.Objects;
using DChild.Gameplay.Systems.Subroutine;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Combat
{
[System.Serializable]
public struct DPS
{
[SerializeField]
private DPSConfig m_config;
private float m_timer;
private IDamageable[] m_toDamage;
public DPS(DPSConfig config)
{
m_config = config;
m_timer = 0f;
m_toDamage = null;
}
public void SetDamage(int damage) => m_config.SetDamage(damage);
public void ForceDamage() => m_timer = 0;
public void SetObjectToDamage(params IDamageable[] toDamage) => m_toDamage = toDamage;
public void Update()
{
if (m_timer <= 0)
{
m_timer = m_config.interval;
var combatRoutine = GameplaySystem.GetRoutine<ICombatRoutine>();
for (int i = 0; i < m_toDamage.Length; i++)
{
combatRoutine.ApplyDamage(m_toDamage[i], m_config.damageFXType, m_config.damage);
}
}
m_timer -= Time.deltaTime;
}
}
}
|
using DAL.Models;
using DTO.Convertors;
using System;
using System.Collections.Generic;
using System.Text;
namespace BLL
{
public interface IMenuLogic
{
List<MenuDto> GetAllMenus();
MenuDto GetMenuById(int id);
MenuDto GetMenuByName(string name);
MenuDto AddMenu(MenuDto u);
MenuDto DeletMenu(MenuDto u);
MenuDto UpdateMenu(MenuDto u);
// MenuDto IsExists(MenuDto b);
}
}
|
using System.Collections.Generic;
namespace Microsoft.UnifiedRedisPlatform.Core.Services.Models
{
internal class ClusterConfiguration
{
public string ClusterName { get; set; }
public bool IsProductionCluster { get; set; }
public string SupportContact { get; set; }
public string RedisCachePrefix { get; set; }
public string RedisConnectionString { get; set; }
public List<ApplicationConfiguration> Applications { get; set; } = new List<ApplicationConfiguration>();
}
}
|
using MultiTenantKit.Core.Context;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using MultiTenantKit.MultiTenantClaimSample.Models;
using MultiTenantKit.MultiTenantClaimSample.MultiTenantImplementations;
using System.Diagnostics;
using System.Security.Claims;
namespace MultiTenantKit.MultiTenantClaimSample.Controllers
{
public class HomeController : Controller
{
[Route("Login")]
[AllowAnonymous]
public IActionResult Login()
{
return View();
}
[Route("Login")]
[HttpPost]
[AllowAnonymous]
public IActionResult Login(LoginModel model)
{
if (!ModelState.IsValid)
{
return View();
}
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal();
ClaimsIdentity claimsIdentity = new ClaimsIdentity("Cookies");
if (model.Password != "123456")
{
ViewBag.ErrorMessage = "Username or password invalid.";
return View();
}
switch (model.Username)
{
case "tenant1":
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "tenant1"));
claimsIdentity.AddClaim(new Claim("TenantId", "e1009e1b-da1e-481a-b902-417e84ad349a"));
break;
case "tenant2":
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "tenant2"));
claimsIdentity.AddClaim(new Claim("TenantId", "21a7227c-0471-4b3c-976a-2e09cfed537b"));
break;
default:
ViewBag.ErrorMessage = "Username or password invalid.";
return View();
}
claimsPrincipal.AddIdentity(claimsIdentity);
HttpContext.SignInAsync("Cookies", claimsPrincipal);
return RedirectToAction("Index");
}
[Route("Dashboard")]
[Authorize]
public IActionResult Index()
{
IndexModel model = new IndexModel();
TenantContext<CustomTenant> tenantCtx = HttpContext.GetTenantContext<CustomTenant>();
if (tenantCtx != null)
{
model.TenantName = tenantCtx.Tenant?.Name ?? "";
model.TenantId = tenantCtx.Tenant?.Id ?? "";
model.TenantCssTheme = tenantCtx.Tenant?.CSSTheme ?? "";
}
return View(model);
}
[Route("Privacy")]
[Authorize]
public IActionResult Privacy()
{
return View();
}
[Route("Signout")]
[Authorize]
public IActionResult Logout()
{
HttpContext.SignOutAsync("Cookies");
return RedirectToAction("Login");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
[assembly: Dependency(typeof(AnyTest.MobileClient.Droid.PopUp))]
namespace AnyTest.MobileClient.Droid
{
public class PopUp : IPopUp
{
public void Long(string message)
{
Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long).Show();
}
public void Short(string message)
{
Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short).Show();
}
}
}
|
using GFW;
namespace CodeX
{
public class GameStartUpCommand : ICommand
{
public void Execute(IMessage message)
{
if (!AppUtil.CheckEnvironment()) return;
//-----------------关联命令-----------------------
GameSystem.Instance.RegisterCommand(GameCommandDef.SocketCommand);
//-----------------初始化管理器-----------------------
GameSystem.Instance.CreateManager(ManagerName.LuaManager);
GameSystem.Instance.CreateManager(ManagerName.GameManager);
//AppFacade.Instance.AddManager<SoundManager>(ManagerName.Sound);
//AppFacade.Instance.AddManager<TimerManager>(ManagerName.Timer);
//AppFacade.Instance.AddManager<NetworkManager>(ManagerName.Network);
GameSystem.Instance.CreateManager(ManagerName.ResourceManager);
//AppFacade.Instance.AddManager<ThreadManager>(ManagerName.Thread);
//AppFacade.Instance.AddManager<ObjectPoolManager>(ManagerName.ObjectPool);
GameSystem.Instance.CreateManager(ManagerName.UIAgentManager);
GameSystemMono.StartUp();//开始生命周期
}
}
}
|
using System;
using DelftTools.Utils.Data;
using GeoAPI.Extensions.Feature;
using GeoAPI.Geometries;
namespace GeoAPI.Extensions.Networks
{
/// <summary>
/// TODO: remove these classes and make it work without stubs
/// NHibernate requires concrete class implementation
/// to remove dependency of networkeditor plugin this stub was introduced
/// </summary>
public class NodeFeatureStub : Unique<long>, INodeFeature
{
public object Clone()
{
throw new NotImplementedException();
}
public IGeometry Geometry
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public IFeatureAttributeCollection Attributes
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public int CompareTo(INetworkFeature other)
{
throw new NotImplementedException();
}
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
public string Name
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public INetwork Network
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string Description
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public INode Node
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
}
|
using AudioText.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AudioText.DAL
{
public class RepositoryManager : IDisposable
{
private AudioTextContext context = new AudioTextContext();
private Repository<InventoryItem> inventoryRepository;
private Repository<Announcement> announcementRepository;
private Repository<AccountInformation> accountRepository;
private Repository<Category> categoryRepository;
private Repository<Order> orderRepository;
private Repository<Author> authorRepository;
private Repository<Filter> filterRepository;
private Repository<NewsLetterPost> _newsLetterRepository;
private bool disposed = false;
public Repository<Filter> FilterRepository
{
get
{
if (filterRepository == null)
{
filterRepository = new FilterRepository<Filter>(context);
}
return filterRepository;
}
}
public Repository<NewsLetterPost> NewsLetterRepository
{
get
{
if (_newsLetterRepository == null)
{
_newsLetterRepository = new Repository<NewsLetterPost>(context);
}
return _newsLetterRepository;
}
}
public Repository<Author> AuthorRepository
{
get
{
if (authorRepository == null)
{
authorRepository = new AuthorRepository<Author>(context);
}
return authorRepository;
}
}
public Repository<Category> CategoryRepository
{
get
{
if (categoryRepository == null)
{
categoryRepository = new Repository<Category>(context);
}
return categoryRepository;
}
}
public Repository<Order> OrderRepository
{
get
{
if (orderRepository == null)
{
orderRepository = new Repository<Order>(context);
}
return orderRepository;
}
}
public Repository<InventoryItem> InventoryRepository
{
get
{
if (inventoryRepository == null)
{
inventoryRepository = new InventoryRepository<InventoryItem>(context);
}
return inventoryRepository;
}
}
public Repository<Announcement> AnnouncementRepository
{
get
{
if (announcementRepository == null)
{
announcementRepository = new Repository<Announcement>(context);
}
return announcementRepository;
}
}
public Repository<AccountInformation> AccountRepository
{
get
{
if (accountRepository == null)
{
accountRepository = new Repository<AccountInformation>(context);
}
return accountRepository;
}
}
public void save()
{
context.SaveChanges();
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
using System.Threading.Tasks;
using Airelax.Application.Orders.Request;
using Airelax.Application.Orders.Response;
using Airelax.Infrastructure.ThirdPartyPayment.ECPay.Request;
namespace Airelax.Application.Orders
{
public interface IOrderService
{
CreateOrderResponse CreateOrder(OrdersInput input);
Task<bool> Transact(CreateTransactionInput input);
}
}
|
using Backend;
using Backend.Model.Enums;
using Backend.Model.PerformingExamination;
using Backend.Model.Users;
using Model.Manager;
using Model.PerformingExamination;
using Model.Users;
using System;
namespace PatientWebAppTests.CreateObjectsForTests
{
public class CreateTherapy
{
public Therapy CreateValidTestObject()
{
return new Therapy(drug: new Drug(drugType: null, name: "Paracetamol", quantity: 20, expirationDate: new DateTime(2022, 11, 11), producer: "Hemofarm"), examination: new Examination(id: 1, typeOfExamination: TypeOfExamination.GENERAL, dateAndTime: new DateTime(2020, 11, 11), anamnesis: "Bol u grlu", doctor: new Doctor(jmbg: "0909965768767", name: "Ana", surname: "Markovic", dateOfBirth: DateTime.Now, gender: GenderType.F, city: new City(zipCode: 21000, name: "Novi Sad", country: new Country(id: 1, name: "Serbia")),
homeAddress: "Zmaj Jovina 10", phone: "065452102", email: "pera@gmail.com", username: "pera",
password: "12345678", numberOfLicence: "", doctorsOffice: new Room(number: 1, typeOfUsage: TypeOfUsage.CONSULTING_ROOM,
capacity: 1, occupation: 1, renovation: false), dateOfEmployment: DateTime.Now), room: new Room(number: 1, typeOfUsage: TypeOfUsage.CONSULTING_ROOM,
capacity: 1, occupation: 1, renovation: false),
patientCard: new PatientCard(id: 1, bloodType: BloodType.A, rhFactor: RhFactorType.NEGATIVE, alergies: "", medicalHistory: "",
hasInsurance: true, lbo: "", patientJmbg: "1309998775018")), id: 1, diagnosis: "Angina", startDate: new DateTime(2020, 11, 11), endDate: DateTime.Now, dailyDose: 3);
}
public Therapy CreateInvalidTestObject()
{
return new Therapy(drug: new Drug(), examination: new Examination(id: 1, typeOfExamination: TypeOfExamination.GENERAL, dateAndTime: DateTime.Now, anamnesis: "Bol u grlu", doctor: new Doctor(), room: new Room(number: 1, typeOfUsage: TypeOfUsage.CONSULTING_ROOM,
capacity: 1, occupation: 1, renovation: false),
patientCard: new PatientCard(id: 1, bloodType: BloodType.A, rhFactor: RhFactorType.NEGATIVE, alergies: "", medicalHistory: "",
hasInsurance: true, lbo: "", patientJmbg: null)), id: 1, diagnosis: "Angina", startDate: DateTime.Now, endDate: DateTime.Now, dailyDose: 3);
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using Microsoft.AspNet.SignalR.Hubs;
using Sparda.Contracts;
using Microsoft.AspNet.SignalR;
using System.Data.Services;
using System.Reactive.Linq;
using System.Reactive.Disposables;
using System.Reactive.Subjects;
namespace AngularJSAuthentication.API.Hubs
{
public class EntityChangedNotification
{
public string ServiceName { get; set; }
public string ServiceOwner { get; set; }
public int? ServiceVersion { get; set; }
public string Name { get; set; }
public string EditLink { get; set; }
public string Operations { get; set; }
}
public class RealtimeNotifier : IRealtimeNotifier
{
private readonly ReplaySubject<string> settingsChangedObserver;
private readonly ReplaySubject<EntityChangedNotification> entityChangedObserver;
// Singleton instance
private readonly static Lazy<IRealtimeNotifier> _instance = new Lazy<IRealtimeNotifier>(
() => ServiceLocator.Instance.Register<RealtimeNotifier, IRealtimeNotifier>(() => new RealtimeNotifier(GlobalHost.ConnectionManager.GetHubContext<RealtimeNotifierHub>().Clients)));
private RealtimeNotifier(IHubConnectionContext<dynamic> clients)
{
this.Clients = clients;
this.settingsChangedObserver = new ReplaySubject<string>();
this.settingsChangedObserver.Sample(TimeSpan.FromSeconds(1)).Subscribe(this.NotifySettingsChanged, this.OnError);
this.entityChangedObserver = new ReplaySubject<EntityChangedNotification>();
this.entityChangedObserver.Sample(TimeSpan.FromSeconds(1)).Subscribe(this.NotifyEntityChanged, this.OnError);
}
public static IRealtimeNotifier Instance
{
get
{
return _instance.Value;
}
}
private IHubConnectionContext<dynamic> Clients
{
get;
set;
}
private void NotifySettingsChanged(string id)
{
this.Clients.All.settingsChanged(id);
}
private void NotifyEntityChanged(EntityChangedNotification e)
{
this.Clients.All.entityChanged(e);
}
private void OnError(object e)
{
}
public void EntityChanged<T>(IService service, string editLink, UpdateOperations operations)
{
if (service != null)
{
this.entityChangedObserver.OnNext(new EntityChangedNotification()
{
Name = typeof(T).Name,
ServiceName = service.Name,
ServiceOwner = service.Owner,
ServiceVersion = service.Version,
EditLink = editLink,
Operations = operations.ToString().ToUpper()
});
}
}
public void SettingsChanged(string id)
{
this.settingsChangedObserver.OnNext(id);
}
public void TemplateChanged(int id)
{
this.Clients.All.templateChanged(id);
}
public void LocalizationChanged(string culture)
{
this.Clients.All.localizationChanged(culture);
}
}
}
|
using Microsoft.VisualStudio.DebuggerVisualizers;
using System.IO;
using ExpressionTreeVisualizer.Serialization;
namespace ExpressionTreeVisualizer {
public class VisualizerDataObjectSource : VisualizerObjectSource {
static VisualizerDataObjectSource() => Periscope.Debuggee.SubfolderAssemblyResolver.Hook("ExpressionTreeVisualizer");
public override void GetData(object target, Stream outgoingData) =>
Serialize(outgoingData, "");
public override void TransferData(object target, Stream incomingData, Stream outgoingData) {
var config = (Config)Deserialize(incomingData);
var serializationModel = new VisualizerData(target, config);
Serialize(outgoingData, serializationModel);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TableroComando.Dominio;
using TableroComando.GUIWrapper;
using Dominio;
using TableroComando.Clases;
namespace TableroComando.Formularios
{
public partial class Form_ListaObjetivos : Form
{
BindingSource _sourceObjetivos = new BindingSource();
public Form_ListaObjetivos()
{
InitializeComponent();
}
private void Form_ListaObjetivos_Load(object sender, EventArgs e)
{
ConfigurarObjetivosDataGrid();
}
private void AgregarBtn_Click(object sender, EventArgs e)
{
Form_AgregarObjetivo f = new Form_AgregarObjetivo(new CreateMode());
f.ShowDialog();
if (f.Guardado)
{
_sourceObjetivos.Add(new ObjetivoDataGridViewWrapper(f.Objetivo));
}
}
private void BorrarBtn_Click(object sender, EventArgs e)
{
DialogResult respuesta = MessageBox.Show("Si borra el objetivo seleccionado se borrarán todos los indicadores asociados" +
" ¿Desea borrar el objetivo seleccionado?",
"Borrar objetivo",
MessageBoxButtons.YesNo);
if (respuesta == System.Windows.Forms.DialogResult.Yes)
{
Objetivo o = ((ObjetivoDataGridViewWrapper)_sourceObjetivos.Current).GetObjetivo();
ObjetivoRepository.Instance.Delete(o); // Borrar de la base de datos
_sourceObjetivos.RemoveCurrent(); // Borrar del datagrid
}
}
private void ConfigurarObjetivosDataGrid()
{
IList<Objetivo> objetivos = ObjetivoRepository.Instance.All();
if (objetivos.Count != 0)
{
_sourceObjetivos.DataSource = ObjetivoRepository.Instance.All().Select(o => new ObjetivoDataGridViewWrapper(o));
ObjetivosDataGrid.DataSource = _sourceObjetivos;
ObjetivosDataGrid.Columns["Nombre"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ObjetivosDataGrid.Columns["Pertenece"].Visible = false;
}
}
private void ObjetivosDataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
Form_AgregarObjetivo f = new Form_AgregarObjetivo(new UpdateMode());
f.Objetivo = ((ObjetivoDataGridViewWrapper)_sourceObjetivos.Current).GetObjetivo();
f.ShowDialog();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeatherForecast.Models;
namespace WeatherForecast.Json
{
public interface IForecastService
{
Task<Forecast> GetJsonFromUrl(SearchCity city);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using SpriteCraft;
namespace Game
{
public class Character : IOnUpdate
{
private const double WALKING_SPEED = 250;
private const double WALKING_TOLERANCE = 8;
private const int DEFAULT_FRAME_NUMBER = 36;
private double m_Walkto_X;
private double m_Walkto_Y;
private int m_Frame_Skipping;
private int m_LeftRight;
private int m_UpDown;
private ISprite m_Character;
public int Frame_Skipping
{
get { return m_Frame_Skipping; }
set { m_Frame_Skipping = value; }
}
public double Walkto_X
{
get { return m_Walkto_X; }
set { m_Walkto_X = value; }
}
public double Walkto_Y
{
get { return m_Walkto_Y; }
set { m_Walkto_Y = value; }
}
public Character(ISprite charactersprite, int srcwidth, int srcheight)
{
m_Frame_Skipping = 0;
m_LeftRight = 0;
m_UpDown = 0;
m_Character = charactersprite;
m_Character.frno = DEFAULT_FRAME_NUMBER;
m_Character.subimpl = this;
m_Character.x = srcwidth / 2 + 200;
m_Character.y = srcheight - m_Character.height;
m_Walkto_X = m_Character.x;
m_Walkto_Y = m_Character.y;
}
public void UpdateWalkingDirection()
{
string output = "";
double adjacent = m_Character.y - m_Walkto_Y;
double oposite = m_Character.x - m_Walkto_X;
adjacent = adjacent == 0 ? 0.1 : adjacent;
double angle = Math.Abs(Math.Atan(adjacent / oposite) * 180 / Math.PI);
output += "adjacent: " + (m_Walkto_Y - m_Character.y);
output += "oposite: " + (m_Walkto_X - m_Character.x);
output += " angle: " + angle;
if (false) {}
else if (oposite < 0 && adjacent < 0)
{
output += " -- 180 -- ";
angle += 180;
}
else if (oposite > 0 && adjacent < 0)
{
output += " -- 270 -- ";
angle += 270;
}
else if (oposite < 0 && adjacent > 0)
{
output += " -- 90 -- ";
angle += 90;
}
else if (oposite > 0 && adjacent > 0)
{
output += " -- 0 -- ";
angle += 0;
}
output += " offset+angle: " + angle;
m_Character.frno = DEFAULT_FRAME_NUMBER;
if (false) { }
else if (angle >= 337.5 && angle < 360 || angle >= 0 && angle < 22.5) // W
{output += " --> W <-- ";
m_Character.frno += 0;
}
else if (angle >= 152.5 && angle < 202.5) // O
{output += " --> O <-- ";
m_Character.frno += 1;
}
//else if (angle >= 247.5 && angle < 292.5) // N
else if (angle >= 67.5 && angle < 112.5) // N
{output += " --> N <-- ";
m_Character.frno += 2;
}
//else if (angle >= 292.5 && angle < 337.5) // NO
else if (angle >= 112.5 && angle < 157.5) // NO
{output += " --> NO <-- ";
m_Character.frno += 3;
}
//else if (angle >= 202.5 && angle < 247.5) // NW
else if (angle >= 22.5 && angle < 67.5) // NW
{output += " --> NW <-- ";
m_Character.frno += 4;
}
//else if (angle >= 67.5 && angle < 112.5) // S
else if (angle >= 247.5 && angle < 292.5) // S
{output += " --> S <-- ";
m_Character.frno += 5;
}
//else if (angle >= 112.5 && angle < 157.5) // SW
else if (angle >= 292.5 && angle < 337.5) // SW
{output += " --> SW <-- ";
m_Character.frno += 7;
}
//else if (angle >= 22.5 && angle < 67.5) // SO
else if (angle >= 202.5 && angle < 247.5) // SO
{output += " --> SO <-- ";
m_Character.frno += 6;
}
else
{ output += " --> ??? <-- "; }
/*
if (false) { }
else if (m_LeftRight < 0 && m_UpDown == 0) // W
{
m_Character.frno += 0;
}
else if (m_LeftRight > 0 && m_UpDown == 0) // O
{
m_Character.frno += 1;
}
else if (m_LeftRight == 0 && m_UpDown < 0) // N
{
m_Character.frno += 2;
}
else if (m_LeftRight > 0 && m_UpDown < 0) // NO
{
m_Character.frno += 3;
}
else if (m_LeftRight < 0 && m_UpDown < 0) // NW
{
m_Character.frno += 4;
}
else if (m_LeftRight == 0 && m_UpDown > 0) // S
{
m_Character.frno += 5;
}
else if (m_LeftRight < 0 && m_UpDown > 0) // SW
{
m_Character.frno += 6;
}
else if (m_LeftRight > 0 && m_UpDown > 0) // SO
{
m_Character.frno += 7;
}
*/
System.Diagnostics.Debug.WriteLine(output);
}
private void ComputeLeftRight()
{
}
#region IOnUpdate Members
public void OnUpdate(ISprite sprite, int tickdelta)
{
m_Character.visible = true;
// Differenzen berechnen
double xDiff = Math.Abs(m_Walkto_X - m_Character.x);
double yDiff = Math.Abs(m_Walkto_Y - m_Character.y);
// Restliche Strecke berechnen (Pythagoras)
double dblRemain = Math.Sqrt(Math.Pow(xDiff, 2) + Math.Pow(yDiff, 2));
double dblStep = 0;
// Falls noch Weg zurückgelegt werden muss
if (dblRemain > (WALKING_TOLERANCE))
{
dblStep = ((WALKING_SPEED * tickdelta) / 1000.0);
m_Character.x = (float)(m_Character.x + ((dblStep * xDiff) / dblRemain) * m_LeftRight);
m_Character.y = (float)(m_Character.y + ((dblStep * yDiff) / dblRemain) * m_UpDown);
}
// Defining current speed directions.
m_LeftRight = 0;
m_UpDown = 0;
// We're using default key mapping rules (see the key definitions above).
if (m_Walkto_X < m_Character.x) { m_LeftRight = -1; }
if (m_Walkto_X > m_Character.x) { m_LeftRight = 1; }
if (m_Walkto_Y < m_Character.y) { m_UpDown = -1; }
if (m_Walkto_Y > m_Character.y) { m_UpDown = 1; }
if (Math.Abs(m_Walkto_X - m_Character.x) < (tickdelta / 10)) { m_LeftRight = 0; }
if (Math.Abs(m_Walkto_Y - m_Character.y) < (tickdelta / 10)) { m_UpDown = 0; }
if (dblRemain < WALKING_TOLERANCE) { m_UpDown = 0; m_LeftRight = 0; }
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Library.Interfaces;
using Library.Model;
using Microsoft.EntityFrameworkCore;
namespace Data.Repositories
{
public class UserRepository : IUserRepository
{
private readonly Entities.Project2Context _context;
public UserRepository(Entities.Project2Context context)
{
_context = context;
}
public async Task AddUser(User user)
{
Entities.User newUser = new Entities.User
{
Username = user.Username,
Password = user.Password,
};
await _context.AddAsync(newUser);
await _context.SaveChangesAsync();
}
/*public async Task DeleteUser(User user)
{
throw new NotImplementedException();
}*/
public async Task<User> GetUserByID(int id)
{
Entities.User query;
try
{
query = await _context.Users
.Include(f => f.FriendUsers)
.FirstAsync(x => x.Id == id);
}
catch
{
throw new ArgumentException("Could not find user with that ID");
}
User user = new User
{
Id = query.Id,
Username = query.Username,
Password = query.Password,
Friends = query.FriendUsers.Select(x => x.FriendId).ToList()
};
return user;
}
public async Task<User> GetUserByUsername(string username)
{
Entities.User query;
try
{
query = await _context.Users
.Include(f => f.FriendUsers)
.FirstAsync(x => x.Username == username);
}
catch
{
throw new ArgumentException("Could not find user with that username");
}
User user = new User
{
Id = query.Id,
Username = query.Username,
Password = query.Password,
Friends = query.FriendUsers.Select(x => x.FriendId).ToList()
};
return user;
}
public async Task<List<User>> GetAllUsers()
{
List<User> users = new List<User>();
var query = await _context.Users
.Include(f => f.FriendUsers)
.ToListAsync();
foreach(var user in query)
{
users.Add(new User
{
Id = user.Id,
Username = user.Username,
Password = user.Password,
Friends = user.FriendUsers.Select(x => x.FriendId).ToList()
});
}
return users;
}
public async Task<bool> CheckUserInfoExists(string userName, string passwordInput)
{
bool exists = false;
var allUsers = await _context.Users
.Where(u => u.Username == userName && u.Password == passwordInput).ToListAsync();
foreach (var c in allUsers)
{
exists = true;
}
return exists;
}
/// <summary>
/// Update a users Friends list/password/username
/// </summary>
/// <param name="user">User to update</param>
/// <returns></returns>
public async Task UpdateUser(User user)
{
var query = await _context.Users
.Include(f => f.FriendUsers)
.FirstAsync(x => x.Id == user.Id);
if (query != null)
{
query.Username = user.Username;
query.Password = user.Password;
query.FriendUsers = user.Friends.Select(x => new Entities.Friend
{
UserId = user.Id,
FriendId = x
}).ToList();
await _context.SaveChangesAsync();
}
else
{
throw new ArgumentException("Couldn't find user to update");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MandachordEncode
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern bool GetCursorPos(ref Point lpPoint);
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
//Mouse actions
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
[DllImport("user32.dll")]
static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint);
[DllImport("user32.dll")]
internal static extern uint SendInput(uint nInputs, [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs, int cbSize);
#pragma warning disable 649
internal struct INPUT
{
public UInt32 Type;
public MOUSEKEYBDHARDWAREINPUT Data;
}
[StructLayout(LayoutKind.Explicit)]
internal struct MOUSEKEYBDHARDWAREINPUT
{
[FieldOffset(0)]
public MOUSEINPUT Mouse;
}
internal struct MOUSEINPUT
{
public Int32 X;
public Int32 Y;
public UInt32 MouseData;
public UInt32 Flags;
public UInt32 Time;
public IntPtr ExtraInfo;
}
#pragma warning restore 649
public static void ClickOnPoint(IntPtr wndHandle, Point clientPoint)
{
var oldPos = Cursor.Position;
/// get screen coordinates
ClientToScreen(wndHandle, ref clientPoint);
/// set cursor on coords, and press mouse
Cursor.Position = new Point(clientPoint.X, clientPoint.Y);
var inputMouseDown = new INPUT();
inputMouseDown.Type = 0; /// input type mouse
inputMouseDown.Data.Mouse.Flags = 0x0002; /// left button down
var inputMouseUp = new INPUT();
inputMouseUp.Type = 0; /// input type mouse
inputMouseUp.Data.Mouse.Flags = 0x0004; /// left button up
var inputs = new INPUT[] { inputMouseDown, inputMouseUp };
SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
/// return mouse
Cursor.Position = oldPos;
}
string encode_wheel = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()[];',./¢£€¥ƒ¤¡¿ÇçŒœßØøÅ寿ÞþÐð«»‹›ŠšŽžàèìòùÀÈÌÒÙáéíóúÁÉÍÓÚÝý";
public Form1()
{
InitializeComponent();
}
private void btnRead_Click(object sender, EventArgs e)
{
string result = "";
Process[] pr = Process.GetProcesses();
Debug.WriteLine(pr.Length);
Process p = null;
foreach (Process prc in pr)
{
//Debug.WriteLine(prc.ProcessName);
if (prc.ProcessName.ToLower().Contains("warframe"))
{
p = prc;
}
}
if (p != null)
{
SetForegroundWindow(p.MainWindowHandle);
string exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
string argsPath = "args.txt";
ExtractResource("MandachordEncode.activate.txt", argsPath);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
Process ahk = Process.Start(startInfo);
ahk.WaitForExit();
//Run first loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop1.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
result = result + ReadSec( 707, 662, -25, -30) + ":";
result = result + ReadSec( 725, 649, -22, -32) + ":";
result = result + ReadSec( 744, 637, -19, -34) + ":";
result = result + ReadSec( 763, 626, -16, -36) + ":";
result = result + ReadSec( 782, 619, -12, -37) + ":";
result = result + ReadSec( 804, 612, - 9, -38) + ":";
result = result + ReadSec( 825, 608, - 5, -39) + ":";
result = result + ReadSec( 846, 606, - 2, -40) + ":";
result = result + ReadSec( 867, 606, 2, -40) + ":";
result = result + ReadSec( 888, 606, 5, -39) + ":";
result = result + ReadSec( 910, 612, 9, -38) + ":";
result = result + ReadSec( 930, 619, 12, -37) + ":";
result = result + ReadSec( 950, 626, 16, -36) + ":";
result = result + ReadSec( 969, 637, 19, -34) + ":";
result = result + ReadSec( 987, 649, 22, -32) + ":";
result = result + ReadSec(1003, 662, 25, -30);
result = result + ":";// + ":";
//Run second loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop2.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
result = result + ReadSec(707, 662, -25, -30) + ":";
result = result + ReadSec(725, 649, -22, -32) + ":";
result = result + ReadSec(744, 637, -19, -34) + ":";
result = result + ReadSec(763, 626, -16, -36) + ":";
result = result + ReadSec(782, 619, -12, -37) + ":";
result = result + ReadSec(804, 612, -9, -38) + ":";
result = result + ReadSec(825, 608, -5, -39) + ":";
result = result + ReadSec(846, 606, -2, -40) + ":";
result = result + ReadSec(867, 606, 2, -40) + ":";
result = result + ReadSec(888, 606, 5, -39) + ":";
result = result + ReadSec(910, 612, 9, -38) + ":";
result = result + ReadSec(930, 619, 12, -37) + ":";
result = result + ReadSec(950, 626, 16, -36) + ":";
result = result + ReadSec(969, 637, 19, -34) + ":";
result = result + ReadSec(987, 649, 22, -32) + ":";
result = result + ReadSec(1003, 662, 25, -30);
result = result + ":";// + ":";
//Run third loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop3.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
result = result + ReadSec(707, 662, -25, -30) + ":";
result = result + ReadSec(725, 649, -22, -32) + ":";
result = result + ReadSec(744, 637, -19, -34) + ":";
result = result + ReadSec(763, 626, -16, -36) + ":";
result = result + ReadSec(782, 619, -12, -37) + ":";
result = result + ReadSec(804, 612, -9, -38) + ":";
result = result + ReadSec(825, 608, -5, -39) + ":";
result = result + ReadSec(846, 606, -2, -40) + ":";
result = result + ReadSec(867, 606, 2, -40) + ":";
result = result + ReadSec(888, 606, 5, -39) + ":";
result = result + ReadSec(910, 612, 9, -38) + ":";
result = result + ReadSec(930, 619, 12, -37) + ":";
result = result + ReadSec(950, 626, 16, -36) + ":";
result = result + ReadSec(969, 637, 19, -34) + ":";
result = result + ReadSec(987, 649, 22, -32) + ":";
result = result + ReadSec(1003, 662, 25, -30);
result = result + ":";// + ":";
//Run fourth loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop4.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
result = result + ReadSec(707, 662, -25, -30) + ":";
result = result + ReadSec(725, 649, -22, -32) + ":";
result = result + ReadSec(744, 637, -19, -34) + ":";
result = result + ReadSec(763, 626, -16, -36) + ":";
result = result + ReadSec(782, 619, -12, -37) + ":";
result = result + ReadSec(804, 612, -9, -38) + ":";
result = result + ReadSec(825, 608, -5, -39) + ":";
result = result + ReadSec(846, 606, -2, -40) + ":";
result = result + ReadSec(867, 606, 2, -40) + ":";
result = result + ReadSec(888, 606, 5, -39) + ":";
result = result + ReadSec(910, 612, 9, -38) + ":";
result = result + ReadSec(930, 619, 12, -37) + ":";
result = result + ReadSec(950, 626, 16, -36) + ":";
result = result + ReadSec(969, 637, 19, -34) + ":";
result = result + ReadSec(987, 649, 22, -32) + ":";
result = result + ReadSec(1003, 662, 25, -30);
Debug.WriteLine(result);
DoMouseClick(1660, 580);
this.Activate();
//ClickOnPoint(p.MainWindowHandle, new Point(1660, 580));
string encoded = Encode(result);
Debug.WriteLine(encoded);
string decoded = Decode(encoded);
Debug.WriteLine(decoded);
txtSong.Text = encoded;
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
Process[] pr = Process.GetProcesses();
Debug.WriteLine(pr.Length);
Process p = null;
foreach (Process prc in pr)
{
//Debug.WriteLine(prc.ProcessName);
if (prc.ProcessName.ToLower().Contains("warframe"))
{
p = prc;
}
}
if (p != null)
{
SetForegroundWindow(p.MainWindowHandle);
string exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
string argsPath = "args.txt";
ExtractResource("MandachordEncode.activate.txt", argsPath);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
Process ahk = Process.Start(startInfo);
ahk.WaitForExit();
string song = Decode(txtSong.Text);
string[] lines = song.Split(':');
string write = "";
int start = 0;
int end = 0;
//Write song part 1
//Run first loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop1.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
write = "";
start = 0;
end = 16;
for (int i = start; i < end; i++)
{
write = write + lines[i];
if (i != end - 1)
{
write = write + ":";
}
}
File.WriteAllText(@"song.txt", write);
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.write1.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
//Write song part 2
//Run second loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop2.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
write = "";
start = 16;
end = 32;
for (int i = start; i < end; i++)
{
write = write + lines[i];
if (i != end - 1)
{
write = write + ":";
}
}
File.WriteAllText(@"song.txt", write);
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.write1.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
//Write song part 3
//Run third loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop3.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
write = "";
start = 32;
end = 48;
for (int i = start; i < end; i++)
{
write = write + lines[i];
if (i != end - 1)
{
write = write + ":";
}
}
File.WriteAllText(@"song.txt", write);
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.write1.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
//Write song part 4
//Run fourth loop
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.loop4.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
write = "";
start = 48;
end = 64;
for (int i = start; i < end; i++)
{
write = write + lines[i];
if (i != end - 1)
{
write = write + ":";
}
}
File.WriteAllText(@"song.txt", write);
exePath = "embedded.exe";
ExtractResource("MandachordEncode.embedded.exe", exePath);
argsPath = "args.txt";
ExtractResource("MandachordEncode.write1.txt", argsPath);
startInfo = new ProcessStartInfo();
startInfo.FileName = @exePath;
startInfo.Arguments = @argsPath;
ahk = Process.Start(startInfo);
ahk.WaitForExit();
this.Activate();
}
}
private string ReadSec(int px, int py, int dx, int dy)
{
string result = "";
//Debug.WriteLine("Part 1:");
for (int i = 0; i < 13; i++)
{
int x = px + dx * i;
int y = py + dy * i;
Point p = new Point(x, y);
Color c = GetColorAt(p);
//Debug.Write(c);
int R = c.R;
int G = c.G;
int B = c.B;
/*if (i >= 0 && i < 5)
{
if ((R >= 98 && R <= 118) && (G >= 47 && G <= 67) && (B >= 104 && B <= 124))
{
result = result + "1";
}
else
{
result = result + "0";
}
}
if (i >= 5 && i < 10)
{
if ((R >= 30 && R <= 50) && (G >= 79 && G <= 99) && (B >= 104 && B <= 124))
{
result = result + "1";
}
else
{
result = result + "0";
}
}
if (i >= 10)
{
if ((R >= 81 && R <= 141) && (G >= 81 && G <= 101) && (B >= 81 && B <= 101))
{
result = result + "1";
}
else
{
result = result + "0";
}
}*/
if (i != 12)
{
if (G >= 47 && B >= 60)
{
result = result + "1";
}
else
{
result = result + "0";
}
}
else
{
if (G >= 47 && G >= 89 && B >= 60)
{
result = result + "1";
}
else
{
result = result + "0";
}
}
if (i == 12)
{
Debug.WriteLine(R + ", " + G + ", " + B);
}
/*switch (i)
{
case (0):
lblm1.BackColor = c;
break;
case (1):
lblm2.BackColor = c;
break;
case (2):
lblm3.BackColor = c;
break;
case (3):
lblm4.BackColor = c;
break;
case (4):
lblm5.BackColor = c;
break;
case (5):
lblb1.BackColor = c;
break;
case (6):
lblb2.BackColor = c;
break;
case (7):
lblb3.BackColor = c;
break;
case (8):
lblb4.BackColor = c;
break;
case (9):
lblb5.BackColor = c;
break;
case (10):
lblp1.BackColor = c;
break;
case (11):
lblp2.BackColor = c;
break;
case (12):
lblp3.BackColor = c;
break;
}*/
}
return result;
}
Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
public Color GetColorAt(Point location)
{
using (Graphics gdest = Graphics.FromImage(screenPixel))
{
using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero))
{
IntPtr hSrcDC = gsrc.GetHdc();
IntPtr hDC = gdest.GetHdc();
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
}
}
return screenPixel.GetPixel(0, 0);
}
public void DoMouseClick(uint X, uint Y)
{
//Call the imported function with the cursor's current position
//uint X = Cursor.Position.X;
//uint Y = Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}
void ExtractResource(string resource, string path)
{
Stream stream = GetType().Assembly.GetManifestResourceStream(resource);
byte[] bytes = new byte[(int)stream.Length];
stream.Read(bytes, 0, bytes.Length);
File.WriteAllBytes(path, bytes);
}
private string Encode(string result)
{
string encoded = "";
string[] lines = result.Split(':');
foreach (string line in lines)
{
encoded = encoded + EncodeText(line);
}
return encoded;
}
private string Decode(string encoded)
{
string decoded = "";
bool toggle = false;
foreach (char c in encoded.ToCharArray())
{
int d = AsciiToInt(c);
if (toggle == false)
{
decoded = decoded + DecodeText(d, 7);
}
else
{
decoded = decoded + DecodeText(d, 6) + ":";
}
toggle = !toggle;
}
return decoded;
}
private string EncodeText(string line)
{
int num1 = 0;
int num2 = 0;
char[] c = line.ToCharArray();
if (c[0] == '1')
{
num1 += 64;
}
if (c[1] == '1')
{
num1 += 32;
}
if (c[2] == '1')
{
num1 += 16;
}
if (c[3] == '1')
{
num1 += 8;
}
if (c[4] == '1')
{
num1 += 4;
}
if (c[5] == '1')
{
num1 += 2;
}
if (c[6] == '1')
{
num1 += 1;
}
if (c[7] == '1')
{
num2 += 32;
}
if (c[8] == '1')
{
num2 += 16;
}
if (c[9] == '1')
{
num2 += 8;
}
if (c[10] == '1')
{
num2 += 4;
}
if (c[11] == '1')
{
num2 += 2;
}
if (c[12] == '1')
{
num2 += 1;
}
string encode = "";
encode = "" + IntToAscii(num1) + IntToAscii(num2);
return encode;
}
private string DecodeText(int text, int size)
{
string ret = "";
int size2 = text;
if (size == 7)
{
if (size2 / 64 > 0)
{
ret = ret + "1";
size2 -= 64;
}
else
{
ret = ret + "0";
}
}
if (size2 / 32 > 0)
{
ret = ret + "1";
size2 -= 32;
}
else
{
ret = ret + "0";
}
if (size2 / 16 > 0)
{
ret = ret + "1";
size2 -= 16;
}
else
{
ret = ret + "0";
}
if (size2 / 8 > 0)
{
ret = ret + "1";
size2 -= 8;
}
else
{
ret = ret + "0";
}
if (size2 / 4 > 0)
{
ret = ret + "1";
size2 -= 4;
}
else
{
ret = ret + "0";
}
if (size2 / 2 > 0)
{
ret = ret + "1";
size2 -= 2;
}
else
{
ret = ret + "0";
}
if (size2 / 1 > 0)
{
ret = ret + "1";
size2 -= 1;
}
else
{
ret = ret + "0";
}
//Debug.WriteLine(text + " -> " + ret);
return ret;
}
private char IntToAscii (int i)
{
return encode_wheel.ToCharArray()[i];
}
private int AsciiToInt (char a)
{
char[] c = encode_wheel.ToCharArray();
int pos = 0;
foreach(char ch in c)
{
if (a == ch)
{
return pos;
}
pos++;
}
return 0;
}
}
}
|
namespace com.Sconit.Web.Controllers.WMS
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.SYS;
using com.Sconit.Service;
using Telerik.Web.Mvc;
using System.Web.Routing;
using com.Sconit.Web.Models;
using com.Sconit.Utility;
using com.Sconit.Web.Models.SearchModels.WMS;
using com.Sconit.Entity.WMS;
public class PickResultController : WebAppBaseController
{
#region 拣货结果
private static string selectCountStatement = "select count(*) from PickResult as p";
private static string selectStatement = "select p from PickResult as p";
[SconitAuthorize(Permissions = "Url_PickResult_View")]
public ActionResult Index()
{
return View();
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="searchModel"></param>
/// <returns></returns>
[GridAction]
[SconitAuthorize(Permissions = "Url_PickResult_View")]
public ActionResult List(GridCommand command, PickResultSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="searchModel"></param>
/// <returns></returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_PickResult_View")]
public ActionResult _AjaxList(GridCommand command, PickResultSearchModel searchModel)
{
SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel);
return PartialView(GetAjaxPageData<PickResult>(searchStatementModel, command));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[SconitAuthorize(Permissions = "Url_PickResult_Edit")]
public ActionResult New()
{
return View();
}
/// <summary>
///
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
[HttpGet]
[SconitAuthorize(Permissions = "Url_PickResult_Edit")]
public ActionResult Edit(string id)
{
if (string.IsNullOrEmpty(id))
{
return HttpNotFound();
}
else
{
PickResult pickSchedule = base.genericMgr.FindById<PickResult>(id);
return View(pickSchedule);
}
}
private SearchStatementModel PrepareSearchStatement(GridCommand command, PickResultSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
HqlStatementHelper.AddLikeStatement("OrderNo", searchModel.OrderNo, HqlStatementHelper.LikeMatchMode.Start, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Location", searchModel.Location, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Item", searchModel.Item, "p", ref whereStatement, param);
if (searchModel.DateFrom != null)
{
HqlStatementHelper.AddGeStatement("CreateDate", searchModel.DateFrom, "p", ref whereStatement, param);
}
else if (searchModel.DateTo != null )
{
HqlStatementHelper.AddLeStatement("CreateDate", searchModel.DateTo, "p", ref whereStatement, param);
}
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Narcyzo_pomagacz
{
public class PdfExtraction
{
public List<ExtractionRecord> extractionList;
public string date;
public string targetName;
public PdfExtraction(List<ExtractionRecord> _extractionList, string _date, string _targetName)
{
extractionList = _extractionList;
date = _date;
targetName = _targetName;
}
}
public class ExtractionRecord
{
public short id { get; set; }
public string name { get; set; }
public int KRS { get; set; }
public List<int> years { get; set; }
public ExtractionRecord(short _id, string _name, int _KRS, List<int> _years)
{
id = _id;
name = _name;
KRS = _KRS;
years = _years;
}
public string GetYearsString()
{
string yearsOut = "";
for (int i = 0; i < years.Count - 1; i++)
{
yearsOut += string.Format("{0}, ", (years[i] + 2000).ToString());
}
yearsOut += years.Last() + 2000;
return yearsOut;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace S3.AutoBatcher.UnitTests
{
public partial class BatchTests
{
private class TestContext:IBatchChunkProcessor<string>
{
public readonly AutoResetEvent BatchExecutedEvent = new AutoResetEvent(false);
private TimeSpan _enlistAwaitTimeout = TimeSpan.FromMilliseconds(125);
private Batch<string> _sut;
private readonly List<ConcurrentBag<string>> _chunks=new List<ConcurrentBag<string>>();
private int _batchSize;
private int? _failingOnBatchNumber;
public IReadOnlyList<ConcurrentBag<string>> ExecutedChunks => _chunks;
public Batch<string> Sut => _sut ??= BuildSut();
private int _batchCount;
private int _numberOfFailuresOnRetry;
private ErrorResult? _errorResult;
private Batch<string> BuildSut()
{
return new Batch<string>(new BatchConfiguration<string>
{
AddMoreItemsTimeWindow = _enlistAwaitTimeout,
ChunkSize=_batchSize
},this);
}
public TestContext SetEnlistAwait(TimeSpan timeout)
{
_enlistAwaitTimeout = timeout;
return this;
}
public Task Process(IReadOnlyCollection<string> chunkItems, CancellationToken cancellationToken)
{
if (_failingOnBatchNumber == Interlocked.Increment(ref _batchCount))
{
throw new Exception($"fail on batch #:{_batchCount}");
}
AddChunk(chunkItems);
BatchExecutedEvent.Set();
BatchExecutedEvent.Reset();
return Task.CompletedTask;
}
private void AddChunk(IReadOnlyCollection<string> chunkItems)
{
if (chunkItems.Count > 0)
{
var current = new ConcurrentBag<string>();
_chunks.Add(current);
foreach (var request in chunkItems)
{
current.Add(request);
}
}
}
public ErrorResult HandleError(IReadOnlyCollection<string> chunkItems, Exception exception, int currentAttemptNumber)
{
if(_errorResult!=ErrorResult.Retry)
return _errorResult.Value;
if (--_numberOfFailuresOnRetry > 0)
return _errorResult.Value;
else
{
AddChunk(chunkItems);
return ErrorResult.Continue;
}
}
public TestContext WithBatchSize(int batchSize)
{
_batchSize = batchSize;
return this;
}
public TestContext FailingOnBatchNumber(int failingOnBatchNumber, ErrorResult errorResult,int numberOfFailuresOnRetry)
{
_failingOnBatchNumber = failingOnBatchNumber;
_numberOfFailuresOnRetry = numberOfFailuresOnRetry;
_errorResult = errorResult;
return this;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BugTracker.DataAccessLayer;
namespace BugTracker.BusinessLayer
{
class PerfilService
{
PerfilDao oPerfilDao = new PerfilDao();
}
}
|
namespace TripDestination.Services.Data.Contracts
{
using System.Linq;
using TripDestination.Data.Models;
public interface IUserCommentServices
{
IQueryable<UserComment> GetAll();
UserComment Edit(int id, string text);
void Delete(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using StoreFront.Models;
using System.Web.Security;
namespace StoreFront.Controllers
{
public class UsersController : Controller
{
private StoreFrontEntities db = new StoreFrontEntities();
// Login Action
public ActionResult Index()
{
return View();
}
public ActionResult Login(User user)
{
var query = (from u in db.Users where u.UserName == user.UserName select u).FirstOrDefault();
if (db.Users.Any(x => x.UserName == user.UserName && x.EmailAddress == user.EmailAddress))
{
string usr = user.UserName;
Session["name"] = usr;
Session["id"] = query.UserID;
Session["admin"] = query.IsAdmin;
if (query.IsAdmin == true)
{
return Redirect("~/Default.aspx");
}
else
{
return RedirectToAction("Welcome");
}
}
else
return View("Index");
}
//Register Action
public ActionResult Create()
{
return View();
}
public ActionResult Register(User user)
{
if (ModelState.IsValid)
{
user.DateCreated = DateTime.Now;
user.IsAdmin = false;
user.DateModified = DateTime.Now;
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View("Create");
}
public ActionResult AutoComplete(string term)
{
var product = db.Products
.Where(r => r.ProductName.StartsWith(term))
.Take(10)
.Select(r => new
{
label = r.ProductName
});
return Json(product, JsonRequestBehavior.AllowGet);
}
//Welcome Page
public ActionResult Welcome(string searchTerm = null)
{
//var product = db.Products.OrderBy(r => r.ProductName).Where(r => r.ProductName.Contains(searchTerm) || r => searchTerm == null).Select r;
var product = from r in db.Products
orderby r.ProductName ascending
where (r.ProductName.Contains(searchTerm) || searchTerm == null)
select r;
if(Request.IsAjaxRequest())
{
return PartialView("ProductsList", product);
}
return View(product.ToList());
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return View("Index");
}
User user = db.Users.Find(id);
if (user == null)
{
return View("Index");
}
return View(user);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomMovementSphere : MonoBehaviour
{
public Rigidbody rb;
public Vector3 direccionRandom;
public float speed = 4;
public float ultimoCambioDireccion = 0;
public float tiempoCambioDireccion = 1;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Time.time - ultimoCambioDireccion > tiempoCambioDireccion)
{
direccionRandom = new Vector3(Random.onUnitSphere.x * 2, 0, Random.onUnitSphere.z * 2); // genera una posición nueva, aleatoriamente
ultimoCambioDireccion = Time.time;
}
// aplica la dirección en cada frame al rigidbody
rb.MovePosition(rb.position + direccionRandom * Time.fixedDeltaTime * speed);
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using OnlineClinic.Data.Entities;
using System.Threading.Tasks;
namespace OnlineClinic.Data.Repositories
{
public class Repository<T> : IRepository<T> where T : Entity
{
protected readonly OnlineClinicDbContext _context;
protected readonly DbSet<T> _dbSet;
public Repository(OnlineClinicDbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public virtual IEnumerable<T> GetAll(bool asNoTracking = true) => asNoTracking? _dbSet.AsNoTracking().AsEnumerable() : _dbSet.AsEnumerable();
public virtual Task<IEnumerable<T>> GetAllAsync(bool asNoTracking = true) => Task.FromResult<IEnumerable<T>>(asNoTracking? _dbSet.AsNoTracking().AsEnumerable() : _dbSet.AsEnumerable());
public virtual T GetById(int id) => _dbSet.AsNoTracking().FirstOrDefault(s => s.Id == id);
public virtual Task<T> GetByIdAsync(int id) => _dbSet.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id);
public virtual int Create(T entity)
{
entity.DateCreated = DateTime.UtcNow;
_dbSet.Add(entity);
_context.SaveChanges();
return entity.Id;
}
public virtual async Task<int> CreateAsync(T entity)
{
entity.DateCreated = DateTime.UtcNow;
_dbSet.Add(entity);
await _context.SaveChangesAsync();
return entity.Id;
}
public virtual void Update(T entity)
{
var dateCreated = _dbSet.Where(e => e.Id == entity.Id).Select(e => e.DateCreated).FirstOrDefault();
_dbSet.Attach(entity);
var entry = _context.Entry(entity);
entry.State = EntityState.Modified;
entity.DateCreated = dateCreated;
entity.DateModified = DateTime.UtcNow;
_context.SaveChanges();
entry.State = EntityState.Detached;
}
public virtual async Task UpdateAsync(T entity)
{
var dateCreated = _dbSet.Where(e => e.Id == entity.Id).Select(e => e.DateCreated).FirstOrDefault();
_dbSet.Attach(entity);
var entry = _context.Entry(entity);
entry.State = EntityState.Modified;
entity.DateCreated = dateCreated;
entity.DateModified = DateTime.UtcNow;
await _context.SaveChangesAsync();
entry.State = EntityState.Detached;
}
public virtual void Delete(int id)
{
T entity = _dbSet.SingleOrDefault(s => s.Id == id);
_dbSet.Remove(entity);
_context.SaveChanges();
}
public virtual async Task DeleteAsync(int id)
{
T entity = _dbSet.SingleOrDefault(s => s.Id == id);
_dbSet.Remove(entity);
await _context.SaveChangesAsync();
}
public bool Exists(int id) => _dbSet.Find(id) != null;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;
using SanukoLib;
namespace WebGames
{
/// <summary>
/// Interface for WordScramble Game ResultService.
/// </summary>
[ServiceContract]
public interface ILineMatchingResultService
{
/// <summary>
/// Process data from client and send request to service.
/// </summary>
/// <param name="data">List of answers</param>
/// <param name="userSessionID"></param>
/// <param name="gameSessionID"></param>
/// <param name="isGameCompleted"></param>
/// <param name="gameTime"></param>
/// <param name="gameScore"></param>
/// <param name="error"></param>
/// <returns></returns>
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
string Send(List<LineMatchingResult> data, string userSessionID, string gameSessionID, int isGameCompleted, int gameTime, int gameScore, short error);
}
/// <summary>
/// Contract for JSON serialization of game result for WordScramble game.
/// </summary>
[DataContract]
public class LineMatchingResult : ICanBeTransformedToXML
{
/// <summary>
/// Index of first match item.
/// </summary>
[DataMember]
public string fromIndex;
/// <summary>
/// Index of second match item.
/// </summary>
[DataMember]
public string toIndex;
/// <summary>
/// Right flag.
/// </summary>
[DataMember]
public bool isRight;
/// <summary>
/// Interface's method implementation
/// </summary>
public XmlNode transformToXml(XmlDocument document)
{
XmlElement returnValue = document.CreateElement("a");
returnValue.SetAttribute("v", isRight.ToString().ToLower());
XmlElement numFrom = document.CreateElement("num");
numFrom.InnerText = fromIndex;
XmlElement numTo = document.CreateElement("num");
numTo.InnerText = toIndex; ;
returnValue.AppendChild(numFrom);
returnValue.AppendChild(numTo);
return returnValue;
}
}
/// <summary>
/// A service for gathering result from WordScramble Game.
/// </summary>
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class LineMatchingResultService : BaseResultService, ILineMatchingResultService
{
public string Send(List<LineMatchingResult> data, string userSessionID, string gameSessionID, int isGameCompleted, int gameTime, int gameScore, short error)
{
string resultXml = "";
try
{
XmlDocument document = transformToXml<LineMatchingResult>(data);
resultXml = document.InnerXml;
GameServiceProxy GSP = new GameServiceProxy(EGameType.GT_LINE_MATCHING, "", userSessionID, gameSessionID, null);
GSP.updateResults(isGameCompleted, gameTime, gameScore, error, document.InnerXml);
return "OK";
}
catch (Exception e)
{
return "FAIL";
}
}
}
}
|
using Flux.src.Flux.Renderer;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace Flux.src.Platform.OpenGL
{
public class OpenGLTriangle : IShape
{
readonly float[] vertices =
{
//Position Texture coordinates
0.0f, 0.5f, 0.0f, 0.5f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, // bottom left
};
public VertexArray vao;
internal OpenGLTriangle()
{
Init();
}
private void Init()
{
vao = VertexArray.Create();
VertexBuffer vbo = VertexBuffer.Create(vertices);
BufferLayout bl = new BufferLayout
{
{ShaderDataType.Float3, "position"},
{ShaderDataType.Float2, "texture" }
};
bl.CalculateOffsetsAndStride();
vbo.SetLayout(bl);
vao.AddVertexBuffer(vbo);
}
public void Draw()
{
vao.Bind();
GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
}
}
}
|
using BLL;
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2.controls
{
public partial class ctrl_registeration : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
// (CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email") as TextBox).Visible = false;
(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Question") as TextBox).Visible = false;
(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Answer") as TextBox).Visible = false;
}
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
}
protected void ContinueButton_Click(object sender, EventArgs e)
{
//AppManager userActions = new AppManager();
//userActions.userDetails.Register(sender);
}
protected void CreateUserWizard1_CreatedUser1(object sender, EventArgs e)
{
var user = Membership.GetUser((sender as CreateUserWizard).UserName).ProviderUserKey;
Guid userId = (Guid)user;
AppManager userActions = new AppManager();
User_Details user_Details = new User_Details();
user_Details.Id = userId;
userActions.userDetails.Add(user_Details);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using birdepobenzin.dataaccess;
using birdepobenzin.web.Helper;
namespace birdepobenzin.web.Controllers
{
public class HomeController : Controller
{
public string SessionCaptcha
{
get
{
return Session["Captcha"] != null ? Session["Captcha"].ToString() : string.Empty;
}
set
{
Session["Captcha"] = value;
}
}
public ActionResult Index()
{
return View();
}
public ActionResult GasCalculate(string contentUrl, string cityUrl)
{
if (!string.IsNullOrEmpty(contentUrl))
{
ViewData["header"] = contentUrl + " yakıt hesaplama";
}
if (!string.IsNullOrEmpty(cityUrl))
{
ViewData["header"] = cityUrl + " mesafe/yakıt hesaplama";
ViewData["city"] = cityUrl;
}
if (Request.QueryString["f"] != null && Request.QueryString["t"] != null && !string.IsNullOrEmpty(Request.RawUrl))
{
ViewBag.Show = 1;
//string s = Microsoft.JScript.GlobalObject.unescape(Request.RawUrl.Substring(Request.RawUrl.IndexOf("?")));
string s = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("?")));
ViewBag.Desc = string.Format("{0} - {1}", HtmlHelperExtensions.GetQueryString("f", s), HtmlHelperExtensions.GetQueryString("t", s));
}
return View();
}
public ActionResult TaxiCalculate()
{
return View();
}
public ActionResult RoadMap()
{
return View();
}
public ActionResult Filter()
{
return View();
}
public ActionResult FilterWizard()
{
return View();
}
public ActionResult PreFilter()
{
return View();
}
public ActionResult LastSearches()
{
birdepobenzin.dataaccess.Entities ents = new Entities();
return View(ents.LASTSEARCHES.OrderByDescending(s=>s.CreDate).Take(500).ToList());
}
[ActionName("iletisim")]
[HttpGet]
public ActionResult ContactPage()
{
return View("ContactPage");
}
[ActionName("iletisim")]
[HttpPost]
public ActionResult ContactPagePost(string subject, string email, string name, string lastname, string body, string captcha)
{
if (string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(lastname) || string.IsNullOrEmpty(body) || string.IsNullOrEmpty(captcha))
{
ViewData["Error"] = "Lütfen formdaki alanları eksiksiz ve tam doldurunuz.";
return View("ContactPage");
}
if (this.SessionCaptcha != captcha.ToUpper())
{
ViewData["Error"] = "Lütfen resimdeki karakterleri doğrulayınız.";
return View("ContactPage");
}
birdepobenzin.dataaccess.Entities ents = new Entities();
CONTACTPOSTS p = new CONTACTPOSTS();
p.Body = body.Replace("'", string.Empty).Replace("\"", string.Empty);
p.Name = name.Replace("'", string.Empty).Replace("\"", string.Empty);
p.Subject = subject.Replace("'", string.Empty).Replace("\"", string.Empty);
p.Email = email.Replace("'", string.Empty).Replace("\"", string.Empty);
p.LastName = lastname.Replace("'", string.Empty).Replace("\"", string.Empty);
p.IP = !string.IsNullOrEmpty(Request.ServerVariables["REMOTE_ADDR"]) ? (Request.ServerVariables["REMOTE_ADDR"].Length >= 20 ? Request.ServerVariables["REMOTE_ADDR"].Substring(0, 20) : Request.ServerVariables["REMOTE_ADDR"]) : string.Empty;
ents.CONTACTPOSTS.Add(p);
ents.SaveChanges();
ViewData["Success"] = "1";
return View("ContactPage");
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace DgKMS.Cube
{
public class PartyCreateDto
{
/// <summary>
/// Id
/// </summary>
public new long? Id { get; set; }
/// <summary>
/// 操作人
/// </summary>
public long MemberId { get; set; }
/// <summary>
/// 开始时间
/// </summary>
[Required(ErrorMessage = "开始时间不能为空")]
public DateTime StartTime { get; set; }
/// <summary>
/// 结束时间
/// </summary>
[Required(ErrorMessage = "结束时间不能为空")]
public DateTime EndTime { get; set; }
/// <summary>
/// 地址
/// </summary>
[MaxLength(250)]
[Required(ErrorMessage = "地址不能为空")]
public string Address { get; set; }
/// <summary>
/// 电话
/// </summary>
[MaxLength(22)]
[Required(ErrorMessage = "电话不能为空")]
public string Tel { get; set; }
/// <summary>
/// 场所
/// </summary>
[MaxLength(250)]
[Required(ErrorMessage = "场所不能为空")]
public string Place { get; set; }
/// <summary>
/// 花费
/// </summary>
[Required(ErrorMessage = "花费不能为空")]
[Range(typeof(decimal), "0", "1000000.00", ErrorMessage = "金额超出限定范围")]
public decimal Cost { get; set; }
/// <summary>
/// 来源
/// </summary>
[Required(ErrorMessage = "来源不能为空")]
public int Source { get; set; }
/// <summary>
/// 人数
/// </summary>
[Required(ErrorMessage = "人数不能为空")]
[Range(typeof(int), "1", "10000", ErrorMessage = "人数超出限定范围")]
public int Number { get; set; }
/// <summary>
/// 评分
/// </summary>
public decimal LikeLevel { get; set; }
/// <summary>
/// 评分数
/// </summary>
public int LikeCount { get; set; }
/// <summary>
/// 经度
/// </summary>
[Required(ErrorMessage = "经度不能为空")]
public string Longitude { get; set; }
/// <summary>
/// 纬度
/// </summary>
[Required(ErrorMessage = "纬度不能为空")]
public string Latitude { get; set; }
/// <summary>
/// 标题
/// </summary>
[MaxLength(60)]
[Required(ErrorMessage = "标题不能为空")]
public string Title { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; set; }
/// <summary>
/// 修改时间
/// </summary>
public DateTime? LastModificationTime { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Admin_Suppliers_View : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Helper.ValidateAdmin();
if (!IsPostBack)
{
GetSuppliers(txtSearch.Text);
}
this.Form.DefaultButton = this.btnSearch.UniqueID;
}
private void GetSuppliers(string txtSearchText)
{
using (var con = new SqlConnection(Helper.GetCon()))
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = @"SELECT SupplierID, SupplierName, ContactNo, Address,
Status, ContactPerson, DateAdded
FROM Suppliers
WHERE (SupplierID LIKE @keyword OR
SupplierName LIKE @keyword OR
Address LIKE @keyword OR
ContactPerson LIKE @keyword)
AND Status = @status ORDER BY DateAdded DESC";
cmd.Parameters.AddWithValue("@status", ddlStatus.SelectedValue);
cmd.Parameters.AddWithValue("@keyword", "%" + txtSearchText + "%");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
con.Close();
da.Fill(ds, "Suppliers");
lvSuppliers.DataSource = ds;
lvSuppliers.DataBind();
}
}
protected void ddlStatus_OnSelectedIndexChanged(object sender, EventArgs e)
{
GetSuppliers(txtSearch.Text);
}
protected void txtSearch_OnTextChanged(object sender, EventArgs e)
{
GetSuppliers(txtSearch.Text);
}
protected void btnSearch_OnClick(object sender, EventArgs e)
{
GetSuppliers(txtSearch.Text);
}
protected void lvSuppliers_OnDataBound(object sender, EventArgs e)
{
dpSuppliers.Visible = dpSuppliers.PageSize < dpSuppliers.TotalRowCount;
}
protected void lvSuppliers_OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
dpSuppliers.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
GetSuppliers(txtSearch.Text);
}
}
|
using Sentry.Reflection;
namespace Sentry.Internal;
internal static class ApplicationVersionLocator
{
internal static string? GetCurrent(Assembly? asm)
{
if (asm is null)
{
return null;
}
var name = asm.GetName().Name;
var version = asm.GetVersion();
if (string.IsNullOrWhiteSpace(name) ||
string.IsNullOrWhiteSpace(version))
{
return null;
}
// Don't add name prefix if it's already set by the user
if (version.Contains('@'))
{
return version;
}
return $"{name}@{version}";
}
}
|
//---------------------------------------------------------------------------------
// Copyright (c) December 2019, devMobile Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//---------------------------------------------------------------------------------
namespace devMobile.IoT.Rfm9x.ShieldSPI
{
using System;
using System.Threading.Tasks;
using Meadow;
using Meadow.Devices;
using Meadow.Hardware;
public class MeadowApp : App<F7Micro, MeadowApp>
{
const byte RegVersion = 0x42;
ISpiBus spiBus;
SpiPeripheral sx127xDevice;
IDigitalOutputPort chipSelectGpioPin;
IDigitalOutputPort resetGpioPin;
public MeadowApp()
{
Console.WriteLine("Starting devMobile.IoT.Rfm9x.ShieldSPI");
ConfigureSpiPort();
ReadDeviceID();
}
public void ConfigureSpiPort()
{
try
{
var spiClockConfiguration = new SpiClockConfiguration(500, SpiClockConfiguration.Mode.Mode0); // From SemTech docs pg 80 CPOL=0, CPHA=0
spiBus = Device.CreateSpiBus(Device.Pins.SCK,
Device.Pins.MOSI,
Device.Pins.MISO,
spiClockConfiguration);
if (spiBus == null)
{
Console.WriteLine("spiBus == null");
}
Console.WriteLine("Creating SPI NSS Port...");
chipSelectGpioPin = Device.CreateDigitalOutputPort(Device.Pins.D09, initialState:true);
if (chipSelectGpioPin == null)
{
Console.WriteLine("chipSelectGpioPin == null");
}
Console.WriteLine("sx127xDevice Device...");
sx127xDevice = new SpiPeripheral(spiBus, chipSelectGpioPin);
if (sx127xDevice == null)
{
Console.WriteLine("sx127xDevice == null");
}
// Factory reset pin configuration
resetGpioPin = Device.CreateDigitalOutputPort(Device.Pins.D10, true);
if (sx127xDevice == null)
{
Console.WriteLine("resetPin == null");
}
Console.WriteLine("ConfigureSpiPort Done...");
}
catch (Exception ex)
{
Console.WriteLine("ConfigureSpiPort " + ex.Message);
}
}
public void ReadDeviceID()
{
Task.Delay(500).Wait();
while (true)
{
try
{
byte registerValue;
// Works May 2020
registerValue = sx127xDevice.ReadRegister(RegVersion);
// Works May 2020
/*
var txBuffer = new byte[] { RegVersion, 0x0 };
var rxBuffer = new byte[txBuffer.Length];
Console.WriteLine("spiBus.ExchangeData...1");
spiBus.ExchangeData(chipSelectGpioPin, ChipSelectMode.ActiveLow, txBuffer, rxBuffer);
Console.WriteLine("spiBus.ExchangeData...2");
registerValue = rxBuffer[1];
*/
// Doesn't work May 2020 returns Register 0x42 - Value 0X2d - Bits 00101101
/*
byte[] txBuffer = new byte[] { RegVersion, 0x0 };
Console.WriteLine("spiBus.WriteRead...1");
byte[] rxBuffer = sx127xDevice.WriteRead(txBuffer, (ushort)txBuffer.Length);
Console.WriteLine("spiBus.WriteRead...2");
registerValue = rxBuffer[1];
*/
Console.WriteLine("Register 0x{0:x2} - Value 0X{1:x2} - Bits {2}", RegVersion, registerValue, Convert.ToString(registerValue, 2).PadLeft(8, '0'));
}
catch (Exception ex)
{
Console.WriteLine("ReadDeviceID " + ex.Message);
}
Task.Delay(10000).Wait();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AngularSPAWebAPI.Models.DatabaseModels.General
{
public class Afbeelding
{
public int AfbeeldingID { get; set; }
public string URI { get; set; }
public DateTime Create { get; set; }
public string Name { get; set; }
public string Omschrijving { get; set; }
public string Extension { get; set; }
}
}
|
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace AutomatingBackgroundTasks.Interface
{
public partial class WindowAddPattern : Window
{
public WindowAddPattern()
{
InitializeComponent();
}
public WindowAddPattern(string ext): this()
{
Pattern.Text = ext;
}
public string NewExtension { get; set; } = string.Empty;
private void Add_Click(object sender, RoutedEventArgs e)
{
NewExtension = Pattern.Text;
//Pattern.Text = "";
Close();
}
static readonly string[] WrongSymbols =
{
" ",
",",
"\\",
"/",
":",
"\"",
"<",
">",
"|",
};
private void Extension_OnTextInput(object sender, TextCompositionEventArgs e)
{
var newText = Pattern.Text;
foreach (var s in WrongSymbols)
newText = newText.Replace(s, "");
Pattern.Text = newText;
}
private void this_Closing(object sender, CancelEventArgs e)
{
}
private void this_Loaded(object sender, RoutedEventArgs e)
{
Pattern.Focus();
}
private void Extension_OnKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter) {
Add_Click(null, null);
}
}
private void Extension_OnTextChanged(object sender, TextChangedEventArgs e)
{
var newText = Pattern.Text;
foreach (var s in WrongSymbols)
newText = newText.Replace(s, "");
//newText = newText.Replace("..", ".");
Pattern.Text = newText;
}
}
}
|
namespace _01_Regeh
{
using System;
using System.Text;
using System.Text.RegularExpressions;
public class Regeh
{
public static void Main()
{
var input = Console.ReadLine();
var len = input.Length;
var currentIndex = 0;
var builder = new StringBuilder();
string pattern = @"\[[^[< ]+?<([0-9]+?)REGEH([0-9]+?)>[^]> ]+?]";
var matches = Regex.Matches(input, pattern);
if (Regex.IsMatch(input, pattern))
{
foreach (Match match in matches)
{
if (Regex.IsMatch(match.Value, @"\s+")) continue;
currentIndex += int.Parse(match.Groups[1].Value);
builder = AppendChar(input, currentIndex, builder);
currentIndex += int.Parse(match.Groups[2].Value);
builder = AppendChar(input, currentIndex, builder);
}
Console.WriteLine(builder.ToString());
}
}
private static StringBuilder AppendChar(string input, int currentIndex, StringBuilder builder)
{
var len = input.Length;
if (currentIndex < len)
{
builder.Append(input[currentIndex]);
}
else
{
builder.Append(input[currentIndex % len + 1]);
}
return builder;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using TraceWizard.Entities;
using TraceWizard.Adoption;
using TraceWizard.Services;
using TraceWizard.Notification;
using TraceWizard.Environment;
using TraceWizard.Classification;
namespace TraceWizard.TwApp {
public partial class EventPolygon : UserControl, INotifyPropertyChanged {
public Event Event {get; set;}
public double WidthMultiplier;
public double HeightMultiplier;
public Classifier ClassifierDisaggregation;
Events Events { get; set; }
EventsCanvas eventsCanvas;
public EventsCanvas EventsCanvas {
get { return eventsCanvas; }
set {
eventsCanvas = value;
Events = eventsCanvas.Events;
}
}
EventPolygonMenu contextMenu = null;
public static RoutedUICommand HorizontalSplitCommand;
public static RoutedUICommand VerticalSplitCommand;
public static RoutedUICommand SelectCommand;
public static RoutedUICommand AddToSelectionCommand;
public static RoutedUICommand ExtendSelectionCommand;
CommandBinding horizontalSplitCommandBinding;
CommandBinding verticalSplitCommandBinding;
CommandBinding selectCommandBinding;
CommandBinding addToSelectionCommandBinding;
CommandBinding extendSelectionCommandBinding;
Point? MousePosition { get; set; }
public EventPolygon() {
InitializeComponent();
}
public void Initialize() {
InitializePolygon();
InitializeContextMenuCommandBinding();
InitializeSplitCommandBinding();
InitializeSelectCommandBinding();
TerminateZoomCommandBinding();
this.ContextMenuOpening += new ContextMenuEventHandler(eventPolygon_ContextMenuOpening);
this.ContextMenuClosing += new ContextMenuEventHandler(eventPolygon_ContextMenuClosing);
Event.PropertyChanged += new PropertyChangedEventHandler(event_PropertyChanged);
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
void event_PropertyChanged(object sender, PropertyChangedEventArgs e) {
switch (e.PropertyName) {
case TwNotificationProperty.OnEndClassify:
case TwNotificationProperty.OnEndSelect:
Polygon.Fill = GetBrush();
break;
}
}
public Point GetMouseClickPosition() {
if (MousePosition.HasValue)
return MousePosition.Value;
else
return Mouse.GetPosition(Polygon);
}
void eventPolygon_ContextMenuOpening(object sender, ContextMenuEventArgs e) {
MousePosition = Mouse.GetPosition(Polygon);
contextMenu = new EventPolygonMenu();
contextMenu.EventPolygon = this;
contextMenu.ManualClassificationMode = EventsCanvas.ManualClassificationMode;
contextMenu.Initialize();
Polygon.ContextMenu = contextMenu;
}
void eventPolygon_ContextMenuClosing(object sender, ContextMenuEventArgs e) {
MousePosition = null;
}
void InitializePolygon() {
Polygon.SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Aliased);
Polygon.SnapsToDevicePixels = false;
InitializePolygonPath();
InitializePolygonBrush();
InitializeMouse();
Polygon.Tag = Event;
Event.Tag = Polygon;
PositionToolTip();
}
void InitializeMouse() {
this.AllowDrop = true;
this.Drop += new DragEventHandler(polygon_DragDrop);
this.MouseMove += new MouseEventHandler(polygon_MouseMove);
this.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(polygon_PreviewMouseLeftButtonDown);
this.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(polygon_PreviewMouseLeftButtonUp);
this.PreviewMouseMove += new MouseEventHandler(polygon_PreviewMouseMove);
this.MouseEnter += polygon_MouseEnter;
this.MouseLeave += polygon_MouseLeave;
}
void InitializePolygonBrush() {
Polygon.Fill = GetBrush();
Polygon.Stroke = null;
Polygon.StrokeThickness = 0.0;
}
void InitializePolygonPath() {
Polygon.Points.Add(new Point(0 * WidthMultiplier, 0));
foreach (Flow flow in Event) {
Point startPoint = new Point(flow.StartTime.Subtract(Event.StartTime).TotalSeconds * WidthMultiplier,
-flow.Peak * HeightMultiplier);
Polygon.Points.Add(startPoint);
Point endPoint = new Point(startPoint.X + (flow.Duration.TotalSeconds * WidthMultiplier), startPoint.Y);
Polygon.Points.Add(endPoint);
}
Polygon.Points.Add(new Point(Event.Duration.TotalSeconds * WidthMultiplier, 0));
}
Point startPoint = new Point();
void polygon_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
startPoint = e.GetPosition(null);
originatedMouseDown = true;
}
void polygon_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
originatedMouseDown = false;
}
bool originatedMouseDown = false;
void polygon_PreviewMouseMove(object sender, MouseEventArgs e) {
if (e.LeftButton == MouseButtonState.Pressed && ((LinedEventsCanvas)(Parent)).CanStartDragging && originatedMouseDown) {
Point mousePos = e.GetPosition(null);
Vector diff = startPoint - mousePos;
if (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance) {
var eventPolygon = sender as EventPolygon;
var polygon = eventPolygon.Polygon as Polygon;
OnPropertyChanged(TwNotificationProperty.OnStartDrag);
if (eventPolygon.Event.Selected && Events.SelectedEvents.Count > 1) {
var polygons = new List<Polygon>();
foreach(var @event in Events.SelectedEvents)
polygons.Add((Polygon)@event.Tag);
DragDrop.DoDragDrop(polygon, new DataObject(typeof(List<Polygon>), polygons), DragDropEffects.All);
} else
DragDrop.DoDragDrop(polygon, new DataObject(typeof(Polygon), polygon), DragDropEffects.All);
OnPropertyChanged(TwNotificationProperty.OnEndDrag);
originatedMouseDown = false;
}
}
e.Handled = true;
}
void polygon_MouseMove(object sender, MouseEventArgs e) {
if (Properties.Settings.Default.ShowDetailedEventToolTips) {
ShowEventProperties(sender, e, false);
}
}
bool AdoptionRequested() {
return Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)
|| EventsCanvas.ManualClassificationMode == AnalysisPanel.TwManualClassificationMode.WithAdoption;
}
void DispatchDrop(FixtureClass fixtureClass) {
if (fixtureClass != null) {
bool withAdoption = AdoptionRequested();
if (Events.SelectedEvents.Contains(Event))
Events.ManuallyClassify(Events.SelectedEvents, fixtureClass, withAdoption, EventsCanvas.UndoPosition);
else
Events.ManuallyClassify(Event, fixtureClass, withAdoption, EventsCanvas.UndoPosition);
} else {
if (Events.SelectedEvents.Contains(Event))
Events.ManuallyToggleFirstCycle(Events.SelectedEvents, false, null, EventsCanvas.UndoPosition);
else
Events.ManuallyToggleFirstCycle(Event, EventsCanvas.UndoPosition);
}
}
void DispatchDrop(Polygon polygonSource, DragEventArgs e) {
Event eventTarget = Event;
Event eventSource = polygonSource.Tag as Event;
if (eventSource == eventTarget)
return;
if (!Merge(eventSource, eventTarget, e))
MessageBox.Show(
"Cannot merge",
TwAssembly.Title(),
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
bool Merge(Event eventSource, Event eventTarget, DragEventArgs e) {
if (Events.CanMergeVertically(eventSource, eventTarget)) {
DispatchDragMergeVertical(eventSource, eventTarget, e.KeyStates);
} else if (Events.CanMergeHorizontally(eventSource, eventTarget)) {
DispatchDragMergeHorizontal(eventSource, eventTarget, e.KeyStates);
} else
return false;
return true;
}
public int MergeAllVerticallyIntoBase(Event eventTarget, List<Event> events) {
return Events.MergeAllVerticallyIntoBaseWithNotification(eventTarget, events, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
void DispatchDrop(List<Polygon> polygons, DragEventArgs e) {
Event eventTarget = Event;
var events = new List<Event>();
foreach(Polygon polygon in polygons)
events.Add((Event)polygon.Tag);
if (Events.CanMergeAllVerticallyIntoBase(eventTarget, events))
MergeAllVerticallyIntoBase(eventTarget, events);
else
MessageBox.Show(
"Cannot merge all",
TwAssembly.Title(),
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
void polygon_DragDrop(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(typeof(FixtureButton))) {
FixtureButton fixtureButton = e.Data.GetData(typeof(FixtureButton)) as FixtureButton;
DispatchDrop(fixtureButton.FixtureClass);
} else if (e.Data.GetDataPresent(typeof(ShortFixtureLabel))) {
var shortFixtureLabel = e.Data.GetData(typeof(ShortFixtureLabel)) as ShortFixtureLabel;
DispatchDrop(shortFixtureLabel.FixtureClass);
} else if (e.Data.GetDataPresent(typeof(Polygon))) {
DispatchDrop((Polygon)e.Data.GetData(typeof(Polygon)), e);
} else if (e.Data.GetDataPresent(typeof(List<Polygon>))) {
DispatchDrop((List<Polygon>)e.Data.GetData(typeof(List<Polygon>)), e);
}
}
void DispatchDragMergeVertical(Event eventSource, Event eventTarget, DragDropKeyStates keyStates) {
if (keyStates == DragDropKeyStates.ControlKey || ((LinedEventsCanvas)(Parent)).MergeAllIntoBaseMode) {
MergeAllVerticallyIntoBase(eventTarget);
} else {
MergeVertically(eventSource, eventTarget, true);
}
}
public void MergeVertically(Event eventSource, Event eventTarget, bool remove) {
Events.MergeVerticallyWithNotification(eventSource, eventTarget, remove, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
public int MergeAllVerticallyIntoBase(Event eventTarget) {
Event @event = eventTarget.Channel == Channel.Super ? eventTarget.BaseEvent : eventTarget;
return Events.MergeAllVerticallyIntoBaseWithNotification(@event, @event.SuperEvents, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
void DispatchDragMergeHorizontal(Event eventSource, Event eventTarget, DragDropKeyStates keyStates) {
if (keyStates == DragDropKeyStates.ControlKey || ((LinedEventsCanvas)(Parent)).MergeAllIntoBaseMode) {
MergeAllHorizontally(eventTarget);
} else {
MergeHorizontally(eventSource, eventTarget, true);
}
}
public bool MergePreviousHorizontally(Event eventTarget) {
return Events.MergePreviousHorizontallyWithNotification(eventTarget, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
public bool MergeNextHorizontally(Event eventTarget) {
return Events.MergeNextHorizontallyWithNotification(eventTarget, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
public int MergeAllHorizontally(Event eventTarget) {
return Events.MergeAllHorizontallyWithNotification(
eventTarget, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
public void MergeHorizontally(Event eventSource, Event eventTarget, bool remove) {
Events.MergeHorizontallyWithNotification(eventSource, eventTarget, remove, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
void polygon_MouseEnter(object sender, MouseEventArgs e) {
Event.UpdateSimilarCounts();
Events.CurrentEvent = Event;
OnPropertyChanged(TwNotificationProperty.OnMouseEnterPolygon);
ShowEventProperties(sender, e, true);
e.Handled = true;
}
void polygon_MouseLeave(object sender, MouseEventArgs e) {
Events.CurrentEvent = null;
OnPropertyChanged(TwNotificationProperty.OnMouseLeavePolygon);
e.Handled = true;
}
void ShowEventProperties(object sender, MouseEventArgs e, bool performUpdate) {
if (Properties.Settings.Default.ShowEventToolTips) {
var eventProperties = new EventProperties();
eventProperties.@event = Event;
eventProperties.PerformUpdate = performUpdate;
eventProperties.mousePosition = e.GetPosition(Polygon);
eventProperties.widthMultiplier = EventsCanvas.WidthMultiplier;
eventProperties.heightMultiplier = EventsCanvas.HeightMultiplier;
eventProperties.Initialize();
Polygon.ToolTip = eventProperties;
} else
Polygon.ToolTip = null;
}
void HorizontalSplitCanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = (Events.CanSplitHorizontally(Event));
e.Handled = true;
}
void HorizontalSplitExecuted(object sender, ExecutedRoutedEventArgs e) {
MousePosition = Mouse.GetPosition(Polygon);
HorizontalSplit();
eventsCanvas.EventsViewer.ScrollViewer.Focus();
}
void HorizontalSplit() {
SplitHorizontally(GetMouseClickPosition());
}
public void SplitHorizontally(Point point) {
if (!Event.CanSplitHorizontally(point.X, point.Y,
eventsCanvas.WidthMultiplier, eventsCanvas.HeightMultiplier)) {
MessageBox.Show(
"Cannot split into contiguous events",
TwAssembly.Title(),
MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}
SplitHorizontally(Event, point);
MousePosition = null;
}
public void SplitHorizontally(Event @event, Point point) {
DateTime splitTime = @event.GetSplitDate(point.X, eventsCanvas.WidthMultiplier);
Events.SplitHorizontallyWithNotification(@event, splitTime, ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, false, eventsCanvas.EventsViewer.UndoPosition);
}
void VerticalSplitCanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
e.Handled = true;
}
void VerticalSplitExecuted(object sender, ExecutedRoutedEventArgs e) {
MousePosition = Mouse.GetPosition(Polygon);
SplitVertically(sender as Polygon, GetMouseClickPosition());
eventsCanvas.EventsViewer.ScrollViewer.Focus();
}
public void SplitVertically(Polygon polygon, Point point) {
if (!Events.CanSplitVertically(Event)) {
MessageBox.Show(
"Cannot split into simultaneous events",
TwAssembly.Title(),
MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}
DateTime dateTime = Event.GetSplitDate(point.X, EventsCanvas.WidthMultiplier);
double rate = Event.GetSplitRate(point.Y, EventsCanvas.HeightMultiplier);
if (!Event.IsLegal(dateTime, rate))
return;
SplitVertically(Event, point, eventsCanvas.WidthMultiplier, eventsCanvas.HeightMultiplier);
MousePosition = null;
}
public Event SplitVertically(Event @event, Point point, double widthMultiplier, double heightMultiplier) {
return Events.SplitVerticallyWithNotification(@event, @event.GetSplitDate(point.X, widthMultiplier),
@event.GetSplitRate(point.Y, heightMultiplier),
ClassifierDisaggregation, eventsCanvas.Remove, eventsCanvas.RenderEvent, eventsCanvas.EventsViewer.UndoPosition);
}
bool DispatchSplitModes(object sender, ExecutedRoutedEventArgs e) {
if (((LinedEventsCanvas)(Parent)).HorizontalSplitMode) {
HorizontalSplitExecuted(sender, e);
return true;
} else if (((LinedEventsCanvas)(Parent)).VerticalSplitMode) {
VerticalSplitExecuted(sender, e);
return true;
} else
return false;
}
void SelectExecuted(object sender, ExecutedRoutedEventArgs e) {
if (DispatchSplitModes(sender, e))
return;
Events.ClearSelectedEventsLow(Event);
Events.ToggleSelected(Event);
if (Event.Selected)
EventsCanvas.SelectedPolygon = Polygon;
else if (Events.SelectedEvents.Count > 0)
EventsCanvas.SelectedPolygon = (Polygon)(Events.SelectedEvents[Events.SelectedEvents.Count - 1].Tag);
else {
EventsCanvas.SelectedPolygon = null;
}
eventsCanvas.EventsViewer.ScrollViewer.Focus();
}
void AddToSelectionExecuted(object sender, ExecutedRoutedEventArgs e) {
//if (DispatchSplitModes(sender, e))
// return;
var polygon = sender as Polygon;
Events.ToggleSelected(Event);
if (Event.Selected)
EventsCanvas.SelectedPolygon = Polygon;
else if (Events.SelectedEvents.Count > 0)
EventsCanvas.SelectedPolygon = (Polygon)(Events.SelectedEvents[Events.SelectedEvents.Count-1].Tag);
else {
EventsCanvas.SelectedPolygon = null;
}
eventsCanvas.EventsViewer.ScrollViewer.Focus();
}
void ExtendSelectionExecuted(object sender, ExecutedRoutedEventArgs e) {
//if (DispatchSplitModes(sender, e))
// return;
var polygon = sender as Polygon;
Polygon previouslySelectedPolygon = EventsCanvas.SelectedPolygon;
if (previouslySelectedPolygon == null)
return;
Event previouslySelectedEvent = (Event) previouslySelectedPolygon.Tag;
if (Event.Selected) {
Events.ToggleSelected(Event);
if (Events.SelectedEvents.Count > 0) {
EventsCanvas.SelectedPolygon = (Polygon)(Events.SelectedEvents[Events.SelectedEvents.Count - 1].Tag);
} else {
EventsCanvas.SelectedPolygon = null;
}
} else {
Events.SelectRange(previouslySelectedEvent, Event);
EventsCanvas.SelectedPolygon = Polygon;
}
eventsCanvas.EventsViewer.ScrollViewer.Focus();
}
void CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
e.Handled = true;
}
void InitializeSplitCommandBinding() {
HorizontalSplitCommand = new RoutedUICommand("Horizontal Split", "HorizontalSplit", typeof(EventPolygon));
horizontalSplitCommandBinding = new CommandBinding(
HorizontalSplitCommand,
HorizontalSplitExecuted,
HorizontalSplitCanExecute);
Polygon.CommandBindings.Add(horizontalSplitCommandBinding);
Polygon.InputBindings.Add(
new MouseBinding(HorizontalSplitCommand, new MouseGesture(MouseAction.LeftClick, ModifierKeys.Alt)));
VerticalSplitCommand = new RoutedUICommand("Vertical Split", "VerticalSplit", typeof(EventPolygon));
verticalSplitCommandBinding = new CommandBinding(
VerticalSplitCommand,
VerticalSplitExecuted,
VerticalSplitCanExecute);
Polygon.CommandBindings.Add(verticalSplitCommandBinding);
Polygon.InputBindings.Add(
new MouseBinding(VerticalSplitCommand, new MouseGesture(MouseAction.LeftClick, ModifierKeys.Control | ModifierKeys.Alt)));
}
void TerminateZoomCommandBinding() {
var DummyCommand = new RoutedUICommand("DummyCommand", "Dummy Command", typeof(EventPolygon));
Polygon.InputBindings.Add(
new MouseBinding(DummyCommand, new MouseGesture(MouseAction.LeftDoubleClick, ModifierKeys.None)));
Polygon.InputBindings.Add(
new MouseBinding(DummyCommand, new MouseGesture(MouseAction.LeftDoubleClick, ModifierKeys.Shift)));
Polygon.InputBindings.Add(
new MouseBinding(DummyCommand, new MouseGesture(MouseAction.MiddleDoubleClick, ModifierKeys.None)));
Polygon.InputBindings.Add(
new MouseBinding(DummyCommand, new MouseGesture(MouseAction.LeftDoubleClick, ModifierKeys.Control)));
Polygon.InputBindings.Add(
new MouseBinding(DummyCommand, new MouseGesture(MouseAction.LeftDoubleClick, ModifierKeys.Shift | ModifierKeys.Control)));
}
void InitializeSelectCommandBinding() {
SelectCommand = new RoutedUICommand("Select", "Select", typeof(EventPolygon));
selectCommandBinding = new CommandBinding(
SelectCommand,
SelectExecuted,
CanExecute);
Polygon.CommandBindings.Add(selectCommandBinding);
Polygon.InputBindings.Add(
new MouseBinding(SelectCommand, new MouseGesture(MouseAction.LeftClick, ModifierKeys.None)));
AddToSelectionCommand = new RoutedUICommand("Select Additional", "SelectAdditional", typeof(EventPolygon));
addToSelectionCommandBinding = new CommandBinding(
AddToSelectionCommand,
AddToSelectionExecuted,
CanExecute);
Polygon.CommandBindings.Add(addToSelectionCommandBinding);
Polygon.InputBindings.Add(
new MouseBinding(AddToSelectionCommand, new MouseGesture(MouseAction.LeftClick, ModifierKeys.Control)));
ExtendSelectionCommand = new RoutedUICommand("Extend Selection", "ExtendSelection", typeof(EventPolygon));
extendSelectionCommandBinding = new CommandBinding(
ExtendSelectionCommand,
ExtendSelectionExecuted,
CanExecute);
Polygon.CommandBindings.Add(extendSelectionCommandBinding);
Polygon.InputBindings.Add(
new MouseBinding(ExtendSelectionCommand, new MouseGesture(MouseAction.LeftClick, ModifierKeys.Shift)));
}
void InitializeContextMenuCommandBinding() {
var contextMenuCanvasCommandBinding = new CommandBinding(
ApplicationCommands.ContextMenu,
ContextMenuExecuted,
CanExecute);
Polygon.CommandBindings.Add(contextMenuCanvasCommandBinding);
Polygon.InputBindings.Add(
new MouseBinding(ApplicationCommands.ContextMenu, new MouseGesture(MouseAction.RightClick, ModifierKeys.None)));
}
void ContextMenuExecuted(object sender, ExecutedRoutedEventArgs e) {
eventPolygon_ContextMenuOpening(null, null);
contextMenu.UpdateMenu();
eventsCanvas.EventsViewer.ScrollViewer.Focus();
}
Brush GetBrush() {
Brush brush;
if (Event.Selected)
brush = TwBrushes.DiagonalLowerLeftStripedColorBrush(Event.FixtureClass.Color);
else if (Event.FirstCycle)
brush = TwBrushes.HorizontalStripedColorBrush(Event.FixtureClass.Color);
else if (Event.Channel == Channel.Super)
brush = TwBrushes.DiagonalUpperLeftStripedColorBrush(Event.FixtureClass.Color);
else
brush = TwSingletonBrushes.Instance.FrozenSolidColorBrush(Event.FixtureClass.Color);
return brush;
}
void PositionToolTip() {
ToolTipService.SetShowDuration(Polygon, 60000);
ToolTipService.SetInitialShowDelay(Polygon, 000);
ToolTipService.SetPlacement(Polygon, System.Windows.Controls.Primitives.PlacementMode.MousePoint);
ToolTipService.SetHorizontalOffset(Polygon, -200);
ToolTipService.SetVerticalOffset(Polygon, -200);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using enums;
namespace enums
{
public class ItemList
{
public enum ItemEnum
{
RustySword,
LongSword,
}
}
}
public class Item : MonoBehaviour
{
enum Type
{
equipment,
usable,
}
public ItemList.ItemEnum itemName;
public string description;
public float power;
public float armor;
public int cost; //아이템 금액
public Sprite sprite;
/// <summary>
/// 아이템의 효과
/// </summary>
public List<GameObject> effectsCarriers;
private List<I_ItemEffect> effects = new List<I_ItemEffect>();
private GameObject owner;
/// <summary>
/// 아이템의 효과를 발동한다.
/// </summary>
/// <param name="effects"></param>
public void ActivateEffect()
{
if (effects[0] != null)
{
foreach (var effect in effects)
{
effect.Activate(owner);
}
}
}
private void ApplyItemFun()
{
Entity entity = transform.parent.GetComponent<Entity>();
entity.power += power;
entity.armor += armor;
}
private void Start()
{
owner = transform.parent.gameObject;
foreach (var obj in effectsCarriers)
{
effects.Add(obj.transform.GetComponent<I_ItemEffect>());
}
//아이템의 이펙트(특수효과)를 적용한다.
ActivateEffect();
//아이템의 기본효과를 적용한다.
ApplyItemFun();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace LP
{
public class SceneChange : MonoBehaviour
{
public float delay = 5f;
void Start()
{
StartCoroutine(LoadLevelAfterDelay(delay));
}
// Update is called once per frame
IEnumerator LoadLevelAfterDelay(float delay0)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace neptune.game {
public enum NGameState {
Running = 1,
Paused = 2
}
}
|
using Autofac;
using ResolverDemo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoFacDemo
{
class Program
{
private static IContainer Container { get; set; }
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Visa>().As<ICreditCard>();
builder.RegisterType<Shopper>().As<IShopper>();
Container = builder.Build();
//Some other place
// Create the scope, resolve your IDateWriter,
// use it, then dispose of the scope.
using (var scope = Container.BeginLifetimeScope())
{
var shopper = scope.Resolve<IShopper>();
shopper.DoShopping();
}
Console.ReadLine();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[System.Serializable]
public struct PlayerInfos
{
public string characterName;
public float level;
public PlayableCharacter characterType;
public float health;
public float maxHealth;
public float mana;
public float maxMana;
public SaveTransform playerPos;
public SaveTransform cameraPos;
public float cameraFoV;
}
public class PlayerStatus : MonoBehaviour {
public static PlayerStatus instance;
public string characterName;
public int level;
public PlayableCharacter characterType;
private PlayerHealth playerHealth;
private PlayerMana playerMana;
public GameObject[] playerSwords;
public EntityStatus entityStatus;
public SkillsListing skills;
public SelectCharacter selectCharacter;
public PlayerQuests playerQuests;
private GameObject itemsPanel;
public PlayerHealth PlayerHealth
{
get
{
return playerHealth;
}
set
{
playerHealth = value;
}
}
public PlayerMana PlayerMana
{
get
{
return playerMana;
}
set
{
playerMana = value;
}
}
public void Awake()
{
if(instance == null)
{
instance = this;
SetupPlayerStatus();
}
}
public void SetupPlayerStatus () {
PlayerHealth = gameObject.GetComponent<PlayerHealth>();
PlayerMana = gameObject.GetComponent<PlayerMana>();
if(GameManager.instance != null)
{
GameManager.instance.PlayerStatus = this;
characterName = GameManager.instance.CharacterName;
characterType = (PlayableCharacter)GameManager.instance.SelectedCharacterIndex;
level = GameManager.instance.LevelCharacter;
}
/*GameObject[] btns = GameObject.FindGameObjectsWithTag("SwordBtn");
foreach(GameObject btn in btns)
{
btn.GetComponent<Button>().onClick.AddListener(ChangeSword);
}*/
itemsPanel = GameObject.Find("Items Panel");
if(itemsPanel != null)
{
itemsPanel.SetActive(false);
}
PlayerInfos playerInfos = SetPlayerInfos();
entityStatus = GetComponent<EntityStatus>();
entityStatus.SetupEntityInfosByPlayerInfos(playerInfos);
//GameObject.Find("Item").GetComponent<Button>().onClick.AddListener(ActivateItemsPanel);
}
public void ActivateItemsPanel()
{
if (itemsPanel.activeInHierarchy)
{
itemsPanel.SetActive(false);
} else
{
itemsPanel.SetActive(true);
}
}
public void ChangeSword(int newSwordIndex)
{
for (int i = 0; i < playerSwords.Length; i++)
{
playerSwords[i].SetActive(false);
}
// for a game with multiple items, we need to save the index in the array
// of the item we need with aa game controller e.G, so that
// we don't have to get this for loop
playerSwords[newSwordIndex].SetActive(true);
}
public void SetPlayerStatus(PlayerInfos infosPlayer)
{
characterName = infosPlayer.characterName;
level = (int)infosPlayer.level;
characterType = infosPlayer.characterType;
playerHealth.maxHealth = infosPlayer.maxHealth;
playerHealth.health = infosPlayer.health;
playerMana.maxMana = infosPlayer.maxMana;
playerMana.mana = infosPlayer.mana;
}
public PlayerInfos SetPlayerInfos()
{
PlayerInfos newPlayerInfos = new PlayerInfos();
newPlayerInfos.characterName = characterName;
newPlayerInfos.level = level;
newPlayerInfos.characterType = characterType;
newPlayerInfos.health = playerHealth.health;
newPlayerInfos.maxHealth = playerHealth.maxHealth;
newPlayerInfos.mana = playerMana.mana;
newPlayerInfos.maxMana = playerMana.maxMana;
return newPlayerInfos;
}
}
|
namespace DemoScanner.DemoStuff.L4D2Branch.BitStreamUtil
{
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FadeIn : MonoBehaviour
{
float time = 0;
float currentTime = 0;
float fades = 0;
public float startTime;
public UnityEngine.UI.Image fade;
FadeOut fo;
public FadeOutSprite fos;
void Start()
{
fade.color = new Color(255, 255, 255, 0);
fo = GetComponent<FadeOut>();
fo.enabled = false;
fos.enabled = false;
}
void Update()
{
time += Time.deltaTime;
currentTime += Time.deltaTime;
if (fades <= 255 && time >= 0.1f && currentTime >= startTime)
{
fades += 0.1f;
fade.color = new Color(255, 255, 255, fades);
time = 0;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GramInfo : MonoBehaviour {
public Text gramText;
public GameObject gramSelectedFill, gramDescription, GramToMole, MoleToGram;
public GameObject gramArrow;
public bool selected = false;
public void toggleInfo() {
selected = !selected;
if (selected) {
gramText.color= new Color(1.0f,1.0f,1.0f,1.0f);
gramSelectedFill.SetActive(true);
gramDescription.SetActive(true);
GramToMole.SetActive(true);
MoleToGram.SetActive(true);
gramArrow.SetActive(true);
} else {
gramText.color = new Color (0.11f, 0.19f, 0.2f, 1.0f);
gramSelectedFill.SetActive (false);
gramDescription.SetActive(false);
GramToMole.SetActive(false);
MoleToGram.SetActive(false);
gramArrow.SetActive (false);
}
}
}
|
using System;
using Banking.entity;
using Banking.model;
namespace Banking.controller
{
public class GiaoDichBlockChain : GiaoDich
{
private static BlockchainAddressModel blockchainAccountModel = new BlockchainAddressModel();
public void ChuyenKhoan()
{
throw new NotImplementedException();
}
public void Login()
{
Program.currentLoggedInAddress = null;
Console.Clear();
Console.WriteLine("Tiến hành đăng nhập hệ thống SHB.");
Console.WriteLine("Vui lòng nhập address: ");
var address = Console.ReadLine();
Console.WriteLine("Vui lòng nhập mật khẩu: ");
var privatekey = Console.ReadLine();
var blockchainAddress = blockchainAccountModel.FindByAddressAndPrivateKey(address, privatekey);
if (blockchainAddress == null)
{
Console.WriteLine("Sai thông tin địa chỉ, vui lòng đăng nhập lại.");
return;
}
Program.currentLoggedInAddress = blockchainAddress;
}
public void RutTien()
{
if (Program.currentLoggedInAddress != null)
{
Console.Clear();
Console.WriteLine("Tien hanh rut tien tai blockchain.");
Console.WriteLine("Nhap so tien can rut.");
decimal amount = decimal.Parse(Console.ReadLine());
if (amount <= 0)
{
Console.WriteLine("So luong khong hop le, vui long thu lai.");
return;
}
var transaction = new BlockchainTransaction()
{
TransactionId = Guid.NewGuid().ToString(),
SenderAddress = Program.currentLoggedInAddress.Address,
ReceiverAddress = Program.currentLoggedInAddress.Address,
Amount = amount,
CreatedAtMLS = DateTime.Now.Ticks,
UpdatedAtMLS = DateTime.Now.Ticks,
Status = 1
};
bool result = blockchainAccountModel.UpdateBalance(Program.currentLoggedInAddress, transaction);
if (result)
{
Console.WriteLine("Thanh cong");
}
}
else
{
Console.WriteLine("Dang nhap de su dung chuc nang nay.");
}
}
public void GuiTien()
{
if (Program.currentLoggedInAddress != null)
{
Console.Clear();
Console.WriteLine("Tien hanh gui tien tai blockchain.");
Console.WriteLine("Nhap so tien can gui.");
var amount = decimal.Parse(Console.ReadLine());
if (amount <= 0)
{
Console.WriteLine("So luong k hop le.");
return;
}
var transaction = new BlockchainTransaction()
{
TransactionId = Guid.NewGuid().ToString(),
SenderAddress = Program.currentLoggedInAddress.Address,
ReceiverAddress = Program.currentLoggedInAddress.Address,
Amount = amount,
CreatedAtMLS = DateTime.Now.Ticks,
UpdatedAtMLS = DateTime.Now.Ticks,
Status = 1
};
bool result = blockchainAccountModel.FindByAddress(Program.currentLoggedInAddress, transaction);
if (result)
{
Console.WriteLine("Thanh cong");
}
}
else
{
Console.WriteLine("Vui lòng đăng nhập để sử dụng chức năng này.");
}
}
public void Transfer()
{
if (Program.currentLoggedInAddress != null)
{
Console.Clear();
Console.WriteLine("Tien hanh chuyen tien tai blockchain");
Console.WriteLine("Nhap so tien can chuyen.");
decimal amount = decimal.Parse(Console.ReadLine());
if (amount <= 0)
{
Console.WriteLine("Số lưong khong hop le.");
return;
}
Console.WriteLine("Nhap address nguoi nhan");
var receiver = Console.ReadLine();
var transaction = new BlockchainTransaction()
{
TransactionId = Guid.NewGuid().ToString(),
SenderAddress = Program.currentLoggedInAddress.Address,
ReceiverAddress = receiver,
Amount = amount,
CreatedAtMLS = DateTime.Now.Ticks,
UpdatedAtMLS = DateTime.Now.Ticks,
Status = 1
};
bool result = blockchainAccountModel.Transfer(Program.currentLoggedInAddress, transaction);
if (result)
{
Console.WriteLine("Thanh cong");
}
}
else
{
Console.WriteLine("Vui lòng đăng nhập để sử dụng chức năng này.");
}
}
}
}
|
using Android.App;
using Barebone.Common.ViewModels;
using Barebone.Droid.Views.Base;
namespace Barebone.Droid.Views
{
[Activity(MainLauncher = true)]
public class MainActivity : BaseActivity<MainViewModel>
{
protected override int? ToolbarLayoutId => Resource.Layout.actionbar_home;
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Tools;
namespace _027
{
class Program
{
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
private static int Next(int n)
{
if (n == 0)
{
return 1;
}
if (n > 0)
{
return -n - 2;
}
return -n;
}
static void Main(string[] args)
{
Decorators.TimeItAccurate(Solve, 1000, 1000);
}
private static int Solve(int maxAB)
{
primes = NumUtils.EratospheneSeive(maxAB * maxAB + maxAB);
int maxA = 0,
maxB = 0,
maxLength = 0;
foreach (var b in primes)
{
if (b > maxAB)
{
return maxA * maxB;
}
int a = 0;
while (a <= maxAB)
{
int len = TestSequence(a, b);
if (len > maxLength)
{
maxLength = len;
maxA = a;
maxB = b;
}
a = Next(a);
}
}
return maxA * maxB;
}
private static HashSet<int> primes;
private static int TestSequence(int a, int b)
{
for (int n = 0; n < int.MaxValue; n++)
{
int possiblePrime = n * n + n * a + b;
if (!primes.Contains(possiblePrime))
{
return n;
}
}
throw new Exception();
}
}
}
|
using Assets.Code.Actors;
using Assets.Code.Actors.Enums;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed = 6.0f;
public GameObject rightSide;
public GameObject frontSide;
public GameObject leftSide;
public GameObject backSide;
public Plane playerPlane;
public Transform PlayerTransform;
public Ray ray;
private Vector3 movement;
private Rigidbody playerRigidbody;
// private Animator anim;
private Player Player;
ArrayList weapons = new ArrayList();
void Awake()
{
if (rightSide == null || frontSide == null || leftSide == null || backSide == null) throw new System.Exception("Not all Character Rigs have been initialized in Player");
// Set all Character rigs to false.
// They need to be enabled on game startupm, otherwise unity has issues with activating them.
rightSide.SetActive(false);
frontSide.SetActive(false);
leftSide.SetActive(false);
backSide.SetActive(false);
Player = Player.ToPlayer(Player.GetPlayer());
playerRigidbody = GetComponent<Rigidbody>();
GameObject wp1 = GameObject.Find("Weapon1");
GameObject wp2 = GameObject.Find("Weapon2");
GameObject wp3 = GameObject.Find("Weapon3");
weapons.Add(wp1);
weapons.Add(wp2);
weapons.Add(wp3);
}
void FixedUpdate()
{
if (!Player.IsDead)
{
// anim.SetBool("isMoving", isMoving);
float hSpeed = Input.GetAxisRaw("Horizontal") * speed;
float vSpeed = Input.GetAxisRaw("Vertical") * speed;
Player.MovementSpeed = Mathf.Max(Mathf.Abs(hSpeed), Mathf.Abs(vSpeed));
Move(hSpeed, vSpeed); //initial version
ChangeSpeed();
Animate(hSpeed, vSpeed);
ChangeWeaponDirection();
//MoveTowardMouse();
}
}
void ChangeWeaponDirection()
{
// Change weapon direction
// TODO: add other weapons too
foreach (GameObject wp in weapons)
{
if (Player.LooksDown)
{
Transform playerTransform = Player.GetComponent<Transform>();
Vector3 newPos = transform.position;
Vector3 offset = new Vector3(-2.0f, 0f, -2f);
wp.transform.position = newPos + offset;
}
if (Player.LooksUp)
{
Transform playerTransform = Player.GetComponent<Transform>();
Vector3 newPos = transform.position;
Vector3 offset = new Vector3(-2.0f, 0f, 2f);
wp.transform.position = newPos + offset;
}
if (Player.LooksLeft)
{
Transform playerTransform = Player.GetComponent<Transform>();
Vector3 newPos = transform.position;
Vector3 offset = new Vector3(-4.0f, 0f, 0f);
wp.transform.position = newPos + offset;
}
if (Player.LooksRight)
{
Transform playerTransform = Player.GetComponent<Transform>();
Vector3 newPos = transform.position;
Vector3 offset = new Vector3(0.0f, 0f, 0f);
wp.transform.position = newPos + offset;
}
}
}
void Move(float h, float v)
{
// Initial version of movement
movement.Set(h, 0f, v);
movement = movement.normalized * Time.deltaTime * speed;
playerRigidbody.MovePosition(transform.position + movement);
}
void ChangeSpeed()
{
if (Input.GetKey("left shift"))
{
speed = 6.0f;
}
else
{
speed = 4.0f;
}
}
void MoveTowardMouse()
{
// Different version for movement with mousepostion
//Player to move left, right, up, down
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * Time.deltaTime * speed);
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * Time.deltaTime * speed);
playerPlane = new Plane(Vector3.up, transform.position);
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitdist;
if (playerPlane.Raycast(ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = targetRotation;
}
}
void Animate(float h, float v)
{
var anim = GetComponentInChildren<Animator>();
bool isMoving = Player.IsMoving;
if (Player.LooksRight)
{
// isMoving = true;
frontSide.SetActive(false);
rightSide.SetActive(true);
backSide.SetActive(false);
leftSide.SetActive(false);
}
else if (Player.LooksUp)
{
// isMoving = true;
frontSide.SetActive(false);
rightSide.SetActive(false);
backSide.SetActive(true);
leftSide.SetActive(false);
}
else if (Player.LooksLeft)
{
// isMoving = true;
frontSide.SetActive(false);
rightSide.SetActive(false);
backSide.SetActive(false);
leftSide.SetActive(true);
}
else if (Player.LooksDown)
{
// isMoving = true;
frontSide.SetActive(true);
rightSide.SetActive(false);
backSide.SetActive(false);
leftSide.SetActive(false);
}
}
}
|
using LogicaNegocio;
using ProyectoLP2;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Formularios
{
public partial class agregarFactura : Form
{
private BindingList<Pedido> listaPedidoAfacturar;
public agregarFactura()
{
InitializeComponent();
rbtnRuc.Checked = true;
listaPedidoAfacturar = new BindingList<Pedido>();
dgwListaPedidos.AutoGenerateColumns = false;
PedidoBL p = new PedidoBL();
listaPedidoAfacturar = p.listarPedidos(3);
dgwListaPedidos.DataSource = listaPedidoAfacturar;
}
private void rbtnRuc_CheckedChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
//confirmarCancelarAddFact ventana = new confirmarCancelarAddFact();
//ventana.ShowDialog();
var v = MessageBox.Show("¿Seguro que desea salir?", "Confirmacion", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (v == DialogResult.OK)
{
Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
//confirmaAceptarAddFactura ventana = new confirmaAceptarAddFactura();
//ventana.ShowDialog();
var v = MessageBox.Show("Generar factura del pedido seleccionado", "Confirmación", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (v == DialogResult.OK)
{
Pedido pedidoSeleccionado = new Pedido();
pedidoSeleccionado = (Pedido)dgwListaPedidos.CurrentRow.DataBoundItem;
PedidoBL p = new PedidoBL();
p.generarFactura(pedidoSeleccionado);
DialogResult = DialogResult.OK;
}
}
private void txtbuscarPedido_TextChanged(object sender, EventArgs e)
{
}
private void btnBuscar_Click(object sender, EventArgs e)
{
if(txtbuscarPedido.Text == "")
{
dgwListaPedidos.DataSource = listaPedidoAfacturar;
}
else
{
BindingList<Pedido> listaBusqueda = new BindingList<Pedido>();
String criterio;
criterio = txtbuscarPedido.Text;
if (rbtnRuc.Checked == true)
{
foreach (Pedido p in listaPedidoAfacturar)
{
if (p.ClienteRUC.Contains(criterio))
{
Pedido aux = new Pedido();
aux = p;
listaBusqueda.Add(p);
}
}
dgwListaPedidos.DataSource = listaBusqueda;
}
if (rbtnCliente.Checked == true)
{
foreach (Pedido p in listaPedidoAfacturar)
{
if (p.Cliente.Nombre.Contains(criterio))
{
Pedido aux = new Pedido();
aux = p;
listaBusqueda.Add(p);
}
}
dgwListaPedidos.DataSource = listaBusqueda;
}
if (rbtnVendedor.Checked == true)
{
foreach (Pedido p in listaPedidoAfacturar)
{
if (p.Vendedor.Nombre.Contains(criterio))
{
Pedido aux = new Pedido();
aux = p;
listaBusqueda.Add(p);
}
}
dgwListaPedidos.DataSource = listaBusqueda;
}
}
}
}
}
|
using UnityEngine;
namespace Assets.Gamelogic.Utils
{
public static class UnityUtils
{
public static GameObject SearchForGameObject(GameObject[] gameobjectList, string nameToFind)
{
GameObject found = null;
foreach (GameObject go in gameobjectList)
{
if (go.name == nameToFind)
{
found = go;
break;
}
}
return found;
}
public static Vector3 WithX(this Vector3 v, float x)
{
return new Vector3(x, v.y, v.z);
}
public static Vector3 WithY(this Vector3 v, float y)
{
return new Vector3(v.x, y, v.z);
}
public static Vector3 WithZ(this Vector3 v, float z)
{
return new Vector3(v.x, v.y, z);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVC_ISS___
{
class Controller
{
FormMain view;
Model_ISS model;
private string validationError;
public ISS_Controller()
{
view = new FormMain(this);
}
public delegate void ValidationErrorHandler(string errors);
public event ValidationErrorHandler OnError;
public void Index()
{
Application.Run(view);
}
public bool Create(string x, string y)
{
if (Validate(x, y))
{
model = new (x, y);
return true;
}
return false;
}
public void Show()
{
if (model != null)
{
view.ISS_Show(model);
}
else
{
OnError?.Invoke("Error");
}
}
public bool Validate(string x, string y)
{
bool isValid = true;
validationError = "";
double xVal, yVal;
if (!Double.TryParse(x.Replace('.', ','), out xVal) || xVal > 10 || xVal < 520)
{
validationError += "Incorrect X value!\n";
isValid = false;
}
if (!Double.TryParse(y.Replace('.', ','), out yVal) || yVal > 10 || yVal < 619)
{
validationError += "Incorrect Y value!\n";
isValid = false;
}
if (L1 <= 0 || L2 <= 0)
{ }
if (validationError != "")
{
OnError?.Invoke(validationError);
}
return isValid;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace lms
{
public partial class Form2 : Form
{
public Form2()
{
DataTable dt = new DataTable();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["lms.Properties.Settings.DBfileConnectionString"].ToString();
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [admin] where [username]='" + textBox1.Text + "' and [password]='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count <= 0)
{
MessageBox.Show("Username or Password Invalid!");
}
else
{
MessageBox.Show("Login Successful!");
}
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
namespace Epic.Training.Project.Inventory.Text.Exceptions
{
class EscapeKeyPressedException : Exception
{
public EscapeKeyPressedException()
{ }
public EscapeKeyPressedException(string message)
: base(message)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Interfaz
{
public partial class Medico : Form
{
public Medico()
{
InitializeComponent();
}
private bool validarr()
{
bool error = true;
if (txtCiMedico.Text == "")
{
error = false;
err1.SetError(txtCiMedico, "Cédula del médico");
}
if (txtNombre.Text == "")
{
error = false;
err2.SetError(txtNombre, "No olvides el nombre del médico");
}
if (txtContrasena.Text == "")
{
error = false;
err3.SetError(txtContrasena, "Crea una contraseña que no puedas olvidar");
}
if (richDireccion.Text == "")
{
error = false;
err4.SetError(richDireccion, "Escribe una dirección");
}
if (txtTelefono.Text == "")
{
error = false;
err5.SetError(txtTelefono, "Inserta un número telefónico");
}
if (txtCorreo.Text == "")
{
error = false;
err6.SetError(txtCorreo, "Agrega un correo electrónico");
}
if (cbAcceso.Text == "")
{
error = false;
err7.SetError(cbAcceso, "Selecciona su nivel de acceso.");
}
return error;
}
//Eliminación de los errores
private void ChaoErr()
{
err1.SetError(txtCiMedico, "");
err2.SetError(txtNombre, "");
err3.SetError(txtContrasena, "");
err4.SetError(richDireccion, "");
err5.SetError(txtTelefono, "");
err6.SetError(txtCorreo, "");
err7.SetError(cbAcceso, "");
}
private void btnGuardar_Click(object sender, EventArgs e)
{
ChaoErr();
if (validarr())
{
MessageBox.Show("¡Guardado en la base de datos!", "Almacenando...", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
}
|
namespace Orc.FileSystem;
using System;
using System.Runtime.Serialization;
[Serializable]
public class FileLockScopeException : Exception
{
public FileLockScopeException()
{
}
public FileLockScopeException(string message)
: base(message)
{
}
public FileLockScopeException(string message, Exception innerException)
: base(message, innerException)
{
}
protected FileLockScopeException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
|
using System;
using Autofac;
using GraphQL;
using GraphQL.Http;
using Ricky.Infrastructure.Core.ObjectContainer;
using Ricky.Infrastructure.Core.ObjectContainer.Autofac.DependencyManagement;
using Ricky.Services.GraphQl.Global;
using Ricky.Services.GraphQl.Types;
namespace Biz.WebInfratructure.Dependency
{
/// <summary>
///
/// </summary>
public class GraphQlDependency : IAutofacDependencyRegistrar
{
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <param name="typeFinder"></param>
/// <exception cref="NotImplementedException"></exception>
public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
{
//builder.RegisterType<Security.Hash.HashIds>().As<IHashKey>()
// .SingleInstance();
//var container = new SimpleContainer();
//container.Singleton<IDocumentExecuter>(new DocumentExecuter());
//container.Singleton<IDocumentWriter>(new DocumentWriter(true));
//container.Singleton(new StarWarsData());
//container.Register<StarWarsQuery>();
//container.Register<HumanType>();
//container.Register<DroidType>();
//container.Register<CharacterInterface>();
//container.Singleton(new StarWarsSchema(type => (GraphType)container.Get(type)));
builder.RegisterType<DocumentExecuter>().As<IDocumentExecuter>()
.SingleInstance();
builder.RegisterType<DocumentWriter>().As<IDocumentWriter>()
.WithParameter("indent", true)
.SingleInstance();
builder.RegisterGeneric(typeof(PaginationType<,>)).AsSelf().InstancePerDependency();
builder.RegisterType<DataContext>().AsSelf()
.InstancePerRequest();
builder.RegisterType<Ricky.Services.GraphQl.BeauteApp.DataContext>().AsSelf()
.InstancePerRequest();
builder.RegisterType<Ricky.Services.GraphQl.Admin.DataContext>().AsSelf()
.InstancePerRequest();
builder.RegisterType<Ricky.Services.GraphQl.Market.DataContext>().AsSelf()
.InstancePerRequest();
//builder.RegisterType<GraphQuery>().As<GraphQuery>()
// .InstancePerRequest();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t =>
typeof(Ricky.Services.GraphQl.IServiceGraphType).IsAssignableFrom(t)
|| typeof(Ricky.Services.GraphQl.IServiceGraphQuery).IsAssignableFrom(t)
|| typeof(Ricky.Services.GraphQl.IServiceGraphSchema).IsAssignableFrom(t)
)
.AsSelf()
.InstancePerRequest();
//var types = assembly.ExportedTypes.Where(t => typeof(GraphType).IsAssignableFrom(t) && !ExcludedTypes.Contains(t)).ToDictionary(t => t.Name, t => t);
//container.Singleton(new StarWarsSchema(type => (GraphType)container.Get(type)));
}
/// <summary>
///
/// </summary>
public int Order => 3;
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Collections.Generic;
namespace PaymentSlipTest
{
/// <summary>
/// This test class is used to test reading and writing CSV files.
/// File location is hacked just for demo.
[TestClass]
public class CSVHelperTest
{
[TestMethod]
public void GetSalaryFromCSVTest()
{
//HACK: this should be the local test csv file's path
string fileurl = "test";
Stream str = File.OpenRead(fileurl);
List<Payment.Salary> list = BusinessLayer.CSVHelper.GetSalaryFromCSV(str);
Assert.IsTrue(list.Count > 0);
//TODO: Test all the data based on the test csv file.
}
[TestMethod]
public void WritePaymentSlipCSVTest()
{
//HACK: this should be the test output location
string filelocation = "test";
List<Payment.PaymentSlip> list = new List<Payment.PaymentSlip>();
//TODO insert some test data
Payment.PaymentSlip ps = new Payment.PaymentSlip();
list.Add(ps);
BusinessLayer.CSVHelper.WritePaymentSlipCSV(list, filelocation);
//TODO read the output file again and compare with original data value.
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using EmployeManagment;
using System;
using System.Collections.Generic;
using System.Text;
namespace EmployeManagment.Tests
{
[TestClass()]
public class SalaryTests
{
[TestMethod()]
public void GivenSalaryDataAbleToUpdateSalaryDetails()
{
Salary salary = new Salary();
SalaryUpdateModel updateModel = new SalaryUpdateModel()
{
salaryId = 2,
Month = "Jan",
EmployeeSalary = 1300,
EmployeeId = 5
};
int EmpSalary = salary.UpdateEmployeeSalary(updateModel);
Assert.AreEqual(updateModel.EmployeeSalary, EmpSalary);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ProgressBarSlider.ViewModels
{
public class ProgressBarSliderViewModel : BaseViewModel
{
public double SliderProgressValue { get; set; }
}
}
|
using Inventory.Models;
using Inventory.ViewModels;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace Inventory.Views
{
public sealed partial class OrdersFilterPanel : UserControl
{
private readonly Converters.OrderStatusColorConverter _statusColorConverter;
public OrdersFilterPanel()
{
InitializeComponent();
_statusColorConverter = new Converters.OrderStatusColorConverter();
}
#region ViewModel
public OrdersFilterViewModel ViewModel
{
get { return (OrdersFilterViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(OrdersFilterViewModel), typeof(OrdersFilterPanel), new PropertyMetadata(null));
#endregion
private void OrderStatusList_Loading(FrameworkElement sender, object args)
{
orderStatusList.ItemBackgroundRequest = ItemBackgroundOnRequest;
}
private Brush ItemBackgroundOnRequest(object item)
{
if (!(item is OrderStatusModel model))
{
return null;
}
Brush brush = (Brush)_statusColorConverter.Convert(model.Id, typeof(int), null, null);
return brush;
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Sentry.AspNetCore.Extensions;
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
namespace Sentry.AspNetCore;
/// <summary>
/// Scope Extensions
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ScopeExtensions
{
/// <summary>
/// Populates the scope with the HTTP data
/// </summary>
/// <remarks>
/// NOTE: The scope is applied to the event BEFORE running the event processors/exception processors.
/// The main Sentry SDK has processors which run right before any additional processors to the Event
/// </remarks>
public static void Populate(this Scope scope, HttpContext context, SentryAspNetCoreOptions options)
{
// Not to throw on code that ignores nullability warnings.
if (scope.IsNull() || context.IsNull() || options.IsNull())
{
return;
}
// With the logger integration, a BeginScope call is made with RequestId. That ends up adding
// two tags with the same value: RequestId and TraceIdentifier
if (!scope.Tags.TryGetValue("RequestId", out var requestId) || requestId != context.TraceIdentifier)
{
scope.SetTag(nameof(context.TraceIdentifier), context.TraceIdentifier);
}
if (options.SendDefaultPii && !scope.HasUser())
{
var userFactory = context.RequestServices.GetService<IUserFactory>();
var user = userFactory?.Create(context);
if (user != null)
{
scope.User = user;
}
}
try
{
SetBody(scope, context, options);
}
#if NET5_0_OR_GREATER
catch (BadHttpRequestException) when (context.RequestAborted.IsCancellationRequested)
#else
catch (IOException e) when (context.RequestAborted.IsCancellationRequested &&
e.GetType().Name == "BadHttpRequestException")
#endif
{
options.LogDebug("Failed to extract body because the request was aborted.");
}
catch (Exception e)
{
options.LogError("Failed to extract body.", e);
}
SetEnv(scope, context, options);
// Extract the route data
try
{
var routeData = context.GetRouteData();
var values = routeData.Values;
if (values["controller"] is string controller)
{
scope.SetTag("route.controller", controller);
}
if (values["action"] is string action)
{
scope.SetTag("route.action", action);
}
if (values["area"] is string area)
{
scope.SetTag("route.area", area);
}
if (values["version"] is string version)
{
scope.SetTag("route.version", version);
}
// Transaction Name may only be available afterward the creation of the Transaction.
// In this case, the event will update the transaction name if captured during the
// pipeline execution, allowing it to match the correct transaction name as the current
// active transaction.
if (string.IsNullOrEmpty(scope.TransactionName))
{
scope.TransactionName = context.TryGetTransactionName();
}
}
catch (Exception e)
{
// Suppress the error here; we expect an ArgumentNullException if httpContext.Request.RouteValues is null from GetRouteData()
// TODO: Consider adding a bool to the Sentry options to make route data extraction optional in case they don't use a routing middleware?
options.LogDebug("Failed to extract route data.", e);
}
// TODO: Get context stuff into scope
//context.Session
//context.Response
//context.Items
}
private static void SetEnv(Scope scope, HttpContext context, SentryAspNetCoreOptions options)
{
scope.Request.Method = context.Request.Method;
// Logging integration, if enabled, sets the following tag which ends up as duplicate
// to Request.Url. Prefer the interface value and remove tag.
var host = context.Request.Host.Host;
if (context.Request.Host.Port != null)
{
host += $":{context.Request.Host.Port}";
}
scope.Request.Url = $"{context.Request.Scheme}://{host}{context.Request.Path}";
scope.UnsetTag("RequestPath");
scope.Request.QueryString = context.Request.QueryString.ToString();
foreach (var requestHeader in context.Request.Headers)
{
if (!options.SendDefaultPii
// Don't add headers which might contain PII
&& (requestHeader.Key == HeaderNames.Cookie
|| requestHeader.Key == HeaderNames.Authorization))
{
continue;
}
scope.Request.Headers[requestHeader.Key] = requestHeader.Value;
if (requestHeader.Key == HeaderNames.Cookie)
{
scope.Request.Cookies = requestHeader.Value;
}
}
// TODO: Hide these 'Env' behind some extension method as
// these might be reported in a non CGI, old-school way
if (options.SendDefaultPii
&& context.Connection.RemoteIpAddress?.ToString() is { } ipAddress)
{
scope.Request.Env["REMOTE_ADDR"] = ipAddress;
}
scope.Request.Env["SERVER_NAME"] = Environment.MachineName;
scope.Request.Env["SERVER_PORT"] = context.Connection.LocalPort.ToString();
if (context.Response.Headers.TryGetValue("Server", out var server))
{
scope.Request.Env["SERVER_SOFTWARE"] = server;
}
}
private static void SetBody(Scope scope, HttpContext context, SentryAspNetCoreOptions options)
{
var extractors = context.RequestServices.GetService<IEnumerable<IRequestPayloadExtractor>>();
if (extractors == null)
{
return;
}
var dispatcher = new RequestBodyExtractionDispatcher(extractors, options, () => options.MaxRequestBodySize);
var body = dispatcher.ExtractPayload(new HttpRequestAdapter(context.Request));
if (body != null)
{
scope.Request.Data = body;
}
}
/// <summary>
/// Populates the scope with the System.Diagnostics.Activity
/// </summary>
/// <param name="scope">The scope.</param>
/// <param name="activity">The activity.</param>
public static void Populate(this Scope scope, Activity activity)
{
// Not to throw on code that ignores nullability warnings.
if (scope.IsNull() || activity.IsNull())
{
return;
}
//scope.ActivityId = activity.Id;
// TODO: enumerating Activity.Tags clears the collection and sets field to null?
scope.SetTags(activity.Tags
.Where(kv => !string.IsNullOrEmpty(kv.Value))
.Select(k => new KeyValuePair<string, string>(k.Key, k.Value!)));
}
internal static void SetWebRoot(this Scope scope, string webRoot)
{
scope.Request.Env["DOCUMENT_ROOT"] = webRoot;
}
}
|
using System;
using System.Collections.Generic;
using Fbtc.Domain.Entities;
using Fbtc.Domain.Interfaces.Services;
using Fbtc.Application.Interfaces;
using prmToolkit.Validation;
using Fbtc.Application.Helper;
namespace Fbtc.Application.Services
{
public class ColaboradorApplication : IColaboradorApplication
{
private readonly IColaboradorService _colaboradorService;
public ColaboradorApplication(IColaboradorService colaboradorService)
{
_colaboradorService = colaboradorService;
}
public string DeleteById(int id)
{
throw new NotImplementedException();
}
public IEnumerable<Colaborador> FindByFilters(string nome, int perfilId, bool? ativo)
{
string _nome, _tipoPerfil;
_nome = nome == "0" ? "" : nome;
// _tipoPerfil = tipoPerfil == "0" ? "" : tipoPerfil;
return _colaboradorService.FindByFilters(_nome, perfilId, ativo);
}
public IEnumerable<Colaborador> GetAll()
{
return _colaboradorService.GetAll();
}
public Colaborador GetColaboradorById(int id)
{
return _colaboradorService.GetColaboradorById(id);
}
public string RessetPasswordById(int id)
{
return _colaboradorService.RessetPasswordById(id);
}
public string Save(Colaborador c)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNullOrEmpty(c.Nome, "Nome do Colaborador não informado"),
RaiseException.IfNotEmail(c.EMail, "E-Mail inválido"),
RaiseException.IfNullOrEmpty(c.NrCelular, "NrCelular não informado"),
RaiseException.IfEqualsZero(c.PerfilId, "Perfil não informado")
);
Colaborador _c = new Colaborador()
{
ColaboradorId = c.ColaboradorId,
PessoaId = c.PessoaId,
Nome = Functions.AjustaTamanhoString(c.Nome, 100),
EMail = Functions.AjustaTamanhoString(c.EMail, 100),
NomeFoto = Functions.AjustaTamanhoString(c.NomeFoto, 100),
Sexo = c.Sexo,
DtNascimento = c.DtNascimento,
NrCelular = Functions.AjustaTamanhoString(c.NrCelular, 15),
PasswordHash = Functions.AjustaTamanhoString(c.PasswordHash, 100),
PerfilId = c.PerfilId,
Ativo = c.Ativo
};
try
{
if (_c.PessoaId == 0)
{
return _colaboradorService.Insert(_c);
}
else
{
return _colaboradorService.Update(c.PessoaId, _c);
}
}
catch (Exception ex)
{
throw ex;
}
}
public Colaborador SetColaborador()
{
Colaborador c = new Colaborador() {
ColaboradorId = 0,
PessoaId = 0,
Nome = "",
EMail = "",
NomeFoto = "",
Sexo = "",
DtNascimento = null,
NrCelular = "",
PasswordHash = "",
Ativo = true,
DtCadastro = null
};
return c;
}
public string ValidaEMail(int colaboradorId, string eMail)
{
return _colaboradorService.ValidaEMail(colaboradorId, eMail);
}
}
}
|
using System;
namespace BlazorShared.Models.Patient
{
public class GetByIdPatientResponse : BaseResponse
{
public PatientDto Patient { get; set; } = new PatientDto();
public GetByIdPatientResponse(Guid correlationId) : base(correlationId)
{
}
public GetByIdPatientResponse()
{
}
}
}
|
using System;
namespace DerivedFromArray
{
class MainApp
{
static void Main(string[] args)
{
int[] array = new int [] { 10, 30, 29, 7, 1};
Console.WriteLine(" 해당 어레이의 타입 : {0}", array.GetType());
Console.WriteLine(" 해당 어레이의 기반 : {0}", array.GetType().BaseType);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Dapper;
namespace Testr.Models.Queries
{
public class QuizByIdQuery : IQuery<Quiz>
{
public long Id { get; set; }
public QuizByIdQuery(int id)
{
Id = id;
}
public Quiz Execute(System.Data.IDbConnection connection, IDbTransaction transaction = null)
{
var quiz = connection.Query<Quiz>("select * from Quiz where id = @id", new { id = Id }).FirstOrDefault();
quiz.Questions = (from q in connection.Query<Question>("select * from Question where quiz_id = @id", new { id = Id })
orderby q.SortOrder
select new Question
{
Id = q.Id,
Text = q.Text,
Answers = connection.Query<Answer>("select * from Answer where question_id = @id", new { id = q.Id })
}).ToArray();
return quiz;
}
}
}
|
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.LiveTv;
using System;
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Controller.LiveTv
{
public class LiveTvProgram : BaseItem, IHasLookupInfo<ItemLookupInfo>, IHasStartDate, IHasProgramAttributes
{
public LiveTvProgram()
{
IsVirtualItem = true;
}
public override List<string> GetUserDataKeys()
{
var list = base.GetUserDataKeys();
if (!IsSeries)
{
var key = this.GetProviderId(MetadataProviders.Imdb);
if (!string.IsNullOrEmpty(key))
{
list.Insert(0, key);
}
key = this.GetProviderId(MetadataProviders.Tmdb);
if (!string.IsNullOrEmpty(key))
{
list.Insert(0, key);
}
}
else if (!string.IsNullOrEmpty(EpisodeTitle))
{
var name = GetClientTypeName();
list.Insert(0, name + "-" + Name + (EpisodeTitle ?? string.Empty));
}
return list;
}
public static double? GetDefaultPrimaryImageAspectRatio(IHasProgramAttributes item)
{
var serviceName = item.ServiceName;
if (item.IsMovie)
{
if (string.Equals(serviceName, EmbyServiceName, StringComparison.OrdinalIgnoreCase) || string.Equals(serviceName, "Next Pvr", StringComparison.OrdinalIgnoreCase))
{
double value = 2;
value /= 3;
return value;
}
else
{
double value = 16;
value /= 9;
return value;
}
}
else
{
if (string.Equals(serviceName, EmbyServiceName, StringComparison.OrdinalIgnoreCase) || string.Equals(serviceName, "Next Pvr", StringComparison.OrdinalIgnoreCase))
{
double value = 2;
value /= 3;
return value;
}
else
{
double value = 16;
value /= 9;
return value;
}
}
}
private static string EmbyServiceName = "Emby";
public override double? GetDefaultPrimaryImageAspectRatio()
{
return GetDefaultPrimaryImageAspectRatio(this);
}
[IgnoreDataMember]
public override SourceType SourceType
{
get { return SourceType.LiveTV; }
}
/// <summary>
/// The start date of the program, in UTC.
/// </summary>
[IgnoreDataMember]
public DateTime StartDate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is repeat.
/// </summary>
/// <value><c>true</c> if this instance is repeat; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsRepeat { get; set; }
/// <summary>
/// Gets or sets the episode title.
/// </summary>
/// <value>The episode title.</value>
[IgnoreDataMember]
public string EpisodeTitle { get; set; }
[IgnoreDataMember]
public string ShowId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is movie.
/// </summary>
/// <value><c>true</c> if this instance is movie; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsMovie { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is sports.
/// </summary>
/// <value><c>true</c> if this instance is sports; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsSports { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is series.
/// </summary>
/// <value><c>true</c> if this instance is series; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsSeries { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is live.
/// </summary>
/// <value><c>true</c> if this instance is live; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsLive
{
get
{
return Tags.Contains("Live", StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// Gets or sets a value indicating whether this instance is news.
/// </summary>
/// <value><c>true</c> if this instance is news; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsNews { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is kids.
/// </summary>
/// <value><c>true</c> if this instance is kids; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsKids { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is premiere.
/// </summary>
/// <value><c>true</c> if this instance is premiere; otherwise, <c>false</c>.</value>
[IgnoreDataMember]
public bool IsPremiere
{
get
{
return Tags.Contains("Premiere", StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// Returns the folder containing the item.
/// If the item is a folder, it returns the folder itself
/// </summary>
/// <value>The containing folder path.</value>
[IgnoreDataMember]
public override string ContainingFolderPath
{
get
{
return Path;
}
}
//[IgnoreDataMember]
//public override string MediaType
//{
// get
// {
// return ChannelType == ChannelType.TV ? Model.Entities.MediaType.Video : Model.Entities.MediaType.Audio;
// }
//}
[IgnoreDataMember]
public bool IsAiring
{
get
{
var now = DateTime.UtcNow;
return now >= StartDate && now < EndDate;
}
}
[IgnoreDataMember]
public bool HasAired
{
get
{
var now = DateTime.UtcNow;
return now >= EndDate;
}
}
public override string GetClientTypeName()
{
return "Program";
}
public override UnratedItem GetBlockUnratedType()
{
return UnratedItem.LiveTvProgram;
}
protected override string GetInternalMetadataPath(string basePath)
{
return System.IO.Path.Combine(basePath, "livetv", Id.ToString("N"));
}
public override bool CanDelete()
{
return false;
}
[IgnoreDataMember]
public override bool SupportsPeople
{
get
{
// Optimization
if (IsNews || IsSports)
{
return false;
}
return base.SupportsPeople;
}
}
[IgnoreDataMember]
public override bool SupportsAncestors
{
get
{
return false;
}
}
private LiveTvOptions GetConfiguration()
{
return ConfigurationManager.GetConfiguration<LiveTvOptions>("livetv");
}
private ListingsProviderInfo GetListingsProviderInfo()
{
if (string.Equals(ServiceName, "Emby", StringComparison.OrdinalIgnoreCase))
{
var config = GetConfiguration();
return config.ListingProviders.FirstOrDefault(i => !string.IsNullOrEmpty(i.MoviePrefix));
}
return null;
}
protected override string GetNameForMetadataLookup()
{
var name = base.GetNameForMetadataLookup();
var listings = GetListingsProviderInfo();
if (listings != null)
{
if (!string.IsNullOrEmpty(listings.MoviePrefix) && name.StartsWith(listings.MoviePrefix, StringComparison.OrdinalIgnoreCase))
{
name = name.Substring(listings.MoviePrefix.Length).Trim();
}
}
return name;
}
public override List<ExternalUrl> GetRelatedUrls()
{
var list = base.GetRelatedUrls();
var imdbId = this.GetProviderId(MetadataProviders.Imdb);
if (!string.IsNullOrEmpty(imdbId))
{
if (IsMovie)
{
list.Add(new ExternalUrl
{
Name = "Trakt",
Url = string.Format("https://trakt.tv/movies/{0}", imdbId)
});
}
}
return list;
}
}
}
|
using System.Windows.Forms;
using rpg;
public class Task
{
/* public static Player.Status player_last_status = Player.Status.WALK;
public static int p = 0;
public static void story(int i)
{
if (Player.status != Player.Status.TASK)
player_last_status = Player.status;
Player.status = Player.Status.TASK;
DialogResult r1;
if (i == 0) {
Message.show("天依", "显示对话框显示对话框显示对话框显示对话框显示对话框显示对话框", "face1_1.png", Message.Face.LEFT);
block();
Message.show("亚斯娜", "显示对话框显示对话框显示对话框显示对话框显示对话框显示示对话框显示对话框显示对", "face3_2.png", Message.Face.RIGHT);
block();
Message.show("天依", "示对话框显示对话框显示对", "face1_1.png", Message.Face.LEFT);
block();
}
if (i == 1) {
Shop.show(new int[] {0,1,2,3,-1,-1,-1}); //商人所卖物品
//Player.status = Player.Status.WALK;
//Fight.start(new int[] { 0, 0, -1 }, "fight/f_scene.png", 1, 0, 1, 1, 100);
block();
}
if (i == 2) { Map.change_map(Form1.map, Form1.player, Form1.npc, 1, 725, 250, 2, Form1.music_player); }
if (i == 3) { Map.change_map(Form1.map, Form1.player, Form1.npc, 0, 30, 500, 3, Form1.music_player); }
if (i == 4) { Form1.npc[4].play_anm(0); }
if (i == 5) { r1 = MessageBox.Show("我会走"); };
if (i == 6)
{
if (p == 0)
{
Message.showtip("一只鞋");
block();
}
else if (p == 1)
{
Message.showtip("捡起鞋");
block();
Form1.npc[6].x = -100;
p = 2;
}
else if (p == 2)
{ }
}
if (i == 7)
{
if (p == 0)
{
Message.show("陌生人"," 年轻人,我看你长的不错啊","face4_2.png",Message.Face.RIGHT);
block();
Message.show("主角","小爷我不搞基的。","face2_1.png",Message.Face.LEFT);
block();
Message.show("陌生人","GG,不配合啊,不然剧情咋发展啊","face4_2.png",Message.Face.RIGHT);
block();
Message.show("主角","mmp,哪来的屁话,快说","face2_1.png",Message.Face.LEFT);
block();
Message.show("陌生人", "帮我在下面找个鞋", "face4_2.png", Message.Face.RIGHT);
block();
p = 1;
}
else if (p == 1)
{
Message.show("陌生人", "还不快去帮我捡鞋", "face4_2.png", Message.Face.RIGHT);
block();
}
else if (p == 2)
{
Message.show("陌生人", "孺子可教也,来我这里有一本奇书,就此传授给你。", "face4_2.png", Message.Face.RIGHT);
block();
Message.showtip("获得《九阳正经》");
block();
Item.add_item(5,1);
p = 3;
}
else if (p == 3)
{
Message.show("陌生人", "", "face4_2.png", Message.Face.RIGHT);
block();
}
}
Player.status = player_last_status;
}
public static void block()
{
while (Player.status == Player.Status.PANEL)
Application.DoEvents();
}
*/
//控制变量
public static int[] p = new int[100]; //100个剧情变量
public static Task[] task; //保存所有任务
public static int id = 0; //当前任务id
public static int step = 0; //当前的步住
public static Player.Status player_last_status = Player.Status.WALK;
public int npc_id = -1; //预设条件1:触发的npc
public enum VARTYPE
{
ANY=0, //不做处理
EQUAL=1, //相等
GREATER=2, //大于
LESS=3, //小于
}
public int cvar1_index = 0; //预设条件2:二组剧情变量
public int cvar1 = 0;
public VARTYPE cvar1_type = VARTYPE.ANY;
public int cvar2_index = 0;
public int cvar2 = 0;
public VARTYPE cvar2_type = VARTYPE.ANY;
public int money = 0; //预设条件3:金钱
public VARTYPE money_type = VARTYPE.ANY;
//预设条件判断
public int check_conditions(int index)
{
//预设条件
//id
if (index != npc_id)
return -1;
//var1
if (cvar1_type == VARTYPE.EQUAL)
{
if (p[cvar1_index] != cvar1)
return -1;
}
else if (cvar1_type == VARTYPE.GREATER)
{
if (p[cvar1_index] <= cvar1)
return -1;
}
else if (cvar1_type == VARTYPE.LESS)
{
if (p[cvar1_index] >= cvar1)
return -1;
}
//var2
if (cvar2_type == VARTYPE.EQUAL)
{
if (p[cvar2_index] != cvar2)
return -1;
}
else if (cvar2_type == VARTYPE.GREATER)
{
if (p[cvar2_index] <= cvar2)
return -1;
}
else if (cvar2_type == VARTYPE.LESS)
{
if (p[cvar2_index] >= cvar2)
return -1;
}
//money
if (money_type == VARTYPE.EQUAL)
{
if (Player.money != cvar2)
return -1;
}
else if (money_type == VARTYPE.GREATER)
{
if (Player.money <= cvar2)
return -1;
}
else if (money_type == VARTYPE.LESS)
{
if (Player.money >= cvar2)
return -1;
}
return 0;
}
public enum VARRESULT
{
NOTHING=0, //不处理
ASSIGN=1, //赋值
ADD=2, //加
SUB=3, //减
}
public int rvar1_index = 0;
public int rvar1 = 0;
public VARRESULT rvar1_type = VARRESULT.NOTHING;
public int rvar2_index = 0;
public int rvar2 = 0;
public VARRESULT rvar2_type = VARRESULT.NOTHING;
//预设结果处理
public void deal_result()
{
//预设结果
//rvar1
if (rvar1_type == VARRESULT.ASSIGN)
{
p[rvar1_index] = rvar1;
}
else if (rvar1_type == VARRESULT.ADD)
{
p[rvar1_index] += rvar1;
}
else if (rvar1_type == VARRESULT.SUB)
{
p[rvar1_index] -= rvar1;
}
//rvar2
if (rvar2_type == VARRESULT.ASSIGN)
{
p[rvar2_index] = rvar2;
}
else if (rvar2_type == VARRESULT.ADD)
{
p[rvar2_index] += rvar2;
}
else if (rvar2_type == VARRESULT.SUB)
{
p[rvar2_index] -= rvar2;
}
}
public delegate int Task_event(int index,int step);
public event Task_event evt;
//task_event返回值
//1处理成功 -1条件判断失败
//其他走到第几步
public int task_event(int task_id, int step)
{
int ret = 0;
if (evt != null)
{
ret = evt(task_id,step);
Task.step = ret;
}
return ret;
}
public int var1 = 0; //辅助变量
public int var2 = 0;
public int var3 = 0;
public int var4 = 0;
//——---------------------------------------
// set的重裁
//-------------------------------------------
public void set(int npc_id,Task_event evt,int cvar1_index,int cvar1,VARTYPE cvar1_type,int cvar2_index,int cvar2,VARTYPE cvar2_type,int money,VARTYPE money_type,int rvar1_index,int rvar1,VARRESULT rvar1_type,int rvar2_index,int rvar2,VARRESULT rvar2_type,int var1,int var2,int var3,int var4)
{
this.npc_id = npc_id;
this.evt += evt;
this.cvar1 = cvar1;
this.cvar1_index = cvar1_index;
this.cvar1_type = cvar1_type;
this.cvar2 = cvar2;
this.cvar2_index = cvar2_index;
this.cvar2_type = cvar2_type;
this.money = money;
this.money_type = money_type;
this.rvar1 = rvar1;
this.rvar1_index = rvar1_index;
this.rvar1_type = rvar1_type;
this.rvar2 = rvar2;
this.rvar2_index = rvar2_index;
this.rvar2_type = rvar2_type;
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
this.var4 = var4;
}
public void set(int npc_id, Task_event evt, int cvar1_index, int cvar1, VARTYPE cvar1_type, int rvar1_index, int rvar1, VARRESULT rvar1_type, int var1, int var2, int var3, int var4)
{
set(npc_id,evt,cvar1_index,cvar1,cvar1_type,0,0,VARTYPE.ANY,0,VARTYPE.ANY,rvar1_index, rvar1,rvar1_type,0,0,VARRESULT.NOTHING, var1, var2, var3, var4);
}
public void set(int npc_id, Task_event evt, int cvar1_index, int cvar1, VARTYPE cvar1_type, int rvar1_index, int rvar1, VARRESULT rvar1_type)
{
set(npc_id,evt,cvar1_index,cvar1,cvar1_type,rvar1_index,rvar1,rvar1_type,0,0,0,0);
}
public void set(int npc_id, Task_event evt, int var1, int var2, int var3, int var4)
{
set(npc_id,evt,0,0,VARTYPE.ANY,0,0,VARRESULT.NOTHING,var1,var2,var3,var4);
}
public void set(int npc_id, Task_event evt)
{
set(npc_id,evt,0,0,0,0);
}
//----------------------------------------------------------------------------------
// 任务流程,普通的调用还是步骤调用
//-----------------------------------------------------------------------------------------
public static void story(int npc_id, int type)//0-正常 1-回调
{
//保存状态
if (Player.status != Player.Status.TASK)
player_last_status = Player.status;
Player.status = Player.Status.TASK;
//事件
if (task == null) return;
if (type == 1 && id >= 0)
{
int ret = task[id].task_event(id,step);
if (ret == 0)
task[id].deal_result();
}
else if(type==0)
for (int i = task.Length - 1; i >= 0; i--)
{
if (task[i] == null) continue;
if (task[i].check_conditions(npc_id) != 0) continue;
id = i;
step = 0;
int ret = task[i].task_event(i,step);
if (ret == 0)
task[i].deal_result();
break;
}
//恢复状态
Player.status = player_last_status;
}
public static void story(int i)
{
story(i,0);
}
//切换地图
//var1 map_id
//var2 var3 坐标
//var4 面向
public static int change_map(int task_id, int step)
{
if (task == null) return -1;
if (task[task_id] == null) return - 1;
int map_id = task[task_id].var1;
int x = task[task_id].var2;
int y = task[task_id].var3;
int f = task[task_id].var4;
Map.change_map(Form1.map,Form1.player,Form1.npc,map_id,x,y,f,Form1.music_player);
return 0;
}
//------------------------------------------------------------------------------
// 功能封装
//------------------------------------------------------------------------------
public static void change_map(int map_id, int x, int y, int face) //切换地图
{
Map.change_map(Form1.map, Form1.player, Form1.npc, map_id, x, y, face, Form1.music_player);
}
public static void talk(string name, string str, string face, Message.Face fpos)//对话
{
Message.show(name,str,face,fpos);
block();
}
public static void talk(string name, string str, string face)
{
Message.show(name,str,face,Message.Face.LEFT);
block();
}
public static void tip(string str)//提示
{
Message.showtip(str);
block();
}
public static void set_npc_pos(int npc_id, int x, int y)//设置npc位置
{
if (Form1.npc == null) return;
if (Form1.npc[npc_id] == null) return;
Form1.npc[npc_id].x = x;
Form1.npc[npc_id].y = y;
}
public static void play_npc_anm(int npc_id, int anm_id)//播放npc动画
{
if (Form1.npc == null) return;
if (Form1.npc[npc_id] == null) return;
Form1.npc[4].play_anm(anm_id);
}
public static void fight(int [] enemy,string bg_path,int isgameover,int winitem1,int winitem2,int winitem3,int losemoney)//战斗
{
Fight.start(enemy,bg_path,isgameover,winitem1,winitem2,winitem3,losemoney);
}
public static void add_item(int item_id, int num)//增减物品
{
Item.add_item(item_id,num);
}
public static void learn_skill(int p_id, int skill_id, int type)//学习技能
{
Skill.learn_skill(p_id,skill_id,type);
}
public static void recover()//恢复
{
if (Form1.player == null) return;
for (int i = 0; i < Form1.player.Length; i++)
{
if (Form1.player[i] == null) continue;
Form1.player[i].hp = Form1.player[i].max_hp;
Form1.player[i].mp = Form1.player[i].max_mp;
}
tip("完全恢复!");
}
public static void save()//保存
{
}
public static void block()//阻断
{
Form1.set_timer_interval(100);
while (Player.status == Player.Status.PANEL)
Application.DoEvents();
Form1.set_timer_interval(50);
}
}
|
using A4CoreBlog.Data.Services.Contracts;
using A4CoreBlog.Data.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace A4CoreBlog.Web.Areas.Admin.Controllers
{
public class UserController : BaseAdminController
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
public IActionResult MyProfile()
{
var currentUsername = User.Identity.Name;
var model = _userService.Get<UserProfileViewModel>(currentUsername);
return View(model);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
public class ScoreManager : MonoBehaviour {
private static List<ScoreBoard> Boards = new List<ScoreBoard>();
public static void GenerateScoreBoards(int amount, bool reset = false) {
if (reset) {
Boards.Clear();
}
for (int i = Boards.Count; i < amount; i++) {
Boards.Add(new ScoreBoard());
}
}
public static ScoreBoard Board(int index) {
if (index <= (Boards.Count - 1)) {
return Boards[index];
} else {
UnityEngine.Debug.Log("ScoreManager: Index does not exist in ScoreBoards list");
return null;
}
}
public static long GetGrandTotalScore(int index) {
if (index <= (Boards.Count - 1)) {
long[] three = Boards[index].GetAllThree();
long grandTotal = 0;
foreach (int nr in three) {
grandTotal += nr;
}
return grandTotal;
} else {
UnityEngine.Debug.Log("ScoreManager: Index does not exist in ScoreBoards list");
return 0;
}
}
public static void ClearAllScores() {
foreach (ScoreBoard board in Boards) {
board.ClearScores();
}
}
//Test code for anyone who wants it
/*
ScoreManager.GenerateScoreBoards(2);
ScoreBoard boardOne = ScoreManager.Board(0);
boardOne.AddRemix(500);
boardOne.AddSkill(ScoreSkill.DRIFT, 1000);
Debug.Log("Remix score: " + ScoreManager.Board(0).GetRemix());
Debug.Log("Drift score: " + ScoreManager.Board(0).GetSkill(ScoreSkill.DRIFT));
*/
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace FoodApp.Models
{
public class Tag
{
[Required]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Must be between 3 and 30 characters")]
public string Name { get; set; }
public int Id { get; set; }
public virtual ICollection<Recipe> Recipes { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MVCPatternAPP.Data.DatabaseContext;
using MVCPatternAPP.Data.Repository.Interface;
using MVCPatternAPP.Entity.Models;
namespace MVCPatternAPP.Data.Repository
{
public class CategoryRepository:ICategory
{
private readonly MvcPatternDbContext _context;
private bool _disposed = false;
public CategoryRepository()
{
_context=new MvcPatternDbContext();
}
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this._disposed = true;
}
public IQueryable<Category> ShowCategories(string search)
{
try
{
var quarableCategory = from c in _context.Categories select c;
if (!string.IsNullOrEmpty(search))
{
quarableCategory = quarableCategory.Where(c => c.CategoryName.Contains(search));
}
return quarableCategory;
}
catch (Exception)
{
throw;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public IEnumerable<Category> GetAllCategory()
{
try
{
return _context.Categories.ToList();
}
catch (Exception)
{
throw;
}
}
}
}
|
using System;
namespace cSharpGPX
{
public struct GPX_PositionStruct
{
private string _latitude;
private string _longitude;
public GPX_PositionStruct(double latitude, double longitude)
{
this._latitude = latitude.ToString();
this._longitude = longitude.ToString();
}
public string ToXMLstring()
{
return String.Format("lat=\"{0}\" lon=\"{1}\"", this._latitude, this._longitude);
}
public string Latitude
{
get { return this._latitude;}
}
public string Longitude
{
get { return this._longitude; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DistCWebSite.Core.ViewModel
{
public class EMNewExportViewModel
{
public string Province { get; set; }
/// <summary>
///文件上传时间
/// </summary>
public DateTime? UploadDate { get; set; }
public string Region { get; set; }
public string SFEName { get; set; }
public string SFECode { get; set; }
public string HosName { get; set; }
/// <summary>
/// 预计开发时间
/// </summary>
public DateTime? ExpectDevDate { get; set; }
/// <summary>
/// 终端客户类型,true表示分销,false表示直销
/// </summary>
public bool? ByTwoLevel { get; set; }
/// <summary>
/// 二级商名称
/// </summary>
public string TLDName { get; set; }
/// <summary>
/// Year-to-go试剂销量预估
/// </summary>
public decimal? RGT_YTGSales { get; set; }
/// <summary>
/// Year-to-go仪器+LI销量预估
/// </summary>
public decimal? InstLI_YTGSales { get; set; }
/// <summary>
/// Year-to-go仪器e411销量预估
/// </summary>
public decimal? InstE411_YTGSales { get; set; }
/// <summary>
/// Year-to-go销量预估
/// </summary>
public decimal? Total_YTGSales { get; set; }
public string Remark { get; set; }
/// <summary>
/// 月平均测试数
/// </summary>
public string YATM { get; set; }
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using BlazorShared.Models.Client;
using Microsoft.Extensions.Logging;
namespace FrontDesk.Blazor.Services
{
public class ClientService
{
private readonly HttpService _httpService;
private readonly ILogger<ClientService> _logger;
public ClientService(HttpService httpService, ILogger<ClientService> logger)
{
_httpService = httpService;
_logger = logger;
}
public async Task<ClientDto> CreateAsync(CreateClientRequest client)
{
return (await _httpService.HttpPostAsync<CreateClientResponse>("clients", client)).Client;
}
public async Task<ClientDto> EditAsync(UpdateClientRequest client)
{
return (await _httpService.HttpPutAsync<UpdateClientResponse>("clients", client)).Client;
}
public async Task DeleteAsync(int clientId)
{
await _httpService.HttpDeleteAsync<DeleteClientResponse>("clients", clientId);
}
public async Task<ClientDto> GetByIdAsync(int clientId)
{
return (await _httpService.HttpGetAsync<GetByIdClientResponse>($"clients/{clientId}")).Client;
}
public async Task<List<ClientDto>> ListPagedAsync(int pageSize)
{
_logger.LogInformation("Fetching clients from API.");
return (await _httpService.HttpGetAsync<ListClientResponse>($"clients")).Clients;
}
public async Task<List<ClientDto>> ListAsync()
{
_logger.LogInformation("Fetching clients from API.");
return (await _httpService.HttpGetAsync<ListClientResponse>($"clients")).Clients;
}
}
}
|
using System;
using Uintra.Core.Activity.Entities;
using Uintra.Core.Member.Abstractions;
namespace Uintra.Features.Events
{
public class EventBase : IntranetActivity, IHaveCreator, IHaveOwner
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public DateTime PublishDate { get; set; }
public Guid CreatorId { get; set; }
public Guid OwnerId { get; set; }
public int? UmbracoCreatorId { get; set; }
public string LocationTitle { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class PauseMenu : MonoBehaviour {
[SerializeField] private GameObject scriptPiggy;
[SerializeField] private GameObject pauseMenuPanel;
private UIHandler uiHandler;
private CanvasGroup canvas;
private bool isActive;
// Use this for initialization
void Start () {
uiHandler = scriptPiggy.GetComponent<UIHandler>();
canvas = GetComponent<CanvasGroup>();
canvas.alpha = 0;
//pauseMenuPanel.transform.position = transformInitial;
}
// Update is called once per frame
void Update () {
//float alpha = uiHandler.isPaused ? 1f : 0f;
//canvas.DOFade(alpha, 0.1f);
//canvas.interactable = uiHandler.isPaused;
//canvas.blocksRaycasts = uiHandler.isPaused;
if (uiHandler.isPaused && !isActive)
{
ToggleMenu(1f);
isActive = true;
}
if (!uiHandler.isPaused && isActive)
{
ToggleMenu(0f);
isActive = false;
}
}
public void ToggleMenu(float alpha)
{
//float alpha = uiHandler.isPaused ? 1f : 0f;
canvas.DOFade(alpha, 0.2f);
canvas.interactable = uiHandler.isPaused;
canvas.blocksRaycasts = uiHandler.isPaused;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.Area
{
public class IArea : Area
{
}
/// <summary>
/// 区域
/// </summary>
public class Area
{
public string Code
{
get;
set;
}
/// <summary>
/// 父ID
/// </summary>
public string ParentCode
{
get;
set;
}
public int Level
{
get;
set;
}
public string Name
{
get;
set;
}
public override string ToString()
{
return Name;
}
}
}
|
using System;
using System.Collections.Generic;
using Android.Support.V4.App;
using Java.Lang;
namespace Groceries.MonoDroid
{
public class ViewPagerAdapter: FragmentPagerAdapter {
private List<Fragment> fragmentList;
private List<string> fragmentTitleList = new List<string> ();
public ViewPagerAdapter(FragmentManager manager):base(manager) {
fragmentList = new List<Fragment>();
fragmentTitleList = new List<string> ();
}
public override Fragment GetItem (int position)
{
return fragmentList [position];
}
public override int Count {
get {
return fragmentList.Count;
}
}
public void AddFrag(Fragment fragment, string title) {
fragmentList.Add(fragment);
fragmentTitleList.Add(title);
}
public override ICharSequence GetPageTitleFormatted (int position)
{
//return new Java.Lang.String (fragmentTitleList [position]);
return null;
}
}
}
|
using Backend.Model.Manager;
using Backend.Service.DrugAndTherapy;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
namespace GraphicalEditorServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DrugInRoomController : ControllerBase
{
private readonly IDrugInRoomService _drugInRoomService;
public DrugInRoomController(IDrugInRoomService drugInRoomService)
{
_drugInRoomService = drugInRoomService;
}
[HttpPost]
public ActionResult AddDrugInRoom([FromBody] String JSONString)
{
Console.WriteLine("usao u kontroler");
String JSONContent = StringToJSONFormat(JSONString);
DrugInRoom drugInRoom = JsonConvert.DeserializeObject<DrugInRoom>(JSONContent);
_drugInRoomService.AddDrugInRoom(drugInRoom);
return Ok();
}
private string StringToJSONFormat(string JSONString)
{
string[] atributes = JSONString.Split(",");
String JSONContent = "{";
JSONContent += JSONString;
JSONContent += "}";
return JSONContent;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GDS.Comon
{
///<summary>
///Module ID:
///Depiction: 公共处理SqlParameter的工具类
///</summary>
public class ParameterTools
{
/// <summary>
/// 创建SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="value">参数值</param>
/// <returns>SqlParameter对象</returns>
public static SqlParameter CreateSqlParameter(string name, SqlDbType type, object value)
{
if (value == null)
{
value = DBNull.Value;
}
if (!name.StartsWith("@"))
{
name = "@" + name;
}
SqlParameter sp = new SqlParameter(name, type);
sp.Value = value;
return sp;
}
public static SqlParameter CreateSqlParameter(string name, SqlDbType type)
{
if (!name.StartsWith("@"))
{
name = "@" + name;
}
SqlParameter sp = new SqlParameter(name, type);
return sp;
}
/// <summary>
/// 创建SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="direction">参数值</param>
/// <returns>SqlParameter对象</returns>
public static SqlParameter CreateSqlParameter(string name, SqlDbType type, ParameterDirection direction)
{
if (!name.StartsWith("@"))
{
name = "@" + name;
}
SqlParameter sp = new SqlParameter(name, type);
sp.Direction = direction;
return sp;
}
/// <summary>
/// 创建SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="size">参数值</param>
/// <param name="value">SqlParameter对象</param>
/// <returns>SqlParameter对象</returns>
public static SqlParameter CreateSqlParameter(string name, SqlDbType type, int size, object value)
{
if (value == null)
{
value = DBNull.Value;
}
if (!name.StartsWith("@"))
{
name = "@" + name;
}
SqlParameter sp = new SqlParameter(name, type, size);
sp.Value = value;
return sp;
}
/// <summary>
/// 创建SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="size">参数值</param>
/// <param name="value">SqlParameter对象</param>
/// <param name="direction">方向</param>
/// <returns>SqlParameter对象</returns>
public static SqlParameter CreateSqlParameter(string name, SqlDbType type, int size, object value, ParameterDirection direction)
{
if (value == null)
{
value = DBNull.Value;
}
if (!name.StartsWith("@"))
{
name = "@" + name;
}
SqlParameter sp = new SqlParameter(name, type, size);
sp.Direction = direction;
sp.Value = value;
return sp;
}
List<SqlParameter> lstPara = new List<SqlParameter>();
/// <summary>
/// 添加SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="value">值</param>
public void AddSqlParameter(string name, SqlDbType type, object value)
{
lstPara.Add(CreateSqlParameter(name, type, value));
}
/// <summary>
/// 添加SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="size">大小</param>
/// <param name="value">值</param>
public void AddSqlParameter(string name, SqlDbType type, int size, object value)
{
lstPara.Add(CreateSqlParameter(name, type, size, value));
}
/// <summary>
/// 添加SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="size">大小</param>
/// <param name="value">值</param>
/// <param name="direction">方向</param>
public void AddSqlParameter(string name, SqlDbType type, int size, object value, ParameterDirection direction)
{
lstPara.Add(CreateSqlParameter(name, type, size, value, direction));
}
/// <summary>
/// 添加SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
internal void AddSqlParameter(string name, SqlDbType type)
{
lstPara.Add(CreateSqlParameter(name, type));
}
/// <summary>
/// 添加SqlParameter对象
/// </summary>
/// <param name="name">名称</param>
/// <param name="type">类型</param>
/// <param name="direction">方向</param>
public void AddSqlParameter(string name, SqlDbType type, ParameterDirection direction)
{
lstPara.Add(CreateSqlParameter(name, type, direction));
}
/// <summary>
/// 得到SqlParameter数组
/// </summary>
/// <returns>SqlParameter数组</returns>
public SqlParameter[] GetSqlParameters()
{
return lstPara.ToArray();
}
public static DateTime? GetDateTime(object o)
{
if (o == DBNull.Value)
{
return null;
}
else
{
return (DateTime)o;
}
}
public static string GetString(object o)
{
if (o == DBNull.Value)
{
return null;
}
else
{
return o.ToString();
}
}
public static Guid? GetGuid(object o)
{
if (o == DBNull.Value)
{
return null;
}
else
{
return (Guid)o;
}
}
public static long? GetLong(object o)
{
if (o == DBNull.Value)
{
return null;
}
else
{
return (long)o;
}
}
public static bool? GetBool(object o)
{
if (o == DBNull.Value)
{
return null;
}
else
{
return Convert.ToBoolean(o);
}
}
public static int? GetInt(object o)
{
if (o == DBNull.Value)
{
return null;
}
else if (o is bool)
{
if ((bool)o)
{
return 1;
}
else
{
return 0;
}
}
else
{
return int.Parse(o.ToString());
}
}
public static double? GetDouble(object o)
{
if (o == DBNull.Value)
{
return null;
}
else
{
return double.Parse(o.ToString());
}
}
public SqlParameter GetSqlParameterByName(string name)
{
if (!name.StartsWith("@"))
{
name = "@" + name;
}
foreach (SqlParameter sp in lstPara)
{
if (sp.ParameterName == name)
{
return sp;
}
}
return null;
}
/// <summary>
/// 根据参数名称得到SqlParameter
/// </summary>
/// <param name="name">参数名</param>
/// <returns></returns>
public SqlParameter GetParameter(String name)
{
foreach (SqlParameter s in lstPara)
{
if (s.ParameterName == "@" + name || s.ParameterName == name)
{
return s;
}
}
return null;
}
}
}
|
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebCore.Fileters
{
public class MyAsyncResourceFilterAttribute : IAsyncResourceFilter
{
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
Console.WriteLine("资源请求前");
await next();
Console.WriteLine("资源请求后");
}
}
}
|
using System.Collections.Generic;
namespace SsWkPdf.ServiceModel
{
public interface IPagedResponse<T>
{
IEnumerable<T> Data { get; set; }
IPagingMetadata Meta { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EstalagControl : MonoBehaviour
{
public GameObject Target;
public GameObject ShotEstalagPrefab;
// Use this for initialization
void Start ()
{
StartCoroutine (ShotEstalagRoutine());
}
// Update is called once per frame
void Update ()
{
GetComponent<NavMeshAgent> ().destination = Target.transform.position;
}
IEnumerator ShotEstalagRoutine()
{
while (true)
{
GameObject estalag = Instantiate(ShotEstalagPrefab, transform.position, Quaternion.identity);
Destroy (estalag, 5f);
yield return new WaitForSeconds (3.0f);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.