text stringlengths 13 6.01M |
|---|
namespace IRO.ImageOrganizer.Logic
{
public sealed class MetadataStripper
{
private static readonly MetadataStripper m_instance = new MetadataStripper();
/// <summary>
/// Gets the instance.
/// </summary>
public static MetadataStripper Instance { get { return m_instance; } }
/// <summary>
/// Prevents a default instance of the <see cref="MetadataStripper"/> class from being created.
/// </summary>
private MetadataStripper() { }
}
}
|
using System;
using Terraria.ID;
using Terraria.ModLoader;
namespace Caserraria
{
class Caserraria : Mod
{
internal bool thoriumLoaded;
internal bool calamityLoaded;
internal bool cosmeticvarietyLoaded;
internal bool tremorLoaded;
static internal Caserraria instance;
public Caserraria()
{
Properties = new ModProperties()
{
Autoload = true,
AutoloadGores = true,
AutoloadSounds = true
};
}
public override void PostSetupContent()
{
Mod LootBags = ModLoader.GetMod("LootBags");
if (LootBags != null)
{
LootBags.Call(.0, ItemType("Unknownparts"), 1, 1, 6);
LootBags.Call(.0, ItemType("KnightmetalBar"), 10, 30, 3);
}
try
{
thoriumLoaded = ModLoader.GetMod("ThoriumMod") != null;
calamityLoaded = ModLoader.GetMod("CalamityMod") != null;
cosmeticvarietyLoaded = ModLoader.GetMod("CosmeticVariety") != null;
tremorLoaded = ModLoader.GetMod("Tremor") != null;
}
catch (Exception e)
{
ErrorLogger.Log("Caserraria PostSetupContent Error: " + e.StackTrace + e.Message);
}
Mod bossChecklist = ModLoader.GetMod("BossChecklist");
if (bossChecklist != null)
{
// To include a description:
bossChecklist.Call("AddBossWithInfo", "Forest Spirit", 1.1f, (Func<bool>)(() => MyWorld.downedForestSpirit), "Use [i:" + ItemType("ForestTotem") + "] during the day");
}
}
public override void Load()
{
instance = this;
}
public override void AddRecipes()
{
if (Caserraria.instance.thoriumLoaded)
{
ModRecipe recipe = new ModRecipe(this);
recipe.AddIngredient(null, "TrueHallowedComp", 1);
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("TrueHemmorage"));
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModLoader.GetMod("ThoriumMod").ItemType("TerraBow"));
recipe.AddRecipe();
recipe = new ModRecipe(this);
recipe.AddIngredient(null, "TrueHallowedComp", 1);
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("TrueEternalNight"));
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModLoader.GetMod("ThoriumMod").ItemType("TerraBow"));
recipe.AddRecipe();
recipe = new ModRecipe(this);
recipe.AddIngredient(null, "HallowedComp", 1);
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("StrangePlating"), 12);
recipe.AddIngredient(ItemID.HallowedBar, 4);
recipe.AddIngredient(ItemID.SoulofMight, 5);
recipe.AddTile(ModLoader.GetMod("ThoriumMod").TileType("SoulForge"));
recipe.SetResult(ModLoader.GetMod("ThoriumMod").ItemType("DestroyersRage"));
recipe.AddRecipe();
if (Caserraria.instance.calamityLoaded)
{
recipe = new ModRecipe(this);
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("TrueBloodThirster"));
recipe.AddIngredient(ItemID.TrueExcalibur, 1);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModLoader.GetMod("CalamityMod").ItemType("TerraEdge"));
recipe.AddRecipe();
recipe = new ModRecipe(this);
recipe.AddIngredient(ModLoader.GetMod("CalamityMod").ItemType("TrueCausticEdge"));
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("TrueBloodThirster"));
recipe.AddIngredient(ItemID.FlaskofVenom, 5);
recipe.AddIngredient(ItemID.FlaskofCursedFlames, 5);
recipe.AddIngredient(ItemID.ChlorophyteBar, 15);
recipe.AddTile(TileID.DemonAltar);
recipe.SetResult(ModLoader.GetMod("CalamityMod").ItemType("TyrantYharimsUltisword"));
recipe.AddRecipe();
recipe = new ModRecipe(this);
recipe.AddIngredient(ModLoader.GetMod("CalamityMod").ItemType("TrueCausticEdge"));
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("TrueBloodThirster"));
recipe.AddIngredient(ItemID.FlaskofVenom, 5);
recipe.AddIngredient(ItemID.FlaskofIchor, 5);
recipe.AddIngredient(ItemID.ChlorophyteBar, 15);
recipe.AddTile(TileID.DemonAltar);
recipe.SetResult(ModLoader.GetMod("CalamityMod").ItemType("TyrantYharimsUltisword"));
recipe.AddRecipe();
if (Caserraria.instance.tremorLoaded)
{
recipe = new ModRecipe(this);
recipe.AddIngredient(ModLoader.GetMod("Tremor").ItemType("TrueBloodCarnage"));
recipe.AddIngredient(ItemID.TrueExcalibur, 1);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModLoader.GetMod("CalamityMod").ItemType("TerraEdge"));
recipe.AddRecipe();
recipe = new ModRecipe(this);
recipe.AddIngredient(ModLoader.GetMod("CalamityMod").ItemType("TrueCausticEdge"));
recipe.AddIngredient(ModLoader.GetMod("Tremor").ItemType("TrueBloodCarnage"));
recipe.AddIngredient(ItemID.FlaskofVenom, 5);
recipe.AddIngredient(ItemID.FlaskofCursedFlames, 5);
recipe.AddIngredient(ItemID.ChlorophyteBar, 15);
recipe.AddTile(TileID.DemonAltar);
recipe.SetResult(ModLoader.GetMod("CalamityMod").ItemType("TyrantYharimsUltisword"));
recipe.AddRecipe();
recipe = new ModRecipe(this);
recipe.AddIngredient(ModLoader.GetMod("CalamityMod").ItemType("TrueCausticEdge"));
recipe.AddIngredient(ModLoader.GetMod("Tremor").ItemType("TrueBloodCarnage"));
recipe.AddIngredient(ItemID.FlaskofVenom, 5);
recipe.AddIngredient(ItemID.FlaskofIchor, 5);
recipe.AddIngredient(ItemID.ChlorophyteBar, 15);
recipe.AddTile(TileID.DemonAltar);
recipe.SetResult(ModLoader.GetMod("CalamityMod").ItemType("TyrantYharimsUltisword"));
recipe.AddRecipe();
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.Azure;
using System.Data.SqlClient;
using UniversityDbCommon.Models;
using System.Data;
using System.IO;
using System.Net.Mail;
using System.Web.Script.Serialization;
namespace UniversityDbWorker
{
public class WorkerRole : RoleEntryPoint
{
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);
private CloudQueue imagesQueue;
private CloudBlobContainer imagesBlobContainer;
private string connString;
private SqlConnection connection;
public override void Run()
{
Trace.TraceInformation("UniversityDbWorker is running");
CloudQueueMessage message = null;
if (connection == null) {
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "NHATVHNSE61418\\MS5";
builder.InitialCatalog = "UniversityDatabase";
builder.UserID = "sa";
// builder.Password = "123";
builder.IntegratedSecurity = true;
connection = new SqlConnection(builder.ConnectionString);
connection.Open();
}
while (true)
{
try
{
GetGradeMailMessage();
getInformailMessage();
}
catch (StorageException e)
{
if (message != null && message.DequeueCount > 5)
{
this.imagesQueue.DeleteMessage(message);
Trace.TraceError("Deleting poison queue item: '{0}'", message.AsString);
}
Trace.TraceError("Exception in UniversityDbWorker: '{0}'", e.Message);
System.Threading.Thread.Sleep(5000);
}
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357.
try
{
connString = CloudConfigurationManager.GetSetting("UniversityDbConnectionString");
// Open storage account using credentials from .cscfg file.
var storageAccount = CloudStorageAccount.Parse
(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
Trace.TraceInformation("Creating images blob container");
var blobClient = storageAccount.CreateCloudBlobClient();
imagesBlobContainer = blobClient.GetContainerReference("university-images");
if (imagesBlobContainer.CreateIfNotExists())
{
// Enable public access on the newly created "images" container.
imagesBlobContainer.SetPermissions(
new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
}
Trace.TraceInformation("Creating images queue");
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
imagesQueue = queueClient.GetQueueReference("university-images");
imagesQueue.CreateIfNotExists();
Trace.TraceInformation("Storage initialized");
}
catch (Exception)
{
throw;
}
Trace.TraceInformation("UniversityDbWorker has been started");
return base.OnStart();
}
public override void OnStop()
{
Trace.TraceInformation("UniversityDbWorker is stopping");
this.cancellationTokenSource.Cancel();
this.runCompleteEvent.WaitOne();
if (connection != null)
{
connection.Close();
}
base.OnStop();
Trace.TraceInformation("UniversityDbWorker has stopped");
}
private async Task RunAsync(CancellationToken cancellationToken)
{
// TODO: Replace the following with your own logic.
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation("Working");
await Task.Delay(1000);
}
}
private string getProfileEmail(int id)
{
string url = null;
string query = "SELECT Email FROM Student WHERE ID = @id";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@id", id);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
url = reader[0].ToString();
}
reader.Close();
return url;
}
public void GetGradeMailMessage()
{
CloudStorageAccount ac = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
CloudQueueClient qclient = ac.CreateCloudQueueClient();
CloudQueue que = qclient.GetQueueReference("nhatvhnqueue");
que.CreateIfNotExists();
CloudQueueMessage mess = que.GetMessage();
if (mess != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMessage emailcontent = serializer.Deserialize<JsonMessage>(mess.AsString);
newGradeMail(emailcontent);
que.DeleteMessage(mess);
}
}
public void getInformailMessage() {
CloudStorageAccount ac = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
CloudQueueClient qclient = ac.CreateCloudQueueClient();
CloudQueue que = qclient.GetQueueReference("StudentMail");
que.CreateIfNotExists();
CloudQueueMessage mess = que.GetMessage();
if (mess != null)
{
String[] content = (mess.AsString).Split(new[] { "[thisisthespliter]" }, StringSplitOptions.RemoveEmptyEntries);
informMail(int.Parse(content[0]) , content[1]);
que.DeleteMessage(mess);
}
}
public async void newGradeMail(JsonMessage mailcontent)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("nhatvhn99@gmail.com")); // replace with valid value
message.From = new MailAddress("dwarpro@gmail.com"); // replace with valid value
message.Subject = "Thong bao sua diem";
String content = "";
content = content + " <p style = 'text-align: center;' ><img title = 'TinyMCE Logo' src = 'www.tinymce.com/images/glyph-tinymce@2x.png' alt = 'TinyMCE Logo' width = '110' height = '97' /></p>";
content = content + " <h1 style = 'text-align: center;' > Hello " + getProfileEmail(int.Parse(mailcontent.StudentID)) + " </h1>";
content = content + " <p> There are some changes in your grades of the " + mailcontent.CourseID + " : </p>";
content = content + " <p> </p>";
content = content + " <table style = 'text -align: center;' border='1' >";
content = content + " <thead>";
content = content + " <tr>";
content = content + " <th> </th>";
content = content + " <th> Quiz 1 </th>";
content = content + " <th> Quiz 2 </th>";
content = content + " <th> Quiz 3 </th>";
content = content + " <th> Project </th>";
content = content + " <th> Midterm </th>";
content = content + " <th> Final </th>";
content = content + " </tr>";
content = content + " </thead>";
content = content + " <tbody>";
content = content + " <tr>";
content = content + " <td> Old </td>";
content = content + " <td>[OldQuiz1] </td>";
content = content + " <td>[OldQuiz2] </td>";
content = content + " <td>[OldQuiz3] </td>";
content = content + " <td>[OldProject] </td>";
content = content + " <td>[OldMidterm] </td>";
content = content + " <td>[OldFinal] </td>";
content = content + " </tr>";
content = content + " <tr>";
content = content + " <td> New </td>";
content = content + " <td>[Quiz1] </td>";
content = content + " <td>[Quiz2] </td>";
content = content + " <td>[Quiz3] </td>";
content = content + " <td>[Project] </td>";
content = content + " <td>[Midterm] </td>";
content = content + " <td>[Final] </td>";
content = content + " </tr>";
content = content + " </tbody>";
content = content + " </table>";
content = content.Replace("[OldQuiz1]", mailcontent.oldQuiz1);
content = content.Replace("[OldQuiz2]", mailcontent.oldQuiz2);
content = content.Replace("[OldQuiz3]", mailcontent.oldQuiz3);
content = content.Replace("[OldProject]", mailcontent.oldProject);
content = content.Replace("[OldMidterm]", mailcontent.oldMidterm);
content = content.Replace("[OldFinal]", mailcontent.oldFinal);
content = content.Replace("[Quiz1]", mailcontent.Quiz1);
content = content.Replace("[Quiz2]", mailcontent.Quiz2);
content = content.Replace("[Quiz3]", mailcontent.Quiz3);
content = content.Replace("[Project]", mailcontent.Project);
content = content.Replace("[Final]", mailcontent.Final);
content = content.Replace("[Midterm]", mailcontent.Midterm);
message.Body = string.Format(body, "dwarpro@gmail.com", "dwarpro@gmail.com", content);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "dwarpro@gmail.com", // replace with valid value
Password = "320395qww" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
}
}
public async void informMail(int id, String content)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress(getProfileEmail(id))); // replace with valid value
message.From = new MailAddress("dwarpro@gmail.com"); // replace with valid value
message.Subject = "Thong bao sua diem";
message.Body = string.Format(body, "dwarpro@gmail.com", "dwarpro@gmail.com", content);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "dwarpro@gmail.com", // replace with valid value
Password = "320395qww" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
}
}
}
public class JsonMessage
{
public JsonMessage(string json)
{
}
public String CourseID { get; set; }
public String StudentID { get; set; }
public String Quiz1 { get; set; }
public String Quiz2 { get; set; }
public String Quiz3 { get; set; }
public String Midterm { get; set; }
public String Project { get; set; }
public String Final { get; set; }
public String oldQuiz1 { get; set; }
public String oldQuiz2 { get; set; }
public String oldQuiz3 { get; set; }
public String oldMidterm { get; set; }
public String oldProject { get; set; }
public String oldFinal { get; set; }
public JsonMessage()
{
CourseID = "";
StudentID = "";
Quiz1 = "";
Quiz2 = "";
Quiz3 = "";
Midterm = "";
Project = "";
Final = "";
oldQuiz1 = "";
oldQuiz2 = "";
oldQuiz3 = "";
oldMidterm = "";
oldProject = "";
oldFinal = "";
}
}
}
|
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;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Data;
using Windows.UI.Xaml.Media.Animation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace FinalProject_AltaherAl_Dulaimi
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
// Gobal Sql Connection
const string connectionString = "Server=(local);Database=Spring2021Exam;User=PapaDario;Password=12345";
private SqlConnection conn = new SqlConnection();
private SqlCommand cmd;
public MainPage()
{
this.InitializeComponent();
nav.OpenPaneLength = 230;
}
protected string myName = "Altaher"; // test purposes
//User u = new User();
// Navigation View
private void NavigationView_Loaded(object sender, RoutedEventArgs e)
{
ContentFrame.Navigate(typeof(Page6));
var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
appView.Title = "Papa Dario Pizza Store";
}
// Navigation View default
private async void NavigationView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
// Firch check the selected item is settings
if (args.IsSettingsSelected)
{
// Launch computer settings when clicked
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:home"));
}
else
{
NavigationViewItem item = args.SelectedItem as NavigationViewItem;
switch (item.Tag.ToString())
{
case "Page1":
ContentFrame.Navigate(typeof(Page1), null, new DrillInNavigationTransitionInfo());
break;
case "Page2":
ContentFrame.Navigate(typeof(Page2), null, new DrillInNavigationTransitionInfo());
Debug.WriteLine(User.getUserInfo());
Debug.WriteLine(User.getFirstLateName());
break;
case "Page3":
ContentFrame.Navigate(typeof(Page3));
break;
case "Page4":
ContentFrame.Navigate(typeof(Page4));
break;
case "Page5":
ContentFrame.Navigate(typeof(Page5));
break;
case "Page6":
ContentFrame.Navigate(typeof(Page6));
break;
case "Page7":
ContentFrame.Navigate(typeof(Page7));
break;
}
}
}
// Connect
public static void SqlConnection()
{
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
Debug.WriteLine(sqlConn.State.ToString());
}
}
// insert
public void tryOut()
{
// when the form loads
conn.ConnectionString = connectionString;
// command object to excute our query
cmd = conn.CreateCommand();
try
{
string query = "INSERT into [dbo].[user] VALUES('"
+ myName + "')";
Debug.WriteLine("before cmd Query");
cmd.CommandText = query;
Debug.WriteLine("After cmd Query");
conn.Open(); // if password , or userName are wrong. Throws error here.
Debug.WriteLine("before EXECUTE");
cmd.ExecuteScalar();
Debug.WriteLine("AFTER EXECUTE");
Debug.WriteLine("Flight Added Successfully");
}
catch (Exception ex)
{
Debug.WriteLine("The throwed error is: " + ex);
}
finally
{
// always executed
cmd.Dispose(); // freze up resources (Memory)
conn.Close(); // close connection
}
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace WebStore.Domain.ViewModels
{
public record SectionViewModel
{
public int Id { get; init; }
public string Name { get; init; }
public int Order { get; init; }
public SectionViewModel Parent { get; init; }
public List<SectionViewModel> ChildSections { get; } = new();
public int ProductsCount { get; set; }
public int TotalProductsCount => ProductsCount + ChildSections.Sum(c => c.TotalProductsCount);
}
}
|
using Microsoft.AspNetCore.Mvc;
using PlayNGoCoffee.Business.ServiceContract;
using System.Collections.Generic;
namespace PlayNGoCoffee.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RecipeIngredientsController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly ICoffeeService _service;
public RecipeIngredientsController(ApplicationDbContext context)
{
this._context = context;
this._service = new CoffeeService(context);
}
// GET: api/RecipeIngredients
[HttpGet]
public IEnumerable<RecipeIngredientDataModel> Get()
{
var recipeIngredients = _service.GetAllIngredients();
return recipeIngredients;
}
// GET: api/RecipeIngredients/5
[HttpGet("{id}", Name = "GetRecipeIngredient")]
public IEnumerable<RecipeIngredientDataModel> Get(int id)
{
var recipeIngredients = this._service.GetIngredientsByRecipeId(id);
return recipeIngredients;
}
// POST: api/RecipeIngredients
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT: api/RecipeIngredients/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] IEnumerable<StockDataModel> updatedStocks)
{
this._service.UpdateStock(updatedStocks, id);
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
|
using System;
using UnityEngine;
namespace Assets.Common.Extensions
{
[Serializable]
public struct Point
{
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public int x;
public int y;
public Vector2 ToVector2()
{
return new Vector2(x, y);
}
}
} |
using System.ComponentModel.DataAnnotations;
using System.Runtime.Remoting.Activation;
namespace MVC4_DavaValidation.Models
{
public class AddUrlViewModel
{
[Required]
[DataType(DataType.Url)]
public string OriginalUrl { get; set; }
public bool UseCustomSlug { get; set; }
[RequiredIfTrue(BooleanPropertyName = "UseCustomSlug", ErrorMessage = "Please provide a custom slug if you opt for one.")]
public string CustomSlug { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ChoiceCenium.Services;
namespace ChoiceCenium.Models
{
public class KjedeInfo
{
private static List<KjedeInfoes> _kjeder;
public static List<KjedeInfoes> GetKjedeInfo()
{
if (_kjeder == null)
{
var db = new ChoiceCenium_dbEntities();
try
{
_kjeder = db.KjedeInfoes.ToList();
}
catch (Exception e)
{
//LogService.Register(e.Message, e.Source, e.ToString());
throw;
}
}
return _kjeder;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GFW
{
/// <summary>
/// 抽象UI挂件基类
/// </summary>
public abstract class UIWidget:UIPanel
{
/// <summary>
/// 打开UI的参数
/// </summary>
protected object m_openArg;
/// <summary>
/// 调用它以打开UIWidget
/// </summary>
public sealed override void Open(object arg = null)
{
LogMgr.Log("Open() arg:{0}", arg);
m_openArg = arg;
if(!this.gameObject.activeSelf)
{
this.gameObject.SetActive(true);
}
OnOpen(arg);
}
/// <summary>
/// 调用它以关闭UIWidget
/// </summary>
public sealed override void Close(object arg = null)
{
LogMgr.Log("Close() arg:{0}", arg);
if(this.gameObject.activeSelf)
{
this.gameObject.SetActive(false);
}
OnClose(arg);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Shimakaze.Toolkit.Csf.Data;
using Shimakaze.Toolkit.Csf.Properties;
namespace Shimakaze.Toolkit.Csf
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
Resource.ResourceManager.I18NInitialize();
ControlzEx.Theming.ThemeManager.Current.ThemeSyncMode = ControlzEx.Theming.ThemeSyncMode.SyncAll;
ControlzEx.Theming.ThemeManager.Current.SyncTheme();
base.OnStartup(e);
this.ChangeThemeBaseColor("Dark");
this.ChangeThemeColorScheme("Purple");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Vendas.Models
{
[Table("tb_pedidovenda")]
public class PedidoVenda
{
[Key]
public int idPedidoVenda { get; set; }
[Required(ErrorMessage = "O campo Razão Social é obrigatório")]
public virtual int? idCliente { get; set; }
public virtual Cliente Cliente { get; set; }
[DisplayName("Data de Emissão")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime dtEmissao { get; set; }
[DisplayName("Valor Total")]
public decimal vValorTotalPedido { get; set; }
public virtual List<PedidoVendaItem> PedidoVendaItens { get; set; }
}
} |
#pragma warning disable 169
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class LaunchLogic : MonoBehaviour
{
[SerializeField]
InputField m_Username;
[SerializeField]
Toggle m_NetPlayToggle;
[SerializeField]
InputField m_HostName;
[SerializeField]
InputField m_Port;
[SerializeField]
Toggle m_ServerToggle;
[SerializeField]
Popup m_Popup;
[SerializeField]
Network m_Network;
public void OnUsernameChanged()
{
LocaleManager.SetSubstitution( "USER", m_Username.text );
}
public void OnLaunch()
{
if ( m_NetPlayToggle.isOn == false )
Application.LoadLevel( "Play" );
else if ( m_ServerToggle.isOn )
StartServer();
else
StartClient();
}
void StartServer()
{
m_Popup.Show( "SERVER_TITLE", "WAIT_FOR_CLIENT", new Dictionary<string,string> () {
{ "PORT", m_Port.text }
});
m_Network.StartServer( int.Parse( m_Port.text ) );
}
void StartClient()
{
m_Popup.Show( "CLIENT_TITLE", "WAIT_FOR_SERVER", new Dictionary<string, string>() {
{ "HOSTNAME", m_HostName.text },
{ "PORT", m_Port.text }
});
m_Network.StartClient( m_HostName.text, int.Parse( m_Port.text ) );
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRAP.Global;
namespace IRAP_FVS_SPCO.XBarR
{
/// <summary>
/// XBar-R 的判定准则
/// </summary>
public class XBarRCriteria
{
private Quantity ucl;
private double highLimitA;
private double highLimitB;
private double middle;
private double lowLimitB;
private double lowLimitA;
private Quantity lcl;
private bool criteria1Judged = false;
private bool criteria2Judged = false;
private bool criteria3Judged = false;
private bool criteria4Judged = false;
private bool criteria5Judged = false;
private bool criteria6Judged = false;
private bool criteria7Judged = false;
private bool criteria8Judged = false;
public XBarRCriteria(
Quantity lcl,
Quantity ucl,
double middle,
int rule)
{
this.ucl = ucl;
this.lcl = lcl;
highLimitA = 0;
highLimitB = 0;
this.middle = middle;
lowLimitB = 0;
lowLimitA = 0;
double splitter1 = (ucl.DoubleValue - middle) / 3;
double splitter2 = (middle - lcl.DoubleValue) / 3;
highLimitA = ucl.DoubleValue - splitter1;
highLimitB = ucl.DoubleValue - splitter1 * 2;
lowLimitB = lcl.DoubleValue + splitter2 * 2;
lowLimitA = lcl.DoubleValue + splitter2;
this.middle = middle;
criteria1Judged = (rule & 1) == 1;
criteria2Judged = (rule & 2) == 2;
criteria3Judged = (rule & 4) == 4;
criteria4Judged = (rule & 8) == 8;
criteria5Judged = (rule & 16) == 16;
criteria6Judged = (rule & 32) == 32;
criteria7Judged = (rule & 64) == 64;
criteria8Judged = (rule & 128) == 128;
}
/// <summary>
/// 准则1:1点落在A区以外
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public bool Criteria1Passed(long point)
{
if (criteria1Judged)
return point <= ucl.IntValue && point >= lcl.IntValue;
else
return true;
}
/// <summary>
/// 准则2:连续6点递增或递减
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public bool Criteria2Passed(List<long> points)
{
if (!criteria2Judged)
return true;
if (points.Count < 6)
return true;
int increasing = 0;
int decreasing = 0;
int equation = 0;
for (int i = 0; i < 5; i++)
{
if (points[i] < points[i + 1])
increasing++;
else if (points[i] > points[i + 1])
decreasing++;
else
equation++;
}
if (increasing == 6 || decreasing == 6)
return false;
else
return true;
}
/// <summary>
/// 准则3:连续7点落在中心线同一侧
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public bool Criteria3Passed(List<long> points)
{
if (!criteria3Judged)
return true;
if (points.Count < 7)
return true;
int cntOfHighArea = 0;
int cntOfLowArea = 0;
for (int i = 0; i < 7; i++)
{
if (points[i] > middle)
cntOfHighArea++;
else if (points[i] < middle)
cntOfLowArea++;
}
if (cntOfHighArea == 7 || cntOfLowArea == 7)
return false;
else
return true;
}
/// <summary>
/// 准则4:连续14点中相邻点交替上下
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public bool Criteria4Passed(List<long> points)
{
if (!criteria4Judged)
return true;
if (points.Count < 14)
return true;
for (int i = 0; i < 12; i++)
{
if ((points[i] - points[i + 1]) *
(points[i + 1] - points[i + 2]) >= 0)
return true;
}
return false;
}
/// <summary>
/// 准则5:连续3点中有2点落在中心线同一侧的B区以外,如果最后一点落在B区内则不算
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public bool Criteria5Passed(List<long> points)
{
if (!criteria5Judged)
return true;
if (points.Count < 3)
return true;
int cntOfHighAreaA = 0;
int cntOfLowAreaA = 0;
for (int i = 0; i < 3; i++)
{
if (points[i] > highLimitA)
cntOfHighAreaA++;
if (points[i] < lowLimitA)
cntOfLowAreaA++;
}
if ((cntOfHighAreaA >= 2 ||
cntOfLowAreaA >= 2) &&
(points[2] > highLimitA ||
points[2] < lowLimitA))
return false;
else
return true;
}
/// <summary>
/// 准则6:连续5点中有4点落在中心线同一侧的C区以外
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public bool Criteria6Passed(List<long> points)
{
if (!criteria6Judged)
return true;
if (points.Count < 5)
return true;
int cntOfHighArea = 0;
int cntOfLowArea = 0;
for (int i = 0; i < 5; i++)
{
if (points[i] > highLimitB)
cntOfHighArea++;
if (points[i] < lowLimitB)
cntOfLowArea++;
}
if (cntOfHighArea >= 4 || cntOfLowArea >= 4)
return false;
else
return true;
}
/// <summary>
/// 准则7:连续15点落在中心线两侧的C区之内
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public bool Criteria7Passed(List<long> points)
{
if (!criteria7Judged)
return true;
if (points.Count < 15)
return true;
int cntOfPerfectArea = 0;
for (int i = 0; i < 15; i++)
{
if (points[i] <= highLimitB &&
points[i] >= lowLimitB)
cntOfPerfectArea++;
}
return cntOfPerfectArea != 15;
}
/// <summary>
/// 准则8:连续8点落在中心线两侧且无一在C区之内
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
public bool Criteria8Passed(List<long> points)
{
if (!criteria8Judged)
return true;
if (points.Count < 8)
return true;
int cntOfOutPerfectArea = 0;
for (int i = 0; i < 8; i++)
{
if (points[i] > highLimitB ||
points[i] < lowLimitB)
cntOfOutPerfectArea++;
}
return cntOfOutPerfectArea != 8;
}
}
}
|
// <copyright file="TableOfCMAP.cs" company="WaterTrans">
// © 2020 WaterTrans
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using WaterTrans.GlyphLoader.Internal.SFNT;
namespace WaterTrans.GlyphLoader.Internal
{
/// <summary>
/// Table of CMAP.
/// </summary>
internal sealed class TableOfCMAP
{
private readonly Dictionary<int, ushort> _glyphMap;
/// <summary>
/// Initializes a new instance of the <see cref="TableOfCMAP"/> class.
/// </summary>
/// <param name="reader">The <see cref="TypefaceReader"/>.</param>
internal TableOfCMAP(TypefaceReader reader)
{
long basePosition = reader.Position;
TableVersionNumber = reader.ReadUInt16();
NumTables = reader.ReadUInt16();
for (int i = 1; i <= NumTables; i++)
{
EncodingRecords.Add(new EncodingRecord(reader));
}
foreach (var record in EncodingRecords)
{
reader.Position = basePosition + record.Offset;
ushort format = reader.ReadUInt16();
if (format == 0) // Byte encoding table
{
// TODO Not tested. Please provide the font file.
ushort length = reader.ReadUInt16();
ushort language = reader.ReadUInt16();
for (int i = 1; i <= 256; i++)
{
record.GlyphMap[i] = reader.ReadByte();
}
}
else if (format == 2) // High-byte mapping through table
{
ushort length = reader.ReadUInt16();
ushort language = reader.ReadUInt16();
var subHeaderKeys = new List<ushort>();
ushort key;
int maxIndex = 0;
for (int i = 1; i <= 256; i++)
{
key = reader.ReadUInt16();
if (key != 0 && key / 8 > maxIndex)
{
maxIndex = key / 8;
}
subHeaderKeys.Add(key);
}
var subHeaders = new List<Tuple<ushort, ushort, short, ushort>>();
for (int i = 0; i <= maxIndex; i++)
{
subHeaders.Add(Tuple.Create(reader.ReadUInt16(), reader.ReadUInt16(), reader.ReadInt16(), reader.ReadUInt16()));
}
// TODO Not tested. Please provide the font file.
}
else if (format == 4) // Segment mapping to delta values
{
ushort length = reader.ReadUInt16();
ushort language = reader.ReadUInt16();
ushort segCountX2 = reader.ReadUInt16();
ushort searchRange = reader.ReadUInt16();
ushort entrySelector = reader.ReadUInt16();
ushort rangeShift = reader.ReadUInt16();
var endCodes = new List<ushort>();
int segCount = segCountX2 / 2;
for (int i = 1; i <= segCount; i++)
{
endCodes.Add(reader.ReadUInt16());
}
ushort reservedPad = reader.ReadUInt16();
var startCodes = new List<ushort>();
for (int i = 1; i <= segCount; i++)
{
startCodes.Add(reader.ReadUInt16());
}
var idDeltas = new List<short>();
for (int i = 1; i <= segCount; i++)
{
idDeltas.Add(reader.ReadInt16());
}
var idRangeOffsets = new List<ushort>();
for (int i = 1; i <= segCount; i++)
{
idRangeOffsets.Add(reader.ReadUInt16());
}
long currentPosition = reader.Position;
for (int i = 0; i < segCount; i++)
{
ushort start = startCodes[i];
ushort end = endCodes[i];
short delta = idDeltas[i];
ushort rangeOffset = idRangeOffsets[i];
if (start != 65535 && end != 65535)
{
for (int j = start; j <= end; j++)
{
if (rangeOffset == 0)
{
record.GlyphMap[j] = (ushort)((j + delta) % 65536);
}
else
{
long glyphOffset = currentPosition + (((rangeOffset / 2) + (j - start) + (i - segCount)) * 2);
reader.Position = glyphOffset;
int glyphIndex = reader.ReadUInt16();
if (glyphIndex != 0)
{
glyphIndex += delta;
glyphIndex %= 65536;
record.GlyphMap[j] = (ushort)glyphIndex;
}
}
}
}
}
}
else if (format == 6) // Trimmed table mapping
{
ushort length = reader.ReadUInt16();
ushort language = reader.ReadUInt16();
ushort firstCode = reader.ReadUInt16();
ushort entryCount = reader.ReadUInt16();
for (int i = 0; i < entryCount; i++)
{
record.GlyphMap[firstCode + i] = reader.ReadUInt16();
}
}
else if (format == 8) // mixed 16-bit and 32-bit coverage
{
ushort reserved = reader.ReadUInt16();
uint length = reader.ReadUInt32();
uint language = reader.ReadUInt32();
var is32 = new List<byte>();
for (int i = 0; i < 8192; i++)
{
is32.Add(reader.ReadByte());
}
uint numGroups = reader.ReadUInt32();
var sequentialMapGroups = new List<Tuple<uint, uint, uint>>();
for (int i = 0; i < numGroups; i++)
{
sequentialMapGroups.Add(Tuple.Create(reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32()));
}
// TODO Not tested. Please provide the font file.
}
else if (format == 10) // Trimmed array
{
// This format is not widely used and is not supported by Microsoft.
}
else if (format == 12) // Segmented coverage
{
ushort reserved = reader.ReadUInt16();
uint length = reader.ReadUInt32();
uint language = reader.ReadUInt32();
uint numGroups = reader.ReadUInt32();
var sequentialMapGroups = new List<Tuple<uint, uint, uint>>();
for (int i = 0; i < numGroups; i++)
{
sequentialMapGroups.Add(Tuple.Create(reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32()));
}
for (int i = 0; i < sequentialMapGroups.Count; i++)
{
uint start = sequentialMapGroups[i].Item1;
uint end = sequentialMapGroups[i].Item2;
uint glyphIndex = sequentialMapGroups[i].Item3;
for (uint j = start; j <= end; j++)
{
record.GlyphMap[(int)j] = (ushort)(glyphIndex + (j - start));
}
}
}
else if (format == 13) // Many-to-one range mappings
{
ushort reserved = reader.ReadUInt16();
uint length = reader.ReadUInt32();
uint language = reader.ReadUInt32();
uint numGroups = reader.ReadUInt32();
var constantMapGroups = new List<Tuple<uint, uint, uint>>();
for (int i = 0; i < numGroups; i++)
{
constantMapGroups.Add(Tuple.Create(reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32()));
}
for (int i = 0; i < constantMapGroups.Count; i++)
{
uint start = constantMapGroups[i].Item1;
uint end = constantMapGroups[i].Item2;
uint glyphIndex = constantMapGroups[i].Item3;
for (uint j = start; j <= end; j++)
{
record.GlyphMap[(int)j] = (ushort)glyphIndex;
}
}
}
else if (format == 14) // Unicode Variation Sequences
{
uint length = reader.ReadUInt32();
uint numVarSelectorRecords = reader.ReadUInt32();
var variationSelectors = new List<Tuple<uint, uint, uint>>();
for (int i = 0; i < numVarSelectorRecords; i++)
{
variationSelectors.Add(Tuple.Create(reader.ReadUInt24(), reader.ReadUInt32(), reader.ReadUInt32()));
}
for (int i = 0; i < variationSelectors.Count; i++)
{
// [SKIP] defaultUVSOffset
// if (variationSelectors[i].Item2 > 0)
// {
// reader.Stream.Position = basePosition + record.Offset + variationSelectors[i].Item2;
// uint numUnicodeValueRanges = reader.ReadUInt32();
// var unicodeRanges = new List<Tuple<uint, byte>>();
// for (uint j = 0; j < numUnicodeValueRanges; j++)
// {
// unicodeRanges.Add(Tuple.Create(reader.ReadUInt24(), reader.ReadByte()));
// }
// }
// nonDefaultUVSOffset
if (variationSelectors[i].Item3 > 0)
{
reader.Position = basePosition + record.Offset + variationSelectors[i].Item3;
uint numUVSMappings = reader.ReadUInt32();
var uvsMappings = new List<Tuple<uint, ushort>>();
for (int j = 0; j < numUVSMappings; j++)
{
uvsMappings.Add(Tuple.Create(reader.ReadUInt24(), reader.ReadUInt16()));
}
for (int j = 0; j < numUVSMappings; j++)
{
var key = Tuple.Create(uvsMappings[j].Item1, variationSelectors[i].Item1);
record.VariationGlyphMap[key] = uvsMappings[j].Item2;
}
}
}
}
}
var sorted = new SortedDictionary<int, Dictionary<int, ushort>>();
foreach (var record in EncodingRecords)
{
if (record.PlatformID == 0 && record.EncodingID == 6)
{
sorted.Add(1, record.GlyphMap);
continue;
}
if (record.PlatformID == 0 && record.EncodingID == 4)
{
sorted.Add(2, record.GlyphMap);
continue;
}
if (record.PlatformID == 3 && record.EncodingID == 10)
{
sorted.Add(3, record.GlyphMap);
continue;
}
if (record.PlatformID == 0 && record.EncodingID == 3)
{
sorted.Add(4, record.GlyphMap);
continue;
}
if (record.PlatformID == 3 && record.EncodingID == 1)
{
sorted.Add(5, record.GlyphMap);
continue;
}
if (record.PlatformID == 0 && record.EncodingID == 2)
{
sorted.Add(6, record.GlyphMap);
continue;
}
if (record.PlatformID == 0 && record.EncodingID == 1)
{
sorted.Add(7, record.GlyphMap);
continue;
}
if (record.PlatformID == 0 && record.EncodingID == 0)
{
sorted.Add(8, record.GlyphMap);
continue;
}
}
_glyphMap = sorted.Values.ToArray()[0];
}
/// <summary>Gets a list of EncodingRecord.</summary>
public List<EncodingRecord> EncodingRecords { get; } = new List<EncodingRecord>();
/// <summary>Gets a table version number.</summary>
public ushort TableVersionNumber { get; }
/// <summary>Gets a number of encoding tables.</summary>
public ushort NumTables { get; }
/// <summary>Gets the mapping of a charactor code point to a glyph index optimal.</summary>
public Dictionary<int, ushort> GlyphMap
{
get { return _glyphMap; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace Sample.Wcf
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ISampleService
{
[OperationContract]
IEnumerable<RouteHit> FetchRouteHits();
[OperationContract]
string ServiceMethodThatIsNotProfiled();
[OperationContract]
string MassiveNesting();
[OperationContract]
string MassiveNesting2();
[OperationContract]
string Duplicated();
}
[DataContract]
public class RouteHit
{
[DataMember]
public string RouteName { get; set; }
[DataMember]
public Int64 HitCount { get; set; }
}
}
|
using System;
using System.Threading.Tasks;
namespace Szogun1987.EventsAndTasks.Callbacks
{
public static class CallbacksHelper
{
public static Task<T> Invoke<T>(Action<Action<T, Exception>> asyncMethod)
{
var completionSource = new TaskCompletionSource<T>();
asyncMethod((arg, exception) =>
{
if (exception != null)
{
completionSource.SetException(exception);
}
else
{
completionSource.SetResult(arg);
}
});
return completionSource.Task;
}
}
} |
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using Rexxar.Identity.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Rexxar.Identity
{
public class ProfileService : IProfileService
{
UserManager<RexxarUser> _userManager;
// 注入AspNetCore Identity的用户管理类
public ProfileService(UserManager<RexxarUser> userManager)
{
this._userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var claims = context.Subject.Claims.ToList();
// sub属性就是用户id
var userId = claims.First(r => r.Type == "sub");
// 查找用户
var user = await _userManager.FindByIdAsync(userId.Value);
claims.Add(new Claim("username", user.UserName));
claims.Add(new Claim("email", user.Email));
claims.Add(new Claim("avatar", user.Avatar));
// 这里是设置token包含的用户属性claim
context.IssuedClaims = claims;
}
/// <summary>
/// 用户是否激活
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
await Task.CompletedTask;
}
}
}
|
using Npgsql;
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 VYS_Proje
{
public partial class musteriListelemeForm : Form
{
public musteriListelemeForm()
{
InitializeComponent();
}
NpgsqlConnection baglanti = new NpgsqlConnection("server=localhost;port=5432; Database=stok_takip;user Id=postgres; password=1234");
DataSet daset = new DataSet();
private void musteriListelemeForm_Load(object sender, EventArgs e)
{
Kayit_Goster();
}
private void Kayit_Goster()
{
baglanti.Open();
NpgsqlDataAdapter adtr = new NpgsqlDataAdapter("SELECT *FROM MUSTERi ", baglanti);
adtr.Fill(daset, "musteri");
dataGridView1.DataSource = daset.Tables["musteri"];
baglanti.Close();
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
tcTextBox.Text = dataGridView1.CurrentRow.Cells["tc"].Value.ToString();
adsoyadTextBox.Text = dataGridView1.CurrentRow.Cells["adsoyad"].Value.ToString();
telTextBox.Text = dataGridView1.CurrentRow.Cells["telefon"].Value.ToString();
adresTestBox.Text = dataGridView1.CurrentRow.Cells["adres"].Value.ToString();
emailTextBox.Text = dataGridView1.CurrentRow.Cells["email"].Value.ToString();
}
private void guncelleButton_Click(object sender, EventArgs e)
{
baglanti.Open();
NpgsqlCommand komut2 = new NpgsqlCommand("UPDATE musteri SET adsoyad=@adsoyad,telefon=@telefon,adres=@adres,email=@email WHERE tc=@tc",baglanti);
komut2.Parameters.AddWithValue("@tc", tcTextBox.Text);
komut2.Parameters.AddWithValue("@adsoyad", adsoyadTextBox.Text);
komut2.Parameters.AddWithValue("@telefon", telTextBox.Text);
komut2.Parameters.AddWithValue("@adres", adresTestBox.Text);
komut2.Parameters.AddWithValue("@email", emailTextBox.Text);
komut2.ExecuteNonQuery();
baglanti.Close();
daset.Tables["musteri"].Clear();
Kayit_Goster();
MessageBox.Show("Musteri Kaydi Guncellendi");
foreach (Control item in this.Controls)
{
if (item is TextBox)
{
item.Text = "";
}
}
}
private void silButton_Click(object sender, EventArgs e)
{
baglanti.Open();
string sql1 = "select *from musteriSil('" + dataGridView1.CurrentRow.Cells["tc"].Value.ToString() + "')";
NpgsqlCommand komut = new NpgsqlCommand(sql1, baglanti);
komut.ExecuteNonQuery();
baglanti.Close();
daset.Tables["musteri"].Clear();
Kayit_Goster();
MessageBox.Show("Musteri Kaydi Silindi");
}
private void tcAraTextBox_TextChanged(object sender, EventArgs e)
{
DataTable tablo = new DataTable();
baglanti.Open();
NpgsqlDataAdapter adtr = new NpgsqlDataAdapter ("SELECT *FROM musteri WHERE tc like '%" + tcAraTextBox.Text +"%'",baglanti);
adtr.Fill(tablo);
dataGridView1.DataSource = tablo;
baglanti.Close();
}
}
}
|
using Alabo.Domains.Enums;
using Alabo.Framework.Basic.Grades.Domain.Configs;
using Alabo.Users.Entities;
using Alabo.Users.Enum;
using Alabo.Web.Mvc.ViewModel;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Data.People.Users.ViewModels
{
/// <summary>
/// 后台用户编辑视图
/// </summary>
public class ViewAdminEdit : BaseViewModel
{
/// <summary>
/// 登录用户ID
/// </summary>
public long LoginUserId { get; set; }
/// <summary>
/// 要Edit的用户ID
/// </summary>
public long EditUserId { get; set; }
/// <summary>
/// 所属门店
/// </summary>
[Display(Name = "所属门店")]
public string ServiceCenterName { get; set; }
/// <summary>
/// Gets or sets the 会员.
/// </summary>
public User User { get; set; }
/// <summary>
/// Gets or sets the 会员 detail.
/// </summary>
public UserDetail UserDetail { get; set; }
/// <summary>
/// 门店用户名,不是数据库字段
/// </summary>
[Display(Name = "所属门店用户")]
public string ServiceCenterUserName { get; set; }
/// <summary>
/// Gets or sets the status.
/// </summary>
[Display(Name = "状态")]
public Status Status { get; set; }
/// <summary>
/// Gets or sets the password.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Gets or sets the confirm password.
/// </summary>
public string ConfirmPassword { get; set; }
/// <summary>
/// 修改密码的类型 1表示修改登录密码,2表示修改支付密码,3表示修改详情,0表示修改基本资料
/// </summary>
public int Type { get; set; } = 0;
/// <summary>
/// 将修改的密码发送短信通知
/// </summary>
public bool SendPassword { get; set; } = true;
/// <summary>
/// Gets or sets the sex.
/// </summary>
[Display(Name = "性别")]
public Sex Sex { get; set; }
/// <summary>
/// Gets or sets the parent.
/// </summary>
public User Parent { get; set; }
/// <summary>
/// 所属区域
/// </summary>
[Display(Name = "所属区域")]
public long RegionId { get; set; }
/// <summary>
/// 地址
/// </summary>
[Display(Name = "详细地址")]
public string Address { get; set; }
/// <summary>
/// 区域名称
/// </summary>
public string RegionName { get; set; }
public UserGradeConfig UserGradeConfig { get; set; }
/// <summary>
/// Gets or sets the avator.
/// </summary>
public string Avator { get; set; }
/// <summary>
/// 实名认证状态
/// </summary>
public IdentityStatus IdentityStatus { get; set; } = IdentityStatus.IsNoPost;
/// <summary>
/// 会员等级列表
/// </summary>
public List<UserGradeConfig> GradeList { get; set; }
public object StatusList { get; set; }
}
} |
using System;
namespace _44ЗубачатыеМассивы
{
class Program
{
static void Main(string[] args)
{
int[][] myArray = new int[3][];
myArray[0] = new int[5];
myArray[1] = new int[2];
myArray[2] = new int[10];
Random random = new Random();
for (int y = 0; y < myArray.Length; y++)
{
for (int x = 0; x < myArray[y].Length; x++)
{
myArray[y][x] = random.Next(99);
}
Console.WriteLine("");
}
for (int i = 0; i < myArray.Length; i++)
{
for (int j = 0; j < myArray[i].Length; j++)
{
Console.Write (myArray[i][j]+" ");
}
Console.WriteLine("");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PROnline.Models.Users;
using PROnline.Models;
using PROnline.Src;
namespace PROnline.Controllers.Users
{
public class AdministratorController : Controller
{
private PROnlineContext db = new PROnlineContext();
//
// GET: /Administrator/
public ViewResult Index()
{
//得到未删除的管理员列表
var administrator = db.Administrator.Where(admin => admin.User.isDeleted == false)
.Where(admin => admin.User.UserTypeId != UserType.ADMIN)
.OrderBy(r => r.User.RoleId).ThenBy(r => r.User.RealName);
return View(administrator.ToList());
}
//
// GET: /Administrator/Details/5
//type:个人空间或者后台管理或者其它
public ViewResult Details(Guid id, String type)
{
Administrator administrator = db.Administrator.Find(id);
ViewBag.type = type;
return View(administrator);
}
//
// GET: /Administrator/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Administrator/Create
[HttpPost]
public ActionResult Create(Administrator administrator,String role)
{
if (Request.Params.Get("YYYY") == "" || Request.Params.Get("MM") == "" || Request.Params.Get("DD") == "")
{
ModelState.AddModelError("Birthday", "请选择生日!");
}
if (ModelState.IsValid)
{
administrator.User.Id = Guid.NewGuid();
administrator.User.Password = Utils.GetMd5(administrator.User.Password);
administrator.User.UserTypeId = UserType.MANAGER;
administrator.User.RoleId = role;
administrator.User.CreateDate = DateTime.Now;
int year = int.Parse(Request.Params.Get("YYYY"));
int month = int.Parse(Request.Params.Get("MM"));
int day = int.Parse(Request.Params.Get("DD"));
DateTime birthday = new DateTime(year, month, day);
administrator.Birthday = birthday;
administrator.AdministratorID = Guid.NewGuid();
db.Administrator.Add(administrator);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(administrator);
}
//
// GET: /Administrator/Edit/5
public ActionResult Edit(Guid id)
{
Administrator administrator = db.Administrator.Find(id);
return View(administrator);
}
//
// POST: /Administrator/Edit/5
[HttpPost]
public ActionResult Edit(Administrator administrator)
{
if (ModelState.IsValid)
{
Administrator temp = db.Administrator.Find(administrator.AdministratorID);
temp.Telephone = administrator.Telephone;
temp.MobileTelephone = administrator.MobileTelephone;
temp.Address = administrator.Address;
db.Entry(temp).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details","Users");
}
return View(administrator);
}
//
// GET: /Administrator/Delete/5
public ActionResult Delete(Guid id)
{
Administrator administrator = db.Administrator.Find(id);
return View(administrator);
}
//
// POST: /Administrator/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(Guid id)
{
Administrator administrator = db.Administrator.Find(id);
administrator.User.isDeleted = true;
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
} |
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using OnlineGallery.Areas.Identity.Data;
using OnlineGallery.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
namespace OnlineGallery.Models
{
public partial class Tools
{
// Save Image To Folder
public static string SaveImage(IWebHostEnvironment webHostEnvironment, IFormFile image)
{
string wwwRootPath = webHostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(image.FileName);
string extension = Path.GetExtension(image.FileName);
fileName = fileName + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss") + extension;
string path = Path.Combine(wwwRootPath + "/images", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
image.CopyTo(fileStream);
}
return fileName;
}
// Remove Image From Folder
public static void RemoveImage(IWebHostEnvironment webHostEnvironment, string image)
{
if (image != null)
{
var imagePath = Path.Combine(webHostEnvironment.WebRootPath, "images", image);
if (System.IO.File.Exists(imagePath))
{
System.IO.File.Delete(imagePath);
}
}
}
//
public static bool CheckGalleryProduct(ApplicationDbContext context, int productId)
=> context.ProductImages.Any(e => e.ProductId.Equals(productId));
// Product List Have Gallery
public static List<Product> GetProductNotAuctioned(ApplicationDbContext context)
{
var auctioningList = context.Auctions.Where(e => e.Status || e.StartDay.Value.CompareTo(DateTime.Now) > 0).Select(e => e.ProductId).ToList();
var productsHaveGallery = context.ProductImages.Where(e => !auctioningList.Contains(e.ProductId) && e.Product.Status).Select(e => e.Product).Distinct().ToList();
return productsHaveGallery;
}
//
public static List<string> GetProductImages(ApplicationDbContext context, int productId)
=> context.ProductImages.Where(e => e.ProductId.Equals(productId)).Select(e => e.Image).ToList();
// Check My Favorites
public static bool IsMyFavorites(ApplicationDbContext context, string userId, int productId)
{
return context.MyFavorites.Any(e => e.UserId.Equals(userId) && e.ProductId.Equals(productId));
}
// Get the winner
public static bool IsWinner(ApplicationDbContext context, AuctionRecord record)
{
if ((!record.Auction.Status && record.Auction.ClosingDay.Value.CompareTo(DateTime.Now) < 0))
{
var lastRecord = context.AuctionRecords.Where(e => e.AuctionId.Value.Equals(record.AuctionId.Value)).OrderBy(e => e.Id).Last();
return lastRecord.Equals(record);
}
return false;
}
// Check true if product is in cart, otherwise false
public static bool IsInCart(ApplicationDbContext context, string userId, int productId)
{
return context.Carts.Any(e => e.UserId.Equals(userId) && e.ProductId.Equals(productId));
}
// Check if user have cart
public static bool IsHaveCart(ApplicationDbContext context, string userId)
{
return context.Carts.Any(e => e.UserId.Equals(userId));
}
// Check if product has been sold
public static bool IsSold(ApplicationDbContext context, int id)
{
var soldProducts = context.TransactionDetails.Select(e => e.ProductId).ToList();
return soldProducts.Contains(id);
}
// Check if product has been sold before auction end
public static bool IsSoldBeforeAuctionEnd(ApplicationDbContext context, int id)
{
context.Transactions.ToList();
var product = context.Products.Find(id);
if (!product.Status)
{
var transaction = context.TransactionDetails.Where(e => e.ProductId.Equals(id)).Select(e => e.Transaction).FirstOrDefault();
return !transaction.Auctioned;
}
return false;
}
// Check if that user buy that product
public static bool IsUserSold(ApplicationDbContext context, string userId, int productId)
{
var transactionId = context.TransactionDetails.Where(e => e.ProductId.Equals(productId)).Select(e => e.TransactionId).FirstOrDefault();
var transaction = context.Transactions.Find(transactionId);
return transaction.UserId.Equals(userId);
}
// OVERVIEW PER MONTH
// Get registration amount
public static int GetTotalRegistration(ApplicationDbContext context)
{
var userIds = context.Users.Where(e => e.EmailConfirmed).Select(e => e.Id);
return context.UserRoles.Where(e => e.RoleId.Equals("2") && userIds.Contains(e.UserId)).Count();
}
// Get this month sales
public static decimal GetThisMonthSales(ApplicationDbContext context)
=> context.TransactionDetails.Where(e =>
e.Transaction.CompletionDate.Value.Month.Equals(DateTime.Now.Month) &&
e.Transaction.CompletionDate.Value.Year.Equals(DateTime.Now.Year) && e.Transaction.Status
).Count();
// Get last month sales
public static decimal GetLastMonthSales(ApplicationDbContext context)
=> context.TransactionDetails.Where(e =>
e.Transaction.CompletionDate.Value.Month.Equals(DateTime.Now.Month - 1) &&
e.Transaction.CompletionDate.Value.Year.Equals(DateTime.Now.Year) && e.Transaction.Status
).Count();
// Get this month profit
public static decimal GetThisMonthProfit(ApplicationDbContext context)
=> context.Transactions.Where(e =>
e.CompletionDate.Value.Month.Equals(DateTime.Now.Month) &&
e.CompletionDate.Value.Year.Equals(DateTime.Now.Year) && e.Status
).Select(e => e.TotalPrice).Sum();
// Get last month profit
public static decimal GetLastMonthProfit(ApplicationDbContext context)
=> context.Transactions.Where(e =>
e.CompletionDate.Value.Month.Equals(DateTime.Now.Month - 1) &&
e.CompletionDate.Value.Year.Equals(DateTime.Now.Year) && e.Status
).Select(e => e.TotalPrice).Sum();
// Get sales rate
public static decimal GetSalesRateCompareLastMonth(ApplicationDbContext context)
{
var thisMonthSales = GetThisMonthSales(context);
var lastMonthSales = GetLastMonthSales(context);
if (lastMonthSales == 0)
{
if (thisMonthSales > 0)
{
return 100;
}
if (thisMonthSales == 0)
{
return 0;
}
}
return thisMonthSales * 100 / lastMonthSales;
}
// Get profit rate
public static decimal GetProfitRateCompareLastMonth(ApplicationDbContext context)
{
var thisMonthProfit = GetThisMonthProfit(context);
var lastMonthProfit = GetLastMonthProfit(context);
if (lastMonthProfit == 0)
{
if (thisMonthProfit > 0)
{
return 100;
}
if (thisMonthProfit == 0)
{
return 0;
}
}
return thisMonthProfit * 100 / lastMonthProfit;
}
}
}
|
using Fbtc.Domain.Entities;
using System.Collections.Generic;
namespace Fbtc.Application.Interfaces
{
public interface IIsencaoApplication
{
IEnumerable<Isencao> GetAll(string tipoIsencao);
Isencao GetIsencaoById(int id);
Isencao SetIsencao(string tipoIsencao);
string Save(Isencao isencao);
string DeleteById(int id);
IEnumerable<Isencao> FindByFilters(string tipoIsencao, string nomeAssociado, string descricao, int ano, int eventoId);
IEnumerable<IsencaoDao> FindIsencaoByFilters(string tipoIsencao, string nomeAssociado, int ano, string identificacao, string tipoEvento);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace PayByPhoneTwitter
{
public interface IAuthenticator
{
WebRequest AuthenticateRequest(WebRequest request);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace ProjectGrace.Data.Soaper.ServiceModels
{
[DataContract]
public class RoomTraineesDao
{
[DataMember]
public int RoomTraineeID { get; set; }
[DataMember]
public int RoomID { get; set; }
[DataMember]
public int TraineeID { get; set; }
}
} |
using UnityEngine;
public class TrackSelector : MonoBehaviour {
public GameObject[] tracks;
public int index = 0;
void Start(){
for(int i=0; i<tracks.Length; i++) tracks[i].SetActive(i==index);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreditasChallenge.Helpers
{
public class Guardian
{
public static void ForNullOrEmpty(string value, string msgError)
{
if (string.IsNullOrEmpty(value))
throw new Exception(msgError);
}
public static void ForStringLength(string value, int maxLenght, string msgError)
{
if (value.Length > maxLenght)
throw new Exception(msgError);
}
public static void ForPositiveValue(uint value, string msgError)
{
if (0 > value)
throw new Exception(msgError);
}
public static void ForMaxUintValue(uint value, string msgError)
{
if(value > uint.MaxValue)
{
throw new Exception(msgError);
}
}
}
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool IsBalanced(TreeNode root) {
if (Helper(root) == -1) {
return false;
} else {
return true;
}
}
// returns -1 if not balanced, height otherwise
public int Helper(TreeNode root) {
// exit
if (root == null) return 0;
// divide
int leftRes = Helper(root.left);
int rightRes = Helper(root.right);
// merge
if (leftRes == -1 || rightRes == -1 || Math.Abs(rightRes-leftRes) > 1) {
return -1;
} else {
return Math.Max(leftRes, rightRes) + 1;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace AxisEq
{
public class SRP_WriteLine : SRPCommand
{
public SRP_WriteLine(string text)
{
_quest = Encoding.GetEncoding(1251).GetBytes(text+"\n\r");
}
public override bool NeedResponse
{
get { return false; }
}
}
}
|
using System.Runtime.Serialization;
namespace XH.APIs.WebAPI.Models.Tenants
{
[DataContract]
public class UpdateTenantRequest : CreateOrUpdateTenantRequest
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _14.Bit_Exchange
{
class BitExchange
{
static void Main()
{
//Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32 int.
int number = int.Parse(Console.ReadLine());
//Console.WriteLine(Convert.ToString(number, 2).PadLeft(32, '0'));
int threeFourFive = number & 0x00000038; // get bits 3-5
int twentyThreeFourFive = number & 0x07000000; // get bits 24-26
number &= ~0x07000038; // clear bits 3-5 and 24-26
number |= threeFourFive << 21; // put bits 3-5 in 24-26
number |= twentyThreeFourFive >> 21; // put bits 24-26 in 3-5
//Console.WriteLine(Convert.ToString(number, 2).PadLeft(32, '0'));
Console.WriteLine(number);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace UploadClass
{
class ImgUploadClass
{
public class UploadImgInput
{
/// <summary>
/// Husk disse værdier!!
/// Husk at lave mapperne som den skal gemmes i.
/// </summary>
/// <param name="image">File som bliver sæt med på Postefile</param>
/// <param name="uploadmappe">Hvor henne skal billedet bliv gemt i dens originale billed størrelse</param>
/// <param name="ThumpsMappe">Hvilke Thumpsmappe skal den lige i</param>
/// <param name="Croppedmappe">Hvilke CroppedeMappe skal den over i.</param>
/// <param name="Width">Hvilke størrelse skal den have i bredden</param>
/// <param name="Height">Hvilke størrelse skal den have i højden</param>
/// <param name="MulitUploadCropped">True/false skal den lave Cropped eller ej?</param>
public static void UploadMethod(HttpPostedFile image, string uploadmappe, string ThumpsMappe, string Croppedmappe, int Width, int Height, bool MulitUploadCropped)
{
//hent at hent "ImageResizer" til at kunne gøre det her på billedet.
//laver nyt navn til billedet.
//Du har mulighed for at lad være med at tag file navnet og tilføj det ovn i den unikke værdi, men du kan bare også skrive + ".png", ".jpg" eller andet hvis du ønsker det.
string filename = DateTime.Now.ToFileTime() + "_" + UploadImgInput.GetRandomNumber(190, 999) + image.FileName;
//Gem det originale billede på det angivet sted som du har i upload
image.SaveAs(uploadmappe + filename);
//definer hvordan thumbsnail skal skaleres
ImageResizer.ResizeSettings billedeskalering = new ImageResizer.ResizeSettings();
//checker på om den er sat på False
if (MulitUploadCropped == false)
{
billedeskalering.Width = Width;
//udfør selv skaleringen,
ImageResizer.ImageBuilder.Current.Build(uploadmappe + filename, ThumpsMappe + filename, billedeskalering);
//har gjort det færdig.
//Mulighed for at lige det ind i databasen her
}
//Checker på om den er sat til true til at skulle Croppede billedet.
else if (MulitUploadCropped == true)
{
billedeskalering.Width = Width;
//udfør selv skaleringen,
ImageResizer.ImageBuilder.Current.Build(uploadmappe + filename, ThumpsMappe + filename, billedeskalering);
//har gjort det færdig.
billedeskalering = new ImageResizer.ResizeSettings();
billedeskalering.Width = Width;
billedeskalering.Height = Height;
billedeskalering.Mode = ImageResizer.FitMode.Crop;
ImageResizer.ImageBuilder.Current.Build(uploadmappe + filename, Croppedmappe + filename, billedeskalering);
//har gjort det færdig.
//Mulighed for at lige det ind i databasen her
}
}
//laver random tal for dig som du sætter ind i "min" og "max"
//Kode er hente her fra: http://stackoverflow.com/a/3854950/5543141
public static readonly Random getrandom = new Random();
public static readonly object syncLock = new object();
private static int GetRandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return getrandom.Next(min, max);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using BankApp.DTO;
using BankApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BankAppCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ReportController : ControllerBase
{
[Authorize(Roles = "Admin")]
[Route("GenerateCsv")]
public HttpResponseMessage GenerateCsv(ReportPeriod reportPeriod)
{
ReportCreator csvCreator = new CsvCreator();
Report rep = csvCreator.GenerateReport(reportPeriod);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(rep.Data)
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "Report" + DateTime.Now + ".csv"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
} |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Payment.Api.Controllers
{
[Route("api/[controller]")]
public class StatusController : ControllerBase
{
private readonly IHostEnvironment _hostEnvironment;
public StatusController(IHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}
[HttpGet, Route("")]
public IActionResult Get()
{
// return application health data
return Ok();
}
}
}
|
#nullable disable
namespace Algorithms.LeetCode
{
public class NumArray
{
private TreeNode _root;
public NumArray(int[] nums)
{
_root = BuildTree(nums, 0, nums.Length - 1);
}
public void Update(int index, int val) => Update(_root, index, val);
public int SumRange(int left, int right) => SumRange(_root, left, right);
private TreeNode BuildTree(int[] nums, int start, int end)
{
if (start > end)
return null;
var node = new TreeNode()
{
Start = start,
End = end
};
if (start == end)
{
node.Sum = nums[start];
}
else
{
var mid = (start + end) / 2;
node.Left = BuildTree(nums, start, mid);
node.Right = BuildTree(nums, mid + 1, end);
node.Sum = node.Left.Sum + node.Right.Sum;
}
return node;
}
private void Update(TreeNode node, int index, int val)
{
if (node.Start == node.End)
{
node.Sum = val;
return;
}
var mid = (node.Start + node.End) / 2;
Update(index <= mid ? node.Left : node.Right, index, val);
node.Sum = node.Left.Sum + node.Right.Sum;
}
private int SumRange(TreeNode node, int left, int right)
{
if (node.Start == left && node.End == right)
return node.Sum;
var mid = (node.Start + node.End) / 2;
if (right <= mid)
{
return SumRange(node.Left, left, right);
}
else if (left >= mid + 1)
{
return SumRange(node.Right, left, right);
}
else
{
return SumRange(node.Left, left, mid) + SumRange(node.Right, mid + 1, right);
}
}
private class TreeNode
{
public int Sum { get; set; }
public TreeNode Left { get; set; }
public TreeNode Right { get; set; }
public int Start { get; set; }
public int End { get; set; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPI_Connection_ReExam.Custom
{
//Android側からのGETリクエストを受ける独自クラス
public class RequestValue
{
private string workName { get; set; } //@param1 部品名
private int count { get; set; } //@param2 必要結果数
}
} |
public interface IEndGameOverObserver
{
void Notify();
}
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SujaySarma.Sdk.Azure.MarketplaceCatalog
{
/// <summary>
/// Azure Marketplace Catalog entry
/// </summary>
/// <remarks>This is the data from the global list (_menu.json)</remarks>
public class CatalogEntry
{
/// <summary>
/// ID of the catalog item
/// </summary>
[JsonPropertyName("id")]
public string CatalogID { get; set; }
/// <summary>
/// UI-friendly display name of the catalog
/// </summary>
[JsonPropertyName("text")]
public string Name { get; set; }
// These two are meant for service calls. Information is set here when the
// CatalogEntry is retrieved. We use it to retrieve the groups and its items
// in the same langauge as the master list.
internal string Language = "en";
internal string Locale = "en-us";
/// <summary>
/// Get the groups in this catalog. Key is the GroupId of the entry.
/// </summary>
public ReadOnlyDictionary<string, CatalogGroupEntry> Groups
{
get
{
if (_groups != null)
{
_groups = new Dictionary<string, CatalogGroupEntry>();
foreach (CatalogGroupEntry entry in CatalogDataProvider.GetCatalogDetail(CatalogID, Language, Locale))
{
_groups.Add(entry.GroupId, entry);
}
}
return new ReadOnlyDictionary<string, CatalogGroupEntry>( _groups);
}
}
private IDictionary<string, CatalogGroupEntry> _groups = null;
/// <summary>
/// Instantiate the marketplace catalog entry
/// </summary>
public CatalogEntry() { }
}
}
|
using Hangfire;
using Hangfire.JobSDK;
using Hangfire.Server;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.ComponentModel;
using System.Threading;
namespace Hangfire.TestJobs
{
[ManagementPage("Test Jobs", "Test Jobs")]
public class TestJobs : IJob,IModuleInitializer
{
public void Init(IServiceCollection serviceCollection,string environmentName)
{
//Add services required by job
}
[DisplayName("Test")]
[Description("Test that jobs are running with simple console output.")]
[AutomaticRetry(Attempts = 0)]
[DisableConcurrentExecution(90)]
public void Test(PerformContext context, IJobCancellationToken token,
[DisplayData("Output Text", "Enter text to output.")] string outputText,
[DisplayData("Repeat When Completed", "Repeat")] bool repeat,
[DisplayData("Test Date", "Enter date")] DateTime testDate)
{
// context.WriteLine(outputText);
Thread.Sleep(15000);
token.ThrowIfCancellationRequested();
if (repeat)
{
// context.WriteLine("Enquing the job again from the job.");
BackgroundJob.Enqueue<TestJobs>(m => m.Test(context, token, outputText, repeat,testDate));
}
}
[DisplayName("Test2")]
[Description("Test that jobs are running with simple console output.")]
[AutomaticRetry(Attempts = 0)]
[DisableConcurrentExecution(90)]
public void Test2(PerformContext context, IJobCancellationToken token)
{
// context.WriteLine(outputText);
Thread.Sleep(15000);
token.ThrowIfCancellationRequested();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class itemController : MonoBehaviour {
public bool pickedUp, outSideBox;
public Vector3 originalPos;
private void Start() {
originalPos = transform.position;
}
void Update () {
// Enable item outline when picked up and set it back to its original position when it falls out of bounds
if (pickedUp) {
this.GetComponent<Outline>().enabled = true;
} else {
this.GetComponent<Outline>().enabled = false;
if (outSideBox == true) {
this.transform.position = originalPos;
outSideBox = false;
}
}
}
// This is where the game box will tell the item if it's fallen out
void ResetPos() {
outSideBox = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.MDM
{
/// <summary>
/// 质量检查标准
/// </summary>
public class InspectionStandard
{
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 参数叶标识
/// </summary>
public int T20LeafID { get; set; }
/// <summary>
/// 参数名称
/// </summary>
public string ParameterName { get; set; }
/// <summary>
/// 低限值
/// </summary>
public long LowLimit { get; set; }
/// <summary>
/// 标准
/// </summary>
public string Criterion { get; set; }
/// <summary>
/// 高限值
/// </summary>
public long HighLimit { get; set; }
/// <summary>
/// 放大数量级
/// </summary>
public int Scale { get; set; }
/// <summary>
/// 计量单位
/// </summary>
public string UnitOfMeasure { get; set; }
/// <summary>
/// 首检应检数
/// </summary>
public long QtyForFirstInspection { get; set; }
/// <summary>
/// 过程检应检数(每次)
/// </summary>
public long QtyForInProcessInspection { get; set; }
/// <summary>
/// 过程检批量
/// </summary>
public long InProcessInspectionBatchSize { get; set; }
/// <summary>
/// 末检应检数
/// </summary>
public long QtyForLastInspection { get; set; }
/// <summary>
/// 是否全检
/// </summary>
public bool FullInspection { get; set; }
/// <summary>
/// 是否来自模板引用数据
/// </summary>
public bool Reference { get; set; }
public InspectionStandard Clone()
{
return MemberwiseClone() as InspectionStandard;
}
}
} |
using JT808.Protocol.Attributes;
using JT808.Protocol.Formatters;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 车辆所在的市域 ID
/// </summary>
public class JT808_0x8103_0x0082 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0082>
{
public override uint ParamId { get; set; } = 0x0082;
/// <summary>
/// 数据 长度
/// </summary>
public override byte ParamLength { get; set; } = 2;
/// <summary>
/// 车辆所在的市域 ID
/// </summary>
public ushort ParamValue { get; set; }
public JT808_0x8103_0x0082 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8103_0x0082 jT808_0x8103_0x0082 = new JT808_0x8103_0x0082();
jT808_0x8103_0x0082.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0082.ParamLength = reader.ReadByte();
jT808_0x8103_0x0082.ParamValue = reader.ReadUInt16();
return jT808_0x8103_0x0082;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0082 value, IJT808Config config)
{
writer.WriteUInt32(value.ParamId);
writer.WriteByte(value.ParamLength);
writer.WriteUInt16(value.ParamValue);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class QuickAttack : NetworkBehaviour
{
[SerializeField]
float spreadAngle = 45;
[SerializeField]
float range = 5;
[SerializeField]
int damage = 20;
[SerializeField]
float cooldown = 0.5f;
float cooldownLeft = 0f;
public float SpreadAngle => spreadAngle;
public float Range => range;
public int Damage => damage;
[SerializeField]
GameObject effectPrefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (cooldownLeft > 0)
cooldownLeft -= Time.deltaTime;
}
public void Attack(Vector3 attackDirection, GameObject attacker)
{
if (!isServer || cooldownLeft > 0)
return;
cooldownLeft = cooldown;
Quaternion effectRotation = Quaternion.Euler(0, Vector3.SignedAngle(Vector3.forward, attackDirection, Vector3.up), 0);
RpcDisplayEffect(transform.position + transform.up + transform.forward * 0.5f, effectRotation);
Collider[] avatars = Physics.OverlapSphere(transform.position, range, 1 << 8); // Layer mask for avatars
foreach(Collider other in avatars)
{
// skip our own collider
if (other.gameObject == gameObject)
continue;
Vector3 direction = other.transform.position - transform.position;
bool blocked = Physics.Raycast(origin: transform.position,
direction: direction,
maxDistance: direction.magnitude,
layerMask: 1 << 9);
if (!blocked && Vector3.Angle(direction, attackDirection) < spreadAngle / 2)
other.GetComponent<AvatarControl>().TakeDamage(damage, attacker);
}
}
[ClientRpc]
void RpcDisplayEffect(Vector3 position, Quaternion rotation)
{
Instantiate(effectPrefab, position, rotation);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Patterns.Pattern.Ef6;
namespace Plugin.Payment.Stripe.Data
{
public class StripeContext : DataContext
{
static StripeContext()
{
Database.SetInitializer<StripeContext>(null);
}
public StripeContext()
: base("Name=WelicDbContext")
{
}
public DbSet<StripeConnect> StripeConnects { get; set; }
public DbSet<StripeTransaction> StripeTransactions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Configurations.Add(new StripeConnectMap());
modelBuilder.Configurations.Add(new StripeTransactionMap());
}
}
}
|
namespace ProgFrog.Interface.TaskRunning
{
public enum RunnedTaskErrorType
{
RuntimeException = 0
}
} |
namespace BookShop
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using BookShop.Models;
using Data;
using Initializer;
public class StartUp
{
public static void Main()
{
using (var db = new BookShopContext())
{
//DbInitializer.ResetDatabase(db);
string input = Console.ReadLine();
string result = GetBooksByCategory(db, input);
Console.WriteLine(result);
}
}
//P01
public static string GetBooksByAgeRestriction(BookShopContext context, string command)
{
StringBuilder sb = new StringBuilder();
var books = context
.Books
.Where(b => b.AgeRestriction.ToString().ToLower() == command.ToLower())
.Select(b => new
{
b.Title
})
.OrderBy(b => b.Title)
.ToList();
foreach (var b in books)
{
sb.AppendLine(b.Title);
}
return sb.ToString().TrimEnd();
}
//P02
public static string GetGoldenBooks(BookShopContext context)
{
var bookTitles = context
.Books
.Where(b => b.EditionType == Models.Enums.EditionType.Gold && b.Copies < 5000)
.OrderBy(b => b.BookId)
.Select(b => b.Title);
var result = string.Join(Environment.NewLine, bookTitles);
return result;
}
//P03
public static string GetBooksByPrice(BookShopContext context)
{
StringBuilder sb = new StringBuilder();
var books = context
.Books
.Where(b => b.Price > 40)
.OrderByDescending(b => b.Price)
.Select(b => new
{
b.Title,
b.Price
});
foreach (var book in books)
{
sb.AppendLine($"{book.Title} - ${book.Price:f2}");
}
return sb.ToString().TrimEnd();
}
//P04
public static string GetBooksNotReleasedIn(BookShopContext context, int year)
{
var bookTitles = context
.Books
.Where(b => b.ReleaseDate.Value.Year != year)
.OrderBy(b => b.BookId)
.Select(b => b.Title);
var result = string.Join(Environment.NewLine, bookTitles);
return result;
}
//P05
public static string GetBooksByCategory(BookShopContext context, string input)
{
string[] categories = input
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(c => c.ToLower())
.ToArray();
var books = context
.Books
.Where(b => b.BookCategories.Any(bc => categories.Contains(bc.Category.Name.ToLower())))
.Select(b => b.Title)
.OrderBy(b => b)
.ToList();
return string.Join(Environment.NewLine, books);
}
//P06
public static string GetBooksReleasedBefore(BookShopContext context, string date)
{
StringBuilder sb = new StringBuilder();
var format = "dd-MM-yyyy";
var provider = CultureInfo.InvariantCulture;
var parsedDate = DateTime.ParseExact(date, format, provider);
var books = context
.Books
.Where(b => b.ReleaseDate < parsedDate)
.OrderByDescending(b => b.ReleaseDate)
.Select(b => new
{
b.Title,
b.EditionType,
b.Price
});
foreach (var book in books)
{
sb.AppendLine($"{book.Title} - {book.EditionType} - ${book.Price:f2}");
}
return sb.ToString().TrimEnd();
}
//P07
public static string GetAuthorNamesEndingIn(BookShopContext context, string input)
{
var authorsNames = context
.Authors
.Where(a => a.FirstName.EndsWith(input))
.OrderBy(a => a.FirstName)
.ThenBy(a => a.LastName)
.Select(a => $"{a.FirstName} {a.LastName}");
var result = string.Join(Environment.NewLine, authorsNames);
return result;
}
//P08
public static string GetBookTitlesContaining(BookShopContext context, string input)
{
input = input.ToLower();
var bookTitles = context
.Books
.Where(b => b.Title.ToLower().Contains(input))
.OrderBy(b => b.Title)
.Select(b => b.Title);
var result = string.Join(Environment.NewLine, bookTitles);
return result;
}
//P09
public static string GetBooksByAuthor(BookShopContext context, string input)
{
input = input.ToLower();
var booksAndAuthors = context
.Books
.Where(b => b.Author.LastName.ToLower().StartsWith(input))
.OrderBy(b => b.BookId)
.Select(b => $"{b.Title} ({b.Author.FirstName} {b.Author.LastName})");
var result = string.Join(Environment.NewLine, booksAndAuthors);
return result;
}
//P10
public static int CountBooks(BookShopContext context, int lengthCheck)
{
var books = context
.Books
.Where(b => b.Title.Length > lengthCheck);
return books.Count();
}
//P11
public static string CountCopiesByAuthor(BookShopContext context)
{
StringBuilder sb = new StringBuilder();
var authors = context
.Authors
.Select(a => new
{
FullName = $"{a.FirstName} {a.LastName}",
BooksCount = a.Books.Select(b => b.Copies).Sum()
})
.OrderByDescending(a => a.BooksCount);
foreach (var author in authors)
{
sb.AppendLine($"{author.FullName} - {author.BooksCount}");
}
return sb.ToString().TrimEnd();
}
//P12
public static string GetTotalProfitByCategory(BookShopContext context)
{
StringBuilder sb = new StringBuilder();
var categories = context
.Categories
.Select(c => new
{
c.Name,
TotalProfit = c.CategoryBooks
.Select(cb => cb.Book.Copies * cb.Book.Price).Sum()
})
.OrderByDescending(c => c.TotalProfit);
foreach (var category in categories)
{
sb.AppendLine($"{category.Name} ${category.TotalProfit:f2}");
}
return sb.ToString().TrimEnd();
}
//P13
public static string GetMostRecentBooks(BookShopContext context)
{
StringBuilder sb = new StringBuilder();
var categories = context
.Categories
.OrderBy(c => c.Name)
.Select(c => new
{
c.Name,
Books = c.CategoryBooks
.OrderByDescending(cb => cb.Book.ReleaseDate)
.Take(3)
.Select(cb => new
{
cb.Book.Title,
cb.Book.ReleaseDate.Value.Year
})
.ToList()
});
foreach (var category in categories)
{
sb.AppendLine($"--{category.Name}");
foreach (var book in category.Books)
{
sb.AppendLine($"{book.Title} ({book.Year})");
}
}
return sb.ToString().TrimEnd();
}
//P14
public static void IncreasePrices(BookShopContext context)
{
var books = context
.Books
.Where(b => b.ReleaseDate.Value.Year < 2010);
foreach (var book in books)
{
book.Price += 5;
}
context.SaveChanges();
}
//P15
public static int RemoveBooks(BookShopContext context)
{
var books = context
.Books
.Where(b => b.Copies < 4200)
.ToList();
context.Books.RemoveRange(books);
context.SaveChanges();
return books.Count();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public enum CatColor { Grey, Orange, Black, Brown, White }
public class CatMiniGame : MonoBehaviour {
public Text timerText;
public GameObject[] catPrefabs;
public GameObject upperLeftSpawnLimit, upperRightSpawnLimit, lowerLeftSpawnLimit, lowerRightSpawnLimit;
[SerializeField]
int miniGameDuration = 20;
[SerializeField]
int numberOfCatsRunningAround = 10;
Timer timer;
List<GameObject> cats = new List<GameObject>();
CatColor targetCatColor = CatColor.White;
void Start () {
timer = new Timer();
timer.OnTimeUp += HandleTimeUp;
timer.OnSecondsChanged += HandleSecondsChanged;
// Start the timer
InitTimer();
SetTargetCat(CatColor.White);
}
private void Update()
{
// Dev controls
if (Input.GetKeyDown(KeyCode.C))
{
StartMiniGame();
}
// Dev controls
//if (Input.GetKeyDown(KeyCode.L))
//{
// SetTargetCat(CatColor.White);
//}
}
void FixedUpdate()
{
// Update the timer
timer.Update();
}
// Timer Callbacks
void HandleTimeUp()
{
// Debug.Log("Time is up!");
StopMiniGame();
}
void HandleSecondsChanged(int secondsRemaining)
{
// Debug.Log("Seconds Remaining: " + secondsRemaining);
timerText.text = secondsRemaining.ToString();
}
// Mini Game Setup
void InitTimer()
{
timer.SetTimer(miniGameDuration);
timerText.text = miniGameDuration.ToString();
}
void BirthCats()
{
while (cats.Count < numberOfCatsRunningAround - 1)
{
int i = Random.Range(0, catPrefabs.Length);
if (catPrefabs[i].GetComponent<Cat>().catColor == targetCatColor)
continue;
GameObject catObject = Instantiate(catPrefabs[i], GetSpawnPoint(), Quaternion.identity);
catObject.GetComponent<Cat>().OnCatSelected += HandleCatSelection;
cats.Add(catObject);
}
for (int i = 0; i < catPrefabs.Length; i++)
{
if (catPrefabs[i].GetComponent<Cat>().catColor == targetCatColor)
{
GameObject targetCatObject = Instantiate(catPrefabs[i], GetSpawnPoint(), Quaternion.identity);
targetCatObject.GetComponent<Cat>().OnCatSelected += HandleCatSelection;
cats.Add(targetCatObject);
}
}
}
Vector3 GetSpawnPoint()
{
Vector3 position = Vector3.zero;
bool left = Random.value > 0.5f;
position.x = left ? lowerLeftSpawnLimit.transform.position.x : lowerRightSpawnLimit.transform.position.x;
position.y = Random.Range(left ? lowerLeftSpawnLimit.transform.position.y : lowerRightSpawnLimit.transform.position.y,
left ? upperLeftSpawnLimit.transform.position.y : upperRightSpawnLimit.transform.position.y);
return position;
}
// Mini Game Control
public void StartMiniGame()
{
// Debug.Log("Cat MiniGame Started");
timer.StartTimer();
StartCoroutine("RunGame");
}
public void StopMiniGame()
{
// Debug.Log("Cat MiniGame Stopped");
StopCoroutine("RunGame");
StartCoroutine("ResetGame");
LevelManager.Instance.LoadScene(Level.MainGame);
GameManager.Instance.playedJon = true;
}
IEnumerator RunGame()
{
// Debug.Log("Cat MiniGame Running");
// Check if the cats are running
for (int i = 0; i < cats.Count; i++)
{
// Make them run.
if (!cats[i].GetComponent<Cat>().running)
{
cats[i].GetComponent<Cat>().StartRunning();
}
yield return new WaitForSeconds(Random.Range(0.2f, 0.7f));
}
yield return new WaitForSeconds(1);
StartCoroutine("RunGame");
}
IEnumerator ResetGame()
{
// Debug.Log("Cat MiniGame Reseting");
yield return new WaitForSeconds(2);
for (int i = 0; i < cats.Count; i++)
{
cats[i].GetComponent<Cat>().StopRunning();
cats[i].transform.position = GetSpawnPoint();
}
InitTimer();
}
public void SetTargetCat(CatColor targetCatColor)
{
// Debug.Log("Setting targetCatColor to " + targetCatColor.ToString());
this.targetCatColor = targetCatColor;
BirthCats();
}
public void HandleCatSelection(Cat selectedCat)
{
if(selectedCat.catColor == targetCatColor)
{
// Debug.Log("You win");
selectedCat.StopRunning();
selectedCat.PlaySatisfied();
timer.StopTimer();
StopMiniGame();
}
else
{
selectedCat.MaxSpeed();
selectedCat.PlayDissatisfied();
// Debug.Log("You lose stop hitting cats");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
//public bool disableInput = false;
public bool facingRight;
[Tooltip("Use key will be reserved by the first action in a frame. Restricts multiple actions mixing up at same frame.")]
public bool useKeyFree = true;
public bool spotted = false;
private float moveSpeed;
public float walkSpeed;
public float runSpeed;
public float crawlSpeed;
float curSpeed;
public GameObject imUsingObj;
public GameObject keyIndicatorTop;
public GameObject keyIndicatorBot;
private AudioSource audioSource;
public Rigidbody2D rb2d;
public Animator anim;
private SpriteRenderer spriteRenderer;
public Collider2D col; // Hold collider from frontal collider
public enum PlayerState { Idling,Disabling,Walking,Running,Hiding,Using }
public PlayerState state;
void Start () {
audioSource = GetComponent<AudioSource>();
spriteRenderer = GetComponent<SpriteRenderer>();
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
state = PlayerState.Idling;
ToggleKeyIndicators();
}
public void ToggleKeyIndicators()
{
// DEFAULT NULL
keyIndicatorTop.GetComponent<SpriteRenderer>().sprite = null;
keyIndicatorBot.GetComponent<SpriteRenderer>().sprite = null;
// SEEK FOR CONDITIONS TO ENABLE SPRITES
if (col != null && state != PlayerState.Using)
keyIndicatorTop.GetComponent<SpriteRenderer>().sprite = keyIndicatorBot.GetComponent<KeyIndicator>().arrowSprites[0];
else if (imUsingObj != null)
{
// SPAWN AND SETUP KEY INDICATOR
if (imUsingObj.tag == "Computer")
{
keyIndicatorBot.GetComponent<SpriteRenderer>().sprite = keyIndicatorBot.GetComponent<KeyIndicator>().arrowSprites[0];
}
else if (imUsingObj.tag == "Stairs")
{
keyIndicatorTop.GetComponent<SpriteRenderer>().sprite = keyIndicatorBot.GetComponent<KeyIndicator>().arrowSprites[0];
keyIndicatorTop.GetComponent<SpriteRenderer>().sprite = keyIndicatorBot.GetComponent<KeyIndicator>().arrowSprites[0];
}
else if (imUsingObj.tag == "Hide")
{
keyIndicatorBot.GetComponent<SpriteRenderer>().sprite = keyIndicatorBot.GetComponent<KeyIndicator>().arrowSprites[0];
}
}
}
void FixedUpdate()
{
if (Input.GetKeyUp(KeyCode.E)) // IMPORTANT TO RESET USE KEY ONLY AFTER KEY UP
useKeyFree = true; // Free use key in start of every frame to be reserved by the first action that comes by
if (state == PlayerState.Idling || state == PlayerState.Walking) // Only allow movement in these states
{
// MOVEMENT
curSpeed = moveSpeed;
float horizontalSpeed = Input.GetAxisRaw("Horizontal"); // GetAxis vs GetAxisRaw?
rb2d.velocity = new Vector2(Mathf.Lerp(0, horizontalSpeed * curSpeed * moveSpeed, 1f), 0f);
// CHECK ORIENTATION
if (Input.GetAxisRaw("Horizontal") < 0 && facingRight) // Check against player input
Flip();
else if (Input.GetAxisRaw("Horizontal") > 0 && !facingRight)
Flip();
// SET STATE
var checkInput = Mathf.Abs(Input.GetAxisRaw("Horizontal")); // Get absolute value in case input negative
if (checkInput > 0) // If there is input there is movement
{
anim.Play("Walk");
state = PlayerState.Walking;
}
else
{
anim.Play("Idle");
state = PlayerState.Idling;
}
}
// PLAYER WANTS TO RUN
if (Input.GetKey(KeyCode.LeftShift))
moveSpeed = runSpeed;
else
moveSpeed = walkSpeed; // Return to default speed when shift up
if (Input.GetKeyDown(KeyCode.W))
{
if (TryToUse())
{
}
}
if (Input.GetKeyDown(KeyCode.S))
{
if (TryToUse()) // col != null and !spotted
{
if (state == PlayerState.Hiding)
{
ToggleState(PlayerState.Idling, null, "Idle"); // Return to idle
}
}
}
// PLAYER WANTS TO INTERACT
if (Input.GetKeyDown(KeyCode.E) && useKeyFree)
{
useKeyFree = false; // Reserve use key after keypress
// WHEN HIDING
if (state == PlayerState.Hiding)
{
ToggleState(PlayerState.Idling, null, "Idle"); // Return to idle
}
// WHEN USING STUFF
else if (state == PlayerState.Using) { } // do nothing as Useable.cs has all the control over player
// WHEN IDLING, MOVING ETC
else
{
// FRONTAL COLLIDING WITH SOMETHING USABLE
if (TryToUse())
{
if (col.gameObject.name == "CyborgBack")
ToggleState(PlayerState.Disabling, col.gameObject, "Disabling");
else if (col.gameObject.name == "Computer")
ToggleState(PlayerState.Using, col.gameObject, "Use");
else if (col.gameObject.tag == "Hide")
ToggleState(PlayerState.Hiding, col.gameObject, "Hide");
else if (col.gameObject.tag == "Stairs")
UseStairs(col.gameObject);
}
else
UI.canvas.Cannot();
}
}
}
public bool TryToUse()
{
if (col == null)
{
return false;
}
if (spotted)
{
return false;
}
return true;
}
void UseStairs(GameObject stairs)
{
float yTransition = GameManager.gameManager.floorHeight;
int floorChange = 1; // Adds to GameManger currentFloor
if (stairs.GetComponent<Stairs>().stairPosition == Stairs.StairPosition.Upstairs) // If player is using upstairs negate values
{
yTransition = -yTransition;
floorChange = -floorChange;
}
transform.position = new Vector3(transform.position.x, transform.position.y + yTransition, 0f);
GameManager.gameManager.ChangeFloor(floorChange);
}
public void Spotted(bool boolean) // Spotted by cyborg, run by GameManager
{
spotted = boolean;
if ((state == PlayerState.Using) && boolean) // Stop using stuff when true
imUsingObj.GetComponent<Useable>().StopUsing(false); // Useable will return player state to idle
}
public void ToggleState(PlayerState newState, GameObject useableObject,string clip)
{
print("ToggleUse()");
// COMMON SETTINGS
state = newState; // Set new state
rb2d.velocity = Vector2.zero; // Stop physics
anim.Play(clip);
imUsingObj = useableObject; // Save reference to obj currently using
ToggleKeyIndicators();
if (newState == PlayerState.Using) // For computer
{
// SET POSITION TO APPLICABLE OBJ'S
Vector3 usePos = useableObject.transform.position;
transform.position = new Vector3(usePos.x, transform.position.y, 0f);
useableObject.GetComponent<Useable>().StartUsing(9); // Amount of keys to press
}
else if (newState == PlayerState.Disabling) // For cyborg
{
// SET POSITION TO APPLICABLE OBJ'S
useableObject.GetComponent<Useable>().StartUsing(4);
}
else if (newState == PlayerState.Hiding)
{
gameObject.layer = 2; // Set layer to 2 = Ignore Raycast to make player invisible to cyborg
// SET FACING
string faceTo = "Left"; // Init default value to get rid of error below
if (useableObject.name == "HideRight")
faceTo = "Left"; // Hide on the right side, face left
else if (useableObject.name == "HideLeft")
faceTo = "Right"; // Hide on the left side, face right
else
print("Error! ManageState Hideobj name is not right: " + useableObject.name);
if (faceTo == "Left" && facingRight)
Flip();
else if (faceTo == "Right" && !facingRight)
Flip();
// SET POSITION
Vector3 hidePos = useableObject.transform.position;
transform.position = new Vector3(hidePos.x, hidePos.y, 1.5f); // Step away from Z0 Lightsource
}
else if (newState == PlayerState.Idling) // Reset player basically
{
imUsingObj = null;
gameObject.layer = 0; // Reset layer
float resetYPosition = GameManager.gameManager.floorHeight * GameManager.gameManager.currentFloor;
transform.position = new Vector3(transform.position.x, resetYPosition, 0f); // Step away from shadows
}
}
// MAKE THIS INHERITABLE BY ALL MOVING OBJS
public void Flip()
{
//print("Player flipped.");
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1; // Need to flip whole gameobject in order to flip frontal collider etc
transform.localScale = theScale;
}
}
|
// Copyright (c) 2019 Jennifer Messerly
// This code is licensed under MIT license (see LICENSE for details)
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes;
using Kingmaker.Blueprints.Classes.Selection;
using Kingmaker.EntitySystem.Stats;
using Kingmaker.UI.Common;
using System;
using System.Collections.Generic;
using System.Text;
using RES = EldritchArcana.Properties.Resources;
namespace EldritchArcana
{
static class HeavensMystery
{
static LibraryScriptableObject library => Main.library;
static BlueprintCharacterClass oracle => OracleClass.oracle;
static BlueprintCharacterClass[] oracleArray => OracleClass.oracleArray;
internal static (BlueprintFeature, BlueprintFeature) Create(String mysteryDescription, BlueprintFeature classSkillFeat)
{
var skill1 = StatType.SkillKnowledgeArcana;
var skill2 = StatType.SkillPerception;
var mystery = Helpers.CreateProgression("MysteryHeavensProgression", RES.MysteryHeavensName_info, $"{mysteryDescription}\n" +
String.Format(RES.MysteryHeavensDescription_info, UIUtility.GetStatText(skill1), UIUtility.GetStatText(skill2)),
"dabcaefe63bc471dac44e8e23c1c330f",
Helpers.GetIcon("91da41b9793a4624797921f221db653c"), // color spray
UpdateLevelUpDeterminatorText.Group,
AddClassSkillIfHasFeature.Create(skill1, classSkillFeat),
AddClassSkillIfHasFeature.Create(skill2, classSkillFeat));
mystery.Classes = oracleArray;
var spells = Bloodlines.CreateSpellProgression(mystery, new String[] {
"91da41b9793a4624797921f221db653c", // color spray
Spells.hypnoticPatternId,
"bf0accce250381a44b857d4af6c8e10d", // searing light (should be: daylight)
"4b8265132f9c8174f87ce7fa6d0fe47b", // rainbow pattern
FlySpells.overlandFlight.AssetGuid,
"645558d63604747428d55f0dd3a4cb58", // chain lightning
"b22fd434bdb60fb4ba1068206402c4cf", // prismatic spray
"e96424f70ff884947b06f41a765b7658", // sunburst
FireSpells.meteorSwarm.AssetGuid,
});
var revelations = new List<BlueprintFeature>()
{
// TODO
};
var description = new StringBuilder(mystery.Description).AppendLine();
description.AppendLine(RES.MysteryHeavensDescription2_info);
foreach (var r in revelations)
{
description.AppendLine($"• {r.Name}");
r.InsertComponent(0, Helpers.PrerequisiteFeature(mystery));
}
mystery.SetDescription(description.ToString());
var entries = new List<LevelEntry>();
for (int level = 1; level <= 9; level++)
{
entries.Add(Helpers.LevelEntry(level * 2, spells[level - 1]));
}
// TODO:
//var finalRevelation = CreateFinalRevelation();
//entries.Add(Helpers.LevelEntry(20, finalRevelation));
mystery.LevelEntries = entries.ToArray();
mystery.UIGroups = Helpers.CreateUIGroups(new List<BlueprintFeatureBase>(spells) { /*TODO:finalRevelation*/ });
var revelation = Helpers.CreateFeatureSelection("MysteryFlameRevelation", "Flame Revelation",
mystery.Description, "40db1e0f9b3a4f5fb9fde0801b158216", null, FeatureGroup.None,
Helpers.PrerequisiteFeature(mystery));
revelation.Mode = SelectionMode.OnlyNew;
revelation.SetFeatures(revelations);
return (mystery, revelation);
}
}
} |
// Copyright 2016 Serilog Contributors
//
// 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 Serilog.Data;
/// <summary>
/// A base class for visitors that rewrite the value with modifications. For example, implementations
/// might remove all structure properties with a certain name, apply size/length limits, or convert scalar properties of
/// one type into scalar properties of another.
/// </summary>
/// <typeparam name="TState"></typeparam>
public abstract class LogEventPropertyValueRewriter<TState> : LogEventPropertyValueVisitor<TState, LogEventPropertyValue>
{
/// <summary>
/// Visit a <see cref="ScalarValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="scalar">The value to visit.</param>
/// <returns>The result of visiting <paramref name="scalar"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="scalar"/> is <code>null</code></exception>
protected override LogEventPropertyValue VisitScalarValue(TState state, ScalarValue scalar)
{
return Guard.AgainstNull(scalar);
}
/// <summary>
/// Visit a <see cref="SequenceValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="sequence">The value to visit.</param>
/// <returns>The result of visiting <paramref name="sequence"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="sequence"/> is <code>null</code></exception>
protected override LogEventPropertyValue VisitSequenceValue(TState state, SequenceValue sequence)
{
Guard.AgainstNull(sequence);
for (var i = 0; i < sequence.Elements.Count; ++i)
{
var original = sequence.Elements[i];
if (!ReferenceEquals(original, Visit(state, original)))
{
var contents = new LogEventPropertyValue[sequence.Elements.Count];
// There's no need to visit any earlier elements: they all evaluated to
// a reference equal with the original so just fill in the array up until `i`.
for (var j = 0; j < i; ++j)
{
contents[j] = sequence.Elements[j];
}
for (var k = i; k < contents.Length; ++k)
{
contents[k] = Visit(state, sequence.Elements[k]);
}
return new SequenceValue(contents);
}
}
return sequence;
}
/// <summary>
/// Visit a <see cref="StructureValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="structure">The value to visit.</param>
/// <returns>The result of visiting <paramref name="structure"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="structure"/> is <code>null</code></exception>
protected override LogEventPropertyValue VisitStructureValue(TState state, StructureValue structure)
{
Guard.AgainstNull(structure);
for (var i = 0; i < structure.Properties.Count; ++i)
{
var original = structure.Properties[i];
if (!ReferenceEquals(original.Value, Visit(state, original.Value)))
{
var properties = new LogEventProperty[structure.Properties.Count];
// There's no need to visit any earlier elements: they all evaluated to
// a reference equal with the original so just fill in the array up until `i`.
for (var j = 0; j < i; ++j)
{
properties[j] = structure.Properties[j];
}
for (var k = i; k < properties.Length; ++k)
{
var property = structure.Properties[k];
properties[k] = new(property.Name, Visit(state, property.Value));
}
return new StructureValue(properties, structure.TypeTag);
}
}
return structure;
}
/// <summary>
/// Visit a <see cref="DictionaryValue"/> value.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="dictionary">The value to visit.</param>
/// <returns>The result of visiting <paramref name="dictionary"/>.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="dictionary"/> is <code>null</code></exception>
protected override LogEventPropertyValue VisitDictionaryValue(TState state, DictionaryValue dictionary)
{
Guard.AgainstNull(dictionary);
foreach (var original in dictionary.Elements)
{
if (!ReferenceEquals(original.Value, Visit(state, original.Value)))
{
var elements = new Dictionary<ScalarValue, LogEventPropertyValue>(dictionary.Elements.Count);
foreach (var element in dictionary.Elements)
{
elements[element.Key] = Visit(state, element.Value);
}
return new DictionaryValue(elements);
}
}
return dictionary;
}
/// <summary>
/// Visit a value of an unsupported type. Returns the value unchanged.
/// </summary>
/// <param name="state">Operation state.</param>
/// <param name="value">The value to visit.</param>
/// <returns>The result of visiting <paramref name="value"/>.</returns>
// ReSharper disable once UnusedParameter.Global
// ReSharper disable once VirtualMemberNeverOverriden.Global
protected override LogEventPropertyValue VisitUnsupportedValue(TState state, LogEventPropertyValue value)
{
return value;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BikeRaceApp
{
public partial class FormSearchRider : Form
{
RaceManager rm;
private DataView dv;
public FormSearchRider(RaceManager rm)
{
this.rm = rm;
InitializeComponent();
//populate table
List<Rider> tempriders = rm.GetRiders();
//LISTVIEW PROPERTIES
lvSearch.View = View.Details;
lvSearch.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
//Add Columns
lvSearch.Columns.Add("Name", 100);
lvSearch.Columns.Add("Surname", 150);
lvSearch.Columns.Add("School", 100);
lvSearch.Columns.Add("Race 1", 65);
lvSearch.Columns.Add("Race 2", 65);
lvSearch.Columns.Add("Race 3", 65);
lvSearch.Columns.Add("Race 4", 65);
//Fill Data Table
dv = new DataView(this.rm.FillSearchTable());
PopulateListView(dv);
}
//Making the riders visible to the user in the search area
private void PopulateListView(DataView dv)
{
//clearing list view
lvSearch.Items.Clear();
//adding each rider to the list view 1 by 1
foreach (DataRow row in dv.ToTable().Rows)
{
lvSearch.Items.Add(new ListViewItem(new string[] { row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString(), row[4].ToString(), row[5].ToString(), row[6].ToString() }));
}
}
//sending user back to main menu
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
FormMainMenu window = new FormMainMenu(rm);
window.FormClosed += (s, args) => this.Close();
window.Show();
}
//Updating the rider that are showed based on the text in the Search Bar
private void txbSearchBar_TextChanged(object sender, EventArgs e)
{
//Making sure there are no invalid characters in the search bar
if (!Regex.IsMatch((txbSearchBar.Text), "^[a-zA-Z]*$"))
{
MessageBox.Show("You cannot enter 123!@# ect in a search bar", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Filtering the list view to only displayed searched for riders
dv.RowFilter = string.Format("Name Like '%{0}%'", txbSearchBar.Text);
PopulateListView(dv);
}
//adding custom font to form
private void FormSearchRider_Load(object sender, EventArgs e)
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("Montserrat-Regular.ttf");
foreach (Control c in this.Controls)
{
c.Font = new Font(pfc.Families[0], c.Font.Size, c.Font.Style);
}
}
}
}
|
using Common.Data;
using Common.Exceptions;
using Common.Extensions;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace Entity
{
public partial class MovieMSOAltTitles
{
public string GetBroadcastTitle(string connectionString, string providerName, int id)
{
string result = String.Empty;
//select broadcast_title from movie_mso_alt_titles join system_mso_alt_titles on
//movie_mso_alt_titles.mso_alt_title_id = system_mso_alt_titles.id
//where display_name = @MSO and movie_id = @ID
string sql = "P_Clipboard_MSO_Title";
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@MSO", providerName));
parameters.Add(new SqlParameter("@ID", id));
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectString(sql, parameters: parameters.ToArray());
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
finally
{
parameters.Clear();
}
}
return result;
}
public string GetTitleByType(string connectionString, string type, int msoId, int id)
{
string result = String.Empty;
string sql = "select " + type + "_title from movie_mso_alt_titles where mso_alt_title_id = " +
msoId.ToString() + " and movie_id = " + id.ToString();
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectString(sql);
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public string GetVODTitle(string connectionString, string providerName, int id)
{
string result = String.Empty;
//select vod_title from movie_mso_alt_titles join system_mso_alt_titles on
//movie_mso_alt_titles.mso_alt_title_id = system_mso_alt_titles.id
//where display_name = @MSO and movie_id = @ID
string sql = "P_Clipboard_MSO_Title_VOD";
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@MSO", providerName));
parameters.Add(new SqlParameter("@ID", id));
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectString(sql, parameters: parameters.ToArray());
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
finally
{
parameters.Clear();
}
}
return result;
}
public bool HasAltTitles(string connectionString, string title, int id)
{
bool result = false;
string sql = "select count(*) from movie_mso_alt_titles where id = " + id.ToString() + " " +
"and (broadcast_title like '%" + title.EscapeSingleQuotes() + "%' or vod_title like " +
"'" + title.EscapeSingleQuotes() + "')";
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectInt(sql).GetValueOrDefault() > 0;
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraTwoRotate : MonoBehaviour
{
private Transform myTransform;
private Vector3 newRotate;
private Vector3 curRot;
void Start()
{
myTransform = transform;
curRot = Input.acceleration;
}
private void FixedUpdate()
{
// за допомогою акселератора здійснюємо керування кораблем у режимі без VR
newRotate = new Vector3(-(Input.acceleration.z - curRot.z) * 150, (Input.acceleration.x - curRot.x) * 150, 0);
myTransform.rotation = Quaternion.Lerp(myTransform.rotation, Quaternion.Euler(newRotate), Time.deltaTime);
}
}
|
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 MOTHER3;
using Extensions;
namespace MOTHER3Funland
{
public partial class frmMapViewer : M3Form
{
// Layer stuff
CheckBox[] chkLayer = new CheckBox[3];
CheckBox[] chkTable = new CheckBox[7];
public ComboSearch combo;
public List<Gift>[] Elements;
public int room;
bool loading = false;
// Text cache
string[] mapnames = new string[TextMapNames.Entries];
public frmMapViewer()
{
InitializeComponent();
//Loads the gift box table once
loadGiftBoxTable();
// Draw the layer stuff
for (int i = 0; i < 3; i++)
{
var cb = new CheckBox();
cb.AutoSize = true;
cb.Text = "Layer " + (i + 1).ToString();
cb.Checked = true;
cb.Left = 53 + (i * 80);
cb.Top = 39;
cb.Visible = true;
cb.CheckedChanged += new EventHandler(cboRoom_SelectedIndexChanged);
this.Controls.Add(cb);
chkLayer[i] = cb;
}
for (int u = 0; u < 7; u++)
{
var cc = new CheckBox();
cc.AutoSize = true;
if (u < 5)
{
cc.Text = "Table " + (u + 1).ToString();
cc.Checked = true;
}
else if (u == 5)
{
cc.Text = "Gifts";
cc.Checked = true;
}
else if (u == 6)
{
cc.Text = "Combine";
cc.Checked = false;
}
cc.Left = 53 + (u * 80);
cc.Top = 59;
cc.Visible = true;
cc.CheckedChanged += new EventHandler(cboRoom_SelectedIndexChanged);
this.Controls.Add(cc);
chkTable[u] = cc;
}
MapData.Init();
// Load the map names
loading = true;
Helpers.CheckFont(cboRoom);
combo = cboRoom;
cboRoom.JapaneseSearch = M3Rom.Version == RomVersion.Japanese;
for (int i = 0; i < mapnames.Length; i++)
{
mapnames[i] = TextMapNames.GetName((i != mapnames.Length - 1) ? i + 1 : 0);
cboRoom.Items.Add("[" + i.ToString("X3") + "] " +
mapnames[i].Replace(Environment.NewLine, " "));
}
cboRoom.SelectedIndex = 0;
loading = false;
}
Bitmap a, b, c;
Image pictureBox1Image;
public static Bitmap MergeTwoImages(Image firstImage, Image secondImage)
{
if (firstImage == null)
{
throw new ArgumentNullException("firstImage");
}
if (secondImage == null)
{
throw new ArgumentNullException("secondImage");
}
int outputImageWidth = firstImage.Width;
int outputImageHeight = firstImage.Height;
Bitmap outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (Graphics graphics = Graphics.FromImage(outputImage))
{
graphics.DrawImage(firstImage, new Rectangle(new Point(), firstImage.Size),
new Rectangle(new Point(), firstImage.Size), GraphicsUnit.Pixel);
graphics.DrawImage(secondImage, new Rectangle(new Point(), secondImage.Size),
new Rectangle(new Point(), secondImage.Size), GraphicsUnit.Pixel);
}
return outputImage;
}
private void cboRoom_SelectedIndexChanged(object sender, EventArgs e)
{
if (loading) return;
int flags = 0;
for (int i = 0; i < 3; i++)
flags |= (chkLayer[i].Checked ? (1 << i) : 0);
pMap.Image = MapData.GetMap(cboRoom.SelectedIndex, flags);
pictureBox1Image = MapData.GetSprites(pMap.Image.Width, pMap.Image.Height, cboRoom.SelectedIndex, chkTable, out a, out b, out c, Elements[cboRoom.SelectedIndex]);
if ((pMap.Image != null) && (a != null))
{
pMap.Image = MergeTwoImages(pMap.Image, pictureBox1Image);
pMap.Image = MergeTwoImages(pMap.Image, a);
pMap.Image = MergeTwoImages(pMap.Image, b);
if ((chkTable[6].Checked == true) && (cboRoom.SelectedIndex != 0x374))
{
a = MapData.GetLayer1(cboRoom.SelectedIndex, flags);
if ((a != null) && (cboRoom.SelectedIndex != 0x95) && (cboRoom.SelectedIndex != 0x6D))
pMap.Image = MergeTwoImages(pMap.Image, a);
else
pMap.Image = MergeTwoImages(pMap.Image, MapData.GetLayer2(cboRoom.SelectedIndex, flags));
}
}
else if (pMap.Image == null)
pMap.Image = a;
if (pMap.Image != null & c != null)
pMap.Image = MergeTwoImages(pMap.Image, c);
else if (pMap.Image == null)
pMap.Image = c;
pMap.Refresh();
}
private void mnuMapCopy_Click(object sender, EventArgs e)
{
Helpers.GraphicsCopy(sender);
}
private void mnuMapSave_Click(object sender, EventArgs e)
{
Helpers.GraphicsSave(sender, dlgSaveImage);
}
public override void SelectIndex(int[] index)
{
cboRoom.SelectedIndex = index[0];
}
private void generateObjEditingWindow(object sender, EventArgs e)
{
this.Enabled = false;
frmObjEditor a = new frmObjEditor(this);
}
public override int[] GetIndex()
{
return new int[] { cboRoom.SelectedIndex };
}
private void loadGiftBoxTable()
{
int giftAddress = 0x1165C10;
int pos = M3Rom.Rom.ReadInt(giftAddress + 4) + giftAddress;
int length = M3Rom.Rom.ReadInt(giftAddress + 8);
Elements = new List<Gift>[0x3E8];
for (int i = 0; i < 0x3E8; i++)
Elements[i] = new List<Gift>();
for (int address = pos - giftAddress; address < length; address += 0x10)
{
if ((M3Rom.Rom[address + giftAddress] & 0x1) == 1)
{
Gift tmp = new Gift(M3Rom.Rom, address + giftAddress);
Elements[tmp.Map].Add(tmp);
}
}
}
}
}
|
using UnityEngine;
public class Scaler : MonoBehaviour
{
public float aspect_w = 9f;
public float aspect_h = 16f;
private void Start()
{
Camera cam = GetComponent<Camera>();
var targetAspect = aspect_w / aspect_h;
var initialSize = cam.orthographicSize;
if (cam.aspect < 1.6f)
{
// respect width (modify default behavior)
cam.orthographicSize = initialSize * (targetAspect / Camera.main.aspect);
}
else
{
// respect height (change back to default behavior)
cam.orthographicSize = initialSize;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DPYM;
namespace DPYM_DEBUG
{
public class AboutQuaternion : MonoBehaviour
{
public Quaternion quaterntion;
public Vector3 velocity;
public float angle;
// Use this for initialization
void Start()
{
}
private Vector3 rr = new Vector3(0,1,0);
// Update is called once per frame
void Update()
{
//transform.localRotation = quaterntion;
transform.localRotation = Quaternion.FromToRotation(rr, velocity);
float x = velocity.x, y = velocity.y;
angle = Mathf.Atan2(x,y);
angle *= Mathf.Rad2Deg;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
public static bool GameIsPaused=false;
public GameObject pauseMenuUI;
public GameObject statsMenu;
public GameObject camera;
private double lastSwitch=-1;
[SerializeField] private WindowGraph wg;
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.Escape) && Time.realtimeSinceStartup-lastSwitch>1){
lastSwitch=Time.realtimeSinceStartup;
if(GameIsPaused){
Resume();
}
else{
Pause();
}
}
}
public void Resume(){
pauseMenuUI.SetActive(false);
statsMenu.SetActive(false);
Time.timeScale=1f;
GameIsPaused=false;
camera.gameObject.GetComponent<ThirdPersonOrbitCamBasic>().enabled = true;
}
public void Pause(){
pauseMenuUI.SetActive(true);
Time.timeScale=0f;
GameIsPaused=true;
camera.gameObject.GetComponent<ThirdPersonOrbitCamBasic>().enabled = false;
}
public void LoadMenu(){
SceneManager.LoadScene(1);
}
public void Stats(){
wg.refresh();
pauseMenuUI.SetActive(false);
statsMenu.SetActive(true);
Time.timeScale=0f;
GameIsPaused=true;
camera.gameObject.GetComponent<ThirdPersonOrbitCamBasic>().enabled = false;
}
public void QuitStats(){
pauseMenuUI.SetActive(true);
statsMenu.SetActive(false);
Time.timeScale=0f;
GameIsPaused=true;
camera.gameObject.GetComponent<ThirdPersonOrbitCamBasic>().enabled = false;
}
public void QuitGame(){
Application.Quit();
}
}
|
namespace KnowledgePortal.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class removeTechnology : DbMigration
{
public override void Up()
{
AlterColumn("dbo.Posts", "Summary", c => c.String(nullable: false, maxLength: 150));
DropColumn("dbo.Posts", "Technology");
}
public override void Down()
{
AddColumn("dbo.Posts", "Technology", c => c.String(nullable: false));
AlterColumn("dbo.Posts", "Summary", c => c.String(nullable: false));
}
}
}
|
using AutoMapper;
using Data.Models;
using Services.Representers;
namespace Services
{
public static class AutoMapper
{
public static IMapper Mapper;
/// <summary>
/// Configures Mappings between Data Model and Representer
/// </summary>
static AutoMapper()
{
Mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.CreateMap<RoleRepresenter, Role>().ForMember(roleDataModel => roleDataModel.Users, options => options.MapFrom(roleRepresenter => roleRepresenter.UserRepresentors));
cfg.CreateMap<Role, RoleRepresenter>().ForMember(roleRepresenter => roleRepresenter.UserRepresentors, options => options.MapFrom(roleDataModel => roleDataModel.Users));
cfg.CreateMap<UserRepresenter, User>().ForMember(userDataModel => userDataModel.Roles, options => options.MapFrom(userRepresenter => userRepresenter.RoleRepresentors));
cfg.CreateMap<User, UserRepresenter>().ForMember(userRepresenter => userRepresenter.RoleRepresentors, options => options.MapFrom(userDataModel => userDataModel.Roles));
}));
}
}
} |
using System.Threading.Tasks;
namespace OnboardingSIGDB1.Domain.Empresas.Validators
{
public interface IValidadorDeEmpresaDuplicada
{
Task Valid(Empresa empresa);
}
} |
using EventLite.MongoDB.DTO;
using MongoDB.Bson.Serialization;
namespace EventLite.MongoDB.Map
{
internal static class MongoMappers
{
public static void RegisterMaps()
{
BsonClassMap.RegisterClassMap<EventStreamDTO>(map =>
{
map.AutoMap();
map.SetIgnoreExtraElements(true);
});
BsonClassMap.RegisterClassMap<SnapshotDTO>(map =>
{
map.AutoMap();
map.SetIgnoreExtraElements(true);
});
BsonClassMap.RegisterClassMap<CommitDTO>(map =>
{
map.AutoMap();
map.SetIgnoreExtraElements(true);
});
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZC_IT_TimeTracking.BusinessEntities;
namespace ZC_IT_TimeTracking.Services.Interfaces
{
public interface IGoalRuleServices :IServiceBase
{
List<GoalRule> GetGoalRules(int Goalid);
bool InsertGoalRules(GoalRule gr);
bool DeleteAllGoalRule(int goalid);
}
}
|
using SampleProject.Repository;
using System;
namespace SampleProject
{
public class UnitOfWork : IUnitOfWork
{
private IUserRepository _userRepository;
public UnitOfWork(IUserRepository userRepository)
{
_userRepository = userRepository;
}
void IUnitOfWork.Complete()
{
throw new NotImplementedException();
}
public IUserRepository UserRepository
{
get
{
return _userRepository;
}
}
}
} |
namespace AI2048.AI.SearchTree
{
using AI2048.Game;
public interface ISearchTree
{
IPlayerNode RootNode { get; }
int KnownPlayerNodeCount { get; }
int KnownComputerNodeCount { get; }
void MoveRoot(LogarithmicGrid newGrid);
}
} |
using UnityEngine;
public class DragAndDrop : MonoBehaviour
{
public GameObject transparentObject;
public GameObject background;
public GameObject previousBackground;
private bool _selected;
// Update is called once per frame
void Update()
{
if (_selected)
{
Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector2(cursorPos.x, cursorPos.y);
}
if (Input.GetMouseButtonUp(0))
{
_selected = false;
CheckPosition();
}
}
private void OnMouseOver()
{
if (Input.GetMouseButtonDown(0))
{
_selected = true;
}
}
private void CheckPosition()
{
if (previousBackground)
{
if (previousBackground.activeSelf)
{
float Distance = Vector3.Distance(transform.position, transparentObject.transform.position);
if (Distance < 1)
{
background.SetActive(true);
transparentObject.SetActive(false);
gameObject.SetActive(false);
}
}
}
else
{
float Distance = Vector3.Distance(transform.position, transparentObject.transform.position);
if (Distance < 1)
{
background.SetActive(true);
transparentObject.SetActive(false);
gameObject.SetActive(false);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class FireProjectile : MonoBehaviour {
public GameObject projectilePrefab;
public bool mouseAim = true;
//Changed default speed
public float speed = 200.0f;
public float knockBackAmount = 0.4f;
public Vector3 target;
//The rigidbody to apply knockback to.
public Rigidbody2D knockBackRigidBody;
//Function to modify the projectile, can imagine it like the
//strength of the spell.
public string modifierName = "SetExplosionMagnitude";
public void Fire(float modifierValue = 1.0f)
{
/*
* Moved to MovePosition instead of this Add Force implementation
*
Vector3 finalTarget;
if (mouseAim)
{
finalTarget = Camera.main.ScreenToWorldPoint( Input.mousePosition );
}
else
{
finalTarget = this.target.position;
}
Vector3 direction3D = this.transform.position - finalTarget;
Vector2 direction = new Vector2 (direction3D.x, direction3D.y);
direction.Normalize();
var angle = Quaternion.Euler (0, 0, Mathf.Atan2 (-direction.y, -direction.x) * Mathf.Rad2Deg);
GameObject projectile = (GameObject)Instantiate (projectilePrefab, transform.position, angle);
projectile.SendMessage (modifierName, modifierValue);
var projectileRigidBody = projectile.GetComponent<Rigidbody2D> ();
var projectileImpulseVector = -(direction * speed)*modifierValue;
projectileRigidBody.AddForce (projectileImpulseVector, ForceMode2D.Impulse);
var knockBackImpulseVector = CalculateKnockback (projectileImpulseVector, knockBackAmount);
knockBackRigidBody.AddForce (knockBackImpulseVector , ForceMode2D.Impulse);*/
Vector3 finalTarget;
if (mouseAim)
{
//The position that the player clicked
finalTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else
{
finalTarget = target;
}
//the vector to that target from the player
Vector3 rot = finalTarget - transform.position;
//create projectile infront of the player
GameObject projectile = (GameObject)Instantiate (projectilePrefab, transform.position + transform.forward, Quaternion.identity);
//set this projectiles velocity to the normalised previously calculated direction, modified by speed accordingly.
projectile.GetComponent<Rigidbody2D> ().velocity = (finalTarget - transform.position).normalized * speed;
}
Vector3 CalculateKnockback(Vector2 projectileImpulse, float knockBackScale)
{
var magnitude = projectileImpulse.magnitude;
//Kmockback in opposite direction to projectilw;
var direction = -projectileImpulse.normalized;
//If the magnitude is less than one squaring it will make it smaller.
magnitude = magnitude + 1.0f;
//Square and take the one we added before.
magnitude = magnitude * magnitude * 0.4f - 1.0f;
return direction * magnitude * knockBackScale;
}
}
|
using FeriaVirtual.App.Desktop.Extensions.DependencyInjection;
using FeriaVirtual.App.Desktop.SeedWork.Filters;
using FeriaVirtual.App.Desktop.SeedWork.FormControls;
using FeriaVirtual.App.Desktop.SeedWork.FormControls.MsgBox;
using FeriaVirtual.App.Desktop.SeedWork.Helpers.Utils;
using FeriaVirtual.App.Desktop.Services.Employees;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FeriaVirtual.App.Desktop.Forms.Employees
{
public partial class EmployeeMainForm : MetroFramework.Forms.MetroForm
{
private readonly IEmployeeService _employeeService;
private readonly ThemeManager _themeManager;
private EmployeeFilter _filters;
private Criteria _actualCriteria;
public EmployeeMainForm()
{
InitializeComponent();
_themeManager = ThemeManager.SuscribeForm(this);
_themeManager.DarkMode();
var serviceProvider = DependencyContainer.GetProvider;
_employeeService = serviceProvider.GetService<IEmployeeService>();
}
private void EmployeeMainForm_Load(object sender, System.EventArgs e)
{
ConfigureForm();
ConfigureFilters();
//Task<int> numberOfRecords = CountRecords();
//ConfigurePaginator(numberOfRecords.Result);
LoadRecords();
}
private void ConfigureForm()
{
MenuPanel.BackColor = _themeManager.Style.Equals(MetroFramework.MetroThemeStyle.Dark) ? System.Drawing.Color.DarkSlateGray : System.Drawing.Color.DarkGray;
RefreshToolStripMenuItem.ForeColor = _themeManager.Style.Equals(MetroFramework.MetroThemeStyle.Dark) ? System.Drawing.Color.White : System.Drawing.Color.Black;
NewEmployeeToolStripMenuItem.ForeColor = _themeManager.Style.Equals(MetroFramework.MetroThemeStyle.Dark) ? System.Drawing.Color.White : System.Drawing.Color.Black;
ExitToolStripMenuItem.ForeColor = _themeManager.Style.Equals(MetroFramework.MetroThemeStyle.Dark) ? System.Drawing.Color.White : System.Drawing.Color.Black;
}
private void ConfigureFilters()
{
_filters = EmployeeFilter.CreateFilter();
var configurator = ComboboxConfigurator.Configure(FilterComboBox);
configurator.AddStringList(_filters.GetFilters);
FilterTextBox.Text = string.Empty;
_actualCriteria = _filters.GetCriteriaByIndex(0);
}
private void ConfigurePaginator(int numberOfRecords)
{
var pages = 0;
pages = numberOfRecords / PreferenceData.RowsPerPage;
if((numberOfRecords % PreferenceData.RowsPerPage) != 0)
pages++;
var configurator = ComboboxConfigurator.Configure(ListPageComboBox);
configurator.AddNumbers(1, pages);
ListResultLabel.Text = $"{numberOfRecords} registros encontrados.";
}
private async Task<int> CountRecords()
{
var employeeCounter = new EmployeeCounterViewModel();
int numberOfRecords = 0;
try {
employeeCounter = await _employeeService.GetNumberOfEmployees();
numberOfRecords= employeeCounter.Total;
return numberOfRecords;
} catch {
return numberOfRecords;
}
}
#region "Toolstripmenu events"
private void ToolStripMenuItem_MouseEnter
(object sender, System.EventArgs e)
{
var item = (ToolStripMenuItem)sender;
item.ForeColor = System.Drawing.Color.Black;
}
private void ToolStripMenuItem_MouseLeave
(object sender, System.EventArgs e)
{
var item = (ToolStripMenuItem)sender;
item.ForeColor = _themeManager.Style.Equals(MetroFramework.MetroThemeStyle.Dark) ? System.Drawing.Color.White : System.Drawing.Color.Black;
}
private void ToolStripMenuItem_DropDownOpened
(object sender, System.EventArgs e)
{
var item = (ToolStripMenuItem)sender;
item.ForeColor = System.Drawing.Color.Black;
}
private void ToolStripMenuItem_DropDownClosed
(object sender, System.EventArgs e)
{
var item = (ToolStripMenuItem)sender;
item.ForeColor = System.Drawing.Color.Black;
}
#endregion
private void ExitToolStripMenuItem_Click
(object sender, System.EventArgs e) =>
Close();
private void ListPageComboBox_SelectedIndexChanged
(object sender, System.EventArgs e)
{
if(_actualCriteria is null)
return;
_actualCriteria.PageNumber = int.Parse(ListPageComboBox.Text);
}
private void FilterComboBox_SelectedIndexChanged
(object sender, System.EventArgs e)
{
_actualCriteria = _filters.GetCriteriaByIndex(FilterComboBox.SelectedIndex);
FilterTextBox.Visible = _actualCriteria.RequireInput;
}
private void FilterButton_Click
(object sender, System.EventArgs e)
{
VerifyCriteriaValues();
LoadRecords();
}
private void VerifyCriteriaValues()
{
if(!_actualCriteria.RequireInput)
return;
_actualCriteria.ChangeCriteriaValue(FilterTextBox.Text);
}
private async void LoadRecords()
{
try {
IList < EmployeesViewModel > employeesFound;
if(_actualCriteria.CriteriaType.Equals("search_all"))
employeesFound = await _employeeService.GetAllEmployees(_actualCriteria.PageNumber);
else
employeesFound = await _employeeService.GetEmployeesByCriteria(_actualCriteria);
ConfigureDataGridView(employeesFound);
ConfigurePaginator(employeesFound.Count);
} catch(System.Exception ex) {
MsgBox.Show(this, ex.Message, "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ConfigureDataGridView(IList<EmployeesViewModel> employeesFound)
{
var configurator = DataGridViewConfigurator.Configure(EmployeeGrid);
EmployeeGrid.DataSource = employeesFound;
configurator.HideColumn("UserId");
}
}
}
|
using UnityEngine;
[System.Serializable]
public class MyClass
{
public int x = 0;
public int y = 0;
public int sum = 0;
public int product = 0;
public MyClass()
{
}
public MyClass(int x, int y)
{
this.x = x;
this.y = y;
}
// Update is called once per frame
public void Update ()
{
sum = x + y;
product = x * y;
}
}
|
namespace classicSortingAlgorithms.SortingClasses {
using System.Collections.Generic;
class SelectionSorting<T> : Sort<T> {
public override string ClassName { get; set; } = "Selection";
public override T[] Sorting(T[] array) {
for (int i = 0; i < array.Length; i++) {
int min = i;
for (int j = i + 1; j < array.Length; j++) {
if (Comparer.Compare(array[min], array[j]) == 1)
min = j;
}
if (min != i)
Swap(array, min, i);
}
return array;
}
public SelectionSorting(T[] array, IComparer<T> comparer) : base(array) {
Comparer = comparer;
}
public SelectionSorting(IComparer<T> comparer) : base() {
Comparer = comparer;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Foundry.Website.Models;
using Foundry.Security;
namespace Foundry.Website
{
public class FormsAuthenticationResult : ActionResult
{
private readonly FoundryUser _user;
private readonly bool _rememberMe;
public FormsAuthenticationResult(FoundryUser user, bool rememberMe)
{
_user = user;
_rememberMe = rememberMe;
}
public override void ExecuteResult(ControllerContext context)
{
var ticket = new FormsAuthenticationTicket(1,
_user.Name,
DateTime.Now,
DateTime.Now.AddDays(10),
_rememberMe,
_user.ToString());
var ticketString = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString);
if (_rememberMe)
cookie.Expires = DateTime.Now.AddDays(10);
context.HttpContext.Response.Cookies.Add(cookie);
HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(_user.Name, false));
}
}
} |
using System.ComponentModel.DataAnnotations;
namespace School_Spravki.Models
{
public class StudentModel
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BAH.BOS.WebAPI.ServiceStub
{
/// <summary>
/// 结果代码枚举。
/// </summary>
public enum ResultCode
{
/// <summary>
/// 失败。
/// </summary>
Fail = 0,
/// <summary>
/// 成功。
/// </summary>
Success = 1,
}//end enum
}//end namespace
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace SimpleProject.Mess
{
using SizePacket = UInt16;
public interface IPacker : ITypeID
{
void CreatePacket(BinaryWriter writer, IMessage message);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using ProgrammerAl.DTO.Attributes;
namespace ProgrammerAl.DTO.Generators
{
public class IsValidCheckCodeConfigGenerator
{
public IDtoPropertyIsValidCheckConfig GeneratePropertyIsValidCheckRules(
IPropertySymbol propertySymbol,
AttributeSymbols attributeSymbols,
ImmutableArray<string> allClassesAddingDto)
{
var propertyAttributes = propertySymbol.GetAttributes();
string fullDataTypeName = PropertyUtilities.GenerateDataTypeFullNameFromProperty(propertySymbol);
if (DataTypeIsNullable(fullDataTypeName))
{
return CreateAllowNullPropertyConfig();
}
else if (DataTypeIsString(fullDataTypeName))
{
return CreateDtoPropertyCheckConfigForString(propertyAttributes, attributeSymbols);
}
else if (DataTypeIsAnotherDto(fullDataTypeName, allClassesAddingDto))
{
return CreateDtoPropertyCheckConfigForDto(propertyAttributes, attributeSymbols);
}
return CreateDefaultPropertyConfig();
}
private bool DataTypeIsString(string fullDataTypeName)
{
return
string.Equals("string", fullDataTypeName, StringComparison.OrdinalIgnoreCase)
|| string.Equals("System.String", fullDataTypeName, StringComparison.OrdinalIgnoreCase);
}
private IDtoPropertyIsValidCheckConfig CreateDtoPropertyCheckConfigForString(ImmutableArray<AttributeData> propertyAttributes, AttributeSymbols attributeSymbols)
{
var stringPropertyAttribute = propertyAttributes.FirstOrDefault(x => x.AttributeClass?.Equals(attributeSymbols.DtoStringPropertyCheckAttributeSymbol, SymbolEqualityComparer.Default) is true);
if (stringPropertyAttribute is object)
{
var value = stringPropertyAttribute.NamedArguments.FirstOrDefault(x => x.Key == nameof(StringPropertyCheckAttribute.StringIsValidCheckType)).Value;
var stringCheckType = (StringIsValidCheckType)(value.Value!);
return new DtoStringPropertyIsValidCheckConfig(stringCheckType);
}
//A string could instead have the DtoBasicPropertyCheckAttribute attribute applied. Check for that too
DtoBasicPropertyIsValidCheckConfig? propertyCheckConfig = CreateBasicPropertyCheckFromAttribute(propertyAttributes, attributeSymbols);
if (propertyCheckConfig is object && propertyCheckConfig.AllowNull)
{
return new DtoStringPropertyIsValidCheckConfig(StringIsValidCheckType.AllowNull);
}
return new DtoStringPropertyIsValidCheckConfig(StringPropertyCheckAttribute.DefaultStringIsValidCheckType);
}
private IDtoPropertyIsValidCheckConfig CreateDtoPropertyCheckConfigForBasicProperty(ImmutableArray<AttributeData> propertyAttributes, AttributeSymbols attributeSymbols)
{
DtoBasicPropertyIsValidCheckConfig? propertyCheckConfig = CreateBasicPropertyCheckFromAttribute(propertyAttributes, attributeSymbols);
if (propertyCheckConfig is object)
{
return propertyCheckConfig;
}
return new DtoBasicPropertyIsValidCheckConfig(AllowNull: false);
}
private bool DataTypeIsAnotherDto(string fullDataTypeName, ImmutableArray<string> allDtoNamesBeingGenerated)
{
return allDtoNamesBeingGenerated.Any(x => string.Equals(x, fullDataTypeName, StringComparison.OrdinalIgnoreCase));
}
private bool DataTypeIsNullable(string fullDataTypeName)
{
//TODO: Check for Nullable<> too I guess
return fullDataTypeName.EndsWith("?");
}
private DtoBasicPropertyIsValidCheckConfig? CreateBasicPropertyCheckFromAttribute(ImmutableArray<AttributeData> propertyAttributes, AttributeSymbols attributeSymbols)
{
var basicPropertyAttribute = propertyAttributes.FirstOrDefault(x => x.AttributeClass?.Equals(attributeSymbols.DtoBasicPropertyCheckAttributeSymbol, SymbolEqualityComparer.Default) is true);
if (basicPropertyAttribute is object)
{
var allowNullValue = basicPropertyAttribute.NamedArguments.FirstOrDefault(x => x.Key == nameof(BasicPropertyCheckAttribute.AllowNull)).Value;
var allowNull = (bool)allowNullValue.Value!;
return new DtoBasicPropertyIsValidCheckConfig(allowNull);
}
return null;
}
private IDtoPropertyIsValidCheckConfig CreateDefaultPropertyConfig() => new DtoBasicPropertyIsValidCheckConfig(AllowNull: false);
private IDtoPropertyIsValidCheckConfig CreateAllowNullPropertyConfig() => new DtoBasicPropertyIsValidCheckConfig(AllowNull: true);
private IDtoPropertyIsValidCheckConfig CreateDtoPropertyCheckConfigForDto(ImmutableArray<AttributeData> propertyAttributes, AttributeSymbols attributeSymbols)
{
var dtoPropertyAttribute = propertyAttributes.FirstOrDefault(x => x.AttributeClass?.Equals(attributeSymbols.DtoPropertyCheckAttributeSymbol, SymbolEqualityComparer.Default) is true);
if (dtoPropertyAttribute is object)
{
var checkIsValidValue = dtoPropertyAttribute.NamedArguments.FirstOrDefault(x => x.Key == nameof(DtoPropertyCheckAttribute.CheckIsValid)).Value;
var checkIsValid = (bool)checkIsValidValue.Value!;
var allowNullValue = dtoPropertyAttribute.NamedArguments.FirstOrDefault(x => x.Key == nameof(BasicPropertyCheckAttribute.AllowNull)).Value;
var allowNull = (bool)allowNullValue.Value!;
return new DtoPropertyIsValidCheckConfig(allowNull, checkIsValid);
}
DtoBasicPropertyIsValidCheckConfig? propertyCheckConfig = CreateBasicPropertyCheckFromAttribute(propertyAttributes, attributeSymbols);
if (propertyCheckConfig is object)
{
return propertyCheckConfig;
}
return new DtoPropertyIsValidCheckConfig(CheckIsValid: DtoPropertyCheckAttribute.DefaultCheckIsValid, AllowNull: BasicPropertyCheckAttribute.DefaultAllowNull);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SkeletonBullet : MonoBehaviour
{
[SerializeField]
float speed = 7f;
Rigidbody2D rb;
CharacterController target;
Vector2 direction;
[SerializeField]
int damage = 20;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
target = GameObject.FindObjectOfType<CharacterController>();
direction = (target.transform.position - transform.position).normalized * speed;
rb.velocity = new Vector2(direction.x, direction.y);
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D hit)
{
Character1Health player = hit.GetComponent<Character1Health>();
if (player != null)
{
player.TakeDamage(damage);
Destroy(this.gameObject);
}
Character2Health player2 = hit.GetComponent<Character2Health>();
if (player2 != null)
{
player2.TakeDamage(damage);
Destroy(this.gameObject);
}
Character3Health player3 = hit.GetComponent<Character3Health>();
if (player3 != null)
{
player3.TakeDamage(damage);
Destroy(this.gameObject);
}
}
} |
namespace ChatBot.Domain.Core
{
public interface ILanguageService
{
string GetText();
}
}
|
// <copyright file="BookDataBL.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
namespace SmartLibrary.Services
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Web;
using Infrastructure;
using SmartLibrary.Models;
/// <summary>
/// This class is used to Define Database object for Save, Search, Delete
/// </summary>
/// <CreatedBy>Karan Patel</CreatedBy>
/// <CreatedDate>10-Sep-2018</CreatedDate>
public class BookDataBL
{
#region :: Generic CRUD ::
/// <summary>
/// Save Book
/// </summary>
/// <param name="book">book</param>
/// <returns>Id</returns>
public int SaveBook(Book book)
{
book.Description = HttpUtility.HtmlEncode(book.Description);
return this.Save(book, false, true, 0, "BookName", "ISBNNo");
}
#endregion
#region :: Generic CRUD ::
/// <summary>
/// Save the Current Model
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="entity">Model Object</param>
/// <param name="combinationCheckRequired">Combination Check Required</param>
/// <param name="checkForDuplicate">checkForDuplicate</param>
/// <param name="customerId">customerId</param>
/// <param name="columns">column Name array to check duplicate, Maximum 3 columns</param>
/// <returns>Id</returns>
public int Save<TEntity>(TEntity entity, bool combinationCheckRequired = true, bool checkForDuplicate = true, int? customerId = 0, params string[] columns)
{
using (ServiceContext service = new ServiceContext(combinationCheckRequired, checkForDuplicate, columns))
{
if ((int)entity.GetType().GetProperty("ID").GetValue(entity) > 0)
{
this.SetPropertyValue(entity, "ModifiedBy", ProjectSession.UserId);
this.SetPropertyValue(entity, "ModifiedDate", DateTime.Now);
}
else
{
if (customerId > 0)
{
this.SetPropertyValue(entity, "CreatedBy", customerId);
}
else
{
this.SetPropertyValue(entity, "CreatedBy", ProjectSession.UserId);
}
this.SetPropertyValue(entity, "CreatedDate", DateTime.Now);
}
return service.Save<TEntity>(entity);
}
}
/// <summary>
/// Return the list of model for given search criteria
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="model">model</param>
/// <returns> return List Of BookGenre to display in grid </returns>
public List<TEntity> Search<TEntity>(TEntity model)
{
using (ServiceContext service = new ServiceContext())
{
BaseModel baseModel = (BaseModel)((object)model);
return service.Search<TEntity>(model, baseModel.StartRowIndex, baseModel.EndRowIndex, baseModel.SortExpression, baseModel.SortDirection).ToList();
}
}
/// <summary>
/// Delete BookGenre
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public int Delete<TEntity>(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<TEntity>(id);
}
}
/// <summary>
/// Delete BookGenre
/// </summary>
/// <typeparam name="TEntity">Model Type</typeparam>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public TEntity GetBookDetail<TEntity>(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.SelectObject<TEntity>(id);
}
}
/// <summary>
/// Save Book Borrow
/// </summary>
/// <param name="borrowedbook">borrowedbook</param>
/// <returns>Id</returns>
public int SaveBorrowBook(BorrowedBook borrowedbook)
{
return this.Save(borrowedbook, false, false, borrowedbook.CustomerId);
}
/// <summary>
/// Scheduler Run for All Pending Requests
/// </summary>
/// <param name="schedulerDate">schedulerDate</param>
/// <returns>return Status</returns>
public int SchedulerRunforAllPendingRequests(DateTime schedulerDate)
{
int retVal = 0;
using (CustomContext service = new CustomContext())
{
DataSet ds = service.SchedulerRunforAllPendingRequests(schedulerDate);
if (ds?.Tables.Count > 0)
{
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
retVal = ConvertTo.ToInteger(ds.Tables[0].Rows[0][0]);
}
}
return retVal;
}
}
/// <summary>
/// Delete Book comment
/// </summary>
/// <param name="id">id</param>
/// <returns>IsDelete</returns>
public int DeleteBookComments(int id)
{
using (ServiceContext service = new ServiceContext())
{
return service.Delete<BookDiscussion>(id);
}
}
/// <summary>
/// Delete BookGenre
/// </summary>
/// <param name="entity">entity object</param>
/// <param name="propertyName">Property Name to be set</param>
/// <param name="value">value to assign</param>
private void SetPropertyValue(object entity, string propertyName, object value)
{
if (entity.GetType().GetProperty(propertyName) != null)
{
entity.GetType().GetProperty(propertyName).SetValue(entity, value);
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInventory : MonoBehaviour
{
public InventoryObject inventory;
public CharacterObject character;
public void OnTriggerEnter2D(Collider2D other)
{
var item = other.GetComponent<Item>();
if (item)
{
inventory.AddItem(item.item, 1);
Destroy(other.gameObject);
}
}
private void OnApplicationQuit()
{
inventory.Container.Clear();
character.Container.Clear();
character.helmetEquipped = false;
character.armourEquipped = false;
character.swordEquipped = false;
}
public void SaveData()
{
inventory.Save();
character.Save();
}
public void LoadData()
{
inventory.Load();
character.Load();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Parking
{
/// <summary>
/// Class for work with user input
/// </summary>
public class Input
{
/// <summary>
/// Choose auto type
/// </summary>
/// <returns>Auto type</returns>
public Automobiles ChooseAutoType()
{
Console.WriteLine("\nАвтомобиль какого типа Вы хотите добавить?");
Console.WriteLine("\tМашина - 1 |Грузовое авто - 2 | Мотоцикл - 3");
ConsoleKeyInfo ans = Console.ReadKey();
if (ans.Key == ConsoleKey.D1)
{
Console.WriteLine("\nВы создали машину.");
return Automobiles.Car;
}
if (ans.Key == ConsoleKey.D2)
{
Console.WriteLine("\nВы создали грузовик.");
return Automobiles.Track;
}
if (ans.Key == ConsoleKey.D3)
{
Console.WriteLine("\nВы создали мотоцикл.");
return Automobiles.Bike;
}
throw new ArgumentException("Не выбран ни один из предложенных вариантов");
}
/// <summary>
/// Main menu in console for every created auto
/// </summary>
/// <param name="automobile">Choosen auto type</param>
/// <returns>Parameters for auto</returns>
public MainAutoParameters MainMenu(Automobiles automobile)
{
//Arrange
MainAutoParameters autoParameters = new MainAutoParameters();
string brand = string.Empty;
string number = string.Empty;
int speed = 0;
//Set brand
Console.WriteLine("\nВведите марку:");
brand = Console.ReadLine();
bool brandInputCheck = string.IsNullOrEmpty(brand);
if (!brandInputCheck)
autoParameters.Brand = brand;
if (brandInputCheck)
{
Console.WriteLine("Это поле не может быть пустым, по умолчанию BMW");
autoParameters.Brand = "BMW";
}
//Set speed
Console.WriteLine("\nВведите скорость:");
bool speedInputCheck = int.TryParse(Console.ReadLine(), out speed);
if (speedInputCheck)
autoParameters.Speed = speed;
if(!speedInputCheck)
Console.WriteLine("Вы ввели неверный формат данных, скорость по умолчанию 0");
//Set number
Console.WriteLine("\nВведите номер:");
number = Console.ReadLine();
bool numberInputCheck = string.IsNullOrEmpty(brand);
if (!numberInputCheck)
autoParameters.Number = number;
if (numberInputCheck)
{
Console.WriteLine("Номер не может быть пустым, по умолчанию - 6666");
autoParameters.Number = "6666";
}
//Set carring
if (automobile == Automobiles.Bike)
autoParameters.Carring = BikeMenu();
if (automobile == Automobiles.Track)
autoParameters.Carring = TrackMenu();
if (automobile == Automobiles.Car)
autoParameters.Carring = 200;
return autoParameters;
}
/// <summary>
/// Menu for bike.If bike has pram set carrign 50
/// if not set carring 0
/// </summary>
/// <returns>Carring. </returns>
public int BikeMenu()
{
Console.WriteLine("\nДобавить коляску?(Y/N)");
bool answerAboutPram = ChooseYesNo();
if (answerAboutPram)
{
int pramCarring = 50;
Console.WriteLine("\nКоляска создана.");
return pramCarring;
}
return 0;
}
/// <summary>
/// Menu for track
/// Set carring = user input
/// </summary>
/// <returns>Carring</returns>
public int TrackMenu()
{
Console.WriteLine("Введите грузоподъемность:");
int carring;
var result = int.TryParse(Console.ReadLine(),out carring);
if (result)
return carring;
Console.WriteLine("Не верный ввод");
return 0;
}
/// <summary>
/// Method to ask user.
/// </summary>
/// <returns>Yes/no</returns>
public bool ChooseYesNo()
{
ConsoleKeyInfo ans = Console.ReadKey();
if (ans.Key == ConsoleKey.Y)
{
return true;
}
return false;
}
/// <summary>
/// Set speed = user input
/// </summary>
/// <returns>speed</returns>
public int AskSpeed()
{
Console.WriteLine("\nВведите скорость:");
int carring;
var result = int.TryParse(Console.ReadLine(), out carring);
if (result)
return carring;
Console.WriteLine("Не верный ввод");
return 0;
}
}
}
|
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace eightpicomu.Extensions.Editor {
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer {
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label) {
EditorGUI.BeginDisabledGroup(true);
EditorGUI.PropertyField(_position, _property, _label);
EditorGUI.EndDisabledGroup();
}
}
#endif
} |
using InlämningsUppgiftASP.NET.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace InlämningsUppgiftASP.NET.Models
{
public class SchoolClasses
{
[Required]
[Column(TypeName = "nvarchar(10)")]
public string Id { get; set; }
[Required]
[Column(TypeName ="date")]
public DateTime Year { get; set; }
public string ClassName { get; set; }
public string TeacherId { get; set; }
public string StudentId { get; set; }
public ApplicationUser Teacher { get; set; }
public ApplicationUser Student { get; set; }
public virtual ICollection<ApplicationUser> Students { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
public class ABC118A
{
public static void Main()
{
var split = Console.ReadLine().Split(' ');
var a = int.Parse(split[0]);
var b = int.Parse(split[1]);
if(b%a==0)Console.WriteLine(a+b);
else Console.WriteLine(b-a);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using DelftTools.Functions.Filters;
using DelftTools.Utils;
namespace DelftTools.Functions
{
public class TimeArgumentNavigatable : ITimeNavigatable
{
private readonly VariableValueFilter<DateTime> filter;
public TimeArgumentNavigatable(VariableValueFilter<DateTime> filter)
{
if (filter == null)
{
throw new InvalidOperationException("Filter should not be null");
}
this.filter = filter;
filter.Variable.ValuesChanged += VariableValuesChanged;
}
void VariableValuesChanged(object sender, FunctionValuesChangingEventArgs e)
{
if (TimesChanged != null)
{
TimesChanged();
}
}
public DateTime? TimeSelectionStart
{
get { return filter.Values.Min(); }
}
public DateTime? TimeSelectionEnd
{
get { return filter.Values.Max(); }
}
public TimeNavigatableLabelFormatProvider CustomDateTimeFormatProvider
{
get { return null; }
}
public void SetCurrentTimeSelection(DateTime? start, DateTime? end)
{
filter.Values[0] = start.Value;
OnTimeSelectionChanged();
}
public event Action CurrentTimeSelectionChanged;
private void OnTimeSelectionChanged()
{
if (TimeSelectionChanged != null)
{
TimeSelectionChanged(this, EventArgs.Empty);
}
}
public IEnumerable<DateTime> Times
{
get { return (IEnumerable<DateTime>)filter.Variable.Values; }
}
public event Action TimesChanged;
public TimeSelectionMode SelectionMode
{
get { return TimeSelectionMode.Single; }
}
public SnappingMode SnappingMode
{
get { return SnappingMode.Nearest; }
}
/// <summary>
/// Occurs when the time selection changed.
/// </summary>
public event EventHandler TimeSelectionChanged;
}
} |
using UnityEngine;
using System.Collections;
namespace DiosesModernos {
public class SoundManager : Singleton<SoundManager> {
#region Properties
[Header ("Sources")]
[SerializeField]
[Tooltip ("Audio source which will play the music")]
AudioSource _musicSource;
[SerializeField]
[Tooltip ("Audio source which will play the SFX")]
AudioSource _sfxSource;
[Header ("Sound Variations")]
[SerializeField]
[Tooltip ("Variation of the pitch of a SFX that is randomly played")]
float _pitchVariation = 0.1f;
#endregion
#region API
public void PlaySingle (AudioClip clip) {
_sfxSource.clip = clip;
_sfxSource.Play ();
}
public void RandomizeSfx (params AudioClip[] clips) {
_sfxSource.clip = clips[Random.Range (0, clips.Length)];
_sfxSource.pitch = Mathf.Clamp (Random.Range (-_pitchVariation, _pitchVariation), -3, 3);
_sfxSource.Play ();
}
public void StopMusic () {
_musicSource.Stop ();
}
#endregion
}
} |
using UnityEngine;
using System.Collections;
public class ColorBand : ScriptableObject {
public string name = "New Color Band";
public AnimationCurve RCurve;
public AnimationCurve GCurve;
public AnimationCurve BCurve;
public AnimationCurve ACurve;
public Texture2D previewTexture;
public bool biggerPreview = false;
int Wt = 128, Wt_big = 256;
int Ht = 8, Ht_big = 8;
public ColorBand()
{
previewTexture = new Texture2D(Wt, Ht);
RCurve = AnimationCurve.Linear(timeStart:0f, valueStart:0f, timeEnd:1f, valueEnd:1f);
GCurve = AnimationCurve.Linear(timeStart:0f, valueStart:0f, timeEnd:1f, valueEnd:1f);
BCurve = AnimationCurve.Linear(timeStart:0f, valueStart:0f, timeEnd:1f, valueEnd:1f);
ACurve = AnimationCurve.Linear(timeStart:0f, valueStart:1f, timeEnd:1f, valueEnd:1f); // Initialized as constant to 1f
buildPreviewTexture();
}
void OnEnable()
{
buildPreviewTexture();
}
/// <summary>
/// Builds the preview texture.
/// </summary>
void buildPreviewTexture()
{
// This can happen on load project and other cases
if(previewTexture == null)
{
if(biggerPreview)
previewTexture = new Texture2D(Wt_big, Ht_big);
else
previewTexture = new Texture2D(Wt, Ht);
}
int W = previewTexture.width;
int H = previewTexture.height;
Color[] colors = new Color[W*H];
Color bgColor = Color.black;
for(int i=0; i<W; i++)
{
// Get time corresponding to the current position i
float t = Mathf.Clamp01(((float)i)/((float)W));
// Get the color by evaluating all the curves
Color c = new Color(
RCurve.Evaluate( t ),
GCurve.Evaluate( t ),
BCurve.Evaluate( t ),
ACurve.Evaluate( t )
);
// To optimize the drawing a bit we only draw 1st and 4th lines (and every 4th potentially).
// We do this because we have to draw the checkboard underneath which can be crunched to just 2 different lines.
// Later we propagate those lines to the next 3.
// set preview's pixel on the 1st line. Also blend with a checkboard color
if ((i % 8) < 4)
bgColor = Color.grey;
else
bgColor = Color.black;
colors[i] = c * (c.a) + bgColor * (1f - c.a);
// set preview's pixel on the 4th line. Also blend with a checkboard color
if ((i % 8) >= 4)
bgColor = Color.grey;
else
bgColor = Color.black;
colors[i + W*4] = c * (c.a) + bgColor * (1f - c.a);
}
// Propagate pixels from 1st and every 4th line of pixels to the following lines of lixels
// We use the power of Array.Copy to save CPU
for (int L = 0; L < H; L+=4)
{
for (int l = 0; l < 4; l++)
{
if((L%8) < 4)
System.Array.Copy(colors, 0, colors, L * W + l * W, W);
else
System.Array.Copy(colors, W*4, colors, L * W + l * W, W);
}
}
previewTexture.SetPixels(0,0,W, H, colors);
previewTexture.Apply();
}
public void rebuildPreviewTexture()
{
buildPreviewTexture();
}
public Color Evaluate(float time01)
{
return new Color(RCurve.Evaluate(time01), GCurve.Evaluate(time01), BCurve.Evaluate(time01));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CEMAPI.Models
{
public class ChangeOrderModels
{
}
public class scheduleTotal
{
public scheduleTotal()
{
ScheduleName = "";
ExpectedDate = "";
Amount = null;
ExpectedTax = null;
TotalAmount = null;
}
public string ScheduleName { get; set; }
public string ExpectedDate { get; set; }
public decimal? Amount { get; set; }
public decimal? ExpectedTax { get; set; }
public decimal? TotalAmount { get; set; }
}
public class TermsAndConditions
{
public string Description { get; set; }
public int? SeqNo { get; set; }
public int? DocumentType { get; set; }
public bool? IsDeleted { get; set; }
public string IsTEORJD { get; set; }
public string LaunchType { get; set; }
public DateTime? LastModifiedDate { get; set; }
public string UserName { get; set; }
public int? LastModifiedBy { get; set; }
public int? MasterTermsandConditionID { get; set; }
//public string Description { get; set; }
public int? ProductID { get; set; }
public string ProductType { get; set; }
public int? ProjectID { get; set; }
//public int SeqNo { get; set; }
public int? TandCID { get; set; }
public int? OfferId { get; set; }
public string TitleName { get; set; }
public string SchemeTcId { get; set; }
public string SchmeSeqNo { get; set; }
public string SchemeName { get; set; }
public int? CategoryId { get; set; }
public int? CatSeqNumber { get; set; }
public string CategoryName { get; set; }
public string CatDescription { get; set; }
public string TCTypeName { get; set; }
}
public class scheduledetails
{
public string schedulename { get; set; }
public string expecteddate { get; set; }
public string amount { get; set; }
public string expectedtax { get; set; }
public string totalamount { get; set; }
}
public class ScheduleDetails
{
public int? MileStoneID { get; set; }
public int? ScheduleDetailID { get; set; }
public string ScheduleName { get; set; }
public string ExpectedDate { get; set; }
public decimal? Amount { get; set; } //expect expecteddate,expecetdatax,totalamount
public decimal? ExpectedTax { get; set; }
public int? TotalAmount { get; set; }
public string MIleStoneInterval { get; set; }
public string OfferDateRule { get; set; }
public string MIleStoneType { get; set; }
//public DateTime? ScheduleDate { get; set; }
public int? SeqNo { get; set; }
public decimal? RevenueRatio { get; set; }
public string PaymentType { get; set; }
public string OfferedDate { get; set; }
public string CompletionDate { get; set; }
public string ProjectionDate { get; set; }
public string PayableTo { get; set; }
public bool? isSystemGenerated { get; set; }
public bool? displayDateInAgreement { get; set; }
public string Code { get; set; }
public string Status { get; set; }
public string InvoiceStatus { get; set; }
public string ApprovalStatus { get; set; }
public string CompletionStatus { get; set; }
public string ModifiedProjectionStatus { get; set; }
public bool? IsMileStoneSplitted { get; set; }
public int? IsPD { get; set; }
}
public class NpvDiscount
{
public string Title { get; set; }
public decimal? NpvValue { get; set; }
public decimal? NpvPercentage { get; set; }
}
public class SpecialCondition
{
public int OfferSpecialID { get; set; }
public string SpecialConditionName { get; set; }
public string SPConditionCategory { get; set; }
public string Value { get; set; }
public string SPConditionType { get; set; }
public int? OfferID { get; set; }
public string OfferTitleName { get; set; }
public string OfferCustomerName { get; set; }
}
public class OrderPaymentSchedule
{
public int? MilestoneID { get; set; }
public string ScheduleName { get; set; }
public DateTime? BaseLineDate { get; set; }
public DateTime? ScheduleDate { get; set; }
public DateTime? TodayOfferDate { get; set; }
public DateTime? LastModifiedOn { get; set; }
public int? LastModifiedBy_ID { get; set; }
public string CallName { get; set; }
public string ScheduleCode { get; set; }
public string MileStoneType { get; set; }
public string RevenueType { get; set; }
public int? RelativeInterval { get; set; }
public int? RelativeMileStone { get; set; }
public decimal? RevenueValue { get; set; }
public int? ScheduleDetailID { get; set; }
public int? ScheduleMasterID { get; set; }
public decimal? SchemeRevenueRatio { get; set; }
public int? SequenceOrder { get; set; }
public string OfferDateRule { get; set; }
public string MilestoneInterval { get; set; }
public int? VersionNo { get; set; }
public bool? displaydateinagreement { get; set; }
}
public class TEMultipleOffers
{
//TEOffers
public int OfferID { get; set; }
public int? LeadID { get; set; }
public String OfferTitleName { get; set; }
public int? ProjectID { get; set; }
public int? UnitID { get; set; }
public int? ProductID { get; set; }
public int? SpecsType { get; set; }
public int? PriceBookId { get; set; }
public decimal? CarPetArea { get; set; }
public decimal? BuiltUpArea { get; set; }
public decimal? StandardPlotArea { get; set; }
public decimal? SuperBuiltUpArea { get; set; }
public decimal? SaleableArea { get; set; }
public decimal? EffectiveDiscount { get; set; }
public decimal? EffecDiscPercentage { get; set; }
public decimal? DiscOnBasicCost { get; set; }
public decimal? DiscPaymentTerms { get; set; }
public decimal? DiscSpecialConditions { get; set; }
public String DPIIncentiveApplicable { get; set; }
public String PreparedBy { get; set; }
public int? SubmittedBy { get; set; }
public int? ConnectSalesConsultant { get; set; }
public int? CloseSalesConsultant { get; set; }
public int? AssistedSalesConsultant { get; set; }
public int? CEMmanager { get; set; }
public int? RevisionNo { get; set; }
public String CurrentStatus { get; set; }
public String OrderStatus { get; set; }
public String TransitionStatus { get; set; }
public String OfferCustomerName { get; set; }
public String MergedUnit { get; set; }
public DateTime? ExpiryDate { get; set; }
public int? ExpiredBy { get; set; }
public DateTime? CCPSaleTime { get; set; }
public String SAPCustomerID { get; set; }
public String SAPOrderID { get; set; }
public String BusinesSEGMENT { get; set; }
public int? RegisterCommunicationID { get; set; }
public bool? IsDeleted { get; set; }
public String LastModifiedBy { get; set; }
public DateTime? LastModifiedOn { get; set; }
public int? LastModifiedBy_Id { get; set; }
public int? BaseConsideration { get; set; }
public int? Consideration { get; set; }
public decimal? DiscountPercentage { get; set; }
public int LandPrice { get; set; }
public int ConstructionPrice { get; set; }
public bool IsManualOffer { get; set; }
public decimal? PriceOfferDiscount { get; set; }
public decimal? UpFrontDiscount { get; set; }
public decimal? DefaultNpvValue { get; set; }
public decimal? DefaultNPVpercentage { get; set; }
public String SaleType { get; set; }
public String SaleOrderClassification { get; set; }
public string CustomizationOption { get; set; }
public decimal? PaybletoOwner { get; set; }
public decimal? PayableToDeveloper { get; set; }
public DateTime? CreatedDate { get; set; }
public decimal? CurrentCompletionPercentage { get; set; }
public decimal? JDOwnershipPercentage { get; set; }
public decimal? oldcarparksTotal { get; set; }
public int? NewSpecsType { get; set; }
public DateTime PromisedHandOverDate { get; set; }
public decimal? CancellationFee { get; set; }
public decimal? DelayCompensationRate { get; set; }
public decimal? DelayCompensatoinRule { get; set; }
public decimal? TransferOrderFee { get; set; }
public decimal? ReImbursementAmount { get; set; }
public decimal? RERACarpetArea { get; set; }
public decimal? OutdoorArea { get; set; }
public int[] IsMileStoneSplitted { get; set; }
//TECarParks
public int[] CarParkID { get; set; }
public List<String> TypeName { get; set; }
public List<int> NoOfCarparks { get; set; }
public List<decimal> CostOfPerCarParkRate { get; set; }
public decimal[] TotalCarParkPrice { get; set; }
//TEOfferPriceBreakUP
public int OfferBreakUpDetailsID { get; set; }
public String[] PriceElementname { get; set; }
public decimal[] PriceElementQuantity { get; set; }
public decimal[] PriceElementRate { get; set; }
public decimal[] PriceElementPrice { get; set; }
public String[] SaleableAreaBasis { get; set; }
public String[] ElementType { get; set; }
public int[] IsPD { get; set; }
public string[] PriceElementCode { get; set; }
//TEOfferMilestone
public int[] MileStoneID { get; set; }
public int[] MileStoneSEQNO { get; set; }
public String[] Name { get; set; }
public String[] Code { get; set; }
public DateTime[] OfferedDate { get; set; }
public decimal[] OfferedAmount { get; set; }
public DateTime[] ProjectionDate { get; set; }
public DateTime[] CompletionDate { get; set; }
public String[] Status { get; set; }
public decimal[] TotalEstimatedTax { get; set; }
public decimal[] RevenueRatio { get; set; }
public string[] PaymentType { get; set; }
public string[] PayableTo { get; set; }
public int[] displayDateInAgreement { get; set; }
public int[] isSystemGenerated { get; set; }
public string[] MileStoneType { get; set; }
// public decimal[] ExpectedTax { get; set; }
public decimal[] TotalAmount { get; set; }
public int[] SeqNomilestone { get; set; }
public int[] ScheduleDetailID { get; set; }
public string[] InvoiceStatus { get; set; }
public string[] ApprovalStatus { get; set; }
public string[] CompletionStatus { get; set; }
public string[] ModifiedProjectionStatus { get; set; }
//TESpecialCondition
public int[] OfferSpecialID { get; set; }
public String[] SpecialConditionName { get; set; }
public String[] SPConditionCategory { get; set; }
public String[] Value { get; set; }
public String[] SPConditionType { get; set; }
//TEOfferTermsAndConditions
public int[] OfferTCID { get; set; }
public String[] TCName { get; set; }
public int[] SEQNO { get; set; }
public string[] CategoryName { get; set; }
public string[] TCTypeName { get; set; }
//for Additional Carpark
public int[] additionalCarParkID { get; set; }
public int[] additionalCarNumbers { get; set; }
public int[] additionalCarRate { get; set; }
public string[] additionalCarParkName { get; set; }
//offer schemes
public int SchemaID { get; set; }
public string SchemaName { get; set; }
public int NewSchemeId { get; set; }
//offer premiums
public int[] PremiumId { get; set; }
public decimal[] PremiumValue { get; set; }
public string[] PremiumName { get; set; }
public decimal[] TotalPremiumPrice { get; set; }
public string PersonalDesign { get; set; }
public int pb_selectcolor { get; set; }
public string schemeSelected { get; set; }
}
public class unitDetailsMerged
{
public int UnitID { get; set; }
public string UnitNumber { get; set; }
public string UnitType { get; set; }
public string OwnerShipType { get; set; }
public string Level { get; set; }
public int? Floor { get; set; }
public string CustomizationOption { get; set; }
public int? PremiumPrice { get; set; }
public decimal? carpetarea { get; set; }
public decimal? builtuparea { get; set; }
public decimal? saleablearea { get; set; }
public decimal? consideration { get; set; }
public string Status { get; set; }
public decimal? AddtionalLandArea { get; set; }
public decimal? ExclusiveAccessArea { get; set; }
public decimal? LandPrice { get; set; }
public decimal? ConstructionPrice { get; set; }
public string MergedUnits { get; set; }
public string GardenDirection { get; set; }
public string DoorDirection { get; set; }
}
public class unitDetail
{
public int UnitID { get; set; }
public string UnitNumber { get; set; }
public string UnitType { get; set; }
public string OwnerShipType { get; set; }
public string Level { get; set; }
public int? Floor { get; set; }
public string CustomizationOption { get; set; }
public int? PremiumPrice { get; set; }
public decimal? carpetarea { get; set; }
public decimal? builtuparea { get; set; }
public decimal? saleablearea { get; set; }
public decimal? consideration { get; set; }
public string Status { get; set; }
public decimal? AddtionalLandArea { get; set; }
public decimal? ExclusiveAccessArea { get; set; }
public decimal? LandPrice { get; set; }
public decimal? ConstructionPrice { get; set; }
public string MergedUnits { get; set; }
public string GardenDirection { get; set; }
public string DoorDirection { get; set; }
}
public class generalDetailsMerged
{
public string ProjectName { get; set; }
public string ProjectColor { get; set; }
public string SubProductCode { get; set; }
public string SpecificationID { get; set; }
public string Signatory1 { get; set; }
public string Signatory2 { get; set; }
public string Purchaser { get; set; }
public string CompanyName { get; set; }
public string TermSheetID { get; set; }
public string TermSheetDate { get; set; }
public string SpecificationName { get; set; }
public string SpecificationColor { get; set; }
public string ProjectID { get; set; }
public string ProjectProductID { get; set; }
public string CreatedBy { get; set; }
}
public class generalDetails
{
public decimal? JDOwnershipPercentage { get; set; }
public string CcPercentage { get; set; }
public string CMDSignatory { get; set; }
public string CEOSignatory { get; set; }
public string SHSignatory { get; set; }
public int? OfferID { get; set; }
public string OfferTitleName { get; set; }
public string OrderStatus { get; set; }
public string OfferCustomerName { get; set; }
public string CurrentStatus { get; set; }
public int? AssistedSalesConsultant { get; set; }
public decimal? CarPetArea { get; set; }
public decimal? BuiltUpArea { get; set; }
public decimal? StandardPlotArea { get; set; }
public decimal? SuperBuiltUpArea { get; set; }
public decimal? SaleableArea { get; set; }
public decimal? EffectiveDiscount { get; set; }
public decimal? EffecDiscPercentage { get; set; }
public decimal? DiscOnBasicCost { get; set; }
public decimal? DiscPaymentTerms { get; set; }
public decimal? DiscSpecialConditions { get; set; }
public string BusinesSEGMENT { get; set; }
public string CCPSaleTime { get; set; }
public int? CEMmanager { get; set; }
public int? CloseSalesConsultant { get; set; }
public int? ConnectSalesConsultant { get; set; }
public string DPIIncentiveApplicable { get; set; }
public decimal? UpFrontDiscount { get; set; }
public string SaleType { get; set; }
public string SaleOrderClassification { get; set; }
public decimal? DefaultNpvValue { get; set; }
public int? ExpiredBy { get; set; }
public DateTime? ExpiryDate { get; set; }
public DateTime? CreatedDate { get; set; }
public string LastModifiedBy { get; set; }
public int? LeadID { get; set; }
public string CallName { get; set; }
public string MergedUnit { get; set; }
public int? ProductID { get; set; }
public int? ProjectProductID { get; set; }
public string SubProductCode { get; set; }
public int? SpecificationID { get; set; }
public int? TowerID { get; set; }
public string SpecificationName { get; set; }
public string SpecificationColor { get; set; }
public string TowerName { get; set; }
public string LaunchStatus { get; set; }
public string SpecificationSubColor { get; set; }
public string Signatory1 { get; set; }
public string Signatory2 { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
public string Level { get; set; }
public int? Floor { get; set; }
public string carpetarea { get; set; }
public string builtuparea { get; set; }
public string saleablearea { get; set; }
public int? ProjectID { get; set; }
public string ProjectName { get; set; }
public string ProjectColor { get; set; }
public string ProjectShortName { get; set; }
public string ProjectLogo { get; set; }
public int? RegisterCommunicationID { get; set; }
public int? RevisionNo { get; set; }
public string SAPCustomerID { get; set; }
public string SAPOrderID { get; set; }
public int? SpecsType { get; set; }
public int? SubmittedBy { get; set; }
public string TransitionStatus { get; set; }
public int? UnitID { get; set; }
public bool? IsManualOffer { get; set; }
public string UnitType { get; set; }
public string UnitNumber { get; set; }
public int? LastModifiedBy_Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int? PriceBookId { get; set; }
public int? BaseConsideration { get; set; }
public int? Consideration { get; set; }
public int? ConstructionPrice { get; set; }
public int? LandPrice { get; set; }
public int? MinimumCarParks { get; set; }
public int? MaximumCarParks { get; set; }
public int? SchemeId { get; set; }
public string SchemaName { get; set; }
public decimal? DefaultNPVpercentage { get; set; }
public decimal? PayableToDeveloper { get; set; }
public decimal? PaybletoOwner { get; set; }
public string CustomizationOption { get; set; }
public bool? IsEMD { get; set; }
public bool? IsTSSigned { get; set; }
public decimal? RERACarpetArea { get; set; }
public decimal? OutdoorArea { get; set; }
public string Purchaser { get; set; }
public string CompanyLogo { get; set; }
public string TermSheetID { get; set; }
public string TermSheetDate { get; set; }
public string CreatedBy { get; set; }
public bool? OpenForSale { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string CemManagerName { get; set; }
public string CustomerAddress { get; set; }
public int? ContactID { get; set; }
}
public class priceElements
{
public int? PriceBookId { get; set; }
public string PriceType { get; set; }
public decimal? Rate { get; set; }
public string PricingAreaBasis { get; set; }
public decimal? RateMultiplier { get; set; }
public decimal? TotalPrice { get; set; }
public decimal? JdTotalPrice { get; set; }
public decimal? OldBasicCost { get; set; }
public decimal? Area { get; set; }
public string ProjectRuleType { get; set; }
public int? IsPd { get; set; }
public string OwnerShip { get; set; }
public string PriceElementCode { get; set; }
}
public class MfElements
{
public int? PriceBookId { get; set; }
public string PriceType { get; set; }
public decimal? Rate { get; set; }
public string PricingAreaBasis { get; set; }
public decimal? RateMultiplier { get; set; }
public decimal? TotalPrice { get; set; }
public decimal? OldBasicCost { get; set; }
public decimal? Area { get; set; }
public string ProjectRuleType { get; set; }
public int? IsPd { get; set; }
public string PriceElementsCode { get; set; }
}
public class priceElementsmerged
{
public string PriceType { get; set; }
public decimal? Rate { get; set; }
public string PricingAreaBasis { get; set; }
public decimal PriceMultiplier { get; set; }
public decimal? TotalPrice { get; set; }
public decimal? OldBasicCost { get; set; }
public string Area { get; set; }
public string ProjectRuleType { get; set; }
}
public class CarParks
{
public int NoOfCarparks { get; set; }
public decimal CostOfPerCarParkRate { get; set; }
public decimal TotalCarParkPrice { get; set; }
}
public class Premium
{
public int? PremiumIds { get; set; }
public string premiumName { get; set; }
public string PremiumType { get; set; }
public string Area { get; set; }
public decimal? TotalPrice { get; set; }
public decimal? PremiumPrice { get; set; }
}
public class priceElements_Display
{
public string PriceType { get; set; }
public decimal? Rate { get; set; }
public string PricingAreaBasis { get; set; }
public string PriceMultiplier { get; set; }
public decimal? TotalPrice { get; set; }
}
public class CarParkUnitElement
{
public int? MinimumCarParks { get; set; }
public decimal? CarParkRate { get; set; }
public string Description { get; set; }
public string UnitType { get; set; }
public decimal? UnitOwnershipPrcntage { get; set; }
}
public class MileStone
{
public int? MileStoneId { get; set; }
public int? ScheduleDetailID { get; set; }
public string MileStoneName { get; set; }
public int? Sequence { get; set; }
public DateTime? BasicLineDate { get; set; }
public string OfferDateRule { get; set; }
public string MilestoneInterval { get; set; }
public decimal? RevenueRatio { get; set; }
public string PaymentType { get; set; }
public string MileStoneType { get; set; }
public DateTime? OfferedDate { get; set; }
public DateTime? CompletionDate { get; set; }
public DateTime? ProjectionDate { get; set; }
public string PayableTo { get; set; }
public bool? displayDateInAgreement { get; set; }
public bool? isSystemGenerated { get; set; }
public string Code { get; set; }
public string RelativeMilestoneCode { get; set; }
public string Status { get; set; }
public string ApprovalStatus { get; set; }
public string CompletionStatus { get; set; }
public string ModifiedProjectionStatus { get; set; }
public bool? IsMileStoneSplitted { get; set; }
public string InvoiceStatus { get; set; }
}
public class JDShare
{
public decimal? JDArea { get; set; }
public decimal? JDRate { get; set; }
}
public class TaxDetails_Offer
{
public int? TaxBookId { get; set; }
public string ConsiderationType { get; set; }
public int? ConsiderationType_Id { get; set; }
public decimal? TaxRate { get; set; }
public string TaxType { get; set; }
public string TaxValueType { get; set; }
public string TaxConditionType { get; set; }
public string TaxationInApplicable { get; set; }
public bool? IsTaxInclusive { get; set; }
public int? SequenceNo { get; set; }
}
public class DiscountDetails
{
//public int? SplConditionValue { get; set; }
//public string SplConditionType { get; set; }
public string Heading1 { get; set; }
public string Heading2 { get; set; }
public string Heading3 { get; set; }
public string Heading4 { get; set; }
public List<MainElments> MainElements { get; set; }
}
public class MainElments
{
public string Title1 { get; set; }
public string Title2 { get; set; }
public string Title3 { get; set; }
public string Title4 { get; set; }
public List<SubElements> SubElements { get; set; }
}
public class SubElements
{
public string Details { get; set; }
public decimal? Percentage { get; set; }
public decimal? Area { get; set; }
public decimal? Value { get; set; }
public List<Components> Components { get; set; }
}
public class Components
{
public string Componts_title { get; set; }
public decimal? Componts_percentage { get; set; }
public decimal? Componts_Area { get; set; }
public decimal? Componts_Value { get; set; }
}
public class SalesClasfication
{
public string SalesCls { get; set; }
public string CntSaleConsltnt { get; set; }
public string ClsSaleConsltnt { get; set; }
public string AssSaleConsltnt { get; set; }
public bool DpiApplicable { get; set; }
}
public class test
{
public string catid { get; set; }
public string catname { get; set; }
public string Status { get; set; }
public List<liblist> listitems { get; set; }
}
public class liblist
{
public string libname { get; set; }
public string Status { get; set; }
public string libid { get; set; }
public string SubCategoryName { get; set; }
public string libdesc { get; set; }
public List<specfinal> appspecs { get; set; }
}
public class specfinal
{
public string spec { get; set; }
}
public class testTop1
{
public string catid { get; set; }
public string catname { get; set; }
public List<liblistTop2> listitems { get; set; }
}
public class liblistTop2
{
public string libname { get; set; }
public string libid { get; set; }
List<liblistTop3> liblist3items { get; set; }
}
public class liblistTop3
{
public string libid { get; set; }
public string libdesc { get; set; }
public List<specfinal> appspecs { get; set; }
}
public class specfinalLeast
{
public string spec { get; set; }
}
public class specProdList
{
public string catid { get; set; }
public string LastModifiedBy_Name { get; set; }
public int? LastModifiedBy { get; set; }
public DateTime? LastModifiedDate { get; set; }
public string catname { get; set; }
public string libid { get; set; }
public string libname { get; set; }
public string libdisc { get; set; }
public string specname { get; set; }
public string test { get; set; }
public string Status { get; set; }
public string SubCategoryName { get; set; }
}
public class SmsForofferApproved
{
public int? UserId { get; set; }
public string UserName { get; set; }
public string Phone { get; set; }
}
public class SmsForofferApprovedLead
{
public int? LeadID { get; set; }
public string CallName { get; set; }
public string Mobile { get; set; }
}
//public class PriceBk
//{
// public int? SchemeID { get; set; }
// public int? Specification { get; set; }
// public string Status { get; set; }
// public int prickBkId { get; set; }
//}
public class SchemeList
{
public int? SchemaID { get; set; }
public string SchemaName { get; set; }
public string ValidityStatus { get; set; }
}
public class SpecList
{
public int? SpecificationID { get; set; }
public string SpecificationName { get; set; }
public string HeadingColourCode { get; set; }
}
public class SubTaxDetails
{
public string SubHeading1 { get; set; }
public string SubHeading2 { get; set; }
public string SubHeading3 { get; set; }
public decimal? SubHeading4 { get; set; }
}
public class CostDetails
{
public string SubHeading1 { get; set; }
public decimal? SubHeading2 { get; set; }
public decimal? SubHeading3 { get; set; }
public decimal? SubHeading4 { get; set; }
}
public class CostSplit
{
public string Heading1 { get; set; }
public string Heading2 { get; set; }
public string Heading3 { get; set; }
public decimal Heading4 { get; set; }
public List<CostDetails> Elements { get; set; }
}
public class TaxBrkDetails
{
public string Heading1 { get; set; }
public string Heading2 { get; set; }
public string Heading3 { get; set; }
public decimal? Heading4 { get; set; }
public List<SubTaxDetails> Elements { get; set; }
}
//public class TaxBreakUp
//{
// public List<CostDetails> Elements { get; set; }
// public List<SubTaxDetails> Elements { get; set; }
//}
public class SplConditionList
{
public List<int> SplConditionValue { get; set; }
public List<string> SplConditionType { get; set; }
}
public class costbreakup
{
public string title { get; set; }
public int? area { get; set; }
public int? price { get; set; }
public int? total { get; set; }
public List<priceElements> Elements { get; set; }
public List<Premium> PremElements { get; set; }
//public List<TaxBrkDetails> TaxBrkDetails { get; set; }
//public List<JdShareDetails> JDElements { get; set; }
}
public class costbreakupmerged
{
public string title { get; set; }
public decimal? area { get; set; }
public decimal? price { get; set; }
public decimal? total { get; set; }
public List<priceElements> Elements { get; set; }
public List<Premium> PremElements { get; set; }
//public List<TaxBrkDetails> TaxBrkDetails { get; set; }
//public List<JdShareDetails> JDElements { get; set; }
}
public class CarParkUnitElements
{
public string title { get; set; }
public string area { get; set; }
public string price { get; set; }
public string total { get; set; }
public List<priceElements> Elements { get; set; }
}
public class JdShareDetails
{
public string title { get; set; }
public decimal area { get; set; }
public decimal price { get; set; }
public decimal total { get; set; }
//public List<priceElements> JdElements { get; set; }
//public List<TaxBrkDetails> TaxBrkDetails { get; set; }
public List<costbreakup> Elements { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace UniVM
{
[Serializable]
public abstract class Binding : MonoBehaviour
{
private ViewModel attached;
public string Path;
public void SetPath(string path)
{
Path = path;
if (attached != null)
attached.Bind(this);
}
public void AttachedTo(ViewModel viewModel)
{
attached = viewModel;
}
}
}
|
using Android.Content.Res;
using Plugin.XamJam.Screen.Abstractions;
namespace Plugin.XamJam.Screen
{
/// <summary>
/// Adnroid Screen Implementation
/// </summary>
public class ScreenImplementation : Abstractions.Screen
{
/// <summary>
/// See <see cref="Abstractions.Screen"/>
/// </summary>
public ScreenSize Size
{
get
{
var displayMetrics = Resources.System.DisplayMetrics;
var height = displayMetrics.HeightPixels / displayMetrics.Density;
var width = displayMetrics.WidthPixels / displayMetrics.Density;
return new ScreenSize(true, width, height);
}
}
}
} |
using System;
using System.IO;
namespace NSchedule
{
internal static class Constants
{
// Meta
internal const string USER_AGENT = "NSchedule for Android";
internal const string SHARED_WITH = "Shared with NSchedule.";
// TODO misschien user agent veranderen? Deze user agent zegt praktisch gezien "joehoe! ik gebruik een onofficiele app!"
// Endpoints
internal const string API_ENDPOINT = "https://sa-nhlstenden.xedule.nl/api";
internal const string NHL_STENDEN_AUTH_ENDPOINT = "https://sa-nhlstenden.xedule.nl";
internal const string STENDEN_AUTH_ENDPOINT = "https://sa-nhlstenden.xedule.nl/stenden";
internal const string SURF_ENDPOINT = "https://engine.surfconext.nl:443/authentication/sp/consume-assertion";
internal const string ASSERTION_ENDPOINT = "https://sso.xedule.nl/AssertionService.aspx";
internal const string XEDULE_ENDPOINT = "https://sa-nhlstenden.xedule.nl";
// Database constants
public const string DatabaseFilename = "NSchedule.db3";
public const SQLite.SQLiteOpenFlags Flags =
// open the database in read/write mode
SQLite.SQLiteOpenFlags.ReadWrite |
// create the database if it doesn't exist
SQLite.SQLiteOpenFlags.Create |
// enable multi-threaded database access
SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath
{
get
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(basePath, DatabaseFilename);
}
}
}
}
|
using System;
using System.Xml.Linq;
using Cogito.Web.Configuration;
namespace Cogito.IIS.Configuration
{
/// <summary>
/// Provides configuration methods for 'system.applicationHost/log'.
/// </summary>
public class AppHostLogConfigurator : IWebElementConfigurator
{
readonly XElement element;
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="element"></param>
public AppHostLogConfigurator(XElement element)
{
this.element = element ?? throw new ArgumentNullException(nameof(element));
}
/// <summary>
/// Returns the configuration.
/// </summary>
/// <returns></returns>
public XElement Element => element;
/// <summary>
/// Configures individual site logging.
/// </summary>
/// <param name="configurator"></param>
/// <returns></returns>
public AppHostLogConfigurator UseSite()
{
element.RemoveAll();
element.SetAttributeValue("centralLogFileMode", "Site");
return this;
}
/// <summary>
/// Configures centralized binary logging.
/// </summary>
/// <param name="configurator"></param>
/// <returns></returns>
public AppHostLogConfigurator UseBinary(
string directory = null,
bool? localTimeRollover = false,
AppHostLogPeriod? period = null,
long? truncateSize = null)
{
element.RemoveNodes();
element.SetAttributeValue("centralLogFileMode", "CentralBinary");
return this.Configure("centralBinaryLogFile", e =>
{
e.SetAttributeValue("enabled", true);
if (directory != null)
e.SetAttributeValue("directory", directory);
if (localTimeRollover != null)
e.SetAttributeValue("localTimeRollover", localTimeRollover);
if (period != null)
e.SetAttributeValue("period", Enum.GetName(typeof(AppHostLogPeriod), period));
if (truncateSize != null)
e.SetAttributeValue("truncateSize", truncateSize);
});
}
/// <summary>
/// Configures centralized W3C logging.
/// </summary>
/// <param name="configurator"></param>
/// <returns></returns>
public AppHostLogConfigurator UseW3C(
string directory = null,
bool? localTimeRollover = false,
AppHostLogExtFileFlags? logExtFileFlags = null,
AppHostLogPeriod? period = null,
long? truncateSize = null)
{
element.RemoveNodes();
element.SetAttributeValue("centralLogFileMode", "CentralW3C");
return this.Configure("centralW3CLogFile", e =>
{
e.SetAttributeValue("enabled", true);
if (directory != null)
e.SetAttributeValue("directory", directory);
if (localTimeRollover != null)
e.SetAttributeValue("localTimeRollover", localTimeRollover);
if (logExtFileFlags != null)
e.SetAttributeValue("logExtFileFlags", logExtFileFlags.ToString());
if (period != null)
e.SetAttributeValue("period", Enum.GetName(typeof(AppHostLogPeriod), period));
if (truncateSize != null)
e.SetAttributeValue("truncateSize", truncateSize);
});
}
}
}
|
using System.Windows.Controls;
using JeopardySimulator.Ui.Infrastructure;
namespace JeopardySimulator.Ui.Views
{
/// <summary>
/// Interaction logic for TotalResultsView.xaml
/// </summary>
public partial class TotalResultsView : UserControl
{
public TotalResultsView()
{
ViewModelLocatorHelper.CreateStaticViewModelLocatorForDesigner(this, new ViewModelLocator());
InitializeComponent();
}
}
} |
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Rexxar.Identity.Data
{
public class RexxarUser:IdentityUser<Guid>
{
public string Avatar { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Deterines, where to spawn an Object, what Object(s) to spawn, and how often to spawn the Object.
/// </summary>
/// <remarks>
/// This parent class is implemented by CoalSpawner and WaterSpawner
/// </remarks>
public abstract class Spawner : MonoBehaviour {
// The Spawner object, and the Objects it should spawn.
public GameObject ObjectEmitter;
public GameObject[] Object;
// Base min and max spawn time ranges. To be changed on a spawner by spawner basis.
public float maxTime = 5;
public float minTime = 2;
// Current time since last Object spawn
protected float time = 0;
// The time to spawn the object
protected float spawnTime;
/// <summary>
/// Initialise first random timer
/// </summary>
protected abstract void Start();
/// <summary>
/// Count the time until you need to spawn an object, at which point, set a new random time.
/// </summary>
protected abstract void FixedUpdate();
/// <summary>
/// Gets a random amount of time between the min and max, after which time we spawn the Object.
/// </summary>
protected void SetRandomTime()
{
spawnTime = Random.Range(minTime, maxTime);
}
/// <summary>
/// Spawns the Object, and resets the time for the next spawn.
/// </summary>
protected abstract void SpawnObject();
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VA_ITCMS2000
{
public class DBConnectParam : Param
{
public string DBAddress
{
get { return GetString("DBAddress"); }
set { SaveParam("DBAddress", value); }
}
public string DBUserID
{
get { return GetString("DBUserID"); }
set { SaveParam("DBUserID", value); }
}
public string DBUserPWD
{
get { return GetString("DBUserPWD"); }
set { SaveParam("DBUserPWD", value); }
}
public string DBName
{
get { return GetString("DBName"); }
set { SaveParam("DBName", value); }
}
public string ConnectionString
{
get
{
return string.Format(
"Server={0};initial catalog={1};UID={2};" +
"Password={3};Min Pool Size=2;Max Pool Size=60;",
DBAddress,
DBName,
DBUserID,
DBUserPWD);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ApartmentApps.Client;
using MvvmCross.Core.ViewModels;
using MvvmCross.Platform;
using MvvmCross.Platform.IoC;
using MvvmCross.Plugins.Location;
using Newtonsoft.Json.Linq;
using ResidentAppCross;
using ResidentAppCross.ServiceClient;
using ResidentAppCross.Services;
using ResidentAppCross.ViewModels;
public static class Constants
{
public const string ConnectionString = "Endpoint=sb://aptappspush.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=b8UIg+ith9oTvd+/4bhvCkc81e6nSnombxgsTqTB8ak=";
public const string NotificationHubPath = "apartmentapps";
public const int IOS_BUILD_NUMBER = 6;
public const int ANDROID_BUILD_NUMBER = 8;
}
public class App : MvxApplication
{
//localhost server shared with ngrok
public static Uri LocalEndpoint = new Uri("http://fd0e2249.ngrok.io/");//new Uri("http://localhost:4412/");
public static Uri SiniEndpoint = new Uri("http://5.189.103.91.nip.io:54685/");
public static Uri DevEndpoint = new Uri("http://devservices.apartmentapps.com/");
public static Uri TestEndpoint = new Uri("http://testservices.apartmentapps.com/");
public static Uri ProductionEndpoint = new Uri("https://api.apartmentapps.com/");
public App()
{
Mvx.ConstructAndRegisterSingleton<IImageService, ImageService>();
Mvx.ConstructAndRegisterSingleton<ILocationService, LocationService>();
//local sini pc endpoint
// var apartmentAppsApiService = new ApartmentAppsClient(new Uri("http://5.189.103.91.nip.io:54685/"));
//var apartmentAppsApiService = new ApartmentAppsClient(new Uri("http://devservices.apartmentapps.com/"));
#if DEBUG
var apartmentAppsApiService = new ApartmentAppsClient(DevEndpoint);
#else
var apartmentAppsApiService = new ApartmentAppsClient(ProductionEndpoint);
#endif
Mvx.RegisterSingleton<IApartmentAppsAPIService>(apartmentAppsApiService);
Mvx.RegisterSingleton<ILoginManager>(new LoginService(apartmentAppsApiService));
Mvx.RegisterSingleton<IMvxAppStart>(new CustomAppStart());
Mvx.LazyConstructAndRegisterSingleton<ISharedCommands, SharedCommands>();
Mvx.ConstructAndRegisterSingleton<HomeMenuViewModel, HomeMenuViewModel>();
Mvx.ConstructAndRegisterSingleton<IActionRequestHandler, ActionRequestHandler>();
}
public class CustomAppStart
: MvxNavigatingObject
, IMvxAppStart
{
public void Start(object hint = null)
{
}
}
public class ApartmentAppsClient : ApartmentAppsAPIService
{
public ApartmentAppsClient(Uri baseUri) : base(baseUri, new AparmentAppsDelegating())
{
}
public void Logout()
{
AparmentAppsDelegating.AuthorizationKey = null;
}
public async Task<bool> LoginAsync(string username, string password)
{
var result = await HttpClient.PostAsync(this.BaseUri + "Token", new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"username", username},
{"password", password},
{"grant_type", "password"},
}));
try
{
Logout();
var json = await result.Content.ReadAsStringAsync();
var obj = JObject.Parse(json);
JToken token;
if (obj.TryGetValue("access_token", out token))
{
AparmentAppsDelegating.AuthorizationKey = token.Value<string>();
return true;
}
else
{
AparmentAppsDelegating.AuthorizationKey = null;
}
}
catch (Exception ex)
{
return false;
}
return false;
}
public static Func<string> GetAuthToken { get; set; }
public static Action<string> SetAuthToken { get; set; }
public static Func<string> GetSavedUsername { get; set; }
public static Action<string> SetSavedUsername { get; set; }
public static Func<string> GetSavedPassword { get; set; }
public static Action<string> SetSavedPassword { get; set; }
}
} |
using System;
namespace iSukces.Code.Interfaces
{
public class CompareByReferenceAttribute : Attribute
{
}
} |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace _02._Message_Translator
{
class Program
{
static void Main(string[] args)
{
var numberOfInputs = int.Parse(Console.ReadLine());
var regex = @"\!([A-Z][a-z]*)\!\:\[([A-Za-z]{8,})\]";
for (int i = 0; i < numberOfInputs; i++)
{
var input = Console.ReadLine();
var encrypted = new List<int>();
if (Regex.IsMatch(input,regex))
{
Match match = Regex
.Match(input, regex);
var message =
match
.Groups[2]
.ToString();
foreach (var symbol in message)
{
encrypted.Add(symbol);
}
Console.WriteLine($"{match.Groups[1].ToString()}: {String.Join(" ",encrypted)}");
}
else
{
Console.WriteLine("The message is invalid");
continue;
}
}
}
}
}
|
using System.ComponentModel;
using Newtonsoft.Json;
namespace Entoarox.AdvancedLocationLoader.Configs
{
internal class Location : MapFileLink
{
/*********
** Accessors
*********/
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool Farmable;
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool Outdoor;
[DefaultValue("Default")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string Type;
/*********
** Public methods
*********/
public override string ToString()
{
return $"Location({this.MapName},{this.FileName}){{Outdoor={this.Outdoor},Farmable={this.Farmable},Type={this.Type}}}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// StudentName: Suvashin
/// Student Number: 19003564
/// Module: PROG6212
/// Task: Task1
/// Semester: 2
/// </summary>
namespace BudgetingApp
{
abstract public class Expense//expense parent class
{
protected string description;//expense class attributes
protected DateTime date;
protected double purchasePrice;
protected double deposit;
protected double interestRate;
protected int months;
protected double monthlyCost;
public Expense()//default contructor
{
}
protected Expense(string description, DateTime date, double purchasePrice, double deposit, double interestRate)//expense contructor
{
this.description = description;
this.date = date;
this.purchasePrice = purchasePrice;
this.deposit = deposit;
this.interestRate = interestRate;
}
protected Expense(string description, DateTime date, double deposit, double interestRate, int months)//expense altered contructor, excludes purchase price
{
this.description = description;
this.date = date;
this.deposit = deposit;
this.interestRate = interestRate;
this.months = months;
}
protected Expense(string description, DateTime date, double purchasePrice, double deposit, double interestRate, int months)//expense constructor (includes all attributes)
{
this.description = description;
this.date = date;
this.purchasePrice = purchasePrice;
this.deposit = deposit;
this.interestRate = interestRate;
this.months = months;
}
public string Description { get => description; set => description = value; }//get and set methods for the attributes
public DateTime Date { get => date; set => date = value; }
public double PurchasePrice { get => purchasePrice; set => purchasePrice = value; }
public double Deposit { get => deposit; set => deposit = value; }
public double InterestRate { get => interestRate; set => interestRate = value; }
public int Months { get => months; set => months = value; }
public double MonthlyCost { get => monthlyCost; set => monthlyCost = value; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.