text
stringlengths 13
6.01M
|
|---|
namespace CharacterMultiplier
{
using System;
using System.Linq;
public class StartUp
{
public static void Main(string[] args)
{
var inputLine = Console.ReadLine()
.Split(' ')
.ToArray();
var firstWord = inputLine[0].ToCharArray();
var secondWord = inputLine[1].ToCharArray();
var sum = 0;
var length = Math.Min(firstWord.Length, secondWord.Length);
for (int i = 0; i < length; i++)
{
sum += (int)firstWord[i] * secondWord[i];
}
if (firstWord.Length > secondWord.Length)
{
firstWord = firstWord.Skip(length).Take(firstWord.Length).ToArray();
foreach (var character in firstWord)
{
sum += (int)character;
}
}
else if (firstWord.Length < secondWord.Length)
{
secondWord = secondWord.Skip(length).Take(secondWord.Length).ToArray();
foreach (var character in secondWord)
{
sum += (int)character;
}
}
Console.WriteLine(sum);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Centroid.Models;
namespace Centroid.Areas.Admin.Controllers
{
[Authorize]
public class ProfilesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index()
{
return View(db.PersonalInfoes.ToList());
}
// GET: PersonalInfoes/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PersonalInfo personalInfo = db.PersonalInfoes.Find(id);
if (personalInfo == null)
{
return HttpNotFound();
}
return View(personalInfo);
}
// GET: PersonalInfoes/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PersonalInfo personalInfo = db.PersonalInfoes.Find(id);
if (personalInfo == null)
{
return HttpNotFound();
}
return View(personalInfo);
}
// POST: PersonalInfoes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
PersonalInfo personalInfo = db.PersonalInfoes.Find(id);
var wrIds = db.WorkExperiences.Where(w => w.PersonalInfoId == id).ToList();
db.WorkExperiences.RemoveRange(wrIds);
var edIds = db.Educations.Where(w => w.PersonalInfoId == id).ToList();
db.Educations.RemoveRange(edIds);
var docIds = db.ProfileDocuments.Where(w => w.ProfileId == id).ToList();
db.ProfileDocuments.RemoveRange(docIds);
db.PersonalInfoes.Remove(personalInfo);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using IRAP.Client.Global;
using IRAP.Client.User;
using IRAP.Entity.SSO;
using IRAP.Global;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.GUI.CAS
{
public partial class frmKanbanSPR : IRAP.Client.Global.GUI.frmCustomKanbanBase
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
List<Entity.FVS.AndonEventKanbanSPR> events =
new List<Entity.FVS.AndonEventKanbanSPR>();
public frmKanbanSPR()
{
InitializeComponent();
}
private void GetEvents()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
try
{
IRAPFVSClient.Instance.ufn_GetAndonEventKanban_SPR(
IRAPUser.Instance.CommunityID,
t134ClickStream,
IRAPUser.Instance.SysLogID,
ref events,
out errCode,
out errText);
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
AddLog(new AppOperationLog(DateTime.Now, -1, error.Message));
SetConnectionStatus(false);
return;
}
WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName);
if (errCode == 0)
{
grdEvents.DataSource = events;
for (int i = 0; i < gdvEvents.Columns.Count; i++)
{
if (gdvEvents.Columns[i].Visible)
gdvEvents.Columns[i].BestFit();
}
gdvEvents.OptionsView.RowAutoHeight = true;
gdvEvents.LayoutChanged();
SetConnectionStatus(true);
}
else
{
AddLog(new AppOperationLog(DateTime.Now, -1, errText));
SetConnectionStatus(false);
grdEvents.DataSource = null;
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private void frmKanbanSPR_Activated(object sender, EventArgs e)
{
if (this.Tag is SystemMenuInfoButtonStyle)
{
menuInfo = this.Tag as SystemMenuInfoButtonStyle;
GetEvents();
if (autoSwtich)
{
if (this.events.Count > 0)
{
timer.Interval = this.nextFunction.WaitForSeconds * 1000;
}
else
{
timer.Interval = 1000;
}
}
else
{
timer.Interval = 60000;
}
timer.Enabled = true;
}
else
{
AppOperationLog log = new AppOperationLog(DateTime.Now, -1, "没有正确的传入菜单参数!");
AddLog(log);
timer.Enabled = false;
return;
}
}
private void timer_Tick(object sender, EventArgs e)
{
timer.Enabled = false;
if (autoSwtich)
{
JumpToNextFunction();
return;
}
else
{
GetEvents();
timer.Enabled = true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DAY1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("please input the host address!!!");
}
else
{
textBox2.Text = textBox3.Text = textBox4.Text = "";
IPAddress[] ips = Dns.GetHostAddresses(textBox1.Text);
foreach(IPAddress ip in ips){
textBox2.Text = ip.ToString();
}
textBox3.Text = Dns.GetHostName();
textBox4.Text = Dns.GetHostEntry(Dns.GetHostName()).HostName;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using University.UI.App_Start;
namespace University.UI
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Bootstrapper.Initialise();
AutoMapper.Mapper.Initialize(cfg => cfg.AddProfile<MapperConfg>());
}
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
}
}
|
using System.Collections.Generic;
namespace ListHehe
{
internal class Program
{
public static void Main(string[] args)
{
List<int> list = new List<int>();
list.Add(5);
list.Add(6);
list.Add(4);
}
}
}
|
using JhinBot.GlobalConst;
using JhinBot.Interface;
namespace JhinBot.Convo.Validators
{
public class BodyValidator : IValidator
{
private string _errorMsg;
public BodyValidator(string errorMsg)
{
_errorMsg = errorMsg;
}
public (bool success, string errorMsg) Validate(string input)
{
return (input.Length < Global.Params.MAX_CHAR_PER_MESSAGE, _errorMsg);
}
}
}
|
using PopulationFitness.Models.Genes.BitSet;
namespace PopulationFitness.Models.Genes.LocalMinima
{
public class StyblinksiTangGenes : NormalizingBitSetGenes
{
public StyblinksiTangGenes(Config config) : base(config, 5.0) { }
protected override double CalculateNormalizationRatio(int n)
{
return 85.834 * n;
}
protected override double CalculateFitnessFromIntegers(long[] integer_values)
{
/*
http://www.sfu.ca/~ssurjano/stybtang.html
f(x) = 1/2 * sum{i=1 to n}[x{i}^4 - 16x{i}^2 + 5x{i}]
Dimensions: d
The function is usually evaluated on the hypercube xi ∈ [-5, 5], for all i = 1, …, d.
Global Minimum:
f(x) = -39.16599d at x = (-2.903534,...-2.903534)
*/
double fitness = 39.166 * integer_values.Length;
foreach (long integer_value in integer_values)
{
double x = Interpolate(integer_value);
double xSquared = x * x;
fitness += (xSquared * xSquared - 16 * xSquared + 5 * x);
}
return fitness / 2;
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace zm.Questioning
{
/// <summary>
/// Wrapped all data needed for one Question. Contains list of answers, where only one answer could be correct.
/// Each question must have at least two answers.
/// All fields have to be public to be serialized by JsonUtil.
/// </summary>
[Serializable]
public class Question
{
#region Constructor
private Question(QuestionCategory category, long timeLimit, string text, List<Answer> answers, string audioPath, int points): this()
{
Category = category;
TimeLimit = timeLimit;
Text = text;
Answers = answers;
AudioPath = audioPath;
Points = points;
}
public Question(QuestionCategory category)
: this(category, 0L, "", new List<Answer>(), "", 0) {}
public Question()
{
Id = ++IdGen;
}
#endregion Constructor
#region Fields and Properties
/// <summary>
/// Used for generating unique ids for this class.
/// </summary>
private static int IdGen = 0;
/// <summary>
/// Category to which this question belongs.
/// </summary>
public QuestionCategory Category;
/// <summary>
/// Time limit for this question, in seconds.
/// </summary>
public long TimeLimit;
/// <summary>
/// Text represents body of question.
/// </summary>
public string Text;
/// <summary>
/// List of answers, where only one is correct.
/// </summary>
public List<Answer> Answers;
/// <summary>
/// Each question has unique id. It's used for load/store operations.
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Path to Audio source for this question.
/// </summary>
public string AudioPath;
/// <summary>
/// Number of points that will user get if he answers correctly.
/// </summary>
public int Points;
/// <summary>
/// Current position for this question.
/// </summary>
public Vector3 Position { get; set; }
#endregion Field and Properties
}
public enum QuestionCategory
{
Spells = 0,
Potions,
Hogwarts
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LikDemo.Models.ViewModels
{
public class InvoiceViewModel
{
public string Id { get; set; }
public string Type { get; set; }
public DateTime Date { get; set; }
public string NetAmount { get; set; }
public string Currency { get; set; }
public DateTime DueDate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Views;
using Android.Widget;
using Java.Lang;
using CC.Mobile.Routing;
namespace Gojimo.Tutor.Services
{
public class ActivityIntent: Intent, INavIntent
{
private Activity contex;
public ActivityIntent(Activity contex, Type activityType) : base(contex, activityType){
this.contex = contex;
}
public void Start()
{
contex.StartActivity(this);
contex.Finish();
}
public void Stop()
{
contex.Finish();
}
}
}
|
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
namespace MessageProcessor
{
public static class MessageProcessorFunction
{
[FunctionName("MessageProcessorFunction")]
public static void Run([ServiceBusTrigger("myqueue", Connection = "")]string myQueueItem, ILogger log)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Destroy the gameobject that pass the trigger
/// </summary>
public class ObjectDestroyer : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
Destroy(other.gameObject);
}
}
|
public interface State
{
void Enter(UnityEngine.GameObject theObject, UnityEngine.Animation anim);
bool Reason();
void Act();
StatesEnum Leave();
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Pooling
{
public interface IRecycle
{
GameObject PrefabType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
[Serializable]
public abstract class UpgradeManager //: IUpgrade
{
public UpgradeManager()
{
}
public int id { get; private set; }
public float value { get; private set; }
public bool isOne { get; private set; }
public byte count { get; private set; }
public PlayerClassEnum playerClass{ get; private set; }
public abstract void Upgrade(AbstractSkill skil);
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using NUnit.Framework;
namespace AIMLbot.Tests
{
[TestFixture]
public class UserTests
{
private ChatBot _chatBot;
private User _user;
[OneTimeSetUp]
public void SetupMockObjects()
{
_chatBot = new ChatBot();
}
[OneTimeTearDown]
public void TearDown()
{
_chatBot = null;
}
[Test]
public void TestBadConstructor()
{
_user = new User("", _chatBot);
Assert.That(() => new User("", _chatBot), Throws.TypeOf<Exception>());
}
[Test]
public void TestConstructorPopulatesUserObject()
{
_user = new User("1", _chatBot);
Assert.AreEqual("*", _user.Topic);
Assert.AreEqual("1", _user.UserId);
// the +1 in the following assert is the creation of the default topic predicate
var predicates = ConfigurationManager.GetSection("Predicates") as Dictionary<string, string>;
Assert.IsNotNull(predicates);
Assert.AreEqual(predicates.Count + 1, _user.Predicates.Count);
}
[Test]
public void TestResultHandlers()
{
_user = new User("1", _chatBot);
Assert.AreEqual("", _user.getResultSentence());
var mockRequest = new Request("Sentence 1. Sentence 2", _user, _chatBot);
var mockResult = new Result(_user, _chatBot, mockRequest);
mockResult.InputSentences.Add("Result 1");
mockResult.InputSentences.Add("Result 2");
mockResult.OutputSentences.Add("Result 1");
mockResult.OutputSentences.Add("Result 2");
_user.AddResult(mockResult);
var mockResult2 = new Result(_user, _chatBot, mockRequest);
mockResult2.InputSentences.Add("Result 3");
mockResult2.InputSentences.Add("Result 4");
mockResult2.OutputSentences.Add("Result 3");
mockResult2.OutputSentences.Add("Result 4");
_user.AddResult(mockResult2);
Assert.AreEqual("Result 3", _user.getResultSentence());
Assert.AreEqual("Result 3", _user.getResultSentence(0));
Assert.AreEqual("Result 1", _user.getResultSentence(1));
Assert.AreEqual("Result 4", _user.getResultSentence(0, 1));
Assert.AreEqual("Result 2", _user.getResultSentence(1, 1));
Assert.AreEqual("", _user.getResultSentence(0, 2));
Assert.AreEqual("", _user.getResultSentence(2, 0));
Assert.AreEqual("Result 3", _user.getThat());
Assert.AreEqual("Result 3", _user.getThat(0));
Assert.AreEqual("Result 1", _user.getThat(1));
Assert.AreEqual("Result 4", _user.getThat(0, 1));
Assert.AreEqual("Result 2", _user.getThat(1, 1));
Assert.AreEqual("", _user.getThat(0, 2));
Assert.AreEqual("", _user.getThat(2, 0));
}
}
}
|
// Copyright © 2020 Void-Intelligence All Rights Reserved.
using Vortex.Cost.Utility;
using Nomad.Core;
namespace Vortex.Cost.Kernels.Regression
{
public class CosineProximity : BaseCost
{
public override double Evaluate(Matrix actual, Matrix expected)
{
return Forward(actual, expected);
}
public override double Forward(Matrix actual, Matrix expected)
{
var dotProd = 0.0;
var dot = actual * expected.T();
for (var i = 0; i < dot.Rows; i++)
for (var j = 0; j < dot.Columns; j++)
dotProd += dot[i, j];
var aNorm = 0.0;
dot = actual * actual.T();
for (var i = 0; i < dot.Rows; i++)
for (var j = 0; j < dot.Columns; j++)
aNorm += dot[i, j];
var eNorm = 0.0;
dot = expected * expected.T();
for (var i = 0; i < dot.Rows; i++)
for (var j = 0; j < dot.Columns; j++)
eNorm = dot[i, j];
var error = dotProd / (aNorm * eNorm);
BatchCost += error;
return error;
}
public override Matrix Backward(Matrix actual, Matrix expected)
{
var dotProd = 0.0;
var dot = actual * expected.T();
for (var i = 0; i < dot.Rows; i++)
for (var j = 0; j < dot.Columns; j++)
dotProd += dot[i, j];
var aNorm = 0.0;
dot = actual * actual.T();
for (var i = 0; i < dot.Rows; i++)
for (var j = 0; j < dot.Columns; j++)
aNorm += dot[i, j];
var eNorm = 0.0;
dot = expected * expected.T();
for (var i = 0; i < dot.Rows; i++)
for (var j = 0; j < dot.Columns; j++)
eNorm = dot[i, j];
var a = 1.0 / (eNorm * aNorm);
var b = dotProd / (aNorm * aNorm);
var gradMatrix = new Matrix(actual.Rows, actual.Columns);
for (var i = 0; i < gradMatrix.Rows; i++)
for (var j = 0; j < gradMatrix.Columns; j++)
gradMatrix[i, j] = a * (expected[i, j] - b * actual[i, j]);
return gradMatrix;
}
public override ECostType Type()
{
return ECostType.RegressionCosineProximity;
}
}
}
|
using System;
namespace SimpleMVC.App.Views.Home
{
using System.Text;
using Mvc.Interfaces;
public class LogoutIndex : IRenderable
{
public string Render()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<h1>NotesApp</h1>");
sb.AppendLine("<a href=\"/users/all\">All Users</a>");
sb.AppendLine("<a href=\"/users/logout\">Log Out</a>");
return sb.ToString();
}
}
}
|
using LuckyMasale.BAL.Managers;
using LuckyMasale.Shared.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace LuckyMasale.WebApi.Controllers
{
public class DeliveryAddressController : ApiController
{
#region Properties
private Lazy<IDeliveryAddressManager> deliveryAddressManager;
#endregion
#region Constructors
public DeliveryAddressController(Lazy<IDeliveryAddressManager> deliveryAddressManager)
{
this.deliveryAddressManager = deliveryAddressManager;
}
#endregion
#region Methods
public async Task<List<DeliveryAddress>> GetAllDeliveryAddress()
{
return await deliveryAddressManager.Value.GetAllDeliveryAddress();
}
public async Task<DeliveryAddress> GetDeliveryAddressByOrderID(int id)
{
return await deliveryAddressManager.Value.GetDeliveryAddressByOrderID(id);
}
public async Task<List<DeliveryAddress>> GetDeliveryAddressByUserID(int id)
{
return await deliveryAddressManager.Value.GetDeliveryAddressByUserID(id);
}
public async Task<int> InsertDeliveryAddress(DeliveryAddress deliveryAddress)
{
return await deliveryAddressManager.Value.InsertDeliveryAddress(deliveryAddress);
}
public async Task<int> UpdateDeliveryAddress(DeliveryAddress deliveryAddress)
{
return await deliveryAddressManager.Value.UpdateDeliveryAddress(deliveryAddress);
}
#endregion
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Utilities;
namespace EddiDataDefinitions
{
public class CommodityMarketQuote
{
// should ideally be readonly but we need to set it during JSON parsing
public CommodityDefinition definition { get; private set; }
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
if (definition == null)
{
string _name = null;
if (additionalJsonData != null)
{
if (additionalJsonData.TryGetValue("EDName", out var edName))
{
_name = (string)edName;
}
if (_name == null && (additionalJsonData?.ContainsKey("name") ?? false))
{
_name = (string)additionalJsonData?["name"];
}
}
if (_name != null)
{
definition = CommodityDefinition.FromNameOrEDName(_name);
}
}
additionalJsonData = null;
}
[JsonExtensionData]
private IDictionary<string, JToken> additionalJsonData;
public string invariantName
{
get => definition?.invariantName;
}
public string localizedName
{
get => definition?.localizedName;
}
[PublicAPI, Obsolete("deprecated for UI usage but retained for JSON conversion from the cAPI")]
public string name
{
get => definition?.localizedName;
set
{
if (this.definition == null)
{
CommodityDefinition newDef = CommodityDefinition.FromNameOrEDName(value);
this.definition = newDef;
}
}
}
// Per-station information (prices are usually integers but not always)
[PublicAPI]
public decimal buyprice { get; set; }
[PublicAPI]
public int stock { get; set; }
// StockBracket can contain the values 0, 1, 2, 3 or "" (yes, really) so we use an optional enum
public CommodityBracket? stockbracket { get; set; }
[PublicAPI]
public decimal sellprice { get; set; }
[PublicAPI]
public int demand { get; set; }
// DemandBracket can contain the values 0, 1, 2, 3 or "" (yes, really) so we use an optional enum
public CommodityBracket? demandbracket { get; set; }
public long? EliteID => definition?.EliteID;
[PublicAPI, Obsolete("Please use localizedName or InvariantName")]
public string category => definition?.Category.localizedName;
// Update the definition with the new galactic average price whenever this is set.
// Fleet carriers return zero and do not display the true average price. We must disregard that information so preserve the true average price.
// The average pricing data is the only data which may reference our internal definition, and even then only to obtain an average price.
[PublicAPI]
public decimal avgprice
{
get => definition?.avgprice ?? 0;
set
{
if (definition is null)
{
return;
}
definition.avgprice = value;
}
}
[PublicAPI]
public bool rare => definition?.rare ?? false;
public HashSet<string> StatusFlags { get; set; }
[JsonConstructor]
public CommodityMarketQuote(CommodityDefinition definition)
{
if (definition is null) { return; }
this.definition = definition;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AtendimentoProntoSocorro.Data;
using AtendimentoProntoSocorro.Models;
using AtendimentoProntoSocorro.Repositories;
using Microsoft.AspNetCore.Mvc;
namespace AtendimentoProntoSocorro.Controllers
{
public class FichaController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IPacienteRepository pacienteRepository;
private readonly IFichaRepository fichaRepository;
public FichaController(ApplicationDbContext context, IPacienteRepository pacienteRepository, IFichaRepository fichaRepository)
{
_context = context;
this.pacienteRepository = pacienteRepository;
this.fichaRepository = fichaRepository;
}
public IActionResult Aguardando()
{
var fichas = fichaRepository.GetFichasAguardando();
return View(fichas);
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> AberturaDeFicha(long cpf)
{
Paciente paciente = await pacienteRepository.GetPaciente(cpf);
Ficha ficha = new Ficha
{
Paciente = paciente
};
return View(ficha);
}
[HttpPost]
public async Task<IActionResult> CadastroFichaAsync(Ficha ficha)
{
if (ModelState.IsValid)
{
Paciente paciente = ficha.Paciente = await pacienteRepository.GetPaciente(ficha.Paciente.CPF);
ficha.Paciente = paciente;
ficha.DataFicha = DateTime.Now;
_context.Add(ficha);
await _context.SaveChangesAsync();
TempData["AlertMessage"] = "registro salvo com sucesso";
return RedirectToAction("Index", "Paciente");
}
return View(ficha);
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MyDiplom.Data;
namespace MyDiplom.Controllers
{
[Authorize(Roles = "Admin")]
public class RoleController : Controller
{
private ApplicationDbContext _context;
private readonly IServiceProvider _serviceProvider;
public RoleController(ApplicationDbContext context, IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_context = context;
}
public IActionResult Index() => View(_context.Roles.ToList());
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Create(string name)
{
await CreateUserRoles(_serviceProvider, name);
return RedirectToAction(nameof(Index));
}
public async Task<ActionResult> Delete(string id)
{
var role = await _context.Roles.FirstOrDefaultAsync(m => m.Id == id);
if (role != null)
{
_context.Roles.Remove(role);
await _context.SaveChangesAsync();
}
return RedirectToAction(nameof(Index));
}
private async Task CreateUserRoles(IServiceProvider serviceProvider, string name)
{
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
IdentityResult roleResult;
//Adding Admin Role
var roleCheck = await RoleManager.RoleExistsAsync(name);
if (!roleCheck)
{
//create the roles and seed them to the database
roleResult = await RoleManager.CreateAsync(new IdentityRole(name));
}
}
private async Task GiveUserRoles(IServiceProvider serviceProvider, string name)
{
var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
IdentityUser user = await _context.Users.FirstOrDefaultAsync(m => m.Id == name);
await UserManager.AddToRoleAsync(user, "Admin");
await _context.SaveChangesAsync();
//Assign Admin role to the main User here we have given our newly registered
//login id for Admin management
}
public async Task<ActionResult> giveAccess(string id)
{
await GiveUserRoles(_serviceProvider, id);
return Redirect("~/Admin/Index");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public Text time_text;
void Start()
{
time_text.text = Clock.instance.GetCurrentTime().text;
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ShipDetailPanel : MonoBehaviour {
//public Image ShipImage;
public Text ShipCount;
public Text ArrivalDay;
public Text Destination;
public Text Source;
public void UpdatePanel(Ship ship )
{
ShipCount.text = ship.ShipMovement.ShipCount.ToString();
ArrivalDay.text = "Day " + ship.ShipMovement.ArrivalDay + "(+" + (ship.ShipMovement.ArrivalDay - StateManager.CurrentDay) + ")";
Destination.text = ship.ShipMovement.Destination.planetName;
Source.text = ship.ShipMovement.Source.planetName;
}
}
|
using System.Web.Mvc;
using mvcMongoDB.Models;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using mvcMongoDB.ViewModel;
namespace mvcMongoDB.Controllers
{
public class HomeController : Controller
{
private readonly CountryDB Context = new CountryDB();
public ActionResult Index()
{
var Models = Context.Models.FindAll().SetSortOrder(SortBy<ItemModel>.Ascending(r => r.modelName));
return View(Models);
}
public ActionResult Create()
{
var model = new ItemViewModel
{
ItemModel = new ItemModel(),
Reps = new SelectList(Context.Reps.FindAll().SetSortOrder(SortBy<Rep>.Ascending(r => r.repName)), "Id", "repName"),
Brands = new SelectList(Context.Brands.FindAll().SetSortOrder(SortBy<Brand>.Ascending(r => r.brandName)), "Id", "brandName"),
Testers = new SelectList(Context.Testers.FindAll().SetSortOrder(SortBy<Tester>.Ascending(r => r.testerName)), "Id", "testerName"),
Pics = new SelectList(Context.Pics.FindAll().SetSortOrder(SortBy<Pic>.Ascending(r => r.picName)), "Id", "picName")
};
return View(model);
}
[HttpPost]
public ActionResult Create(ItemViewModel _itemViewModel)
{
if (ModelState.IsValid)
{
Context.Models.Insert(_itemViewModel.ItemModel);
return RedirectToAction("Index");
}
return View();
}
public ActionResult Edit(string Id )
{
var viewModel = new ItemViewModel
{
ItemModel = Context.Models.FindOneById(new ObjectId(Id)),
Reps = new SelectList(Context.Reps.FindAll().SetSortOrder(SortBy<Rep>.Ascending(r => r.repName)), "Id", "repName"),
Brands = new SelectList(Context.Brands.FindAll().SetSortOrder(SortBy<Brand>.Ascending(r => r.brandName)), "Id", "brandName"),
Testers = new SelectList(Context.Testers.FindAll().SetSortOrder(SortBy<Tester>.Ascending(r => r.testerName)), "Id", "testerName"),
Pics = new SelectList(Context.Pics.FindAll().SetSortOrder(SortBy<Pic>.Ascending(r => r.picName)), "Id", "picName")
};
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(ItemViewModel _itemViewModel)
{
if (ModelState.IsValid)
{
Context.Models.Save(_itemViewModel.ItemModel);
return RedirectToAction("Index");
}
return View();
}
[HttpGet]
public ActionResult Delete(string Id)
{
var model = Context.Models.FindOneById(new ObjectId(Id));
return View(model);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(string Id)
{
var rental = Context.Models.Remove(Query.EQ("_id", new ObjectId(Id)));
return RedirectToAction("Index");
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
using Microsoft.Maui;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.PlatformConfiguration.WindowsSpecific;
using Microsoft.Maui.Controls.Xaml.Diagnostics;
using System;
using System.Diagnostics;
using Application = Microsoft.Maui.Controls.Application;
namespace MauiApp
{
public partial class App : Application
{
public App()
{
InitializeComponent();
}
protected override IWindow CreateWindow(IActivationState activationState)
{
// VisualDiagnostics.VisualTreeChanged += VisualDiagnostics_VisualTreeChanged;
this.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>()
.SetImageDirectory("Assets");
//var tabbedPage = new Microsoft.Maui.Controls.TabbedPage();
//tabbedPage.Children.Add(new NavigationPage(new MainPage()));
return new TestWindow(new NavigationPage(new MainPage()));
}
}
public class TestWindow : Window
{
public TestWindow()
{
}
public TestWindow(Microsoft.Maui.Controls.Page page) : base(page)
{
VisualDiagnostics.VisualTreeChanged += VisualDiagnostics_VisualTreeChanged;
}
private void VisualDiagnostics_VisualTreeChanged(object sender, VisualTreeChangeEventArgs e)
{
try
{
var parentSourInfo = VisualDiagnostics.GetXamlSourceInfo(e.Parent);
var childSourInfo = VisualDiagnostics.GetXamlSourceInfo(e.Child);
Debug.WriteLine($"VisualTreeChangeEventArgs {e.ChangeType}:" +
$"{e.Parent}:{parentSourInfo?.SourceUri}:{parentSourInfo?.LineNumber}:{parentSourInfo?.LinePosition}-->" +
$" {e.Child}:{childSourInfo?.SourceUri}:{childSourInfo?.LineNumber}:{childSourInfo?.LinePosition}");
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class StartMenu : MonoBehaviour {
public void OnText (){
SceneManager.LoadScene ("First", LoadSceneMode.Single);
}
}
|
using System;
namespace iSukces.Code
{
public interface IConverterEventArgs<TSource, TResult>
{
TSource SourceValue { get; }
bool Handled { get; set; }
TResult Result { get; set; }
}
public static class ConverterEventArgsExt
{
public static void Handle<TSource, TResult>(this IConverterEventArgs<TSource, TResult> src, TResult textInfo)
{
if (src.Handled)
throw new Exception("already handled");
src.Handled = true;
src.Result = textInfo;
}
}
}
|
using Microsoft.AspNetCore.Http;
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers
{
/// <summary>
/// The header value to use for ReferrerPolicy
/// </summary>
public class ReferrerPolicyHeader : DocumentHeaderPolicyBase
{
private readonly string _value;
/// <summary>
/// Initializes a new instance of the <see cref="ReferrerPolicyHeader"/> class.
/// </summary>
/// <param name="value">The HTTP header value</param>
public ReferrerPolicyHeader(string value)
{
_value = value;
}
/// <inheritdoc />
public override string Header { get; } = "Referrer-Policy";
/// <inheritdoc />
protected override string GetValue(HttpContext context) => _value;
}
}
|
namespace PayRentAndUse_V3.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class updateUserRecord : DbMigration
{
public override void Up()
{
Sql("update dbo.UserClasses set Gender='M'");
}
public override void Down()
{
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Robot.Tests
{
[TestClass]
public class RobotTests
{
[TestMethod]
public void TestPlacementAtInvalidXCoordinateIsIgnored()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsFalse(robot.Place(new Position(new Coordinate(5, 0), Direction.North)));
Assert.IsNull(robot.Report());
}
[TestMethod]
public void TestPlacementAtInvalidYCoordinateIsIgnored()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsFalse(robot.Place(new Position(new Coordinate(0, 5), Direction.North)));
Assert.IsNull(robot.Report());
}
[TestMethod]
public void TestPlacementAtInvalidXAndYCoordinateIsIgnored()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsFalse(robot.Place(new Position(new Coordinate(5, 5), Direction.North)));
Assert.IsNull(robot.Report());
}
[TestMethod]
public void TestPlacementAtValidCoordinateIsExecuted()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 2), Direction.North)));
var position = robot.Report();
Assert.IsNotNull(position);
Assert.AreEqual(new Position(new Coordinate(1, 2), Direction.North), position);
}
[TestMethod]
public void TestSuccessiveValidPlacements()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 2), Direction.North)));
var position = robot.Report();
Assert.IsNotNull(position);
Assert.AreEqual(new Position(new Coordinate(1, 2), Direction.North), position);
Assert.IsTrue(robot.Place(new Position(new Coordinate(3, 4), Direction.North)));
position = robot.Report();
Assert.IsNotNull(position);
Assert.AreEqual(new Position(new Coordinate(3, 4), Direction.North), position);
}
[TestMethod]
public void TestInvalidPlacementAfterValidPlacementIsIgnored()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 2), Direction.North)));
var position = robot.Report();
Assert.IsNotNull(position);
Assert.AreEqual(new Position(new Coordinate(1, 2), Direction.North), position);
Assert.IsFalse(robot.Place(new Position(new Coordinate(10, 4), Direction.North)));
position = robot.Report();
Assert.IsNotNull(position);
Assert.AreEqual(new Position(new Coordinate(1, 2), Direction.North), position);
}
[TestMethod]
public void TestLeftIsIgnoredBeforeValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsNull(robot.Report());
Assert.IsFalse(robot.Left());
Assert.IsNull(robot.Report());
}
[TestMethod]
public void TestRightIsIgnoredBeforeValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsNull(robot.Report());
Assert.IsFalse(robot.Right());
Assert.IsNull(robot.Report());
}
[TestMethod]
public void TestLeftBeforeValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsFalse(robot.Left());
}
[TestMethod]
public void TestRightBeforeValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsFalse(robot.Right());
}
[TestMethod]
public void TestLeftAfterInvalidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsFalse(robot.Place(new Position(new Coordinate(10, 10), Direction.North)));
Assert.IsFalse(robot.Left());
}
[TestMethod]
public void TestRightAfterInvalidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsFalse(robot.Place(new Position(new Coordinate(10, 10), Direction.North)));
Assert.IsFalse(robot.Right());
}
[TestMethod]
public void TestLeftAfterValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 2), Direction.North)));
Assert.IsTrue(robot.Left());
}
[TestMethod]
public void TestRightAfterValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 2), Direction.North)));
Assert.IsTrue(robot.Right());
}
[TestMethod]
public void TestFullTurnLeftAfterValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 2), Direction.North)));
Assert.IsTrue(robot.Left());
Assert.AreEqual(Direction.West, robot.Report()?.Direction);
Assert.IsTrue(robot.Left());
Assert.AreEqual(Direction.South, robot.Report()?.Direction);
Assert.IsTrue(robot.Left());
Assert.AreEqual(Direction.East, robot.Report()?.Direction);
Assert.IsTrue(robot.Left());
Assert.AreEqual(Direction.North, robot.Report()?.Direction);
}
[TestMethod]
public void TestFullTurnRightAfterValidPlacement()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 2), Direction.North)));
Assert.IsTrue(robot.Right());
Assert.AreEqual(Direction.East, robot.Report()?.Direction);
Assert.IsTrue(robot.Right());
Assert.AreEqual(Direction.South, robot.Report()?.Direction);
Assert.IsTrue(robot.Right());
Assert.AreEqual(Direction.West, robot.Report()?.Direction);
Assert.IsTrue(robot.Right());
Assert.AreEqual(Direction.North, robot.Report()?.Direction);
}
[TestMethod]
public void TestInvalidMoveNorth()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(0, 4), Direction.North)));
Assert.IsFalse(robot.Move());
Assert.AreEqual(new Position(new Coordinate(0, 4), Direction.North), robot.Report());
}
[TestMethod]
public void TestInvalidMoveEast()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(4, 0), Direction.East)));
Assert.IsFalse(robot.Move());
Assert.AreEqual(new Position(new Coordinate(4, 0), Direction.East), robot.Report());
}
[TestMethod]
public void TestInvalidMoveSouth()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(0, 0), Direction.South)));
Assert.IsFalse(robot.Move());
Assert.AreEqual(new Position(new Coordinate(0, 0), Direction.South), robot.Report());
}
[TestMethod]
public void TestInvalidMoveWest()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(0, 0), Direction.West)));
Assert.IsFalse(robot.Move());
Assert.AreEqual(new Position(new Coordinate(0, 0), Direction.West), robot.Report());
}
[TestMethod]
public void TestValidMoveNorth()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(0, 3), Direction.North)));
Assert.IsTrue(robot.Move());
Assert.AreEqual(new Position(new Coordinate(0, 4), Direction.North), robot.Report());
}
[TestMethod]
public void TestValidMoveEast()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(3, 0), Direction.East)));
Assert.IsTrue(robot.Move());
Assert.AreEqual(new Position(new Coordinate(4, 0), Direction.East), robot.Report());
}
[TestMethod]
public void TestValidMoveSouth()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(0, 1), Direction.South)));
Assert.IsTrue(robot.Move());
Assert.AreEqual(new Position(new Coordinate(0, 0), Direction.South), robot.Report());
}
[TestMethod]
public void TestValidMoveWest()
{
var world = new World(width:5, height:5);
var robot = new Robot(world);
Assert.IsTrue(robot.Place(new Position(new Coordinate(1, 0), Direction.West)));
Assert.IsTrue(robot.Move());
Assert.AreEqual(new Position(new Coordinate(0, 0), Direction.West), robot.Report());
}
}
}
|
using System;
using System.Text;
namespace Algorithms
{
public static class RDITest
{
/// <summary>
/// 7 - RDI Test - 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
/// </summary>
private static void First100FibonacciNumbers()
{
long num1 = 0; long num2 = 1;
for (int i = 0; i <= 100; i = i + 2)//0 2 4
{
Console.Write(String.Format("{0}, ", num1));//0 1 3 8
Console.Write(String.Format("{0}, ", num2));//1 2 5 13
num1 += num2;
num2 += num1;
}
}
/// <summary>
/// 8 - RDI Test
/// </summary>
private static string AllNumbersConcatString(int[] numbers)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < numbers.Length; i++)
{
if (IsEven(i))
{
result.Append(i);
if (Array.IndexOf(numbers, i) != numbers.Length - 1)
result.Append("|");
}
}
return result.ToString();
}
/// <summary>
/// 9 - RDI Test
/// </summary>
private static bool IsEven(int number)
{
double buffer = (double)number / 2;
//double buffer = ((double)number);
//buffer /= 2;
int result = 0;
int.TryParse(buffer.ToString(), out result);
return result != 0;
}
/// <summary>
/// 10 - RDI Test
/// </summary>
private static int[] FirstTwoWhoseSumEqualsX(int[] array, int x)
{
for (int i = 0; i < array.Length; i++) //Varre o array, 1º For
{
for (int i2 = 0; i2 < array.Length; i2++) // Varre o mesmo array, 2º For, com o primeiro item no ponteiro "array[i]", só que vamos continuar
{ // varrendo todos os numeros no array do 2º For "array[i2, i2+1, i2 +3 ...]" até o final
// para que voltemos ao 2º item do 1º For "i+1" e ir comparando novamente com todos os numeros do 2º For
// sucessivamente até o ultimo numero do 1º For
if (array[i] != array[i2] && (array[i] + array[i2]) == x)
{
return new int[] { array[i], array[i2] };
}
}
}
return null;
}
}
}
|
namespace RosPurcell.Web.Infrastructure.Mapping
{
using System.Linq;
using RosPurcell.Web.Constants.Images;
using RosPurcell.Web.DataModels.Media;
using RosPurcell.Web.ViewModels.Media.Base;
using Umbraco.Core.Models;
using Umbraco.Web;
using Zone.UmbracoMapper;
public class ImageFileMapping<T> : BaseMapping, ICustomMapping<T> where T : BaseImage, new()
{
public T Map(IUmbracoMapper mapper, IPublishedContent content, string alias, bool recursive)
{
var media = content.GetPropertyValue<IPublishedContent>(alias, recursive);
var image = Map<T>(mapper, media);
image.BreakPoints = ImageCrops.Crops[image.BreakPointSet].Select(
x => new BreakPoint
{
MaxWidth = x.MaxWidth,
Url = media?.GetCropUrl(x.Width, quality: 80)
});
image.Url = image.BreakPoints.Last().Url;
return image;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.ServiceFabric.Data.Collections
{
internal class ReliableDictionary<TKey, TValue> : IReliableDictionary<TKey, TValue>, ICommitable where TKey : IComparable<TKey>, IEquatable<TKey>
{
private ConcurrentDictionary<TKey, TValue> store = new ConcurrentDictionary<TKey, TValue>();
private object lockObject = new object();
public string Name { get; internal set; }
public Task<TValue> AddOrUpdateAsync(ITransaction tx, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
{
return Task.Run(() =>
{
Transaction transaction = tx as Transaction;
if (transaction.TransactionObject == null)
{
transaction.TransactionObject = new TransactionContainer<TKey, TValue>();
}
transaction.Store = this;
var transactionContainer = transaction.TransactionObject as TransactionContainer<TKey, TValue>;
return transactionContainer.AddOrUpdate(key, addValue, updateValueFactory);
});
}
public Task TryRemoveAsync(ITransaction tx, TKey key)
{
return Task.Run(() =>
{
Transaction transaction = tx as Transaction;
if (transaction.TransactionObject == null)
{
transaction.TransactionObject = new TransactionContainer<TKey, TValue>();
}
transaction.Store = this;
var transactionContainer = transaction.TransactionObject as TransactionContainer<TKey, TValue>;
store.TryGetValue(key, out TValue value);
return transactionContainer.Remove(key, value);
});
}
public Task<ConditionalValue<TValue>> TryGetValueAsync(ITransaction tx, TKey key)
{
return Task.Run(() =>
{
Transaction transaction = tx as Transaction;
if (transaction.TransactionObject == null)
{
return GetConditionalValueFromStore(key, store);
}
var transactionStore = transaction.TransactionObject as ConcurrentDictionary<TKey, TValue>;
ConditionalValue<TValue> result = GetConditionalValueFromStore(key, transactionStore);
if (result == null)
{
return GetConditionalValueFromStore(key, store);
}
return result;
});
}
private static ConditionalValue<TValue> GetConditionalValueFromStore(TKey key, ConcurrentDictionary<TKey, TValue> transactionStore)
{
return new ConditionalValue<TValue>
{
HasValue = transactionStore.TryGetValue(key, out TValue value),
Value = value
};
}
public Task CommitTransactionAsync(Transaction transaction)
{
return Task.Run(() =>
{
if (transaction.TransactionObject == null)
{
return;
}
var transactionContainer = transaction.TransactionObject as TransactionContainer<TKey, TValue>;
lock (lockObject)
{
foreach (var item in transactionContainer.ItemsToAddOrUpdate)
{
store.AddOrUpdate(item.Key, item.Value, (key, value) => value = item.Value);
}
foreach (var item in transactionContainer.ItemsToRemove)
{
store.TryRemove(item.Key, out TValue result);
}
transactionContainer.Clear();
}
});
}
public Task<bool> ContainsKeyAsync(ITransaction tx, TKey key)
{
return Task.Run(() =>
{
Transaction transaction = tx as Transaction;
if (transaction.TransactionObject != null )
{
var transactionContainer = transaction.TransactionObject as TransactionContainer<TKey, TValue>;
if (transactionContainer.ItemsToAddOrUpdate.ContainsKey(key)) {
return true;
}
if (transactionContainer.ItemsToRemove.ContainsKey(key))
{
return false;
}
return store.ContainsKey(key);
}
return store.ContainsKey(key);
});
}
}
internal class TransactionContainer<TKey, TValue>
{
ConcurrentDictionary<TKey, TValue> _itemsToAddOrUpdate;
public ConcurrentDictionary<TKey, TValue> ItemsToAddOrUpdate
{
get
{
if (_itemsToAddOrUpdate == null)
{
_itemsToAddOrUpdate = new ConcurrentDictionary<TKey, TValue>();
}
return _itemsToAddOrUpdate;
}
}
ConcurrentDictionary<TKey, TValue> _itemsToRemove;
public ConcurrentDictionary<TKey, TValue> ItemsToRemove
{
get
{
if (_itemsToRemove == null)
{
_itemsToRemove = new ConcurrentDictionary<TKey, TValue>();
}
return _itemsToRemove;
}
}
internal TValue AddOrUpdate(TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
{
if (_itemsToRemove != null)
{
_itemsToRemove.TryRemove(key, out TValue result);
}
return ItemsToAddOrUpdate.AddOrUpdate(key, addValue, updateValueFactory);
}
internal bool Remove(TKey key, TValue value)
{
if (_itemsToAddOrUpdate != null)
{
_itemsToAddOrUpdate.TryRemove(key, out value);
}
if (value == null)
{
return false;
}
ItemsToRemove.AddOrUpdate(key, value, (k,v) => value);
return true;
}
internal void Clear()
{
_itemsToRemove = null;
_itemsToAddOrUpdate = null;
}
}
}
|
using PaperPlane.API.ProtocolSchema.Base;
using PaperPlane.API.ProtocolSchema.DataTypes.Auth;
using PaperPlane.API.ProtocolSchema.Internal;
using PaperPlane.API.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PaperPlane.API.ProtocolSchema.Methods.Auth
{
[ConstructorId(0x60469778)]
internal class ReqPQ : TLMethod<ResPQ>
{
public Memory<byte> Nonce { get; }
public ReqPQ(Memory<byte> nonce)
{
this.Nonce = nonce;
}
protected override void SerializePayload(BinaryWriter bw)
{
bw.Write(Nonce);
}
protected override void DeserializePayload(BinaryReader br)
{
throw new NotSupportedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.UTS {
public class LinkedTreeTitle {
}
public class LinkedTreeTip {
/// <summary>
/// 导入导出关联的树标识
/// </summary>
public int TreeID { get; set; }
/// <summary>
/// 选择叶子的提示标签
/// </summary>
public string PromptStr { get; set; }
}
public class LeafSet {
/// <summary>
/// 分区键
/// </summary>
public long PartitioningKey { get; set; }
/// <summary>
/// 叶标识
/// </summary>
public int LeafID { get; set; }
/// <summary>
/// 实体标识
/// </summary>
public int EntityID { get; set; }
/// <summary>
/// 实体代码
/// </summary>
public string Code { get; set; }
/// <summary>
/// 实体名称
/// </summary>
public string LeafName { get; set; }
/// <summary>
/// 叶状态
/// </summary>
public int LeafStatus { get; set; }
}
public class ImportParam {
/// <summary>
/// 信号旗文件路径
/// </summary>
public string FlagFilePath { get; set; }
/// <summary>
/// 数据文件路径
/// </summary>
public string DataFilePath { get; set; }
/// <summary>
/// 文件名前缀
/// </summary>
public string FileNamePrefix { get; set; }
/// <summary>
/// 文件扩展名
/// </summary>
public string FileExtensionName { get; set; }
/// <summary>
/// 格式文件名
/// </summary>
public string FormatFileName { get; set; }
/// <summary>
/// 目标表名
/// </summary>
public string DstTableName { get; set; }
/// <summary>
/// 目标表是否存在
/// </summary>
public string DstTableExist { get; set; }
/// <summary>
/// 创建表存储过程
/// </summary>
public string ProcToCreateTBL { get; set; }
/// <summary>
/// 提示
/// </summary>
public string ToolTip { get; set; }
/// <summary>
/// 校验存储过程名
/// </summary>
public string ProcOnVerification { get; set; }
/// <summary>
/// 是否允许部分加载
/// </summary>
public string PartialLoadPermitted { get; set; }
/// <summary>
/// 加载存储过程
/// </summary>
public string ProcOnLoad { get; set; }
}
public class ImportMetaData {
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 列名
/// </summary>
public string ColName { get; set; }
/// <summary>
/// 列名称
/// </summary>
public string ColDisplayName { get; set; }
/// <summary>
/// 类型
/// </summary>
public string ColType { get; set; }
/// <summary>
/// 长度
/// </summary>
public int Length { get; set; }
/// <summary>
/// 保留几位数
/// </summary>
public int Prec { get; set; }
public int Scale { get; set; }
public int Nullable { get; set; }
/// <summary>
/// 对齐方式
/// </summary>
public string Alignment { get; set; }
/// <summary>
/// 宽度
/// </summary>
public int DisplayWidth { get; set; }
/// <summary>
/// 是否可编辑
/// </summary>
public int EditEnabled { get; set; }
/// <summary>
/// 是否可见
/// </summary>
public string Visible { get; set; }
}
public class ImportErrorTypes {
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 错误类型
/// </summary>
public string ErrType { get; set; }
/// <summary>
/// 背景颜色
/// </summary>
public string BGColor { get; set; }
}
}
|
using System.Collections.Generic;
using Assets.Scripts.Models.ResourceObjects;
using Assets.Scripts.Models.ResourceObjects.CraftingResources;
namespace Assets.Scripts.Models.Weapons
{
public class Knife : Weapon
{
public Knife()
{
WeaponType = WeaponType.Melee;
WeaponInventoryId = 7;
LocalizationName = "knife";
Description = "knife_descr";
IconName = "knife_icon";
Durability = 100;
Damage = 30;
CraftRecipe = new List<HolderObject>();
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(WoodResource), 10));
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Metal), 10));
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Rope), 1));
}
}
}
|
namespace CarDealer.Models.ViewModels
{
public class SaleViewModel
{
public CustomerViewModel Customer { get; set; }
public CarViewModel Car { get; set; }
public double Discount { get; set; }
}
}
|
#region license
// Copyright (c) 2007-2010 Mauricio Scheffer
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using MbUnit.Framework;
using Rhino.Mocks;
using SolrNet.Attributes;
using SolrNet.Impl;
using SolrNet.Mapping.Validation;
using SolrNet.Schema;
namespace SolrNet.Tests {
[TestFixture]
public class SolrServerTests {
[Test]
public void Ping() {
var mocks = new MockRepository();
var basicServer = mocks.StrictMock<ISolrBasicOperations<TestDocument>>();
With.Mocks(mocks)
.Expecting(() => Expect.Call(basicServer.Ping()).Return(new ResponseHeader()))
.Verify(() => {
var s = new SolrServer<TestDocument>(basicServer, null, null);
s.Ping();
});
}
[Test]
public void Commit() {
var mocks = new MockRepository();
var basicServer = mocks.StrictMock<ISolrBasicOperations<TestDocument>>();
With.Mocks(mocks)
.Expecting(() => Expect.Call(basicServer.Commit(null)).Return(new ResponseHeader()))
.Verify(() => {
var s = new SolrServer<TestDocument>(basicServer, null, null);
s.Commit();
});
}
[Test]
public void GetSchema() {
var mocks = new MockRepository();
var basicServer = mocks.StrictMock<ISolrBasicOperations<TestDocument>>();
var mapper = mocks.StrictMock<IReadOnlyMappingManager>();
var validationManager = mocks.StrictMock<IMappingValidator>();
With.Mocks(mocks)
.Expecting(() => Expect.Call(basicServer.GetSchema())
.Repeat.Once()
.Return(new SolrSchema()))
.Verify(() => {
var s = new SolrServer<TestDocument>(basicServer, mapper, validationManager);
s.GetSchema();
});
}
[Test]
public void Validate() {
var mocks = new MockRepository();
var basicServer = mocks.StrictMock<ISolrBasicOperations<TestDocument>>();
var mapper = mocks.StrictMock<IReadOnlyMappingManager>();
var validationManager = mocks.StrictMock<IMappingValidator>();
With.Mocks(mocks)
.Expecting(() => {
Expect.Call(basicServer.GetSchema())
.Repeat.Once()
.Return(new SolrSchema());
Expect.Call(validationManager.EnumerateValidationResults(typeof(TestDocument), new SolrSchema()))
.Repeat.Once()
.IgnoreArguments()
.Return(new List<ValidationResult>());
})
.Verify(() => {
var s = new SolrServer<TestDocument>(basicServer, mapper, validationManager);
s.EnumerateValidationResults().ToList();
});
}
public class TestDocument {
[SolrUniqueKey]
public int id {
get { return 0; }
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class AnimationStart : MonoBehaviour
{
private Animation Anim;
// Start is called before the first frame update
void Start()
{
Anim = gameObject.GetComponent<Animation>();
Anim.Play("CamAnimation2");
}
// Update is called once per frame
}
|
using gView.Framework.Carto;
using gView.Framework.Globalisation;
using gView.Framework.system;
using gView.Framework.UI;
using gView.Plugins.MapTools.Dialogs;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Plugins.MapTools
{
[RegisterPlugInAttribute("61301C1E-BC8E-4081-A8BB-65BCC13C89EC")]
public class OverViewMap : ITool
{
private IMapDocument _doc;
private FormOverviewMap _dlg = null;
#region ITool Member
public string Name
{
get { return LocalizedResources.GetResString("Tools.OverViewMap", "Overview Map Window"); }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return ""; }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return null; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = hook as IMapDocument;
if (_doc is IMapDocumentEvents)
{
((IMapDocumentEvents)_doc).MapScaleChanged += new MapScaleChangedEvent(_doc_MapScaleChanged);
}
}
}
public Task<bool> OnEvent(object MapEvent)
{
if (_doc == null)
{
return Task.FromResult(true);
}
if (_dlg == null)
{
_dlg = new FormOverviewMap(_doc);
_dlg.FormClosing += new FormClosingEventHandler(dlg_FormClosing);
}
_dlg.Show();
return Task.FromResult(true);
}
#endregion
void dlg_FormClosing(object sender, FormClosingEventArgs e)
{
_dlg = null;
}
void _doc_MapScaleChanged(IDisplay sender)
{
if (_dlg != null)
{
_dlg.DrawMapExtent(sender);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public enum ActorMovementType
{
Walk,
Run
}
public enum ActorSignType
{
ExclamationMark,
QuestionMark
}
|
namespace Thesis {
public enum BuildMode
{
Many,
Two,
Three,
Four,
Five
}
} // namespace Thesis
|
using UnityEngine;
using System.Collections;
public class PlayerShooting : MonoBehaviour {
public ParticleSystem muzzleFlash;
//Animator anim;
public GameObject impactPrefab;
//GameObject[] impacts;
//int currentImpact = 0;
//int maxImpacts = 5;
float damage = 25.0f;
bool shooting = false;
// Use this for initialization
void Start () {
/*impacts = new GameObject[maxImpacts];
for(int i = 0; i < maxImpacts; i++)
impacts[i] = (GameObject)Instantiate(impactPrefab);
*/
//anim = GetComponentInChildren<Animator> ();
/*Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;*/
}
// Update is called once per frame
void Update () {
if(Input.GetButtonDown ("Fire1") && !Input.GetKey(KeyCode.LeftShift))
{
muzzleFlash.Play();
//anim.SetTrigger("Fire");
shooting = true;
}
}
void FixedUpdate()
{
if(shooting)
{
shooting = false;
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.forward, out hit, 50f))
{
if(hit.transform.tag == "Player")
{
hit.transform.GetComponent<PhotonView>().RPC ("GetShot", PhotonTargets.All, damage);
}
GameObject hitParticle = Instantiate(impactPrefab, hit.point, Quaternion.identity) as GameObject;
Destroy(hitParticle, 5.0f);
/*impacts[currentImpact].transform.position = hit.point;
impacts[currentImpact].GetComponent<ParticleSystem>().Play();
if(++currentImpact >= maxImpacts)
currentImpact = 0;
*/
}
}
}
}
|
namespace gView.Framework.system
{
static public class Const
{
public static readonly double TilesDpi = 95.999808000012053119158994982752; // ESRI unses this I think, or otherwise inch=0.0254000508001016???
}
}
|
using System.Drawing;
namespace Actividades_de_Aprendizaje_1_U1
{
class NodoListaC
{
public Color relleno;
public Color delineado;
public NodoListaC Siguiente;
/// <summary>
/// Constructor por defecto
/// </summary>
public NodoListaC()
{
}
/// <summary>
/// Contructor que define en color de relleno
/// </summary>
/// <param name="Dato">Color de relleno</param>
/// <param name="linea">Color de delineado en caso de no pasar parametro, sera negro</param>
public NodoListaC(Color Dato, Color? linea=null)
{
if (linea.GetValueOrDefault() == null)
linea = Color.Black;
else
this.delineado = linea.GetValueOrDefault();
this.relleno = Dato;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class InspectorManager : MonoBehaviour
{
// Singleton //
public static InspectorManager instance { get; protected set;}
void Awake () {
if (instance == null) {
instance = this;
} else if (instance != this) {
Destroy (gameObject);
}
}
// Singleton //
public GameObject interactionPanelObjectPrefab;
public GameObject tileInspectorObjectPrefab;
public static InteractionInspector interactionInspector;
public static PhysicalInteractableInspector physicalInteractableInspector;
public static ConditionInspector conditionInspector;
public static SubinteractionInspector subinteractionInspector;
public static TileInspector tileInspector;
public static GraphicStateInspector graphicStateInspector;
// public Interaction loadedInteraction;
// Chosen furniture
Furniture _chosenFurniture;
public Furniture chosenFurniture
{
get
{
return _chosenFurniture;
}
set
{
_chosenFurniture = value;
if ((_chosenFurniture == null) && (chosenCharacter == null))
{
physicalInteractableInspector.DestroyInspector ();
graphicStateInspector.DestroyGraphicStatePanel ();
} else if (_chosenFurniture != null)
{
physicalInteractableInspector.CreateInspector (_chosenFurniture);
}
}
}
// Chosen character
Character _chosenCharacter;
public Character chosenCharacter
{
get
{
return _chosenCharacter;
}
set
{
_chosenCharacter = value;
if ((_chosenCharacter == null) && (chosenFurniture == null))
{
physicalInteractableInspector.DestroyInspector ();
graphicStateInspector.DestroyGraphicStatePanel ();
} else if (_chosenCharacter != null)
{
physicalInteractableInspector.CreateInspector (_chosenCharacter);
}
}
}
// chosen tile interaction property
TileInteraction _chosenTileInteraction;
public TileInteraction chosenTileInteraction
{
get
{
return _chosenTileInteraction;
}
set
{
_chosenTileInteraction = value;
if (_chosenTileInteraction == null)
{
tileInspector.DestroyTileInspector ();
} else {
tileInspector.CreateTileInspector (_chosenTileInteraction);
}
}
}
// Use this for initialization
void Start ()
{
if (interactionInspector == null)
{
interactionInspector = gameObject.AddComponent<InteractionInspector> ();
}
if (physicalInteractableInspector == null)
{
physicalInteractableInspector = gameObject.AddComponent<PhysicalInteractableInspector> ();
}
if (conditionInspector == null)
{
conditionInspector = gameObject.AddComponent<ConditionInspector> ();
}
if (subinteractionInspector == null)
{
subinteractionInspector = gameObject.AddComponent<SubinteractionInspector> ();
}
if (tileInspector == null)
{
tileInspector = gameObject.AddComponent<TileInspector> ();
}
if (graphicStateInspector == null)
{
graphicStateInspector = gameObject.AddComponent<GraphicStateInspector> ();
}
}
public PhysicalInteractable GetChosenPI()
{
if (InspectorManager.instance.chosenFurniture != null)
{
return InspectorManager.instance.chosenFurniture;
} else if (InspectorManager.instance.chosenCharacter != null)
{
return InspectorManager.instance.chosenCharacter;
}
return null;
}
}
|
using System;
using System.Text;
namespace MarcusW.SharpUtils.Core
{
public static class HexConvert
{
/// <summary>
/// Encode bytes as hexadecimal string
/// </summary>
/// <param name="bytes">Bytes</param>
/// <returns>Hex string</returns>
public static string ToHexString(byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException(nameof(bytes));
var resultBuilder = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
string hexComponent = Convert.ToString(b, 16);
if (hexComponent.Length == 1)
resultBuilder.Append('0');
resultBuilder.Append(hexComponent);
}
return resultBuilder.ToString();
}
// Improved version, as soon as this library can be released with targeting .Net Standard 2.1
#if NETSTANDARD2_1
/// <summary>
/// Decode hex string to bytes
/// </summary>
/// <param name="hex">Hex string</param>
/// <returns>Bytes</returns>
public static byte[] FromHexString(ReadOnlySpan<char> hex)
{
if (hex.Length % 2 != 0)
throw new ArgumentException("Odd hex string length.", nameof(hex));
var result = new byte[hex.Length / 2];
for (int i = 0; i < result.Length; i++)
result[i] = Convert.ToByte(hex.Slice(i * 2, 2).ToString(), 16);
return result;
}
#endif
/// <summary>
/// Decode hex string to bytes
/// </summary>
/// <param name="hex">Hex string</param>
/// <returns>Bytes</returns>
public static byte[] FromHexString(string hex)
{
if (hex == null)
throw new ArgumentNullException(nameof(hex));
#if NETSTANDARD2_1
return FromHexString(hex.AsSpan());
#else
if (hex.Length % 2 != 0)
throw new ArgumentException("Odd hex string length.", nameof(hex));
var result = new byte[hex.Length / 2];
for (int i = 0; i < result.Length; i++)
result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
return result;
#endif
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SimulationDemo.Randomness
{
public class RandomStrGenerator
{
public static string GetRandomString(int stringLength = 8)
{
StringBuilder sb = new StringBuilder();
int numGuidsToConcat = (((stringLength - 1) / 32) + 1);
for (int i = 1; i <= numGuidsToConcat; i++)
{
sb.Append(Guid.NewGuid().ToString("N"));
}
return sb.ToString(0, stringLength);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using System;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Nusstudios.Controllers
{
[Route("[controller]")]
public class PT4ZSBController : Controller
{
private IWebHostEnvironment _env;
public PT4ZSBController(IWebHostEnvironment env)
{
_env = env;
}
// GET: /<controller>/
[HttpGet("[action]")]
public IActionResult plus_zsb()
{
string odbpath = Path.Combine(_env.WebRootPath, "auditing", "pt4zsb.odb");
string content = System.IO.File.ReadAllText(odbpath);
string[] arr = content.Split(new string[] { "<SEPARATOR>" }, StringSplitOptions.None);
string final = "";
if (arr.Length != 2)
{
final = "1<SEPARATOR>" + Request.Headers["User-Agent"] + "<SEPCLIENT>";
}
else
{
arr[0] = (Convert.ToUInt64(arr[0]) + 1).ToString();
arr[1] += Request.Headers["User-Agent"] + "<SEPCLIENT>";
final = String.Join("<SEPARATOR>", arr);
}
System.IO.File.WriteAllText(odbpath, final);
Response.Cookies.Append("Voted", "True");
return RedirectToAction("PT4ZSB", "Home");
}
[HttpGet("[action]")]
public string get_zsb()
{
string odbpath = Path.Combine(_env.WebRootPath, "auditing", "pt4zsb.odb");
string content = System.IO.File.ReadAllText(odbpath);
return content.Split(new string[] { "<SEPARATOR>" }, StringSplitOptions.None)[0];
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour {
public Text goldAmountText;
public Text goldIncomeText;
public Button buildButton;
private IncomeManager incomeManager;
public static UIManager Instance { get; private set; }
void Awake() {
if (Instance == null) {
Instance = this;
} else {
Debug.Log("Warning: multiple " + this + " in scene!");
}
}
void Start(){
incomeManager = GameManager.Instance.GetComponent<PlayerController>().player.incomeManager;
incomeManager.GoldAmountChanged += OnGoldAmountChanged;
incomeManager.GoldIncomeChanged += OnGoldIncomeChanged;
}
public void OnGoldAmountChanged(long gold) {
goldAmountText.text = "Gold: " + gold;
}
public void OnGoldIncomeChanged(long goldIncome) {
goldIncomeText.text = "Income: " + goldIncome;
}
void OnDestroy() {
incomeManager.GoldAmountChanged -= OnGoldAmountChanged;
incomeManager.GoldIncomeChanged -= OnGoldIncomeChanged;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Core.Common;
using Tests.Data.Oberon;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.CustomForm
{
public class CustomFormPublishedPageInfo : CustomFormBasePage
{
public CustomFormPublishedPageInfo(Driver driver) : base(driver) { }
public IWebElement PublishedUrl { get { return _driver.FindElement(By.Id("PublishedUrl")); } }
public IWebElement Id { get { return _driver.FindElement(By.Id("Id")); } }
public string PublishedPageInfoCreate(string[] toDelete, long tenantId, string batchToDelete)
{
for (int i = 0; i < toDelete.Length; i++)
{
TenentDbSqlAccess.RemoveContactCustomField(tenantId, toDelete[i]);
}
return PublishedUrl.GetAttribute("value");
}
}
}
|
using NUnit.Framework;
using RulesEngine.Conditions;
namespace RulesEngine.Tests.Conditions
{
[TestFixture]
public class IsNotNullConditionTests
{
[Test]
public void ShouldReturnTrueWhenPassedANonNullValue()
{
var condition = new IsNotNullCondition(true);
var result = condition.IsSatisfied();
Assert.That(result, Is.True);
}
[Test]
public void ShouldReturnFalseWhenPassedANullValue()
{
var condition = new IsNotNullCondition(null);
var result = condition.IsSatisfied();
Assert.That(result, Is.False);
}
}
}
|
using UnityEngine;
using System.Collections;
// Cole Troutman
// Use this OnMouseDown() setup for all items that will be interacting with the inventory system
public class chair : MonoBehaviour {
bool inInventory = false;
void OnMouseDown() {
if (!inInventory) {
// do stuff while item is in room
iManager.AddToInventory (this.gameObject); // add the item to inventory
inInventory = true; // note that this item is in the inventory
}
else if (inInventory) {
// do stuff while item is in inventory
if (iManager.equiped) { // if there is an item equiped already
iManager.swap(this.gameObject, iManager.equipedItem); // swap the items
}
else {
iManager.equipObject(this.gameObject); // if no item was already equiped, then equip the item clicked on
}
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
namespace SciVacancies.WebApp
{
public class CaptchaSettings
{
public int CaptchaDurationSeconds { get; set; }
}
}
|
using UnityEngine;
using SoulHunter.Gameplay;
namespace SoulHunter.Enemy
{
public class EnemyBase : Damageable
{
EnemyAnimation animationOfEnemy;
public SoulData soul;
protected void Start()
{
GameManager.Instance.EnemyListRegistry(this);
animationOfEnemy = GetComponentInChildren<EnemyAnimation>();
}
public override void TakeDamage()
{
base.TakeDamage();
animationOfEnemy.HurtAnimation();
if (!isDead)
{
AudioManager.PlaySound(AudioManager.Sound.EnemyHurt, transform.position);
}
else
{
if (!immuneToDamage)
{
immuneToDamage = true;
GetComponent<Collider2D>().enabled = false;
AudioManager.PlaySound(AudioManager.Sound.EnemyDeath, transform.position);
soul.SpawnParticle(transform.position);
}
}
}
private void OnDestroy()
{
GameManager.Instance.EnemyListRegistry(this);
}
}
}
|
using System;
using System.Windows.Controls;
using System.Windows.Media;
using VMDiagrammer.Helpers;
using VMDiagrammer.Interfaces;
namespace VMDiagrammer.Models
{
/// <summary>
/// Data for a typical Node in our model
/// </summary>
public class VM_Node : BaseVMObject, IDrawingObjects
{
public const double DEFAULT_NODE_RADIUS = 15;
public const double SUPPORT_LINE_THICKNESS = 5.0;
/// <summary>
/// Private members
/// </summary>
private double m_X; // x-coordinate
private double m_Y; // y-coordinate
private SupportTypes m_SupportType; // type of support as an ENUM
/// <summary>
/// Accessor for the X coordinate of our node
/// </summary>
public double X
{
get => m_X;
set { m_X = value; }
}
/// <summary>
/// Accessor for the Y coordinate of our node
/// </summary>
public double Y
{
get => m_Y;
set { m_Y = value; }
}
public SupportTypes SupportType
{
get => m_SupportType;
set { m_SupportType = value; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="x">x position on the canvas</param>
/// <param name="y">y position on the canvas</param>
public VM_Node(double x, double y, SupportTypes support = SupportTypes.SUPPORT_UNDEFINED)
{
X = x;
Y = y;
SupportType = support;
}
/// <summary>
/// Default constructor
/// </summary>
public VM_Node()
{
}
/// <summary>
/// The method to draw this object
/// </summary>
/// <param name="c"></param>
public void Draw(Canvas c)
{
double radius = 15.0;
double offset = radius / 2.0;
switch (m_SupportType)
{
case SupportTypes.SUPPORT_ROLLER_X:
{
// Draw the node icon
DrawingHelpers.DrawCircle(c, this.X, this.Y, Brushes.Black, Brushes.White, DEFAULT_NODE_RADIUS, 1.0);
// Draw the roller "ball"
DrawingHelpers.DrawCircleHollow(c, this.X, this.Y+2.0 * offset, Brushes.Blue, radius, SUPPORT_LINE_THICKNESS);
// Draw the surface line
double startX = this.X - radius;
double startY = this.Y + offset;
double endX = this.X + radius;
double endY = this.Y + offset;
DrawingHelpers.DrawLine(c, startX, startY + 2.0 * offset, endX, endY + 2.0 * offset, Brushes.Blue, SUPPORT_LINE_THICKNESS);
}
break;
case SupportTypes.SUPPORT_ROLLER_Y:
break;
case SupportTypes.SUPPORT_PIN:
{
double insertX = this.X;
double insertY = this.Y + offset;
double startX = insertX - 0.75 * radius;
double startY = insertY+ 2.0 * offset;
double endX = insertX + 0.75 * radius;
double endY = insertY + 2.0 * offset;
double base_startX = startX - 0.5 * radius;
double base_startY = startY;
double base_endX = endX + 0.52 * radius;
double base_endY = endY;
// Draw the node icon
DrawingHelpers.DrawCircle(c, this.X, this.Y, Brushes.Black, Brushes.White, DEFAULT_NODE_RADIUS, 1.0);
// Draw the pin "triangle"
DrawingHelpers.DrawLine(c, startX, startY, insertX, insertY, Brushes.Green, SUPPORT_LINE_THICKNESS);
DrawingHelpers.DrawLine(c, insertX, insertY, endX, endY, Brushes.Green, SUPPORT_LINE_THICKNESS);
DrawingHelpers.DrawLine(c, endX, endY, startX, startY, Brushes.Green, SUPPORT_LINE_THICKNESS);
// Draw the base line
DrawingHelpers.DrawLine(c, base_startX, base_startY, base_endX, base_endY, Brushes.Green, SUPPORT_LINE_THICKNESS);
break;
}
case SupportTypes.SUPPORT_FIXED_HOR:
{
double insertX = this.X;
double insertY = this.Y;
double startX = insertX - radius;
double startY = insertY - 3.0 * offset;
double endX = insertX - radius;
double endY = insertY + 3.0 * offset;
// Draw the node icon
DrawingHelpers.DrawCircle(c, this.X, this.Y, Brushes.Black, Brushes.White, DEFAULT_NODE_RADIUS, 1.0);
// Draw the pin "triangle"
DrawingHelpers.DrawLine(c, startX, startY, endX, endY, Brushes.Red, SUPPORT_LINE_THICKNESS);
break;
}
case SupportTypes.SUPPORT_UNDEFINED:
// Default node
DrawingHelpers.DrawCircle(c, this.X, this.Y, Brushes.Black, Brushes.White, DEFAULT_NODE_RADIUS, 1.0);
break;
case SupportTypes.SUPPORT_FIXED_VERT:
default:
{
throw new NotImplementedException("Support type drawing ability not defined for support type: " + m_SupportType);
}
}
// Draw the node label
DrawNodeLabel(c, this.X, this.Y, 0);
}
private void DrawNodeLabel(Canvas c, double x, double y, double z, double size=DrawingHelpers.DEFAULT_TEXT_HEIGHT, TextPositions pos=TextPositions.TEXT_ABOVE)
{
double xpos = x;
double ypos = y;
double zpos = z;
switch (pos)
{
case TextPositions.TEXT_ABOVE:
ypos -= 2.5*size;
break;
case TextPositions.TEXT_BELOW:
ypos += 0.5 * size -4;
break;
case TextPositions.TEXT_LEFT:
case TextPositions.TEXT_RIGHT:
default:
throw new NotImplementedException("Invalid text position, " + pos + " detected in DrawText function");
}
// Draw the node icon
DrawingHelpers.DrawCircle(c, this.X, this.Y, Brushes.Black, Brushes.White, DEFAULT_NODE_RADIUS, 1.0);
// Draw the node label text
DrawingHelpers.DrawText(c, xpos, ypos, zpos, Index.ToString(), Brushes.Black, DrawingHelpers.DEFAULT_TEXT_HEIGHT);
// Draw the node label icon
DrawingHelpers.DrawCircleHollow(c, xpos+3, ypos+8, Brushes.Black, 1.5 * DrawingHelpers.DEFAULT_TEXT_HEIGHT);
}
}
}
|
using System;
using System.Windows.Forms;
namespace BarPOS
{
static class Program
{
/// <summary>
/// Punto de entrada principal para la aplicación.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AdminScreen adminScreen = new AdminScreen();
adminScreen.StartPosition = FormStartPosition.CenterScreen;
Application.Run(adminScreen);
}
}
}
|
namespace SignalRandUnityDI.Models
{
public interface IIndexViewModel
{
int ClickTotal { get; }
void AddToTotal();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.Content.Services.Interface;
using DFC.ServiceTaxonomy.GraphSync.Extensions;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Parts;
using DFC.ServiceTaxonomy.PageLocation.Constants;
using DFC.ServiceTaxonomy.PageLocation.Models;
using DFC.ServiceTaxonomy.PageLocation.Services;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata;
namespace DFC.ServiceTaxonomy.PageLocation.GraphSyncers
{
public class PageLocationPartGraphSyncer : ContentPartGraphSyncer
{
private readonly IPageLocationClonePropertyGenerator _generator;
private readonly IContentItemsService _contentItemsService;
private readonly IContentDefinitionManager _contentDefinitionManager;
public PageLocationPartGraphSyncer(IPageLocationClonePropertyGenerator generator, IContentItemsService contentItemsService, IContentDefinitionManager contentDefinitionManager)
{
_generator = generator;
_contentItemsService = contentItemsService;
_contentDefinitionManager = contentDefinitionManager;
}
public override string PartName => nameof(PageLocationPart);
private static readonly Func<string, string> _pageLocationPropertyNameTransform = n => $"pagelocation_{n}";
private const string
UrlNamePropertyName = "UrlName",
DefaultPageForLocationPropertyName = "DefaultPageForLocation",
FullUrlPropertyName = "FullUrl",
RedirectLocationsPropertyName = "RedirectLocations";
public override async Task AddSyncComponents(JObject content, IGraphMergeContext context)
{
using var _ = context.SyncNameProvider.PushPropertyNameTransform(_pageLocationPropertyNameTransform);
context.MergeNodeCommand.AddProperty<string>(await context.SyncNameProvider.PropertyName(UrlNamePropertyName), content, UrlNamePropertyName);
context.MergeNodeCommand.AddProperty<string>(await context.SyncNameProvider.PropertyName(FullUrlPropertyName), content, FullUrlPropertyName);
var settings = context.ContentTypePartDefinition.GetSettings<PageLocationPartSettings>();
//TODO : if this setting changes, do we need to also check/remove these properties from the node?
if (settings.DisplayRedirectLocationsAndDefaultPageForLocation)
{
context.MergeNodeCommand.AddProperty<bool>(await context.SyncNameProvider.PropertyName(DefaultPageForLocationPropertyName), content, DefaultPageForLocationPropertyName);
context.MergeNodeCommand.AddArrayPropertyFromMultilineString(
await context.SyncNameProvider.PropertyName(RedirectLocationsPropertyName), content,
RedirectLocationsPropertyName);
}
}
public override async Task<(bool validated, string failureReason)> ValidateSyncComponent(
JObject content,
IValidateAndRepairContext context)
{
using var _ = context.SyncNameProvider.PushPropertyNameTransform(_pageLocationPropertyNameTransform);
(bool matched, string failureReason) = context.GraphValidationHelper.StringContentPropertyMatchesNodeProperty(
UrlNamePropertyName,
content,
await context.SyncNameProvider.PropertyName(UrlNamePropertyName),
context.NodeWithRelationships.SourceNode!);
if (!matched)
return (false, $"{UrlNamePropertyName} did not validate: {failureReason}");
(matched, failureReason) = context.GraphValidationHelper.StringContentPropertyMatchesNodeProperty(
FullUrlPropertyName,
content,
await context.SyncNameProvider.PropertyName(FullUrlPropertyName),
context.NodeWithRelationships.SourceNode!);
if (!matched)
return (false, $"{FullUrlPropertyName} did not validate: {failureReason}");
var settings = context.ContentTypePartDefinition.GetSettings<PageLocationPartSettings>();
if (settings.DisplayRedirectLocationsAndDefaultPageForLocation)
{
(matched, failureReason) = context.GraphValidationHelper.BoolContentPropertyMatchesNodeProperty(
DefaultPageForLocationPropertyName,
content,
await context.SyncNameProvider.PropertyName(DefaultPageForLocationPropertyName),
context.NodeWithRelationships.SourceNode!);
if (!matched)
return (false, $"{DefaultPageForLocationPropertyName} did not validate: {failureReason}");
(matched, failureReason) = context.GraphValidationHelper.ContentMultilineStringPropertyMatchesNodeProperty(
RedirectLocationsPropertyName,
content,
await context.SyncNameProvider.PropertyName(RedirectLocationsPropertyName),
context.NodeWithRelationships.SourceNode!);
return matched ? (true, "") : (false, $"{RedirectLocationsPropertyName} did not validate: {failureReason}");
}
return (true, "");
}
public override async Task MutateOnClone(JObject content, ICloneContext context)
{
string? urlName = (string?)content[nameof(PageLocationPart.UrlName)];
string? fullUrl = (string?)content[nameof(PageLocationPart.FullUrl)];
if (string.IsNullOrWhiteSpace(urlName) || string.IsNullOrWhiteSpace(fullUrl))
{
throw new InvalidOperationException($"Cannot mutate {nameof(PageLocationPart)} if {nameof(PageLocationPart.UrlName)} or {nameof(PageLocationPart.FullUrl)} are missing.");
}
List<ContentItem> pages = await _contentItemsService.GetActive(ContentTypes.Page);
string urlSearchFragment = _generator.GenerateUrlSearchFragment(fullUrl);
IEnumerable<ContentItem> existingClones = pages.Where(x => ((string)x.Content[nameof(PageLocationPart)][nameof(PageLocationPart.FullUrl)]).Contains(urlSearchFragment));
var result = _generator.GenerateClonedPageLocationProperties(urlName, fullUrl, existingClones);
content[nameof(PageLocationPart.UrlName)] = result.UrlName;
content[nameof(PageLocationPart.FullUrl)] = result.FullUrl;
content[nameof(PageLocationPart.DefaultPageForLocation)] = false;
content[nameof(PageLocationPart.RedirectLocations)] = null;
}
}
}
|
using System;
using System.Web;
using System.Web.Security;
using BusinessLogic;
using DataAccess;
namespace FirstWebStore.Pages.Account
{
public partial class LoginPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Login.LoggedIn += SetUserIdToSession;
var retUrl = Request.QueryString["returnurl"];
if (retUrl == null)
{
return;
}
LoginMsg.Text = "Please log in or register before placing your order!";
retUrl = HttpUtility.UrlEncode(retUrl);
Login.DestinationPageUrl = retUrl;
RegisterHyperLink.NavigateUrl += "?returnurl=" + retUrl;
}
private void SetUserIdToSession(object sender, EventArgs e)
{
var curUser = Membership.GetUser(Login.UserName);
var userId = (curUser == null)
? Guid.Empty
: (Guid)curUser.ProviderUserKey;
var businessLogicCart = StrMapContainer.GetInstance.GetContainer.GetInstance<BusinessLogicCart>();
businessLogicCart.AnonimCartToNewUser(userId);
Session["UserId"] = userId;
}
}
}
|
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 Parking_Lot_Project
{
public partial class settingPriceFixForm : Form
{
public settingPriceFixForm()
{
InitializeComponent();
}
private void format()
{
//dataGridView_parked.RowTemplate.Height = 80;
dataGridView_list.Columns[0].HeaderCell.Value = "Mã Dịch Vụ";
dataGridView_list.Columns[1].HeaderCell.Value = "Tên Dịch Vụ";
dataGridView_list.Columns[2].HeaderCell.Value = "Giá Tiền";
dataGridView_list.Columns[0].Width = 150;
dataGridView_list.Columns[1].Width = 150;
foreach (DataGridViewRow row in dataGridView_list.Rows)
{
row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
}
for (int i = 0; i < dataGridView_list.Rows.Count; ++i)
{
if (i % 2 != 0)
{
dataGridView_list.Rows[i].DefaultCellStyle.BackColor = Color.MediumSlateBlue;
dataGridView_list.Rows[i].DefaultCellStyle.ForeColor = Color.Gold;
}
else
{
dataGridView_list.Rows[i].DefaultCellStyle.BackColor = Color.Gold;
dataGridView_list.Rows[i].DefaultCellStyle.ForeColor = Color.MediumSlateBlue;
}
}
dataGridView_list.AllowUserToAddRows = false;
}
private void settingPriceFixForm_Load(object sender, EventArgs e)
{
DataTable table = Worker.Instance.getAllSerVice(2);
dataGridView_list.DataSource = table;
format();
}
private void materialButton_update_Click(object sender, EventArgs e)
{
int id = int.Parse(materialTextBox_id.Text);
int price = int.Parse(materialTextBox_price.Text);
if (Price.Instance.updatePriceFix(id,price) == true)
{
MessageBox.Show("Cập Nhật thành công");
}
}
private void dataGridView_list_DoubleClick(object sender, EventArgs e)
{
materialTextBox_id.Text = dataGridView_list.CurrentRow.Cells[0].Value.ToString();
materialTextBox_name.Text = dataGridView_list.CurrentRow.Cells[1].Value.ToString();
materialTextBox_price.Text = dataGridView_list.CurrentRow.Cells[2].Value.ToString();
}
private void label1_Click(object sender, EventArgs e)
{
settingPriceFixForm_Load(null, null);
}
}
}
|
namespace FixEmails
{
using System;
using System.Collections.Generic;
using System.Text;
public class Startup
{
public static void Main(string[] args)
{
Console.WriteLine(Execute());
}
private static string Execute()
{
var name = Console.ReadLine();
var users = new Dictionary<string, string>();
var res = new StringBuilder();
while (name != "stop")
{
var email = Console.ReadLine();
if (!(email.EndsWith("us") || email.EndsWith("uk") ||
email.EndsWith("US") || email.EndsWith("UK")))
{
users.Add(name, email);
}
name = Console.ReadLine();
}
foreach (var user in users)
{
res.AppendLine($"{user.Key} -> {user.Value}");
}
return res.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AxisPosCore;
using AxisPosCore.Common;
using KartObjects;
using KartObjects.Entities;
namespace AxisPosCore
{
/// <summary>
/// Действие продажа товара
/// </summary>
public class GoodSaleActionExecutor:POSActionExecutor
{
public GoodSaleActionExecutor(POSActionMnemonic action)
: base(action)
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Idle);
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Specification);
}
public GoodSaleActionExecutor()
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Idle);
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Specification);
}
public override void CheckCondition(PosCore model, params object[] args)
{
if ((!(ValidRegistrationModes.Contains(model.RegistrationState.StateMode )))||((model.CurrState is POSMenuState )))
{
var nfe = new POSException("Невозможно выполнить действие '"+action.GetDescription()+"' в данном режиме");
nfe.CashierTip = "В режиме \"" + model.RegistrationState.StateMode.ToString() + "\" выполнить операцию невозможно";
nfe.ExSource = this.ToString();
throw nfe;
}
}
/// <summary>
/// Товар который продаем
/// </summary>
protected Good g;
/// <summary>
/// Текущая позиция чека
/// </summary>
protected ReceiptSpecRecord currReceiptSpecRecord;
/// <summary>
/// поиск товара
/// </summary>
protected virtual bool FindGood(PosCore model,params object[] args)
{
return true;
}
/// <summary>
/// Изменение записи
/// </summary>
protected virtual void ModifyRecord(PosCore model)
{
}
protected override void InnerExecute(PosCore model, params object[] args)
{
if (!FindGood(model, args))
{
POSEnvironment.SendEvent(TypeExtEvent.eeGoodNotFound,POSEnvironment.CurrReceipt, args);
return;
}
if (!DataDictionary.GetParamBoolValue(PosParameterType.EnableZeroPriceSale))
if (g.Price == 0) throw new POSException("Нельзя продать по нулевой цене!");
if ((g.DenySaleTimeBegin != null) && (g.DenySaleTimeEnd != null))
{
bool DenyFlag = false;
if (((DateTime)g.DenySaleTimeBegin) > ((DateTime)g.DenySaleTimeEnd))
{
if ((((DateTime)g.DenySaleTimeBegin).TimeOfDay < DateTime.Now.TimeOfDay) || ((DateTime)g.DenySaleTimeEnd).TimeOfDay > DateTime.Now.TimeOfDay)
DenyFlag = true;
}
else
if ((((DateTime)g.DenySaleTimeBegin).TimeOfDay < DateTime.Now.TimeOfDay) && ((DateTime)g.DenySaleTimeEnd).TimeOfDay > DateTime.Now.TimeOfDay)
DenyFlag = true;
if (DenyFlag)
{
if (POSEnvironment.BCScanner != null)
POSEnvironment.BCScanner.SendBell();
throw new POSException("Для этого товара установлено ограничение продажи по времени!");
}
}
if (POSEnvironment.CurrReceipt == null)
{
POSEnvironment.NewReceipt();
POSEnvironment.SendEvent(TypeExtEvent.eeBeginCheck);
model.RegistrationState.CurrPayType = DataDictionary.SPayTypes[0];
}
long idassortment = DataDictionary.GetIdAssortByIdGood(g.Id);
if (g.Measure == null)
g.Measure = DataDictionary.SMeasures.FirstOrDefault(q => q.Id == g.IdMeasure);
currReceiptSpecRecord = new ReceiptSpecRecord() { IdGood = g.Id, NumPos = POSEnvironment.CurrReceipt.ReceiptSpecRecords.Count + 1, Name = g.Name, IdReceipt = POSEnvironment.CurrReceipt.Id, Quantity = 1, Price = g.Price, DiscountSum = 0, PromoActionEnabled=g.PromoActionEnabled,Good=g,IdAssortment=idassortment,IdOrganization = g.IdOrganization};
POSEnvironment.CurrReceipt.ReceiptSpecRecords.Add(currReceiptSpecRecord);
ModifyRecord(model);
POSEnvironment.Log.WriteToLog("Цена " + currReceiptSpecRecord.Price.ToString("0.00"));
if (currReceiptSpecRecord.Quantity>1)
POSEnvironment.Log.WriteToLog("Кол-во " + currReceiptSpecRecord.Quantity.ToString("0.00"));
model.RegistrationState.CurrPos = POSEnvironment.CurrReceipt.ReceiptSpecRecords.Count ;
//Отправляем событие
if (this is ArticulSaleActionExecutor)
POSEnvironment.SendEvent(TypeExtEvent.eeGoodInsertArticul, POSEnvironment.CurrReceipt, model.RegistrationState.CurrPos);
//else
POSEnvironment.SendEvent(TypeExtEvent.eeGoodInsert, POSEnvironment.CurrReceipt, model.RegistrationState.CurrPos);
POSEnvironment.CustomerDisplayEo.ShowCurrentSale(POSEnvironment.CurrReceipt, model.RegistrationState.CurrPos);
model.PosEnvironment.SaveCurrReceipt();
if (model.RegistrationState.StateMode ==POSRegistrationState.RegistrationStateMode.Idle)
model.RegistrationState.StateMode = POSRegistrationState.RegistrationStateMode.Specification;
}
}
}
|
using System;
using System.Data;
using System.Data.Common;
namespace Kaax
{
internal sealed class DefaultDbConnectionProvider : IDbConnectionProvider
{
private readonly DbProviderFactory dbProviderFactory;
private readonly string connectionString;
public DefaultDbConnectionProvider(DbProviderFactory dbProviderFactory, string connectionString)
{
this.dbProviderFactory = dbProviderFactory ?? throw new ArgumentNullException(nameof(dbProviderFactory));
this.connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
}
public IDbConnection GetConnection()
{
var connection = dbProviderFactory.CreateConnection();
connection.ConnectionString = connectionString;
return connection;
}
}
}
|
using System;
using System.IO;
using SQLite;
using Xamarin.Forms;
using FuelRadar.Data;
using FuelRadar.Droid.Data;
[assembly: Dependency(typeof(AndroidSqliteProvider))]
namespace FuelRadar.Droid.Data
{
/// <summary>
/// The android implementation of the sqlite database interface
/// </summary>
public class AndroidSqliteProvider : ISqliteProvider
{
private const String DB_NAME = "FuelRadar.db3";
public SQLiteConnection GetConnection()
{
String documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return new SQLiteConnection(Path.Combine(documentsPath, DB_NAME));
}
}
}
|
//lesson1 习题
//21.4.21
using System;
namespace Lesson1_exercise
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Lesson1_exercise");
//2.
//Console.WriteLine("请输入用户名");
//Console.ReadLine();
//Console.WriteLine("请输入年龄");
//Console.ReadLine();
//Console.WriteLine("请输入性别");
//Console.ReadLine();
//3.
//Console.WriteLine("您喜欢什么运动");
//Console.ReadLine();
//Console.WriteLine("哈哈,好巧,我也喜欢这个运动");
//4.
Console.WriteLine("**********");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("* *");
Console.WriteLine("**********");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ParkingSystem
{
public class Startup
{
public static void Main(string[] args)
{
Console.WriteLine(Execute());
}
private static string Execute()
{
var args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var n = int.Parse(args[0]);
var m = int.Parse(args[1]);
var dict = new Dictionary<int, bool[]>();
var rowFull = new Dictionary<int, bool>();
var builder = new StringBuilder();
args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
while (!string.Join(" ", args).Equals("stop"))
{
var z = int.Parse(args[0]);
var x = int.Parse(args[1]);
var y = int.Parse(args[2]);
var distance = Math.Abs(z - y);
if (!dict.ContainsKey(x))
{
dict.Add(x, new bool[m]);
rowFull.Add(x, false);
}
if (rowFull[x])
{
builder.AppendLine($"Row {x} full");
}
else if (!dict[x][y])
{
dict[x][y] = true;
distance += y + 1;
builder.AppendLine(distance.ToString());
}
else if (dict[x][y])
{
var left = -1; var right = -1;
for (int i = y - 1; i >= 0; i--)
{
if (!dict[x][i])
{
left = i;
break;
}
}
for (int i = y + 1; i < m; i++)
{
if (!dict[x][i])
{
right = i;
break;
}
}
if ((left == -1 || left == 0) && right == -1)
{
rowFull[x] = true;
builder.AppendLine($"Row {x} full");
}
else
{
if (y - left > right - y || left == 0)
{
dict[x][right] = true;
distance += right - y;
}
else if (y - left == right - y)
{
dict[x][left] = true;
distance += y - left;
}
else if (y - left < right - y)
{
dict[x][left] = true;
distance = y - left;
}
distance++;
builder.AppendLine(distance.ToString());
}
}
args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
return builder.ToString();
}
}
}
|
namespace ServerFramework.Model
{
class UserData
{
public UserData() { }
public UserData( string username, string password)
{
this.Username = username;
this.Password = password;
}
public string Username { get; set; }
public string Password { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class PressurePlate : MonoBehaviour
{
public UnityEvent onPressed;
public UnityEvent onReleased;
public SpriteRenderer visual;
private int pressers;
AudioSource audio;
private void Start()
{
audio = GetComponent<AudioSource>();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.isTrigger)
return;
pressers++;
if (pressers == 1)
{
onPressed.Invoke();
if (visual)
{
var scale = visual.transform.localScale;
scale.y = 0.1f;
visual.transform.localScale = scale;
visual.color = Color.gray;
}
if (audio)
audio.Play();
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.isTrigger)
return;
pressers--;
if (pressers == 0)
{
onReleased.Invoke();
if (visual)
{
var scale = visual.transform.localScale;
scale.y = 0.2f;
visual.transform.localScale = scale;
visual.color = Color.white;
}
if (audio)
audio.Play();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractsInterfaces
{
interface IFirstL5
{
int Number { get; set; }
int this[int k] { get; }
}
interface ISecondL5
{
void SetNum(int n);
int GetNum();
}
interface IMyInterfaceL5 : IFirstL5, ISecondL5
{
void Show();
}
class MyClassL5:IMyInterfaceL5
{
private int Num;
public MyClassL5(int n)
{
Number = n;
Show();
}
public int GetNum()
{
return Num;
}
public void SetNum(int n)
{
Num = n;
}
public int Number
{
get { return GetNum(); }
set { SetNum(value); }
}
public int this[int k]
{
get
{
int r = Number;
for(int i = 0; i < k; i++)
{
r /= 10;
}
return r % 10;
}
}
public void Show()
{
Console.WriteLine("Prop Number = "+ Number);
}
}
internal class InterfaceDemoL5
{
public static void Main05()
{
int m = 9;
MyClassL5 Obj = new MyClassL5(12345);
for (int i = 0; i <= m; i++)
{
Console.Write("|" + Obj[m - i]);
}
Console.WriteLine("|");
}
}
}
|
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Nailhang.IndexBase.Storage;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nailhang.Mongodb.ModulesStorage.Processing
{
class MongoStorage : IModulesStorage
{
readonly IMongoCollection<ModuleEntity> modules;
public MongoStorage(IMongoDatabase database)
{
modules = database.GetCollection<ModuleEntity>("modules");
}
public void StoreModule(IndexBase.Module module)
{
var mentity = new ModuleEntity
{
ModuleHeader = JsonConvert.SerializeObject(module),
Id = module.FullName.GenerateGuid(),
FullName = module.FullName
};
var filter = Builders<ModuleEntity>.Filter.Where(w => w.Id == mentity.Id);
var replaceResult = modules.ReplaceOne(filter, mentity, new ReplaceOptions { IsUpsert = true });
}
public IEnumerable<IndexBase.Module> GetModules()
{
foreach (var moduleEntity in modules.AsQueryable())
yield return ToModule(moduleEntity.ModuleHeader);
}
IndexBase.Module ToModule(string header)
{
return JsonConvert.DeserializeObject<IndexBase.Module>(header);
}
public void DropModules(string namespaceStartsWith)
{
if (string.IsNullOrEmpty(namespaceStartsWith))
modules.DeleteMany(new MongoDB.Bson.BsonDocument());
else
modules.DeleteMany(Builders<ModuleEntity>.Filter
.Where(w => w
.FullName
.StartsWith(namespaceStartsWith)));
}
}
}
|
using UnityEngine;
using System.Collections;
public class GuideAction : MonoBehaviour {
private bool isTapedDisplay;
private bool isReleasedDisplay;
public static bool isPress;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (isTapedDisplay && isReleasedDisplay) {
isTapedDisplay = isReleasedDisplay = false;
isPress = true;
}
}
void DisplayPressed() {
isTapedDisplay = true;
}
void DisplayReleased() {
isReleasedDisplay = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
namespace HMW_HP_department
{
/// <summary>
/// Interaction logic for WorkerAdding.xaml
/// </summary>
public partial class WorkerAdding : Window
{
XmlDataProvider xdp;
public WorkerAdding()
{
InitializeComponent();
xdp = (XmlDataProvider)this.FindResource("provider2");
}
private void addButton_Click(object sender, RoutedEventArgs e)
{
List<string> studentInfo = new List<string>();
foreach (var item in panel1.Children)
if (item is TextBox)
studentInfo.Add((item as TextBox).Text);
XmlDocument doc = new XmlDocument();
string path = @"..\..\Data\workers.xml";
doc.Load(path);
//< worker id = "1" photo = "Images/worker1.png" name = "Leonid" surname = "Leonenkov" middlename = "Sergeevich" birthdate = "21.05.1989" specialization = "office man" position = "office worker" did = "1" dname = "office" />
string[] strings = new string[] { "id", "photo", "name", "surname", "middlename", "birthdate","specialization","position","did","dname" };
XmlElement root = doc.DocumentElement;
XmlElement node = doc.CreateElement("worker");
XmlAttribute[] attributes = new XmlAttribute[strings.Length];
for (int i = 0; i < strings.Length; i++)
attributes[i] = doc.CreateAttribute(strings[i]);
XmlText[] texts = new XmlText[strings.Length];
for (int i = 0; i < strings.Length; i++)
texts[i] = doc.CreateTextNode(studentInfo[i]);
for (int i = 0; i < strings.Length; i++)
attributes[i].AppendChild(texts[i]);
for (int i = 0; i < strings.Length; i++)
node.Attributes.Append(attributes[i]);
root.AppendChild(node);
doc.Save(path);
xdp.Document = doc;
DialogResult = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nailhang.Display.Tools.TextSearch.Base
{
public struct Request
{
public string Message { get; set; }
public float TargetRelevance { get; set; }
}
}
|
using System;
using System.Collections;
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 ProyectoBolera
{
public partial class EmpleadosForm : Form
{
public EmpleadosForm()
{
InitializeComponent();
}
private void TxtCedula_KeyPress(object sender, KeyPressEventArgs e)
{
Validacion.soloNumeros(sender, e);
}
private void TxtNombre_KeyPress(object sender, KeyPressEventArgs e)
{
Validacion.soloTexto( sender, e);
}
private void TxtApellido_KeyPress(object sender, KeyPressEventArgs e)
{
Validacion.soloTexto(sender, e);
}
private void registrarEmpleado() {
string queryCount = String.Format($"SELECT COUNT(*) FROM empleados WHERE idempleado = '{txtCedula.Text}'");
if (!Validacion.validarSiExisteRegistro(queryCount))
{
queryCount = String.Format($"SELECT COUNT(*) FROM usuarios WHERE usuario = '{txtUser.Text}'");
if (!Validacion.validarSiExisteRegistro(queryCount))
{
string query = String.Format($"INSERT INTO empleados VALUES ('{txtCedula.Text}','{txtNombre.Text}','{txtApellido.Text}','{combTipUsuario.SelectedValue.ToString()}')");
Conexion.getQuery(query);
query = String.Format($"INSERT INTO usuarios (usuario, passw, idempleado, tipousuario) VALUES ('{txtUser.Text}','{txtPassword.Text}','{txtCedula.Text}','{combTipUsuario.SelectedValue.ToString()}')");
Conexion.getQuery(query);
MessageBox.Show("Registro Existoso");
llenarDataGrid();
limpiarFormulario();
}
else {
MessageBox.Show("El usuario ya se encuentra registrada en la base de datos");
}
}
else {
MessageBox.Show("La cedula ya se encuentra registrada en la base de datos");
}
}
private void actualizarEmpleado() {
string query = String.Format($"UPDATE empleados SET nombre = '{txtNombre.Text}', apellido = '{txtApellido.Text}', tipo_empleadoid ='{combTipUsuario.SelectedValue.ToString()}' WHERE idempleado = '{txtCedula.Text}'");
Conexion.getQuery(query);
query = String.Format($"UPDATE usuarios SET passw = '{txtPassword.Text}', tipousuario ='{combTipUsuario.SelectedValue.ToString()}' WHERE usuario = '{txtUser.Text}'");
Conexion.getQuery(query);
limpiarFormulario();
llenarDataGrid();
MessageBox.Show("Se ha actualizado el registro con exito");
}
private void llenarDataGrid() {
string query = String.Format($"SELECT empleados.idempleado AS Identificacion, empleados.nombre AS Nombre, apellido, tipoempleado.nombre AS Categoria, usuario, passw FROM empleados INNER JOIN tipoempleado ON tipoempleado.idtipo = empleados.tipo_empleadoid INNER JOIN usuarios ON usuarios.idempleado = empleados.idempleado");
DataSet ds = Conexion.getQuery(query);
if (ds != null)
{
dtgEmpleados.DataSource = ds.Tables[0];
}
}
private void llenarCombobox() {
string query = String.Format($"SELECT idtipo, nombre FROM tipoempleado");
DataSet ds = Conexion.getQuery(query);
if (ds != null)
{
combTipUsuario.DataSource = ds.Tables[0];
combTipUsuario.DisplayMember = "nombre";
combTipUsuario.ValueMember = "idtipo";
}
//combTipUsuario.SelectedValue.ToString()
}
private void limpiarFormulario() {
txtCedula.Text = "";
txtNombre.Text = "";
txtApellido.Text = "";
combTipUsuario.Text = "";
txtUser.Text = "";
txtPassword.Text = "";
}
private void BtnRegistrar_Click(object sender, EventArgs e)
{
if (validarCamporVacios())
{
if (btnRegistrar.Text == "Registrar")
{
if (Validacion.validarPassword(txtPassword.Text))
{
registrarEmpleado();
}
}
else
{
actualizarEmpleado();
}
}else {
MessageBox.Show("Faltan datos por completar");
}
}
private bool validarCamporVacios() {
bool valido = false;
if (txtCedula.Text != "" && txtNombre.Text != "" && txtApellido.Text != "" && txtPassword.Text != "" && txtUser.Text != "") {
valido = true;
}
return valido;
}
private void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
btnRegistrar.Text = "Registrar";
txtCedula.Enabled = true;
txtUser.Enabled = true;
}
private void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
btnRegistrar.Text = "Actualizar";
txtCedula.Enabled = false;
txtUser.Enabled = false;
limpiarFormulario();
}
private void EmpleadosForm_Load(object sender, EventArgs e)
{
llenarDataGrid();
llenarCombobox();
llenarCombFiltrar();
}
private void DtgEmpleados_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
txtCedula.Text = dtgEmpleados.CurrentRow.Cells[0].Value.ToString();
txtNombre.Text = dtgEmpleados.CurrentRow.Cells[1].Value.ToString();
txtApellido.Text = dtgEmpleados.CurrentRow.Cells[2].Value.ToString();
combTipUsuario.Text = dtgEmpleados.CurrentRow.Cells[3].Value.ToString();
txtUser.Text = dtgEmpleados.CurrentRow.Cells[4].Value.ToString();
txtPassword.Text = dtgEmpleados.CurrentRow.Cells[5].Value.ToString();
//string query = String.Format($"SELECT idempleado AS Identificacion, empleados.nombre AS Nombre, apellido, tipo_empleadoid AS TipoID, tipoempleado.nombre AS Categoria, usuario, passw FROM empleados INNER JOIN tipoempleado ON tipoempleado.idtipo = empleados.tipo_empleadoid INNER JOIN usuarios ON usuarios.idempleado = empleados.idempleado");
}
private void BtnBuscar_Click(object sender, EventArgs e)
{
string query = String.Format($"SELECT empleados.idempleado AS Identificacion, empleados.nombre AS Nombre, apellido, tipoempleado.nombre AS Categoria, usuario, passw FROM empleados INNER JOIN tipoempleado ON tipoempleado.idtipo = empleados.tipo_empleadoid INNER JOIN usuarios ON usuarios.idempleado = empleados.idempleado WHERE {combFiltrar.SelectedValue} LIKE '%{txtBuscar.Text}%'");
DataSet ds = Conexion.getQuery(query);
if (ds != null)
{
dtgEmpleados.DataSource = ds.Tables[0];
}
}
private void llenarCombFiltrar() {
var items = new List<Options>
{
new Options() { Name="Identificacion", Value="empleados.idempleado"},
new Options() { Name="Nombre", Value="empleados.nombre"},
new Options() { Name="Apellido", Value="empleados.apellido"},
new Options() { Name="Categoria", Value="tipoempleado.nombre"},
new Options() { Name="Usuario", Value="usuarios.usuario"},
};
combFiltrar.DataSource = items;
combFiltrar.DisplayMember = "Name";
combFiltrar.ValueMember = "Value";
}
public class Options
{
public string Name { get; set; }
public string Value { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FIVIL.Litentity
{
public class SessionData
{
public const int Version = 1;
}
}
|
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using NLog.Web;
namespace LighterApi
{
public class Program
{
public static void Main(string[] args)
{
//CreateHostBuilder(args).Build().Run();
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
/* 使用泛型主机 (IHostBuilder) 时,只能将以下服务类型注入 Startup 构造函数:
IWebHostEnvironment / IHostEnvironment / IConfiguration
*/
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
//配置web服务主机
.ConfigureWebHostDefaults(webHostBuilder =>
{
//ASP.NET Core 项目模板默认使用 Kestrel。
//若要在调用 ConfigureWebHostDefaults 后提供其他配置,请使用 ConfigureKestrel:
//webBuilder.ConfigureKestrel(serverOptions =>
//{
// //配置 Kestrel
//})
webHostBuilder.UseWebRoot("StaticFile");
webHostBuilder.UseStartup<Startup>();
})
//.UseContentRoot(Directory.GetCurrentDirectory())
//NLog 配置
//.ConfigureLogging(logging =>
// {
// logging.ClearProviders();
// logging.SetMinimumLevel(LogLevel.Trace);
// })
//.UseNLog()
#region 文件配置提供程序
//.ConfigureAppConfiguration((hostingContext, config) =>
//{
// config.Sources.Clear();
// var env = hostingContext.HostingEnvironment;
// config.AddIniFile("MyIniConfig.ini", optional: true, reloadOnChange: true)
// .AddIniFile($"MyIniConfig.{env.EnvironmentName}.ini",
// optional: true, reloadOnChange: true);
// config.AddJsonFile("MyIniConfig.ini", optional: true, reloadOnChange: true)
// .AddJsonFile($"MyIniConfig.{env.EnvironmentName}.ini",
// optional: true, reloadOnChange: true);
// config.AddXmlFile("MyIniConfig.ini", optional: true, reloadOnChange: true)
// .AddXmlFile($"MyIniConfig.{env.EnvironmentName}.ini",
// optional: true, reloadOnChange: true);
// config.AddEnvironmentVariables();//环境变量
// if (args != null)
// config.AddCommandLine(args); //命令行
//})
#endregion
//作用域验证
//.UseDefaultServiceProvider((context, options) => {
// options.ValidateScopes = true;
//})
//StartupFilter 注册中间件方式1
//.ConfigureServices(services =>
// services.AddTransient<IStartupFilter, RequestSetOptionsStartupFilter>()
//)
;
};
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmallBedroom : Room
{
protected Rect GenerateCornerBed(Furniture bedPrefab)
{
Orientation orientation = Random.value < .5 ? Orientation.Horizontal : Orientation.Vertical;
int bedWidth = orientation == Orientation.Horizontal ? 3 : 2;
int bedHeight = orientation == Orientation.Vertical ? 3 : 2;
Vector2Int bottomLeftCorner = new Vector2Int(x, y);
Vector2Int bottomRightCorner = new Vector2Int(x + width - bedWidth, y);
Vector2Int topLeftCorner = new Vector2Int(x, y + height - bedHeight);
Vector2Int topRightCorner = new Vector2Int(x + width - bedWidth, y + height - bedHeight);
List<Vector2Int> availablePositions = new List<Vector2Int>();
Rect rect = new Rect(0, 0, bedWidth, bedHeight);
rect.position = bottomLeftCorner;
if (!ObstructsDoorway(rect))
availablePositions.Add(bottomLeftCorner);
rect.position = bottomRightCorner;
if (!ObstructsDoorway(rect))
availablePositions.Add(bottomRightCorner);
rect.position = topLeftCorner;
if (!ObstructsDoorway(rect))
availablePositions.Add(topLeftCorner);
rect.position = topRightCorner;
if (!ObstructsDoorway(rect))
availablePositions.Add(topRightCorner);
Vector2Int bedPosition = availablePositions[Random.Range(0, availablePositions.Count)];
if (orientation == Orientation.Horizontal)
{
Furniture bed = InstantiateFurniture(bedPrefab, bedPosition);
CardinalSprite cardinalSprite = bed.GetComponent<CardinalSprite>();
if (cardinalSprite)
cardinalSprite.direction = Random.value < .5 ? Direction.East : Direction.West;
}
else
{
Furniture bed = InstantiateFurniture(bedPrefab, bedPosition);
CardinalSprite cardinalSprite = bed.GetComponent<CardinalSprite>();
if (cardinalSprite)
cardinalSprite.direction = Random.value < .5 ? Direction.North : Direction.South;
}
return new Rect(bedPosition.x, bedPosition.y, bedWidth, bedHeight);
}
}
|
using AI;
using UnityEngine;
using UnityEngine.Assertions;
namespace Views.Enemies
{
[DisallowMultipleComponent]
public class EnemyView : MonoBehaviour
{
private Transform _transform;
private bool _isDead;
public EnemyLogic Logic { set; private get; }
private void Awake()
{
_transform = transform;
}
private void LateUpdate()
{
Assert.IsNotNull(Logic);
if (_isDead) return;
_isDead = Logic.Health <= 0;
if (_isDead)
{
Die();
}
else
{
_transform.localPosition = Logic.GetPosition();
}
}
private void Die()
{
// TODO: Animate effect for the death.
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResidentAppCross
{
public interface IQueryHomeMenuItems
{
}
}
|
using System.Collections.Generic;
using System;
namespace OurClassLibrary
{
public class clsStaffCollection
{
//private data member that stores the counts of records found
private Int32 recordCount;
//private data member to connect to the database
private clsDataConnection myDB = new clsDataConnection();
//private data member for the Staff list
private List<clsStaff> mStaffList = new List<clsStaff>();
private clsStaff mThisStaff;
//public property for count
public int Count
{
get
{
//return the count property of the private list
return mStaffList.Count;
}
set
{
}
}
//public property for Staff
public List<clsStaff> StaffList
{
//getter sends data to requesting code
get
{
//return the private data member
return mStaffList;
}
//setter accepts data from other objects
set
{
//assign the incoming value to the private data member
mStaffList = value;
}
}
public clsStaff ThisStaff
{
get
{
return mThisStaff;
}
set
{
mThisStaff = value;
}
}
public void FindAllStaff()
{
//re-set the data connection
myDB = new clsDataConnection();
//var to store the index
Int32 Index = 0;
//var to store the staff no of the current record
Int32 StaffNo;
//var to flag the staff member was found
Boolean StaffFound;
//execute the stored procedure
myDB.Execute("sproc_tblStaff_SelectAll");
//get the count of records
recordCount = myDB.Count;
//while there are still records to process
while (Index < myDB.Count)
{
//create an instance of the staff class
clsStaff NewStaff = new clsStaff();
//get the staff member from the database
StaffNo = Convert.ToInt32(myDB.DataTable.Rows[Index]["StaffNo"]);
//find the staff member by invoking the find method
StaffFound = NewStaff.Find(StaffNo);
if (StaffFound == true)
{
//add the staff member to the list
mStaffList.Add(NewStaff);
}
//increment the index
Index++;
}
}
//public contstructor for the class
//public clsStaffCollection()
//{
// //create an instance of the dataconnection
// clsDataConnection DB = new clsDataConnection();
// //execute the stored procedure to get the list of data
// DB.Execute("sproc_tblStaff_SelectAll");
// //get the count of records
// Int32 RecordCount = DB.Count;
// //set up the index for the loop
// Int32 Index = 0;
// //while there are records to process
// while (Index < RecordCount)
// {
// //create an instance of the staff class to store a staff member
// clsStaff AStaff = new clsStaff();
// //set the staff member to Sam
// //AStaff.FirstName = DB.DataTable.Rows[Index]["FirstName"].ToString();
// //get the primary key
// AStaff.StaffNo = Convert.ToInt32(DB.DataTable.Rows[Index]["StaffNo"]);
// //add the second county to the private list of staff members
// mStaffList.Add(AStaff);
// //increment the index
// Index++;
// }
// //the private list now contains two staff members
//}
public int Add()
{
//adds a new record to the database
//connect to the database
clsDataConnection DB = new clsDataConnection();
//set the parameters
DB.AddParameter("@StaffNo", mThisStaff.StaffNo);
DB.AddParameter("@FirstName", mThisStaff.FirstName);
DB.AddParameter("@LastName", mThisStaff.LastName);
DB.AddParameter("@Email", mThisStaff.Email);
DB.AddParameter("@PhoneNo", mThisStaff.PhoneNo);
//execute the query
return DB.Execute("sproc_tblStaff_Add");
}
void PopulateArray(clsDataConnection DB)
{
//populates the array list based on the data table in the parameter DB
//var for thje index
Int32 Index = 0;
//var to store the record count
Int32 RecordCount;
//get the count of records
RecordCount = DB.Count;
//clear the private array list
mStaffList = new List<clsStaff>();
//while there are records to process
while (Index < RecordCount)
{
//create a blank sale
clsStaff AStaff = new clsStaff();
//read in the fields from the current record
AStaff.StaffNo = Convert.ToInt32(DB.DataTable.Rows[Index]["StaffNo"]);
AStaff.FirstName = Convert.ToString(DB.DataTable.Rows[Index]["FirstName"]);
AStaff.LastName = Convert.ToString(DB.DataTable.Rows[Index]["LastName"]);
AStaff.Email = Convert.ToString(DB.DataTable.Rows[Index]["Email"]);
AStaff.PhoneNo= Convert.ToString(DB.DataTable.Rows[Index]["PhoneNo"]);
//add the record to the private data member
mStaffList.Add(AStaff);
//point at the next record
Index++;
}
}
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
[JsonObject(MemberSerialization.Fields)]
public class TokenString
{
string _text;
public TokenString(string text)
{
_text = text;
}
public string FillWith(CardInfo info)
{
return TokenHelpers.FillAllTokensIn(_text, info);
}
public IEnumerable<Token> GetAllTokens()
{
return TokenHelpers.GetAllTokensFrom(_text);
}
public override string ToString()
{
return "Token: " + _text;
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace ServiceQuotes.Application.Helpers
{
public class NotDefaultAttribute : ValidationAttribute
{
public const string DefaultErrorMessage = "The {0} field must not have the default value";
public NotDefaultAttribute() : base(DefaultErrorMessage) { }
public override bool IsValid(object value)
{
//NotDefault doesn't necessarily mean required
if (value is null)
{
return true;
}
var type = value.GetType();
if (type.IsValueType)
{
var defaultValue = Activator.CreateInstance(type);
return !value.Equals(defaultValue);
}
// non-null ref type
return true;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace hoosa
{
public class Tower
{
private Transform transform;
float timer;
public float FireRate;
public int FireDamage;
public int Price;
public float range = 15f;
Ray shootRay = new Ray();
RaycastHit shootHit;
ParticleSystem gunParticles;
Light gunLight;
LineRenderer gunLine;
int shootableMask;
// private Enemy targetEnemy;
private Transform target;
public Transform partToRotate;
public float turnSpeed = 10f;
public string enemyTag = "Enemy";
void Start()
{
}
void Update()
{
if (Input.GetButton("Fire1") && timer >= FireRate && Time.timeScale != 0)
{
// UpdateTarget();
// LockOnTarget();
Turning();
//Shoot();
}
if (timer >= FireRate * (0.5))
{
DisableEffects();
}
}
public void DisableEffects()
{
gunLine.enabled = false;
gunLight.enabled = false;
}
void Turning()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(camRay))
{
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
}
void LockOnTarget()
{
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
void UpdateTarget()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
float shortestDistance = Mathf.Infinity;
GameObject nearestEnemy = null;
foreach (GameObject enemy in enemies)
{
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
if (distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}
if (nearestEnemy != null && shortestDistance <= range)
{
target = nearestEnemy.transform;
// targetEnemy = nearestEnemy.GetComponent<Enemy>();
}
else
{
target = null;
}
}
void Shoot()
{
timer = 0f;
gunLight.enabled = true;
gunParticles.Stop();
gunParticles.Play();
gunLine.enabled = true;
gunLine.SetPosition(0, transform.position);
if (Physics.Raycast(shootRay, out shootHit, range, shootableMask))
{
// EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>();
// if (enemyHealth != null)
{
// enemyHealth.TakeDamage(FireDamage, shootHit.point);
}
gunLine.SetPosition(1, shootHit.point);
}
else
{
gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GrpcServer.Repository.DBModels;
using GrpcServer.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using System.Configuration;
using Microsoft.Extensions.Configuration;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using System.Text;
using Grpc.Core;
namespace GrpcServer
{
public class Startup
{
//private DBContext db;
//// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// private DBContext db;
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc(options => {
options.MaxReceiveMessageSize = 200 * 1024 * 1024; // 200 MB
options.MaxSendMessageSize = 550 * 1024 * 1024; // 550 MB
});
services.AddDbContext<DBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("grpcDBConn")));
services.AddGrpc(options =>
{
options.EnableDetailedErrors = true;
});
services.AddAuthorization(options =>
{
options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireClaim(ClaimTypes.Name);
});
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateActor = false,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.Default.GetBytes("gRPC-DB-Adriatik-Ademi-Secret-Key-Gen"))
};
});
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DBContext _db)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseStatusCodePages(async context =>
{
if (context.HttpContext.Response.StatusCode == 401)
throw new RpcException(new Status(StatusCode.PermissionDenied, "Nuk keni autorizim!"));
else
throw new RpcException(new Status(StatusCode.PermissionDenied, "Ka ndodhur nje gabim!"));
});
app.Use(async (context, next) =>
{
await next();
// If response is unauthorized and the endpoint is a gRPC method then
// return grpc-status permission denied instead
if (context.Response.StatusCode == StatusCodes.Status401Unauthorized)
{
throw new RpcException(new Status(StatusCode.PermissionDenied, "Nuk keni autorizim!"));
}
});
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
endpoints.MapGrpcService<CustomerService>();
endpoints.MapGrpcService<ChattingService>();
endpoints.MapGrpcService<AuthService>();
endpoints.MapGrpcService<SalesService>();
endpoints.MapGrpcService<ProductsService>();
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Komunikimi me endpoints te gRPC duhet te behete me ane te nje gRPC klienti!"/*"Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"*/);
});
endpoints.MapGet("/generateJwtToken", context =>
{
return context.Response.WriteAsync(GenerateJwtToken(context.Request.Query["name"]));
});
});
}
private string GenerateJwtToken(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new InvalidOperationException("Name is not specified.");
}
var claims = new[] { new Claim(ClaimTypes.Name, name), new Claim(ClaimTypes.Role, "admin") };
var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken("gRPCServer", "Clients", claims, expires: DateTime.Now.AddSeconds(60), signingCredentials: credentials);
return JwtTokenHandler.WriteToken(token);
}
private readonly JwtSecurityTokenHandler JwtTokenHandler = new JwtSecurityTokenHandler();
private readonly SymmetricSecurityKey SecurityKey = new SymmetricSecurityKey(Guid.NewGuid().ToByteArray());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Imp.Core.Domain.Users;
namespace Imp.Data.Mapping.Users
{
/// <summary>
/// role map
/// </summary>
public class RoleMap : BaseEntityMap<Role>
{
public RoleMap()
{
this.ToTable("T_Role");
this.Property(m => m.Name).IsRequired().HasColumnName("Name");
this.Property(m => m.SystemName).HasColumnName("SystemName");
this.Property(m => m.DisplayOrder).HasColumnName("DisplayOrder");
this.Property(m => m.Deleted).HasColumnName("Deleted");
this.HasMany(m => m.Permissions)
.WithMany()
.Map(m =>
{
m.ToTable("T_Role_Permission_Mapping");
m.MapLeftKey("RoleId");
m.MapRightKey("PermissionId");
});
}
}
}
|
namespace ComputeGame.MathExampleHandler
{
public class Example
{
public string Result { get; set; }
public int Count { get; set; }
public string Content { get; set; }
public int Points { get; set; }
public DifficultyLevel DifficultyLevel { get; set; }
public Example(string content, int result, int points)
{
Result = result.ToString();
Content = content;
Points = points;
}
}
}
|
using System;
namespace WaveShaper.Core.PiecewiseFunctions
{
public class PiecewiseFunctionInputOutOfRange : ArgumentOutOfRangeException
{
public PiecewiseFunctionInputOutOfRange()
{
}
public PiecewiseFunctionInputOutOfRange(string paramName) : base(paramName)
{
}
public PiecewiseFunctionInputOutOfRange(string paramName, object actualValue, string message) : base(paramName, actualValue, message)
{
}
}
}
|
using RMS.BO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RMS.DAL
{
public class ProduktetDAL
{
public void InsertProduct(Produkti model)
{
using (DatabaseConn.conn = new SqlConnection(DatabaseConn.connString))
{
DatabaseConn.conn.Open();
DatabaseConn.command = new SqlCommand("usp_InsertProduct", DatabaseConn.conn)
{
CommandType = CommandType.StoredProcedure
};
DatabaseConn.command.Parameters.AddWithValue("@Emri", model.Emri);
DatabaseConn.command.Parameters.AddWithValue("@Madhesia", model.Madhesia);
DatabaseConn.command.Parameters.AddWithValue("@Cmimi", model.Cmimi);
DatabaseConn.command.Parameters.AddWithValue("@InsertBy", 1);
DatabaseConn.command.Parameters.AddWithValue("@InsertDate", DateTime.Now);
//command.Parameters.AddWithValue("@LUD");
//command.Parameters.AddWithValue("@LUN");
//command.Parameters.AddWithValue("@LUB");
DatabaseConn.command.ExecuteNonQuery();
DatabaseConn.conn.Close();
}
}
public DataTable ShowProduktet()
{
using (DatabaseConn.conn = new SqlConnection(DatabaseConn.connString))
{
DatabaseConn.conn.Open();
DatabaseConn.dataAdapter = new SqlDataAdapter("usp_GetProduktet", DatabaseConn.conn);
DataTable dataTable = new DataTable();
DatabaseConn.dataAdapter.Fill(dataTable);
DatabaseConn.conn.Close();
return dataTable;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BE;
using PL.ViewModel;
namespace PL.Views
{
/// <summary>
/// Logique d'interaction pour IceCreamShopUC.xaml
/// </summary>
public partial class IceCreamShopUC : UserControl
{
public Shop shop { get; set; }
public IceCream iceCream { get; set; }
public IceCreamShopVM IceCreamShopVM { get; set; }
public SearchIceCreamUC SearchIceCreamUC { get; set; }
public GraduationUC GraduationUC { get; set; }
public ProfileBarIceCreamUC ProfileBarIceCreamUC { get; set; }
public IceCreamShopUC(Shop shop,IceCream iceCream)
{
InitializeComponent();
this.shop = shop;
this.iceCream = iceCream;
this.IceCreamShopVM = new IceCreamShopVM(this);
this.DataContext = IceCreamShopVM;
// this.ImageViewIceCream.ItemsSource = IceCreamShopVM.C
}
private void Back_btn_Click(object sender, RoutedEventArgs e)
{
SearchIceCreamUC = new SearchIceCreamUC();
((MainWindow)System.Windows.Application.Current.MainWindow).full_content_grid.Children.Clear();
((MainWindow)System.Windows.Application.Current.MainWindow).content_grid.Children.Add(SearchIceCreamUC);
}
private void Graduate_btn_Click(object sender, RoutedEventArgs e)
{
GraduationUC = new GraduationUC(iceCream);
ProfileBarIceCreamUC = new ProfileBarIceCreamUC(iceCream);
((MainWindow)System.Windows.Application.Current.MainWindow).full_content_grid.Children.Clear();
((MainWindow)System.Windows.Application.Current.MainWindow).content_grid.Children.Add(GraduationUC);
((MainWindow)System.Windows.Application.Current.MainWindow).profile_grid.Children.Add(ProfileBarIceCreamUC);
}
}
}
|
using Common.Data;
using Common.Exceptions;
using Common.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Entity
{
public partial class PromotionsProjectChannels
{
public List<string> GetChannelsByProject(string connectionString, int id)
{
List<string> result = new List<string>();
//select channelfrom promotions_project_channel where project_id = @ID
string sql = "P_Promotions_Project_Print_Channel";
SqlParameter parameter = new SqlParameter("@ID", id);
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectStringList(sql, parameters: new SqlParameter[] { parameter });
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
finally
{
parameter = null;
}
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using CapaEntidades;
using CapaNegocio;
// NOTA: puede usar el comando "Cambiar nombre" del menú "Refactorizar" para cambiar el nombre de clase "ServiceCliente" en el código, en svc y en el archivo de configuración a la vez.
public class ServiceCliente : IServiceCliente
{
private ClienteBL clienteBL = new ClienteBL();
// private ClienteEntidad cliente = new ClienteEntidad();
public System.Data.DataSet Listar()
{
return clienteBL.Listar();
}
public List<String> Agregar(CapaEntidades.ClienteEntidad cliente)
{
List<String> Resultados = new List<String>();
String Estado = Convert.ToString(clienteBL.Agregar(cliente));
String Mensaje = clienteBL.Mensaje;
Resultados.Add(Estado);
Resultados.Add(Mensaje);
return Resultados;
}
public List<string> Eliminar(string codCliente)
{
List<String> Resultados = new List<string>();
String Estado = Convert.ToString(clienteBL.Eliminar(codCliente));
String Mensaje = clienteBL.Mensaje;
Resultados.Add(Estado);
Resultados.Add(Mensaje);
return Resultados;
}
/* public string Login(string user, string contrasena)
{
cliente.Usuario = user;
cliente.Contrasena = contrasena;
clienteBL.ValidarUsuario();
return clienteBL.Mensaje;
}*/
}
|
using UnityEngine;
using System.Collections.Generic;
using IEnumerator = System.Collections.IEnumerator;
using System.Linq;
using UnityEngine.Assertions;
public class CardInfo
{
public const string NAME_TOKEN = "name";
private bool _gatheringScheduled = false;
List<CardInfoGatherer> _unusedGatherers;
HashSet<CardInfoGatherer> _busyGatherers = new HashSet<CardInfoGatherer>();
//
// Constructors
// ---
public CardInfo(string name)
{
_info.Add(NAME_TOKEN, new Updateable<string>(name, true));
_unusedGatherers = CardInfoProvider.Get.InfoGatherersCopy();
}
//
// Info
// ---
private Dictionary<string, Updateable<string>> _info = new Dictionary<string, Updateable<string>>(System.StringComparer.InvariantCultureIgnoreCase);
public Updateable<string> GetById(string id)
{
if (!_info.ContainsKey(id))
{
_info.Add(id, new Updateable<string>());
StartGatheringIfNonScheduled();
}
return _info[id];
}
public Updateable<string> this[string id]
{
get
{
return GetById(id);
}
}
//
// Material
// ---
private Material _material = null;
public Material Material
{
get
{
if (_material == null)
{
_material = CardInfoProvider.Get.FrontMaterialCopy();
// TODO Don't just use the first one...
CardInfoProvider.Get.ImageGatherersCopy().First().GatherFor(this, OnImageGathered);
}
return _material;
}
}
void OnImageGathered(Texture2D tex)
{
Material.mainTexture = tex;
}
//
// Gathering
// ---
void StartGatheringIfNonScheduled()
{
if (!_gatheringScheduled)
{
// We need a monobehaviour for coroutines, so we use the CardInfoProvider as a dummy for this
CardInfoProvider.Get.StartCoroutine(DoGathering());
}
}
IEnumerator DoGathering()
{
//Debug.Log("Scheduled gathering for: " + Name);
_gatheringScheduled = true;
yield return new WaitForEndOfFrame();
var missingIds = _info.Where(kvp => !kvp.Value.Ready).Select(kvp => kvp.Key);
//Debug.Log("Mising ids for " + Name + " are: " + string.Join(", ", missingIds.ToArray()));
CardInfoGatherer gatherer;
while ( (gatherer = FindBestUnusedGathererFor(missingIds)) != null )
// While there is a missing id that isn't already being gathered
{
// Capture gatherer in the loop, so it can be used in the lamba (1)
var captured = gatherer;
_unusedGatherers.Remove(captured);
_busyGatherers.Add(captured);
captured.GatherFor(this, dict => { OnInfoGathererFinished(dict, captured); }); //(1)
//Debug.Log("Sending out a gatherer for " + Name + ": " + gatherer);
}
_gatheringScheduled = false;
//Debug.Log("Finished sending out gatherers for: " + Name);
}
CardInfoGatherer FindBestUnusedGathererFor(IEnumerable<string> missingIds)
{
if (_unusedGatherers.Count <= 0)
{
return null;
}
// The one to gather is the first that isn't already being gathered
string toGather = missingIds.FirstOrDefault(id => !_busyGatherers.Any(g => g.PotentialHits.Contains(id)));
if (toGather != null)
{
// Find a gatherer to use, currently simply the first one fr this id
var gatherer = _unusedGatherers.FirstOrDefault(g => g.PotentialHits.Contains(toGather));
// Since I check for an id that isn't being gathered, the chosen gatherer can't be busy already
Assert.IsFalse(_busyGatherers.Contains(gatherer));
return gatherer;
}
else
{
return null;
}
// TODO: Rewrite so the gatherer with most potential hits is used first
}
void OnInfoGathererFinished(Dictionary<string,string> foundValues, CardInfoGatherer usedGatherer)
{
if (foundValues == null)
{
Debug.Log("Info gathering failed for " + Name + " by: " + usedGatherer);
}
else
{
foreach(var kvp in foundValues)
{
var value = GetById(kvp.Key);
if(value.Ready)
{
if (value.Value != kvp.Value)
{
// TODO
// What to do?
// Update anyway?
value.UpdateValue(kvp.Value);
}
//else everything is fine
}
else
{
value.UpdateValue(kvp.Value);
}
}
}
_busyGatherers.Remove(usedGatherer);
// check if any more gathering is needed.
StartGatheringIfNonScheduled();
}
//
// Convenience functions
// ---
public string Name
{
get
{
return _info[NAME_TOKEN].Value;
}
}
//
// Debugging
// ---
public Dictionary<string, Updateable<string>> DebugInfo { get { return _info; } }
public HashSet<CardInfoGatherer> DebugBusyGatherers { get { return _busyGatherers; } }
}
|
using System.Web;
using System.Web.Optimization;
namespace Centroid
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/jqueryUnobtrusive").Include(
"~/Scripts/jquery.unobtrusive-ajax.min.js"));
bundles.Add(new ScriptBundle("~/bundles/isotope").Include(
"~/Scripts/isotope/isotope.pkgd.min.js"));
bundles.Add(new ScriptBundle("~/bundles/backstretch").Include(
"~/Scripts/jquery.backstretch.min.js"));
bundles.Add(new ScriptBundle("~/bundles/appear").Include(
"~/Scripts/jquery.appear.js"));
bundles.Add(new ScriptBundle("~/bundles/jqBootstrapValidation").Include(
"~/Scripts/contact/jqBootstrapValidation.js"));
bundles.Add(new ScriptBundle("~/bundles/contact_me").Include(
"~/Scripts/contact/contact_me.js"));
bundles.Add(new ScriptBundle("~/bundles/custom").Include(
"~/Content/js/custom.js"));
bundles.Add(new ScriptBundle("~/bundles/slider").Include(
"~/Content/js/jquery.devrama.slider.min-0.9.4.js"));
bundles.Add(new ScriptBundle("~/bundles/tinymce").Include(
"~/Scripts/tinymce/tinymce.min.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.min.js"));
bundles.Add(new ScriptBundle("~/bundles/datatables").Include(
"~/Scripts/DataTables/datatables.min.js"));
/////Styles
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap/css/bootstrap.css",
"~/Content/fonts/font-awesome/css/font-awesome.css",
"~/Content/animations.css",
"~/Content/style.css"));
bundles.Add(new StyleBundle("~/Content/datatables").Include(
"~/Content/plugins/DataTables/datatables.min.css"));
}
}
}
|
using ND.FluentTaskScheduling.Command.asyncrequest;
using ND.FluentTaskScheduling.Command.Monitor;
using ND.FluentTaskScheduling.Core.PerformanceCollect;
using ND.FluentTaskScheduling.Helper;
using ND.FluentTaskScheduling.Model;
using ND.FluentTaskScheduling.Model.request;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//**********************************************************************
//
// 文件名称(File Name):NodePerformanceMonitor.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-05-15 17:46:54
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-05-15 17:46:54
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.Core.Monitor
{
public class NodePerformanceMonitor : AbsMonitor
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static List<PerformanceCounterCollectTask> pcounts = new List<PerformanceCounterCollectTask>();
public NodePerformanceMonitor()
{
List<NodePerformanceCollectConfig> configlist = JsonConvert.DeserializeObject<List<NodePerformanceCollectConfig>>(GlobalNodeConfig.NodeInfo.performancecollectjson);
foreach (var item in configlist)
{
pcounts.Add(new PerformanceCounterCollectTask(item));
}
}
public override string Name
{
get
{
return "节点计算机性能监控";
}
}
public override string Discription
{
get
{
return "每隔6秒上报下本节点所在计算机的内存,cpu,io,iis等指标性能";
}
}
/// <summary>
/// 监控间隔时间(ms为单位)10s上报一次性能
/// </summary>
public override int Interval
{
get
{
return 6000;
}
}
protected override void Run()
{
try
{
if (GlobalNodeConfig.NodeInfo.ifmonitor == 0)
return;
if(pcounts.Count <=0)
{
return;
}
tb_nodeperformance model = new tb_nodeperformance();
string fileinstallpath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') ;
double dirsizeM = -1;
if (System.IO.Directory.Exists(fileinstallpath))
{
long dirsize = IOHelper.DirSize(new DirectoryInfo(fileinstallpath));
dirsizeM = (double)dirsize / 1024 / 1024;
model.installdirsize = (double)dirsizeM;
}
foreach (var p in pcounts)
{
var c = p.Collect();
if (p.Name.Contains("cpu"))
{
model.cpu = (double)c;
}
else if (p.Name.Contains("内存"))
{
model.memory = (double)c;
}
else if (p.Name.Contains("网络发送"))
{
model.networkupload = (double)c;
}
else if (p.Name.Contains("网络下载"))
{
model.networkdownload = (double)c;
}
else if (p.Name.Contains("物理磁盘读"))
{
model.ioread = (double)c;
}
else if (p.Name.Contains("物理磁盘写"))
{
model.iowrite = (double)c;
}
else if (p.Name.Contains("IIS请求"))
{
model.iisrequest = (double)c;
}
}
model.nodeid = GlobalNodeConfig.NodeID;
model.lastupdatetime = DateTime.Now;
AddNodePerformanceRequest req = new AddNodePerformanceRequest() { NodePerformance = model, Source = Source.Node,MonitorClassName=this.GetType().Name };
var r = NodeProxy.PostToServer<EmptyResponse, AddNodePerformanceRequest>(ProxyUrl.AddNodePerformance_Url, req);
if (r.Status != ResponesStatus.Success)
{
LogProxy.AddNodeErrorLog("节点性能上报出错,请求地址:" + ProxyUrl.AddNodePerformance_Url + ",请求内容:" + JsonConvert.SerializeObject(req) + ",返回结果:" + JsonConvert.SerializeObject(r));
}
}
catch(Exception ex)
{
LogProxy.AddNodeErrorLog("节点性能监控时出错:nodeid=" + GlobalNodeConfig.NodeID+ ",异常信息:" + JsonConvert.SerializeObject(ex));
}
}
}
}
|
namespace Sentry;
internal interface ISentryFailedRequestHandler
{
void HandleResponse(HttpResponseMessage response);
}
|
using FrbaOfertas.AbmUsuario;
using FrbaOfertas.DataModel;
using FrbaOfertas.Helpers;
using FrbaOfertas.Model;
using FrbaOfertas.Model.DataModel;
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 FrbaOfertas.AbmProveedor
{
public partial class NuevoUsuario : Form
{
List<TextBox> noNulos= new List<TextBox>();
List<TextBox> numericos= new List<TextBox>();
List<TextBox> todos = new List<TextBox>();
public object returnUsuario { get; set; }
Usuario usuario;
List<Rol> roles;
UsuarioData uData;
RolData rData;
Exception exError = null;
bool noDB=false;
public NuevoUsuario(bool db)
{
InitializeComponent();
noDB = db;
}
public NuevoUsuario()
{
InitializeComponent();
}
private void NuevoCliente_Load(object sender, EventArgs e)
{
noNulos.Add(usu_username);
noNulos.Add(usu_contrasenia);
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
todos.Add((TextBox)x);
}
}
uData = new UsuarioData(Conexion.getConexion());
rData = new RolData(Conexion.getConexion());
roles = rData.SelectActivos(out exError); // solo los activos
roles.ForEach(delegate(Rol rol)
{
checkedListRoles.Items.Add(rol.rol_nombre);
});
}
private void guardar_Click(object sender, EventArgs e)
{
usuario = new Usuario();
Boolean rolCliente = false;
Boolean rolProveedor = false;
if (!FormHelper.noNullList(noNulos) || !FormHelper.esNumericoList(numericos))
return;
//List<TextBox> datos = FormHelper.getNoNulos(todos);
FormHelper.setearAtributos(todos, usuario);
usuario.usu_activo = prov_activo.Checked;
if (noDB)
{
this.DialogResult = DialogResult.OK;
this.Close();
return;
}
Int32 i = 0;
roles.ForEach(delegate(Rol f)
{
if (checkedListRoles.GetItemChecked(i))
{
usuario.roles.Add(f);
if (f.rol_nombre == "CLIENTE")
{
rolCliente = true;
}
else if (f.rol_nombre == "PROVEEDOR")
{
rolProveedor = true;
}
}
i++;
});
Int32 id = uData.Create(usuario, usuario.roles, out exError);
if (exError == null)
{
MessageBox.Show("Usuario " + usuario.usu_username + " agregado exitosamente.", "Usuario nuevo", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (!asignarRoles(rolCliente, rolProveedor,id))
return;
this.Close();
}
else
MessageBox.Show("Erro al agregar Usuario, " + exError.Message, "Usuario", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private bool asignarRoles(bool rolCliente, bool rolProveedor,int id_usuario)
{
ClienteData cData = new ClienteData(Conexion.getConexion());
ProveedorData pData = new ProveedorData(Conexion.getConexion());
Dictionary<String, Object> clie = new Dictionary<String, Object>() { { "clie_usuario", usuario.id_usuario } };
Dictionary<String, Object> prov = new Dictionary<String, Object>() { { "prove_usuario", usuario.id_usuario } };
List<Cliente> clientes = cData.FilterSelect(new Dictionary<String, String>(), clie, out exError);
List<Proveedor> proveedores = pData.FilterSelect(new Dictionary<String, String>(), prov, out exError);
if (clientes.Count() > 0)
rolCliente = false;
if (proveedores.Count() > 0)
rolCliente = false;
if (rolCliente || rolProveedor)
{
Asignaciones asignaciones = new Asignaciones(rolCliente, rolProveedor, id_usuario);
asignaciones.Parent = this.Parent;
var result = asignaciones.ShowDialog();
if (result == DialogResult.OK)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
}
}
|
using System;
using NetFive.Models;
namespace NetFive.Services
{
public interface IUsersService
{
User Get(Guid id);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.