text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AI3
{
public class State
{
//массив лунок
public int[] holes;
//значення евристичної функції в стані
public int heuristic;
//різниця евристичних функцій поточного стану та попереднього до нього
public int delta;
//дефолтний конструктор
public State()
{
}
//конструктор ініціалізації
public State(int[] holes)
{
this.holes = holes;
}
//метод обрахунку значення евристичної функції
public int CalculateHeuristic(State finish)
{
heuristic = 0;
for (int i = 0; i < holes.Length; i++)
{
if (holes[i] == finish.holes[i])
{
heuristic++;
}
}
return heuristic;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace WalletWasabi.Models
{
public class ObservableConcurrentHashSet<T> : IReadOnlyCollection<T>, INotifyCollectionChanged
{
private ConcurrentHashSet<T> Set { get; }
private object Lock { get; }
public event NotifyCollectionChangedEventHandler CollectionChanged;
public ObservableConcurrentHashSet()
{
Set = new ConcurrentHashSet<T>();
Lock = new object();
}
// Do not lock here, it results deadlock at wallet loading when filters are not synced.
public int Count => Set.Count;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
// Do not lock here, it results deadlock at wallet loading when filters are not synced.
public IEnumerator<T> GetEnumerator() => Set.GetEnumerator();
public bool TryAdd(T item)
{
var invoke = false;
lock (Lock)
{
if (Set.TryAdd(item))
{
invoke = true;
}
}
if (invoke)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
return invoke;
}
public bool TryRemove(T item)
{
var invoke = false;
lock (Lock)
{
if (Set.TryRemove(item))
{
invoke = true;
}
}
if (invoke)
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
}
return invoke;
}
public void Clear()
{
var invoke = false;
lock (Lock)
{
if (Set.Count > 0)
{
Set.Clear();
invoke = true;
}
}
if (invoke)
{
// "Reset action must be initialized with no changed items."
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
// Do not lock here, it results deadlock at wallet loading when filters are not synced.
public bool Contains(T item) => Set.Contains(item);
}
}
|
//Travis Kroll
//9-23-19
//This program will ask the user for their info and print them out a paystub
using System;
class Payroll {
public static void Main (string[] args) {
int Hours,Pos_Doubletime;
string a,A,Name;
double Rate,Doubletime_Pay, Gross_Total,Net_Total;
//asking a user if they want to use the program
Console.WriteLine ("Do you want to start another paystub? Yes or No");
a = Console.ReadLine();
A = a.ToUpper();
while (A == "YES")
{
//Asking the user for their info
Console.WriteLine ("What is the Employee's name?");
Name = Console.ReadLine();
Console.WriteLine ("How many hours did the employee work this week?");
Hours = int.Parse(Console.ReadLine ());
Console.WriteLine ("How much does this employee make an hour?");
Rate = double.Parse(Console.ReadLine ());
//Doing the math for the paystub
Pos_Doubletime = Hours-40;
Doubletime_Pay = Rate*1.5;
//deciding on wether or no to add overtime
if (Hours>40){
Gross_Total = (40*Rate)+(Doubletime_Pay*Pos_Doubletime);
Net_Total = Gross_Total-100;
//Printing out inputs and totals for everything
Console.WriteLine (Name+" worked "+Hours+" this week at {0:0.00}$ an hour.",Rate);
Console.WriteLine (Name+" earned "+Pos_Doubletime+" hours overtime.");
Console.WriteLine (Name+" earned {0:0.00}$ before healthcare insurance.", Gross_Total);
Console.WriteLine (Name+" earned {0:0.00}$ this week.", Net_Total);
}
//decding on wether or not to add overtime
if (Hours<=40){
Gross_Total = (Hours*Rate);
Net_Total = Gross_Total-100;
//Printing out inputs and totals for everything
Console.WriteLine (Name+" worked "+Hours+" this week at {0:0.00}$ an hour.",Rate);
Console.WriteLine (Name+" earned {0:0.00}$ before healthcare insurance.", Gross_Total);
Console.WriteLine (Name+" earned {0:0.00}$ this week.", Net_Total);
}
//asking the user if they want to restart with a new employee
Console.WriteLine ("Do you want to submit another paystub? Yes or No?");
a = Console.ReadLine();
A = a.ToUpper();
}
}
}
|
using System;
using System.Collections.Generic;
#nullable disable
namespace UCP1.Models
{
public partial class Barang
{
public int IdDetailBarang { get; set; }
public string NamaPengirim { get; set; }
public string NamaPenerima { get; set; }
public string NomorResiPengiriman { get; set; }
public string AlamatPengirim { get; set; }
public string AlamatTujuan { get; set; }
public int? BeratBarang { get; set; }
public int? Harga { get; set; }
public string StatusBarang { get; set; }
public virtual Detail Detail { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using LR.Models.RaceModels;
using LR.Data.Providers;
using LR.Models;
namespace Racing.Core
{
public class RaceManager
{
#region Properties
public static bool IsRaceStarted = false;
public static Thread RaceThread { get; set; }
//started races
public static List<RaceModel> Races { get; set; }
//not started races
public static List<RaceModel> IdleRaces { get; set; }
#endregion
#region PublicMethods
public static RaceModel AddRacer(int racerId, Guid categoryId)
{
InitLists();
RaceModel race = Races.FirstOrDefault(r => r.CategoryId == categoryId && r.Racers.FirstOrDefault(rc => rc.Racer.UserId == racerId) != null);
if (race == null)
{
race = IdleRaces.FirstOrDefault(r => r.CategoryId == categoryId && r.Racers.FirstOrDefault(rc => rc.Racer.UserId == racerId) != null);
}
if (race == null)
{
race = IdleRaces.FirstOrDefault(r => r.Racers.Count < r.RacerMaximimCount && r.CategoryId == categoryId);
if (race == null)
{
race = new RaceModel(categoryId);
IdleRaces.Add(race);
}
RacerModel racer = new RacerModel(DataProvider.UserProfile.GetUserById(racerId), DataProvider.Cars.DefaultCar);
race.Racers.Add(racer);
race.Version++;
}
StartRace();
return race;
}
public static RaceModel GetRaceById(Guid raceId)
{
RaceModel result = Races.FirstOrDefault(r => r.RaceId == raceId);
if (result == null)
{
result = IdleRaces.FirstOrDefault(r => r.RaceId == raceId);
}
return result;
}
public static RacerModel GetRacerById(Guid raceid, int racerId)
{
RacerModel result = GetRaceById(raceid).Racers.FirstOrDefault(r => r.Racer.UserId == racerId);
return result;
}
public static void ChangeRaceState(Guid raceid, int racerId, bool isReady)
{
RacerModel racer = GetRacerById(raceid, racerId);
IncreaceVersion(raceid);
racer.IsReady = isReady;
}
public static void ChangeSpeed(Guid raceId, int racerId, bool isCorrect)
{
RacerModel racer = GetRacerById(raceId, racerId);
IncreaceVersion(raceId);
racer.ChangeSpeed(isCorrect);
}
public static void StartRace()
{
if (!IsRaceStarted)
{
RaceThread = new Thread(new ThreadStart(racingActivity));
IsRaceStarted = true;
RaceThread.Start();
}
}
#endregion
private static void racingActivity()
{
while (IdleRaces.Count > 0 || Races.Count>0)
{
IdleRaces.Where(r => r.Racers.Count == r.RacerMaximimCount).ToList().ForEach(r => r.Racers.ForEach(rc => rc.ReadyTime -= !rc.IsReady && rc.ReadyTime != 0 ? 1 : 0));
List<RaceModel> readyRaces = IdleRaces.Where(r => r.Racers.FirstOrDefault(rc => rc.ReadyTime != 0 && !rc.IsReady) == null).ToList();
readyRaces.ForEach(r => r.IsStarted = true);
IdleRaces.RemoveAll(r => readyRaces.Contains(r));
Races.AddRange(readyRaces);
Races.Where(r=>r.IsFinished).ToList().ForEach(r=>r.Racers.ForEach(rc=>rc.TrysCountToGetResult+= rc.HasGotResults ? 0 : 1));
Races.RemoveAll(r => r.IsFinished && r.Racers.FirstOrDefault(rc => !rc.HasGotResults && rc.TrysCountToGetResult < 5) == null);
Races.Where(r => !r.IsFinished).ToList().ForEach(r => r.Racers.ForEach(rc => MoveRacer(rc, r)));
Thread.Sleep(1000);
}
IsRaceStarted = false;
}
/// <summary>
/// Moves racer forward and returns true if ther racer has finished
/// </summary>
private static void MoveRacer(RacerModel racer, RaceModel race)
{
if (racer.Length <= race.Length)
{
racer.MoveRacer();
}
else if (!racer.IsFinished)
{
if (race.Places.FirstOrDefault(r => r.Racer.UserId == racer.Racer.UserId) == null)
{
race.Places.Add(racer);
int totalScore = (racer.Score * (10 + (race.Racers.Count - race.Places.Count))) / 10;
DataProvider.UserProfile.AddScoreToUser(totalScore, racer.Racer);
racer.Message = string.Format("You finished the race {0}/{1}, with {2} points", race.Places.Count, race.Racers.Count, totalScore);
racer.RaceResult.RacerPlace = race.Places.Count;
racer.RaceResult.RacersCount = race.Racers.Count;
}
racer.Length = race.Length;
racer.Speed = 0;
racer.IsFinished = true;
if (race.Racers.FirstOrDefault(rc => !rc.IsFinished) == null) race.IsFinished = true;
}
}
private static void InitLists()
{
if(Races == null) Races = new List<RaceModel>();
if (IdleRaces == null) IdleRaces = new List<RaceModel>();
}
private static void IncreaceVersion(Guid raceId)
{
GetRaceById(raceId).Version++;
}
}
} |
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using VesApp.ViewModels;
using VesApp.Views;
using Xamarin.Forms;
namespace VesApp.Models
{
public class Project
{
public int IdProject { get; set; }
public string UrlVideo { get; set; }
public string UrlImagen { get; set; }
public string Text { get; set; }
public string Titulo { get; set; }
#region Commands
public ICommand SelectProjectCommand
{
get
{
return new RelayCommand(SelectProject);
}
}
async void SelectProject()
{
MainViewModel.GetInstance().ImageViewModel = new ImageViewModel();
MainViewModel.GetInstance().ImageViewModel.LoadConfig();
MainViewModel.GetInstance().DetailViewModel = new DetailViewModel(project: this);
await App.Navigator.PushAsync(new DetailProjectPage());
}
public ICommand OpenLinkCommand
{
get
{
return new RelayCommand(OpenLink);
}
}
void OpenLink()
{
try
{
string urlVideo = this.UrlVideo;
int index = urlVideo.LastIndexOf('/');
String idVideo = urlVideo.Substring(index + 1);
String video = "watch?v=" + idVideo;
Device.OpenUri(new Uri("vnd.youtube://" + video));
}
catch
{
Device.OpenUri(new Uri(this.UrlVideo));
}
}
#endregion
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace Nac.Wpf.Fuzzy {
/// <summary>
/// Interaction logic for FuzzyRuleEditor.xaml
/// </summary>
public partial class NacWpfFuzzyRuleEditor : Window {
public NacWpfFuzzyRuleEditor() {
InitializeComponent();
}
public NacWpfFuzzyRuleEditor(HashSet<string> rules) {
InitializeComponent();
HashSet<string> edit = rules == null ? new HashSet<string>() : new HashSet<string>(rules);
DataContext = new NacWpfFuzzyRuleEditorViewModel(edit);
}
public HashSet<string> Return { get { return new HashSet<string>((DataContext as NacWpfFuzzyRuleEditorViewModel).Select(fr => fr.Content)); } }
private void Add_Click(object sender, RoutedEventArgs e) {
var viewModel = DataContext as NacWpfFuzzyRuleEditorViewModel;
if (viewModel.Current.IsSyntaxValid) viewModel.Add(new NacWpfFuzzyRule(viewModel.Current));
}
private void Remove_Click(object sender, RoutedEventArgs e) {
var viewModel = DataContext as NacWpfFuzzyRuleEditorViewModel;
var sel = ruleListBox.SelectedItems.OfType<NacWpfFuzzyRule>().ToArray();
foreach (var item in sel) viewModel.Remove(item);
ruleListBox.DataContext = null;
ruleListBox.DataContext = viewModel;
}
private void OK_Click(object sender, RoutedEventArgs e) {
DialogResult = true;
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e) {
DialogResult = false;
Close();
}
}
}
|
using Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
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 MaterialDesignThemes;
namespace Weather
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Rootobject RootObject { get; set; }
string Url = @"https://api.openweathermap.org/data/2.5/forecast?q=Astana&units=metric&appid=d90a95289bca705ac3617d2c0fadb97c";
public MainWindow()
{
InitializeComponent();
RootObject = new Rootobject();
using (WebClient client = new WebClient())
{
var json = client.DownloadString(Url);
var result = JsonConvert.DeserializeObject<Rootobject>(json);
RootObject = result;
textBox_dateFirstDay.Text = result.list[0].dt_txt;
textBox_tempFirstDay.Text = result.list[0].main.temp.ToString();
textBox_dateSecondDay.Text = result.list[8].dt_txt;
textBox_tempSecondDay.Text = result.list[8].main.temp.ToString();
textBox_dateThirdDay.Text = result.list[16].dt_txt;
textBox_tempThirdDay.Text = result.list[16].main.temp.ToString();
}
}
}
}
|
public enum EnumNarrationTexts
{
NextPlayersTurn,
Draw,
SelectHand,
SelectLane,
Skill,
Battle,
End,
WelcometotheSummonersRift,
}
|
using Android.App;
using System;
namespace MobileCollector
{
public class WaitDialogHelper
{
Activity _context;
Action<string, Android.Widget.ToastLength> _makeToast;
public WaitDialogHelper(Activity context, Action<string, Android.Widget.ToastLength> makeToast)
{
_context = context;
_makeToast = makeToast;
}
public async System.Threading.Tasks.Task<int> showDialog(
Func<Action<string, Android.Widget.ToastLength>, System.Threading.Tasks.Task<int>> worker)
{
var progressDialog = ProgressDialog.Show(_context, "Please wait...", "Synchronising with server", true);
await worker(_makeToast);
progressDialog.Hide();
return 0;
}
}
} |
using System;
using Microsoft.AspNetCore.Http;
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.CrossOriginPolicies.EmbedderPolicy
{
/// <summary>
/// This is the default value. Allows the document to fetch cross-origin resources without giving
/// explicit permission through the CORS protocol or the Cross-Origin-Resource-Policy header.
/// From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy#directives
/// </summary>
public class UnsafeNoneDirectiveBuilder : CrossOriginEmbedderPolicyDirectiveBuilderBase
{
/// <summary>
/// Initializes a new instance of the <see cref="UnsafeNoneDirectiveBuilder"/> class.
/// </summary>
public UnsafeNoneDirectiveBuilder() : base("unsafe-none")
{
}
/// <inheritdoc />
internal override Func<HttpContext, string> CreateBuilder()
{
return ctx => Directive;
}
}
} |
// talis.xivplugin.twintania
// ShellViewModel.cs
using FFXIVAPP.Common.Utilities;
using NLog;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using talis.xivplugin.twintania.Interop;
using talis.xivplugin.twintania.Properties;
namespace talis.xivplugin.twintania
{
public sealed class ShellViewModel : INotifyPropertyChanged
{
#region Property Bindings
private static ShellViewModel _instance;
public static ShellViewModel Instance
{
get { return _instance ?? (_instance = new ShellViewModel()); }
}
#endregion
#region Declarations
#endregion
public ShellViewModel()
{
Initializer.LoadSettings();
Initializer.LoadSounds();
Initializer.SetupWidgetTopMost();
Settings.Default.PropertyChanged += DefaultOnPropertyChanged;
}
internal static void Loaded(object sender, RoutedEventArgs e)
{
ShellView.View.Loaded -= Loaded;
}
private static void DefaultOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
var propertyName = propertyChangedEventArgs.PropertyName;
switch (propertyName)
{
case "TwintaniaHPWidgetUIScale":
try
{
Settings.Default.TwintaniaHPWidgetWidth = (int) (250 * Double.Parse(Settings.Default.TwintaniaHPWidgetUIScale));
Settings.Default.TwintaniaHPWidgetHeight = (int) (450 * Double.Parse(Settings.Default.TwintaniaHPWidgetUIScale));
}
catch(Exception ex)
{
Settings.Default.TwintaniaHPWidgetWidth = 250;
Settings.Default.TwintaniaHPWidgetHeight = 450;
}
break;
case "TwintaniaHPWidgetClickThroughEnabled":
WinAPI.ToggleClickThrough(Widgets.Instance.TwintaniaHPWidget);
break;
}
}
#region Loading Functions
#endregion
#region Utility Functions
#endregion
#region Command Bindings
#endregion
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
public class GamController : MonoBehaviour {
public GameObject meteor;
// Use this for initialization
void Awake(){
meteor.transform.position = new Vector3 (0, 0, 0);
meteor.transform.rotation = Random.rotation;
meteor.transform.position = transform.forward * Random.Range (20, 30);
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LevelObjectiveData {
public int LevelID;
public int ObjectiveId;
public int ObjectiveScore;
public string ObjectiveColor;
public int ColorCount;
public string Title;
public string Info;
public int ObjectiveCount;
public int Time;
public string TutorialTitle;
public string TutorialText;
public int BubbleSpeed;
public float FastBubbleTimer;
public LevelObjectiveData()
{
}
public LevelObjectiveData(LevelObjectiveData meta)
{
LevelID = meta.LevelID;
ObjectiveId = meta.ObjectiveId;
ObjectiveScore = meta.ObjectiveScore;
ObjectiveColor = meta.ObjectiveColor;
ColorCount = meta.ColorCount;
Title = meta.Title;
Info = meta.Info;
ObjectiveCount = meta.ObjectiveCount;
Time = meta.Time;
TutorialText = meta.TutorialText;
TutorialTitle = meta.TutorialTitle;
BubbleSpeed = meta.BubbleSpeed;
FastBubbleTimer = meta.FastBubbleTimer;
}
}
|
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 _20200621_CheckBoxApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string strTemp;
private void UpdateLabel(string strTemp, bool @checked)
{
if (true)
{
strTemp = strTemp + ",";
label1.Text = strTemp;
}
/*string fruit1 = "", fruit2 = "", fruit3 = "", fruit4 = ""; //강사님은 else 문을 적었는데 if 문 자체가 그 외에 것을 else처리해서
if (checkBox1.Checked)
{
fruit1 = checkBox1.Text;
}
if (checkBox2.Checked)
{
fruit2 = checkBox2.Text;
}
if(checkBox3.Checked)
{
fruit3 = checkBox3.Text;
}
if(checkBox4.Checked)
{
fruit4 = checkBox4.Text;
}
label1.Text = fruit1 + " " + fruit2 + " " + fruit3 + " " + fruit4;*/
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
UpdateLabel(checkBox1.Text,checkBox1.Checked);
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
UpdateLabel(checkBox3.Text, checkBox3.Checked);
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
UpdateLabel(checkBox2.Text, checkBox2.Checked);
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
UpdateLabel(checkBox4.Text, checkBox4.Checked);
}
private void Form1_Load(object sender, EventArgs e)
{
label2.Text = "좋아하는 과일";
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
|
using Euler_Logic.Helpers;
using System.Collections.Generic;
namespace Euler_Logic.Problems {
public class Problem650 : ProblemBase {
private PrimeSieve _primes;
private Dictionary<ulong, List<Tuple>> _primeFactors = new Dictionary<ulong, List<Tuple>>();
private Dictionary<ulong, PowerSum> _powerSums = new Dictionary<ulong, PowerSum>();
private ulong _mod = 1000000007;
/*
Any individual cell (m,k) can be calculated: m! / (k! * (m - k)!). The product of an entire
row (n) would then be n!^n / ((2)1! * (2)2! * (2)3! ... * (2)(n - 1)!). So I calculate the
prime factors of all these factorials. Then I simply start with the prime factors of n!^n and
subtract the double of all prime factors of all subsequent factorials less than n.
The above will calculate B(n). To calulate D(n), we simply take the sums of all the powers of
the prime factors of B(n) and multiply them. For example, if B(n) = 96, then the prime factors
of 96 would be 2^5 * 3^1. So then, D(96) = (2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5) * (3^0 + 3^1)
= 252. I use a hash dictionary to assist with this. Takes 3gb of ram but it solves in less
than 60 seconds!
*/
public override string ProblemName {
get { return "650: Divisors of Binomial Product"; }
}
public override string GetAnswer() {
ulong max = 20000;
_primes = new PrimeSieve(max);
BuildPrimeFactors(max);
return Solve(max).ToString();
}
private void BuildPrimeFactors(ulong max) {
for (ulong n = 2; n <= max; n++) {
List<Tuple> tuples = new List<Tuple>();
var sub = n;
foreach (var prime in _primes.Enumerate) {
if (sub % prime == 0) {
var tuple = new Tuple() { Prime = prime };
tuples.Add(tuple);
do {
tuple.Power++;
sub /= prime;
} while (sub % prime == 0);
if (sub == 1) {
break;
}
}
}
_primeFactors.Add(n, tuples);
}
}
private ulong Solve(ulong max) {
ulong sum = 1;
var subtract = new Dictionary<ulong, ulong>();
for (ulong n = 2; n <= max; n++) {
var next = FactorialPrimeFactors(n);
ulong subSum = 1;
foreach (var prime in _primes.Enumerate) {
if (prime > n) {
break;
}
if (!subtract.ContainsKey(prime)) {
subtract.Add(prime, next[prime] / (n - 1) * 2);
subSum = (subSum * GetPowerSum(prime, next[prime])) % _mod;
} else {
subSum = (subSum * GetPowerSum(prime, next[prime] - subtract[prime])) % _mod;
subtract[prime] += next[prime] / (n - 1) * 2;
}
}
sum = (subSum + sum) % _mod;
}
return sum;
}
private ulong GetPowerSum(ulong prime, ulong power) {
if (!_powerSums.ContainsKey(prime)) {
_powerSums.Add(prime, new PowerSum() { HighestPowerKey = 0, HighestPowerValue = 1, Sums = new Dictionary<ulong, ulong>() });
_powerSums[prime].Sums.Add(0, 1);
}
if (_powerSums[prime].Sums.ContainsKey(power)) {
return _powerSums[prime].Sums[power];
}
var powerSum = _powerSums[prime];
var sum = powerSum.Sums[powerSum.HighestPowerKey];
for (var next = powerSum.HighestPowerKey + 1; next <= power; next++) {
powerSum.HighestPowerValue = (powerSum.HighestPowerValue * prime) % _mod;
powerSum.HighestPowerKey = next;
sum = (sum + powerSum.HighestPowerValue) % _mod;
powerSum.Sums.Add(powerSum.HighestPowerKey, sum);
}
return sum;
}
private Dictionary<ulong, ulong> FactorialPrimeFactors(ulong n) {
var factors = new Dictionary<ulong, ulong>();
foreach (var prime in _primes.Enumerate) {
if (prime > n) {
break;
}
ulong sum = 0;
ulong power = prime;
ulong result = n / power;
do {
sum += result;
power *= prime;
result = n / power;
} while (result > 0);
factors.Add(prime, sum * (n - 1));
}
return factors;
}
private class Tuple {
public ulong Prime { get; set; }
public ulong Power { get; set; }
}
private class PowerSum {
public Dictionary<ulong, ulong> Sums { get; set; }
public ulong HighestPowerKey { get; set; }
public ulong HighestPowerValue { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _60_Lesson
{
class Character
{
//public int Health
//{
// get
// {
// return health;
// }
// private set
// {
// health = value;
// }
//}
public int Health { get; private set; } = 100;
public void Hit(int damage)
{
if (damage > Health)
damage = Health;
Health -= damage;
}
}
}
|
using System;
using System.Collections.Generic;
using SecureNetRestApiSDK.Api.Models;
using SNET.Core;
namespace SecureNetRestApiSDK.Api.Requests
{
public class UpdateCustomerRequest : SecureNetRequest
{
#region Properties
public string CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string EmailAddress { get; set; }
public bool SendEmailReceipts { get; set; }
public string Notes { get; set; }
public Address Address { get; set; }
public string Company { get; set; }
public List<UserDefinedField> UserDefinedFields { get; set; }
public DeveloperApplication DeveloperApplication { get; set; }
#endregion
#region Methods
public override string GetUri()
{
return String.Format("api/Customers/{0}", CustomerId);
}
public override HttpMethodEnum GetMethod()
{
return HttpMethodEnum.PUT;
}
#endregion
}
}
|
using Newtonsoft.Json;
namespace SecureNetRestApiSDK.Api.Models
{
/// <summary>
/// Additional infomation for terminal details.
/// </summary>
public class AdditionalTerminalInfo
{
#region Properties
/// <summary>
/// Terminal identifier.
/// </summary>
[JsonProperty("terminalId")]
public string TerminalId { get; set; }
/// <summary>
/// City where the terminal is located.
/// </summary>
[JsonProperty("terminalCity")]
public string TerminalCity { get; set; }
/// <summary>
/// State where the terminal is located.
/// </summary>
[JsonProperty("terminalState")]
public string TerminalState { get; set; }
/// <summary>
/// Additional terminal location information.
/// </summary>
[JsonProperty("terminalLocation")]
public string TerminalLocation { get; set; }
/// <summary>
/// Store number where the terminal is located.
/// </summary>
[JsonProperty("storeNumber")]
public string StoreNumber { get; set; }
#endregion
}
}
|
using CSharpServerFramework.Extension;
using CSharpServerFramework.Message;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharpServerFramework;
namespace CSServerJsonProtocol
{
public abstract class JsonExtensionBase:ExtensionBaseEx
{
public JsonExtensionBase():base(JsonMessageDeserializer.Instance)
{
}
}
}
|
using MassTransit;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace MessageOutbox.Outbox
{
internal interface IMessageOutboxProcessor
{
Task ProcessFailedMessages();
}
internal class MessageOutboxProcessor : IMessageOutboxProcessor
{
private readonly IMessageOutboxRepository messageOutboxRepository;
private readonly IBusControl bus;
private readonly ILogger<MessageOutboxProcessor> logger;
public MessageOutboxProcessor(
IMessageOutboxRepository messageOutboxRepository,
IBusControl bus,
ILogger<MessageOutboxProcessor> logger
)
{
this.messageOutboxRepository = messageOutboxRepository;
this.bus = bus;
this.logger = logger;
}
public async Task ProcessFailedMessages()
{
await messageOutboxRepository.ExecuteTransaction(async () =>
{
var unprocessedMessages = await messageOutboxRepository.GetUnprocessed();
var unprocessedMessageTasks = unprocessedMessages
.Select(unprocessedMessage => ProcessFailedMessage(unprocessedMessage));
await Task.WhenAll(unprocessedMessageTasks);
});
}
private async Task ProcessFailedMessage(IMessage message)
{
logger.LogInformation($"Processing message with ID {message.Id}.");
try
{
await bus.Publish(message);
await messageOutboxRepository.Update(message, true);
}
catch (Exception ex)
{
await messageOutboxRepository.Update(message, false);
logger.LogWarning($"Message processing with ID {message.Id} failed. " +
$"{Environment.NewLine} Exception: {ex}");
}
logger.LogInformation($"Finished processing message with ID {message.Id}.");
}
}
}
|
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace BuildHelper.Editor.Core {
/// <summary>
/// Provades request to external programs.
/// </summary>
public class ProgramRequest {
private bool _isAborted;
private readonly Process _process;
private StringBuilder _errorsAsync;
private StringBuilder _outputAsync;
private Action<bool> _onExited;
private Action<string> _onOutput;
private Func<string, bool> _onError;
/// <summary>
/// Create request for program located in specified <i>path</i>.
/// Working directory for program sets to project root.
/// </summary>
/// <param name="path">Path to external program</param>
/// <param name="args">Comand line arguments</param>
public ProgramRequest(string path, string args = "") {
_process = new Process {
StartInfo = {
FileName = path,
Arguments = args,
WorkingDirectory = BuildHelperStrings.ProjRoot(),
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
}
/// <summary>
/// Perform program request and return result.
/// The calling thread is blocks while external program is works.
/// </summary>
/// <exception cref="ExternalException">External program was failed</exception>
/// <remarks>See more exceptions in <see cref="Process.Start()">System.Diagnostics.Process.Start</see></remarks>.
/// <returns>Output of program</returns>
/// <seealso cref="ExecuteAsync"/>
public string Execute() {
_process.Start();
_process.WaitForExit();
return HandleExited(_process.StandardOutput.ReadToEnd(),
_process.StandardError.ReadToEnd());
}
/// <summary>
/// Abort request. In this case,
/// it is considered that the request was not finished successfully.
/// </summary>
public void Abort() {
_isAborted = true;
try {
_process.Kill();
} catch (Exception) {
// ignored
}
}
/// <summary>
/// Asynchronous program request. The calling thread is not blocks.
/// </summary>
/// <param name="OnExited">Invoked after external program is finished.
/// The first callback argument is the last output of program.
/// The second argument is <b>true</b> if request finished successfully.</param>
/// <param name="OnOutput">Received output</param>
/// <param name="OnError">Received error.
/// If you want to stop the request with an error, return <b>true</b>.
/// If you return <b>false</b>, the request will continue execution.</param>
/// <remarks>See exceptions in <see cref="Process.Start()">System.Diagnostics.Process.Start</see></remarks>
/// <seealso cref="Execute"/>
public void ExecuteAsync(Action<bool> OnExited = null, Action<string> OnOutput = null,
Func<string, bool> OnError = null)
{
_onExited = OnExited;
_onOutput = OnOutput;
_onError = OnError;
_errorsAsync = new StringBuilder();
_outputAsync = new StringBuilder();
bool isOutputClosed = false, isErrorsClosed = false;
_process.OutputDataReceived += (sender, args) => {
isOutputClosed = DataReceived(args, OnOutputDataReceived);
};
_process.ErrorDataReceived += (sender, args) => {
isErrorsClosed = DataReceived(args, OnErrorDataReceived);
};
_process.EnableRaisingEvents = true;
_process.Exited += (sender, args) => {
WaitUntilAndDo(() => isOutputClosed && isErrorsClosed, HandleExitedAsync);
};
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
}
private static bool DataReceived(DataReceivedEventArgs args, Action<string> OnReceived) {
if (args.Data != null) {
OnReceived(args.Data);
return false;
}
return true;
}
private void OnOutputDataReceived(string data) {
_outputAsync.AppendLine(data);
if (_onOutput != null)
_onOutput(data);
}
private void OnErrorDataReceived(string data) {
if (_onError == null || _onError(data)) {
_errorsAsync.AppendLine(data);
_process.Kill();
}
}
private string HandleExited(string output, string error) {
var exitCode = _process.ExitCode;
_process.Close();
if (!_isAborted && exitCode != 0 || !string.IsNullOrEmpty(error)) {
throw new ExternalException(string.Format("\nOutput:\n{0}\nError Output:\n{1}", output, error));
}
return output;
}
private void HandleExitedAsync() {
bool success = false;
try {
HandleExited(_outputAsync.ToString(), _errorsAsync.ToString());
success = !_isAborted;
} catch (Exception e) {
UnityEngine.Debug.LogError(e);
} finally {
if (_onExited != null)
MainThreadCallback.Push(() => _onExited(success));
}
}
private static void WaitUntilAndDo(Func<bool> check, Action callbcak, int timeOut = 2000) {
var stopwatch = Stopwatch.StartNew();
new Thread(() => {
while (!check() && stopwatch.ElapsedMilliseconds < timeOut) {
Thread.Sleep(50);
}
callbcak();
}).Start();
}
}
} |
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 Attendance
{
public partial class frm_Depart : Form
{
#region Declaration
cls_BL.Depart Depart = new cls_BL.Depart();
DataTable dt_Depart = new DataTable();
int record_index;
#endregion
public frm_Depart()
{
InitializeComponent();
dgv_Depart.AutoGenerateColumns = false;
Refresh_Data();
}
#region Pro
void Form_Mode(string mode)
{
switch (mode)
{
case "New":
btn_New.Visible = false;
btn_Edit.Visible = false;
btn_Save.Visible = true;
btn_Delete.Visible = false;
btn_Cancel.Visible = true;
txt_DepartName.ReadOnly = false;
dgv_Depart.Enabled = false;
txt_ID.Text = "";
txt_DepartName.Text = "";
txt_DepartName.Focus();
break;
case "Edit":
btn_New.Visible = false;
btn_Edit.Visible = false;
btn_Save.Visible = true;
btn_Delete.Visible = false;
btn_Cancel.Visible = true;
txt_DepartName.ReadOnly = false;
dgv_Depart.Enabled = false;
txt_DepartName.Select();
break;
case "Select":
btn_New.Visible = true;
btn_Edit.Visible = true;
btn_Save.Visible = false;
btn_Delete.Visible = true;
btn_Cancel.Visible = false;
txt_DepartName.ReadOnly = true;
dgv_Depart.Enabled = true;
foreach (DataRow r in dt_Depart.Rows)
{
if (r["ID"].ToString() == dgv_Depart.SelectedRows[0].Cells[0].Value.ToString())
{
txt_ID.Text = r["ID"].ToString();
txt_DepartName.Text = r["Name"].ToString();
break;
}
}
break;
case "Empty":
btn_New.Visible = true;
btn_Edit.Visible = false;
btn_Save.Visible = false;
btn_Delete.Visible = false;
btn_Cancel.Visible = false;
txt_DepartName.ReadOnly = true;
dgv_Depart.Enabled = true;
txt_ID.Text = "";
txt_DepartName.Text = "";
if(dgv_Depart.CurrentRow != null) dgv_Depart.CurrentRow.Selected = false;
break;
}
}
void Var()
{
Depart.ID = (txt_ID.Text != "") ? Convert.ToInt16(txt_ID.Text) : 0;
Depart.Name = txt_DepartName.Text.Trim();
}
void Refresh_Data()
{
dt_Depart = Depart.Select();
dgv_Depart.DataSource = dt_Depart;
}
#endregion
#region Form
private void frm_Depart_Shown(object sender, EventArgs e)
{
if (dgv_Depart.RowCount > 0)
{
Tag = "Select";
Form_Mode("Select");
}
else
{
Tag = "Empty";
Form_Mode("Empty");
}
}
#endregion
#region Control
private void btn_New_Click(object sender, EventArgs e)
{
Tag = "New";
Form_Mode("New");
}
private void btn_Edit_Click(object sender, EventArgs e)
{
Tag = "Edit";
Form_Mode("Edit");
record_index = dgv_Depart.SelectedRows[0].Index;
}
private void btn_Save_Click(object sender, EventArgs e)
{
Var();
if (Tag.ToString() == "New")
{
Depart.Insert();
Refresh_Data();
dgv_Depart.CurrentCell = dgv_Depart.Rows[dgv_Depart.RowCount - 1].Cells[0];
}
else if (Tag.ToString() == "Edit")
{
Depart.Update();
Refresh_Data();
dgv_Depart.CurrentCell = dgv_Depart.Rows[record_index].Cells[0];
}
Tag = "Select";
Form_Mode("Select");
}
private void btn_Delete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("هل بالفعل تريد حذف إدارة " + txt_DepartName.Text, "حذف إدارة", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.No)
{
return;
}
Var();
Depart.Delete();
Refresh_Data();
Tag = "Empty";
Form_Mode("Empty");
}
private void btn_Cancel_Click(object sender, EventArgs e)
{
Tag = "Select";
Form_Mode("Select");
}
#endregion
#region dgv_Departd
private void dgv_Depart_CellClick(object sender, DataGridViewCellEventArgs e)
{
Form_Mode("Select");
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using MathApplication.Models;
namespace MathApplication.DAL
{
public class UserInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<UserContext>
{
protected override void Seed(UserContext context)
{
var userRoles = new List<UserRole>
{
new UserRole
{
ID = 0,
Label="Admin"
},
new UserRole
{
ID = 1,
Label="Student"
}
};
userRoles.ForEach(s => context.UserRoles.Add(s));
context.SaveChanges();
var userAccounts = new List<UserAccount>
{
new UserAccount
{
ID = 1,
Username = "jeremy2909",
Password = "test123",
Name = "Thanh Dang",
UserRole = 1,
UserPoint = 0
},
new UserAccount
{
ID = 2,
Username = "admin123",
Password = "test123",
Name = "Chau Dao",
UserRole = 0
},
new UserAccount
{
ID = 3,
Username = "student01",
Password = "test1",
Name = "Mary",
UserRole = 1
},
new UserAccount
{
ID = 3,
Username = "student02",
Password = "test2",
Name = "Peter",
UserRole = 1
},
new UserAccount
{
ID = 3,
Username = "student03",
Password = "test3",
Name = "John",
UserRole = 1
}
};
userAccounts.ForEach(s => context.UserAccounts.Add(s));
context.SaveChanges();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Compiler.TreeStructure;
using Compiler.TreeStructure.Expressions;
using Compiler.TreeStructure.Visitors;
namespace Compiler.FrontendPart.SemanticAnalyzer.Visitors
{
public class GenericReplacer: BaseVisitor
{
private readonly Dictionary<string, ClassName> _map;
public GenericReplacer(Dictionary<string, ClassName> map) => _map = map;
public override void Visit(ClassName className)
{
base.Visit(className);
if (!_map.ContainsKey(className.Identifier)) return;
var parent = className.Parent;
switch (parent)
{
//TODO add other cases
case ClassName parentClassName:
var i = parentClassName.Specification.IndexOf(className);
L.Log($"Replaced {parentClassName}", 4);
_map[className.Identifier].Parent = className.Parent;
parentClassName.Specification[i] = _map[className.Identifier];
break;
case Expression expression:
if (expression.PrimaryPart != className)
break;
L.Log($"Replaced {expression}", 4);
_map[className.Identifier].Parent = className.Parent;
expression.PrimaryPart = _map[className.Identifier];
break;
}
}
}
} |
using Autofac;
using BeerMapApi.Core.Interfaces;
using BeerMapApi.Core.Models;
using BeerMapApi.Core.UseCases;
namespace BeerMapApi.Core
{
public class CoreModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<BreweryUseCase>().As<IUseCase<Brewery>>().InstancePerLifetimeScope();
}
}
}
|
using NUnit.Framework;
using WpfTest01.Business.Service;
namespace WpfTest01.Test
{
[TestFixture]
public class SearchServiceTest
{
[Test]
public void CallingSearchReturnsSomeResultsTest()
{
var testTarget = new SearchService();
var actual = testTarget.Search("test name");
Assert.IsTrue(actual.Count > 0);
}
}
} |
using System;
using System.Collections.Generic;
namespace CollectionsUtility
{
/// <summary>
/// <see cref="UniqueListEx{T}"/> is a list of unique items that supports item removal and
/// replacement.
///
/// <para>
/// The list maintains the order of items in which they are added.
/// <br/>
/// When each item is added for the first time, it is assigned an index, much like the item index
/// on a <see cref="List{T}"/>.
/// <br/>
/// Adding the same item is an idempotent operation; duplicated additions are ignored.
/// </para>
///
/// <para>
/// To look up an item by index, use <see cref="UniqueListBase{T}.ItemAt(int)"/>.
/// <br/>
/// To look up the index of an item, use <see cref="UniqueListBase{T}.IndexOf(T)"/>.
/// </para>
///
/// <para>
/// Item removal only affects the item being removed. The index values assigned to other items
/// will not be affected.
/// <br/>
/// Removing an item will leave behind a hole. The index value associated with that item will
/// not be reused. Moreover, if an item is removed and then added again, its index value will
/// be reinstated.
/// </para>
///
/// <para>
/// Item replacement guarantees that the new item will take over the index value associated with
/// the old item.
/// </para>
///
/// <para>
/// Removal and replacement can be disabled by setting the respective properties
/// <see cref="CanReplace"/> and <see cref="CanRemove"/> to false.
/// </para>
///
/// <para>
/// This class internally uses a <see cref="Dictionary{TKey, TValue}"/> and its default equality
/// comparer to determine item equality and to detect duplication.
/// <br/>
/// Users should ensure that <see cref="TKey"/> implements <see cref="IEquatable{T}"/> and provides
/// a meaningful implementation of both <see cref="IEquatable{T}.Equals(T)"/> and
/// <see cref="object.GetHashCode()"/>.
/// </para>
///
/// <para>
/// The item indexers are only available via a cast to <see cref="IList{T}"/> or
/// <see cref="IReadOnlyList{T}"/>.
/// <br/>
/// The reverse indexer, <c>this[T item] => int</c>, is not provided because of a potential
/// ambiguity arising from an (<see cref="IUniqueList{T}"/> of <see cref="int"/>).
/// </para>
///
/// <para>
/// Related classes:
/// <br/>
/// <see cref="UniqueList{T}"/> does not allow removal and replacement of items already added.
/// <br/>
/// <see cref="UniqueListEx{T}"/> allows removal and replacement of items already added, although
/// it requires more careful usage as the index range of items does not correspond to
/// <c>(0 <= index < Count)</c>.
/// </para>
/// </summary>
///
/// <typeparam name="T">
/// The type of unique items that can be added to this class.
/// </typeparam>
///
public class UniqueListEx<T>
: UniqueListBase<T>
, IUniqueListEx<T>
{
sealed public override bool CanReplace
{
get;
set;
}
sealed public override bool CanRemove
{
get;
set;
}
public override T this[int index]
{
get => ItemAt(index);
set => ReplaceAt(index, value);
}
public UniqueListEx()
: base()
{
}
public UniqueListEx(int capacity)
: base(capacity)
{
}
public UniqueListEx(IEnumerable<T> items)
: base(items)
{
}
public UniqueListEx(UniqueListBase<T> other)
: base(other)
{
}
sealed public override bool Remove(T item)
{
if (!CanRemove)
{
throw new InvalidOperationException("Remove method is disallowed because CanRemove is false.");
}
if (!_lookup.TryGetValue(item, out int index))
{
return false;
}
if (!_flags[index])
{
return false;
}
_flags[index] = false;
--Count;
return true;
}
sealed public override void RemoveAt(int index)
{
if (!CanRemove)
{
throw new InvalidOperationException("RemoveAt method is disallowed because CanRemove is false.");
}
if (index < 0 || index >= _items.Count)
{
throw new ArgumentOutOfRangeException();
}
_flags[index] = false;
--Count;
}
sealed public override void Replace(T oldItem, T newItem)
{
if (!CanReplace)
{
throw new InvalidOperationException("Replace method is disallowed because CanReplace is false.");
}
if (!_lookup.TryGetValue(oldItem, out int index))
{
Add(newItem);
}
if (!_flags[index])
{
_flags[index] = true;
++Count;
}
_items[index] = newItem;
_lookup.Remove(oldItem);
_lookup.Add(newItem, index);
}
sealed public override void ReplaceAt(int index, T newItem)
{
if (!CanReplace)
{
throw new InvalidOperationException("ReplaceAt method is disallowed because CanReplace is false.");
}
if (index < 0 || index >= _items.Count)
{
throw new ArgumentOutOfRangeException();
}
if (!_flags[index])
{
_flags[index] = true;
++Count;
}
T oldItem = _items[index];
_items[index] = newItem;
_lookup.Remove(oldItem);
_lookup.Add(newItem, index);
}
}
}
|
using Alabo.Data.People.Circles.Domain.Entities;
using Alabo.Domains.Services;
using MongoDB.Bson;
namespace Alabo.Data.People.Circles.Domain.Services
{
public interface ICircleService : IService<Circle, ObjectId>
{
void Init();
}
} |
using System;
namespace CourseHunter_73_Interfaces
{
public class Program
{
static void Main(string[] args)
{
Shape[] shapes = new Shape [2];
shapes[0] = new Triangle(10, 20, 30);
shapes[1] = new Recanlge(10, 20);
foreach (Shape shape in shapes)
{
shape.Draw();
Console.WriteLine(shape.Preimeter());
}
Console.WriteLine(new string ('_', 35));
BankTerminal bankTerminal = new BankTerminal("+21425+");
bankTerminal.Connect();
ModelXTermonal modelXTermonal = new ModelXTermonal("+214257+");
modelXTermonal.Connect();
ModelYTermonal modelYTermonal = new ModelYTermonal("+213565+");
modelYTermonal.Connect();
Console.ReadLine();
}
}
}
|
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using Test_With_Frames.PageObject;
namespace Test_With_Frames.Tests
{
[TestFixture]
public class FrameTests
{
private readonly string PartOfText = "Hello ";
private readonly string PartOfTextWithBoldFont = "world!";
private IWebDriver driver;
[SetUp]
public void SetUp()
{
driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/iframe");
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15);
driver.SwitchTo().Frame(driver.FindElement(Frame.FrameById));
}
[TearDown]
public void TearDown()
{
driver.SwitchTo().DefaultContent();
driver.Quit();
}
[Test]
public void EnterTextWithDifferentFontTest()
{
Frame frame = new Frame(driver);
frame.ClearTextArea();
Assert.True(frame.TextAreaIsCleared(), "Text area isn't cleared.");
frame.EnterText(PartOfText);
Assert.True(frame.TextIsEntered(PartOfText), "First part of text is not entered.");
frame.SetBoldFont();
frame.EnterText(PartOfTextWithBoldFont);
Assert.True(frame.TextIsBold(PartOfTextWithBoldFont), "The second part of text is not entered with bold font.");
}
}
}
|
using System.Text;
using Practica2DIA.Core.Camiones;
namespace Practica2DIA.Core {
using System;
public class Cargamento
{
public string idCargamento;
public int numContenedores;
public Cargamento(string idCarga, Camion.TipoCamion tcam, string idCam, Contenedor.TipoCont tcon, string idCon)
{
if ((tcam.Equals(Camion.TipoCamion.grande) && tcon.Equals(Contenedor.TipoCont.grande)) ||
(tcam.Equals(Camion.TipoCamion.grande) && tcon.Equals(Contenedor.TipoCont.pequeno)) ||
(tcam.Equals(Camion.TipoCamion.pequeno) && tcon.Equals(Contenedor.TipoCont.pequeno)))
{
this.IdCargamento = idCarga;
this.Camion = Camion.Crea(tcam, idCam);
this.Contenedor1 = Contenedor.Crea(tcon, idCon);
this.numContenedores = 1;
}
else
{
throw new System.ArgumentException("Los parámetros introducidos son incompatibles");
}
}
public Cargamento(string idCarga, Camion.TipoCamion tcam, string idCam, Contenedor.TipoCont tcon1, string idCon1,
Contenedor.TipoCont tcon2, string idCon2)
{
if (tcam.Equals(Camion.TipoCamion.grande) && tcon1.Equals(Contenedor.TipoCont.pequeno) &&
tcon2.Equals(Contenedor.TipoCont.pequeno))
{
this.IdCargamento = idCarga;
this.Camion = Camion.Crea(tcam, idCam);
Contenedor1 = Contenedor.Crea(tcon1, idCon1);
Contenedor2 = Contenedor.Crea(tcon2, idCon2);
this.numContenedores = 2;
}
else
{
throw new System.ArgumentException("Los parámetros introducidos son incompatibles");
}
}
public string IdCargamento
{
get => idCargamento;
set => idCargamento = value;
}
public Camion Camion
{
get;
private set;
}
public Contenedor Contenedor1
{
get;
private set;
}
public Contenedor Contenedor2
{
get;
private set;
}
public override string ToString()
{
StringBuilder toret = new StringBuilder("Cargamento ");
toret.Append(IdCargamento);
toret.Append(" ,formado por Camion ");
toret.Append(Camion.ToString());
if (numContenedores == 1)
{
toret.Append(" cargando Contenedor ");
toret.Append(Contenedor1.ToString());
}
if (numContenedores == 2)
{
toret.Append(" cargando Contenedor ");
toret.Append(Contenedor1.ToString());
toret.Append(" y Contenedor ");
toret.Append(Contenedor2.ToString());
}
return toret.ToString();
}
}
} |
using System;
using System.Collections.Generic;
namespace Mastermind.NET.Models
{
/// <summary>
/// Maintains some basic information about the state of the game - number of guess attempts
/// and the generated numbers to be guessed.
/// </summary>
public class GameState : IGameState
{
/// <summary>
/// How many attempts the user made at guessing the numbers.
/// </summary>
public int Attempts { get; private set; }
/// <summary>
/// List (int) of generated numbers to guess.
/// </summary>
public List<int> Numbers { get; private set; }
/// <summary>
/// GameState constructor. Initializes the game by generating numbers and attempts counter.
/// </summary>
public GameState()
{
Attempts = 0;
var rnd = new Random(DateTime.Now.Millisecond);
Numbers = new List<int>();
// Generate 4 random numbers between 1 and 6 to start
for (int i = 0; i < 4; i++)
{
Numbers.Add(rnd.Next(1, 6));
}
}
/// <summary>
/// Attempts to increment the game counter. Throws exception if you already attempted 10 times.
/// </summary>
public void IncrementAttempts()
{
if (Attempts < 10)
{
Attempts++;
}
else
{
throw new GameException("The game is over -- too many attempts!");
}
}
// Indicates whether max attempts are exhausted.
public Boolean MaxAttemptsReached => Attempts == 10;
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using PluralKit.Core;
namespace PluralKit.Bot
{
public class MemberProxy
{
private readonly IDatabase _db;
private readonly ModelRepository _repo;
public MemberProxy(IDatabase db, ModelRepository repo)
{
_db = db;
_repo = repo;
}
public async Task Proxy(Context ctx, PKMember target)
{
if (ctx.System == null) throw Errors.NoSystemError;
if (target.System != ctx.System.Id) throw Errors.NotOwnMemberError;
ProxyTag ParseProxyTags(string exampleProxy)
{
// // Make sure there's one and only one instance of "text" in the example proxy given
var prefixAndSuffix = exampleProxy.Split("text");
if (prefixAndSuffix.Length < 2) throw Errors.ProxyMustHaveText;
if (prefixAndSuffix.Length > 2) throw Errors.ProxyMultipleText;
return new ProxyTag(prefixAndSuffix[0], prefixAndSuffix[1]);
}
async Task<bool> WarnOnConflict(ProxyTag newTag)
{
var query = "select * from (select *, (unnest(proxy_tags)).prefix as prefix, (unnest(proxy_tags)).suffix as suffix from members where system = @System) as _ where prefix = @Prefix and suffix = @Suffix and id != @Existing";
var conflicts = (await _db.Execute(conn => conn.QueryAsync<PKMember>(query,
new {Prefix = newTag.Prefix, Suffix = newTag.Suffix, Existing = target.Id, system = target.System}))).ToList();
if (conflicts.Count <= 0) return true;
var conflictList = conflicts.Select(m => $"- **{m.NameFor(ctx)}**");
var msg = $"{Emojis.Warn} The following members have conflicting proxy tags:\n{string.Join('\n', conflictList)}\nDo you want to proceed anyway?";
return await ctx.PromptYesNo(msg);
}
// "Sub"command: clear flag
if (ctx.MatchClear())
{
// If we already have multiple tags, this would clear everything, so prompt that
if (target.ProxyTags.Count > 1)
{
var msg = $"{Emojis.Warn} You already have multiple proxy tags set: {target.ProxyTagsString()}\nDo you want to clear them all?";
if (!await ctx.PromptYesNo(msg))
throw Errors.GenericCancelled();
}
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(new ProxyTag[0])};
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Proxy tags cleared.");
}
// "Sub"command: no arguments; will print proxy tags
else if (!ctx.HasNext(skipFlags: false))
{
if (target.ProxyTags.Count == 0)
await ctx.Reply("This member does not have any proxy tags.");
else
await ctx.Reply($"This member's proxy tags are:\n{target.ProxyTagsString("\n")}");
}
// Subcommand: "add"
else if (ctx.Match("add", "append"))
{
if (!ctx.HasNext(skipFlags: false)) throw new PKSyntaxError("You must pass an example proxy to add (eg. `[text]` or `J:text`).");
var tagToAdd = ParseProxyTags(ctx.RemainderOrNull(skipFlags: false));
if (tagToAdd.IsEmpty) throw Errors.EmptyProxyTags(target);
if (target.ProxyTags.Contains(tagToAdd))
throw Errors.ProxyTagAlreadyExists(tagToAdd, target);
if (!await WarnOnConflict(tagToAdd))
throw Errors.GenericCancelled();
var newTags = target.ProxyTags.ToList();
newTags.Add(tagToAdd);
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(newTags.ToArray())};
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Added proxy tags {tagToAdd.ProxyString.AsCode()}.");
}
// Subcommand: "remove"
else if (ctx.Match("remove", "delete"))
{
if (!ctx.HasNext(skipFlags: false)) throw new PKSyntaxError("You must pass a proxy tag to remove (eg. `[text]` or `J:text`).");
var tagToRemove = ParseProxyTags(ctx.RemainderOrNull(skipFlags: false));
if (tagToRemove.IsEmpty) throw Errors.EmptyProxyTags(target);
if (!target.ProxyTags.Contains(tagToRemove))
throw Errors.ProxyTagDoesNotExist(tagToRemove, target);
var newTags = target.ProxyTags.ToList();
newTags.Remove(tagToRemove);
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(newTags.ToArray())};
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Removed proxy tags {tagToRemove.ProxyString.AsCode()}.");
}
// Subcommand: bare proxy tag given
else
{
var requestedTag = ParseProxyTags(ctx.RemainderOrNull(skipFlags: false));
if (requestedTag.IsEmpty) throw Errors.EmptyProxyTags(target);
// This is mostly a legacy command, so it's gonna warn if there's
// already more than one proxy tag.
if (target.ProxyTags.Count > 1)
{
var msg = $"This member already has more than one proxy tag set: {target.ProxyTagsString()}\nDo you want to replace them?";
if (!await ctx.PromptYesNo(msg))
throw Errors.GenericCancelled();
}
if (!await WarnOnConflict(requestedTag))
throw Errors.GenericCancelled();
var newTags = new[] {requestedTag};
var patch = new MemberPatch {ProxyTags = Partial<ProxyTag[]>.Present(newTags)};
await _db.Execute(conn => _repo.UpdateMember(conn, target.Id, patch));
await ctx.Reply($"{Emojis.Success} Member proxy tags set to {requestedTag.ProxyString.AsCode()}.");
}
}
}
} |
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.ListadoContrato
{
/// <summary>
/// Modelo de vista de Contrato Párrafo
/// </summary>
/// <remarks>
/// Creación: GMD 20150603 </br>
/// Modificación: </br>
/// </remarks>
public class ContratoParrafoFormulario : GenericViewModel
{
/// <summary>
/// Constructor usado para el registro de datos
/// </summary>
public ContratoParrafoFormulario()
{
this.ContratoParrafo = new ContratoResponse();
}
/// <summary>
/// Constructor usado para el registro de datos
/// </summary>
/// <param name="plantillaParrafo">Lista de Plantilla Párrafo</param>
/// <param name="plantillaParrafoVariable">Lista de Plantilla Párrafo Variable</param>
/// <param name="indicadorUltimoParrafo">Indicador de Último Párrafo</param>
/// <param name="listaVariablePorDefecto">Lista de Variables por Defecto</param>
/// <param name="listaValoresVariableParrafo">Lista de Variables grabadas parcialmente</param>
public ContratoParrafoFormulario(List<PlantillaParrafoResponse> plantillaParrafo, List<PlantillaParrafoVariableResponse> plantillaParrafoVariable, List<CodigoValorResponse> listaVariablePorDefecto, List<ContratoParrafoVariableResponse> listaValoresVariableParrafo, string intervaloTiempoAutoguardado)
{
this.ListaPlantillaParrafo = plantillaParrafo;
this.ListaPlantillaParrafoVariable = plantillaParrafoVariable;
this.IndicadorExistePlantilla = true;
this.ListaVariablePorDefecto = listaVariablePorDefecto;
this.ListaValoresVariableParrafo = listaValoresVariableParrafo;
this.IntervaloTiempoAutoguardado = intervaloTiempoAutoguardado;
}
#region Propiedades
/// <summary>
/// Indicador de Existe Plantilla
/// </summary>
public bool IndicadorExistePlantilla { get; set; }
/// <summary>
/// Clase Response de Contrato Párrafo
/// </summary>
public ContratoResponse ContratoParrafo { get; set; }
/// <summary>
/// Clase Response de Plantilla Párrafo
/// </summary>
public List<PlantillaParrafoResponse> ListaPlantillaParrafo { get; set; }
/// <summary>
/// Lista de Plantilla Párrafo Variable
/// </summary>
public List<PlantillaParrafoVariableResponse> ListaPlantillaParrafoVariable { get; set; }
/// <summary>
/// Lista de Variables
/// </summary>
public List<CodigoValorResponse> ListaVariablePorDefecto { get; set; }
/// <summary>
/// Lista de Valores de las variables de los parrafos de un contrato
/// </summary>
public List<ContratoParrafoVariableResponse> ListaValoresVariableParrafo { get; set; }
/// <summary>
/// Intervalo de Tiempo de Autoguardado
/// </summary>
public string IntervaloTiempoAutoguardado { get; set; }
/// <summary>
/// Copia
/// </summary>
public bool EsCopia { get; set; }
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SQLite;
using Xamarin.Essentials;
// This file has some data that is uhh.. confidential?
namespace NSchedule.Entities
{
public class Settings
{
[PrimaryKey]
[Column("id")]
public int Id { get; set; } = 0;
[Column("sess")]
public string CookieString { get; set; } = "";
[Column("email")]
public string Email { get; set; } = "";
[Column("pass")]
public string Password { get; set; } = "";
[Column("locale")]
public string Locale { get; set; } = "en";
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Collections;
using SQMS.IntegrityServices;
namespace SQMS.IntegrityServices
{
/// <summary>
/// Summary description for FileJoinService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class FileJoinService : System.Web.Services.WebService
{
[WebMethod]
public string BasePath()
{
return Context.Server.MapPath("/QualityData");
}
[WebMethod]
public bool JoinFile(string deviceId, string fileName)
{
try
{
if (!CheckFileName(fileName)) return false;
string basePath = Context.Server.MapPath("/QualityData");
//string basePath = System.IO.Path.GetDirectoryName(fileName);
string baseFileName = Path.GetFileNameWithoutExtension(@basePath + "\\" + fileName);
string baseFileExtName = Path.GetExtension(@basePath + "\\" + fileName);
SQMS.IntegrityServices.FileJoiner fj = new SQMS.IntegrityServices.FileJoiner();
fj.JoinFile(@basePath + "\\" + fileName);
ArrayList fileList = new ArrayList(System.IO.Directory.GetFiles(@basePath, baseFileName + @".*"));
int baseFileNumber = fileList.Count;
for (int i = 0; i < baseFileNumber; i++)
{
if (@basePath + "\\" + baseFileName != fileList[i].ToString())
File.Delete(fileList[i].ToString());
}
if (!File.Exists(@basePath + "\\" + deviceId)) Directory.CreateDirectory(@basePath + "\\" + deviceId);
File.Move(@basePath + "\\" + baseFileName, @basePath + "\\" + deviceId + "\\" + baseFileName);
string[] sArray = baseFileName.Split('.');
File.Move(@basePath + "\\" + sArray[0].ToString() + ".txt", @basePath + "\\" + deviceId + "\\" + sArray[0].ToString() + ".txt");
}
catch (Exception ex)
{
return false;
}
return true;
}
private bool CheckFileName(string filename)
{
if ((filename == "") || (filename == null))
{
return false;
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.IntelligenceDiningTable
{
/// <summary>
/// 菜品详细
/// </summary>
public class E_DishInfo
{
/// <summary>
/// 记录ID
/// </summary>
public int id { get; set; }
/// <summary>
/// 菜品ID
/// </summary>
public int DID { get; set; }
/// <summary>
/// 原料名称
/// </summary>
public string DName { get; set; }
/// <summary>
/// 净用量
/// </summary>
public string Content { get; set; }
/// <summary>
/// 原料ID
/// </summary>
public int RawID { get; set; }
/// <summary>
/// 原料种属
/// </summary>
public string zs { get; set; }
/// <summary>
/// 原料热量
/// </summary>
public string Re { get; set; }
/// <summary>
/// 净用量
/// </summary>
public float numcontent { get; set; }
/// <summary>
/// 是否辅料
/// </summary>
public int IsAccessories { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using com.Sconit.Entity.MD;
namespace com.Sconit.Web.Models.SearchModels.MD
{
public class PartyAddressSearchModel : SearchModelBase
{
public string AddressCode { get; set; }
public string AddressContent { get; set; }
}
} |
namespace E_ticaret.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("kargo")]
public partial class kargo
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public kargo()
{
siparis = new HashSet<sipari>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int kargo_id { get; set; }
[StringLength(50)]
public string firma { get; set; }
public string aciklama { get; set; }
public int? telefon { get; set; }
[StringLength(50)]
public string website { get; set; }
[StringLength(50)]
public string e_posta { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<sipari> siparis { get; set; }
}
}
|
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 SearchForm
{
public partial class Form1 : Form
{
// Class variables for generating random numbers
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
private static int[] arr = new int[100];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
loadArray(arr);
DisplayArray(arr);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void SearchText_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int searchNumber;
//int[] arr = new int[100];
//loadArray(arr);
//DisplayArray(arr);
bool isInputNumeric = Int32.TryParse(SearchText.Text, out searchNumber);
if (isInputNumeric == false)
MessageBox.Show("Please enter a numeric value.");
else
{
//loadArray(arr);
//DisplayArray(arr);
if (SeqSearch(arr, searchNumber) == true)
MessageBox.Show("Sequential Search found " + searchNumber + " in the array!");
else
MessageBox.Show("Sequential Search did not find " + searchNumber + " in the array.");
}
}
public static bool SeqSearch(int[] arr, int sValue)
{
for (int i = 0; i < arr.Length; i++)
if (arr[i] == sValue)
return true;
return false;
}
// This method loads up the array with random integers
public static void loadArray(int[] arr)
{
int Min = 0;
int Max = arr.Length * 10;
for (int i = 0; i < arr.Length; i++)
{
int next = 0;
while (true)
{
next = RandomNumber(Min, Max);
if (!Contains(arr, next))
break;
}
arr[i] = next;
}
}
//Function to get a random number
public static int RandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return random.Next(min, max);
}
}
// Using this to get unique numbers into the array
public static bool Contains(int[] array, int val)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == val)
return true;
}
return false;
}
public static void DisplayArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Console.WriteLine("");
}
}
}
|
using System;
using System.Collections.Generic;
namespace ReactMusicStore.Core.Data.Context.Utilities.Hooks
{
public class HookMetadata
{
/// <summary>
/// The type of entity
/// </summary>
public Type HookedType { get; set; }
/// <summary>
/// The type of the hook class itself
/// </summary>
public Type ImplType { get; set; }
/// <summary>
/// Whether the hook should run in any case, even if hooking has been turned off.
/// </summary>
public bool Important { get; set; }
}
public interface IHookHandler
{
bool HasImportantPreHooks();
bool HasImportantPostHooks();
/// <summary>
/// Triggers all pre action hooks
/// </summary>
/// <param name="entries">Entries</param>
/// <param name="requiresValidation"></param>
/// <param name="importantHooksOnly"></param>
/// <returns><c>true</c> if the state of any entry changed</returns>
bool TriggerPreActionHooks(IEnumerable<HookedEntityEntry> entries, bool requiresValidation, bool importantHooksOnly);
/// <summary>
/// Triggers all post action hooks
/// </summary>
/// <param name="entries">Entries</param>
/// <param name="importantHooksOnly"></param>
void TriggerPostActionHooks(IEnumerable<HookedEntityEntry> entries, bool importantHooksOnly);
}
public sealed class NullHookHandler : IHookHandler
{
private readonly static IHookHandler s_instance = new NullHookHandler();
public static IHookHandler Instance
{
get { return s_instance; }
}
public bool HasImportantPostHooks()
{
return false;
}
public bool HasImportantPreHooks()
{
return false;
}
public void TriggerPostActionHooks(IEnumerable<HookedEntityEntry> entries, bool importantHooksOnly)
{
}
public bool TriggerPreActionHooks(IEnumerable<HookedEntityEntry> entries, bool requiresValidation, bool importantHooksOnly)
{
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShapeLibrary
{
public abstract class Quadrilateral : Shape, IShapeCalc
{
public double Side1Length { get; set; }
public double Side2Length { get; set; }
public double Side3Length { get; set; }
public double Side4Length { get; set; }
public Quadrilateral(string sColour, double s1, double s2, double s3, double s4) : base(sColour)
{
Side1Length = s1;
Side2Length = s2;
Side3Length = s3;
Side4Length = s4;
}
public virtual double GetPerimeter()
{
return Side1Length + Side2Length + Side3Length + Side4Length;
}
public override string ToString()
{
return "Color: " + Colour + " Perimeter: " + GetPerimeter() + " Area: " + GetArea() + " ";
}
public virtual double GetArea()
{
return Side1Length * Side2Length;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PokerEnumLibrary
{
public static class ColourUtilities
{
public static void PrintColours()
{
foreach (Colours colour in Enum.GetValues(typeof(Colours)))
{
Console.WriteLine("{0:D} {0:G}", colour);
}
}
}
}
|
using AsyncInn.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AsyncInn.Web.Services
{
public interface IHotelService
{
Task<List<Hotel>> GetHotels();
Task<Hotel> GetHotelById(long id);
Task<Hotel> Create(Hotel hotel);
Task Delete(long id);
Task<Hotel> Edit(long id, Hotel hotel);
}
}
|
using System;
using System.Collections.Generic;
namespace Restaurants.Domain
{
public interface IMenuRepository : IRepositoryBase<Menu>
{
List<Menu> GetMenuByRestaurant(int idRestaurant);
}
}
|
#pragma warning disable IDE0063 // Use simple 'using' statement
#pragma warning disable IDE0051 // Remove unused private members
using System;
using System.IO;
using System.Linq;
using System.Reflection;
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace Common
{
public static class ScriptableSettingsUtility
{
[InitializeOnLoadMethod]
static void EnsureObjectsCreated()
{
var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.ExportedTypes).Where(t => typeof(ScriptableSettingsBase).IsAssignableFrom(t) && !t.IsAbstract).ToArray();
foreach (var t in types)
{
var method = typeof(ScriptableSettings<>).MakeGenericType(t).GetMethod("EnsureExists", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod);
method?.Invoke(null, null);
}
CreateMenuItems();
}
static void CreateMenuItems()
{
var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.ExportedTypes).
Where(t => typeof(ScriptableSettingsBase).IsAssignableFrom(t) && !t.IsAbstract).
Select(t => (type: t, name: t.Name.Replace("Settings", ""))).
ToArray();
var path = "Assets/Settings/MenuItems.cs";
if (!types.Any())
{
if (AssetDatabase.LoadAssetAtPath<MonoScript>(path) is MonoScript script)
AssetDatabase.DeleteAsset(path);
return;
}
EditorFolderUtility.EnsureFolderExists("Assets/Settings");
using (var writer = new StreamWriter(path))
{
writer.WriteLine("//Automatically generated class, any changes made will be overwritten.");
writer.WriteLine("");
writer.WriteLine("#if UNITY_EDITOR");
writer.WriteLine("");
writer.WriteLine("using UnityEditor;");
writer.WriteLine("");
writer.WriteLine("namespace Common.Settings.MenuItems");
writer.WriteLine("{");
writer.WriteLine("");
writer.WriteLine(" ///<summary>Automatically generated class to provide menu items for each ScriptableSettings under 'Settings' menu item.");
writer.WriteLine(" public static class SettingMenuItems");
writer.WriteLine(" {");
int i = 0;
foreach (var (type, name) in types)
{
writer.WriteLine("");
writer.WriteLine($@" [MenuItem(""Settings/{name}"")]");
writer.WriteLine($@" public static void Item{i}() => ScriptableSettingsUtility.OpenInEditor(""Assets/Settings/Resources/Settings/{type.Name}.asset"");");
i += 1;
}
writer.WriteLine("");
writer.WriteLine(" }");
writer.WriteLine("");
writer.WriteLine("}");
writer.WriteLine("#endif");
}
if (!AssetDatabase.LoadAssetAtPath<MonoScript>(path))
AssetDatabase.Refresh();
}
/// <summary>Opens the ScriptableSettings in an editor window.</summary>
public static void OpenInEditor(string path)
{
var asset = AssetDatabase.LoadAssetAtPath<ScriptableSettingsBase>(path);
if (asset)
{
var window = EditorWindow.GetWindow<Window>(asset.name.Replace("Settings", ""));
window.titleContent = new GUIContent(asset.name.Replace("Settings", ""));
window.target = asset;
window.Show();
}
}
class Window : EditorWindow
{
public ScriptableObject target;
Editor editor;
private void OnGUI()
{
if (!editor)
editor = Editor.CreateEditor(target);
editor.DrawHeader();
editor.OnInspectorGUI();
}
}
}
}
#endif
|
using System;
using System.Collections.Generic;
using ReactMusicStore.Core.Domain.Entities.Foundation;
using ReactMusicStore.Core.Domain.Entities.Validations;
using ReactMusicStore.Core.Domain.Interfaces.Validation;
using ReactMusicStore.Core.Domain.Validation;
namespace ReactMusicStore.Core.Domain.Entities
{
public class Order : BaseEntity, ISelfValidation
{
//public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public decimal Total { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
public ValidationResult ValidationResult { get; private set; }
public bool IsValid
{
get
{
var fiscal = new OrderIsValidValidation();
ValidationResult = fiscal.Valid(this);
return ValidationResult.IsValid;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using ToDoApp.Models;
using Microsoft.EntityFrameworkCore;
namespace ToDoApp.Controllers
{
[ApiController]
[Route("api/tasks")]
public class TaskController : Controller
{
ApplicationContext db;
public TaskController(ApplicationContext context){
db = context;
if (!db.Tasks.Any())
{
db.Tasks.Add(new Task { Text = "To do math!", Category = "Homework", Date = DateTime.Today.Date.AddHours(5), Done = false });
//db.Tasks.Add(new Task { Text = "To do chemistry!", Category = new Category { Name = "Homework", Color = "Yellow" }, Date = DateTime.Today, Done = false });
db.Tasks.Add(new Task { Text = "To add angular material", Category = "Work", Date = DateTime.Today.Date.AddHours(5), Done = false});
db.SaveChanges();
}
}
[HttpGet]
public IEnumerable<Task> Get()
{
return db.Tasks.ToList();
}
[HttpGet("{id}")]
public Task Get(int id)
{
Task task = db.Tasks.FirstOrDefault(x => x.Id == id);
return task;
}
[HttpPost]
public IActionResult Post(Task task)
{
if (ModelState.IsValid)
{
task.Date.AddHours(5);
db.Tasks.Add(task);
db.SaveChanges();
return Ok(task);
}
return BadRequest(ModelState);
}
[HttpPut]
public IActionResult Put(Task task)
{
if (ModelState.IsValid)
{
task.Date.AddHours(5);
db.Update(task);
db.SaveChanges();
return Ok(task);
}
return BadRequest(ModelState);
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
Task task = db.Tasks.FirstOrDefault(x => x.Id == id);
if (task != null)
{
db.Tasks.Remove(task);
db.SaveChanges();
}
return Ok(task);
}
}
}
|
using ParrisConnection.ServiceLayer.Data;
using System.Collections.Generic;
namespace ParrisConnection.ServiceLayer.Services.Employer.Queries
{
public interface IEmployerQueryService
{
IEnumerable<EmployerData> GetEmployers();
IEnumerable<EmployerData> GetEmployersByUserId(string userId);
EmployerData GetEmployerById(int id);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShootScript : MonoBehaviour
{
[SerializeField]
int shootDelay = 3;
public GameObject projectile;
public bool isYellow;
public bool isGreen;
GameObject player;
bool shooted;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindWithTag("Player");
}
void Shoot() {
GameObject p = Instantiate(projectile,
transform.position,
transform.rotation);
p.GetComponent<EnemyProjectileScript>().colour = GetComponent<MeshRenderer>().material.color;
p.GetComponent<EnemyProjectileScript>().target = GetComponent<EnemyMovementScript>().target;
if (isYellow)
p.GetComponent<EnemyProjectileScript>().speed = 250;
else if (isGreen)
p.GetComponent<EnemyProjectileScript>().isGreen = true;
shooted = true;
Invoke("ResetShoot", shootDelay);
}
void ResetShoot() {
shooted = false;
}
// Update is called once per frame
void Update()
{
if (!shooted)
Shoot();
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using PhobiaX.SDL2.Wrappers;
using SDL2;
using static SDL2.SDL;
namespace PhobiaX.SDL2
{
public class SDLKeyboardStates
{
private int numkeys = 0;
private IntPtr keysBuffer;
private byte[] keysCurr = new byte[(int)SDL_Scancode.SDL_NUM_SCANCODES];
private byte[] keysPrev = new byte[(int)SDL_Scancode.SDL_NUM_SCANCODES];
private Dictionary<SDL_Scancode, Action> eventsToActionsMap = new Dictionary<SDL_Scancode, Action>();
private Dictionary<SDL_Scancode, Action> eventsToActionsWhenNotPressedMap = new Dictionary<SDL_Scancode, Action>();
public SDLKeyboardStates(ISDL2 sdl2)
{
_ = sdl2 ?? throw new ArgumentNullException(nameof(sdl2));
keysBuffer = sdl2.GetKeyboardState(out numkeys);
}
public void Clear()
{
eventsToActionsMap.Clear();
eventsToActionsWhenNotPressedMap.Clear();
}
public void RegisterEvents(SDL_Scancode scanCode, bool isReleased, Action eventMethod)
{
if (!isReleased)
{
if (eventsToActionsMap.TryGetValue(scanCode, out var actionMethod))
{
eventsToActionsMap[scanCode] = () => { actionMethod(); eventMethod(); };
}
else
{
eventsToActionsMap.Add(scanCode, eventMethod);
}
}
else
{
if (eventsToActionsWhenNotPressedMap.TryGetValue(scanCode, out var actionMethod))
{
eventsToActionsWhenNotPressedMap[scanCode] = () => { actionMethod(); eventMethod(); };
}
else
{
eventsToActionsWhenNotPressedMap.Add(scanCode, eventMethod);
}
}
}
public void ScanKeys()
{
var tmp = keysPrev;
keysPrev = keysCurr;
keysCurr = tmp;
Marshal.Copy(keysBuffer, keysCurr, 0, numkeys);
for (int i = 0; i < keysCurr.Length; i++)
{
var map = eventsToActionsWhenNotPressedMap;
if (keysCurr[i] == 1)
{
map = eventsToActionsMap;
}
var keyCode = (SDL_Scancode)i;
if (map.TryGetValue(keyCode, out Action eventMethod))
{
eventMethod();
}
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Task1;
namespace PenTests
{
[TestClass]
public class PenTest
{
[TestMethod]
public void Constructor1ParamTest()
{
Pen pen = new Pen(10);
Assert.IsNotNull(pen);
}
[TestMethod]
public void Constructor2ParamsTest()
{
Pen pen = new Pen(10, 1.1);
Assert.IsNotNull(pen);
}
[TestMethod]
public void Constructor3ParamsTest()
{
Pen pen = new Pen(10, 1.1, "RED");
Assert.IsNotNull(pen);
}
[TestMethod]
public void DefautColorTest()
{
Pen pen = new Pen(10, 1.1);
Assert.AreEqual(pen.GetColor(), "BLUE");
}
[TestMethod]
public void ChangeColorTest()
{
Pen pen = new Pen(10, 1.1, "RED");
Assert.AreEqual(pen.GetColor(), "RED");
}
[TestMethod]
public void WritePartialContainer2ParamsTest()
{
Pen pen = new Pen(10, 1.1);
String word = pen.Write("12345");
Assert.AreEqual(word, "12345");
}
[TestMethod]
public void WriteAllContainer2ParamsTest()
{
Pen pen = new Pen(10, 1.1);
String word = pen.Write("1234567890");
Assert.AreEqual(word, "123456789");
}
[TestMethod]
public void WriteAllContainer1ParamTest()
{
Pen pen = new Pen(6);
String word = pen.Write("123456");
Assert.AreEqual(word, "123456");
}
[TestMethod]
public void WritePartialContainer1ParamTest()
{
Pen pen = new Pen(6);
pen.Write("12345");
Assert.AreEqual(pen.Write("6789"), "6");
}
[TestMethod]
public void IsWorkMethodTest()
{
Pen pen = new Pen(5);
pen.Write("12345");
Assert.IsFalse(pen.IsWork());
}
[TestMethod]
public void WriteEmptyTest()
{
Pen pen = new Pen(5);
pen.Write("12345");
Assert.AreEqual(pen.Write("123"), "");
}
[TestMethod]
public void NegativeContainerTest()
{
bool wasException = false;
try
{
Pen pen = new Pen(-2);
}
catch
{
wasException = true;
}
Assert.IsTrue(wasException);
}
[TestMethod]
public void NegativeSizeLetterTest()
{
bool wasException = false;
try
{
Pen pen = new Pen(5, -1.2);
}
catch
{
wasException = true;
}
Assert.IsTrue(wasException);
}
[TestMethod]
public void DoSomethingElseTest()
{
bool wasException = false;
try
{
Pen pen = new Pen(5, -1.2);
}
catch
{
wasException = true;
}
Assert.IsFalse(wasException);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace MoneyShare.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class InternalAdminController : ControllerBase
{
[Authorize(Roles = "Admin")]
public ActionResult GetAction()
{
string name = this.HttpContext.User.Identity.Name;
return Ok();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace JustRipeFarm.ClassEntity
{
class InsertSQL
{
public int addNewCustomer(Customer customer)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " customer(name,email,phone,remark)" +
" VALUES" + " (@name,@email,@phone,@remark)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@name", MySqlDbType.Text).Value = customer.Name;
sqlComm.Parameters.Add("@email", MySqlDbType.Text).Value = customer.Email;
sqlComm.Parameters.Add("@phone", MySqlDbType.Text).Value = customer.Phone;
sqlComm.Parameters.Add("@remark", MySqlDbType.Text).Value = customer.Remark;
return sqlComm.ExecuteNonQuery();
}
public int addNewStore(Storeroom storeroom)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " storeroom(description,storingQty,temperature,availability)" +
" VALUES" + " (@description,@storingQty,@temperature,@availability)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = storeroom.Description;
sqlComm.Parameters.Add("@storingQty", MySqlDbType.UInt32).Value = storeroom.StoringQty;
sqlComm.Parameters.Add("@temperature", MySqlDbType.Text).Value = storeroom.Temperature;
sqlComm.Parameters.Add("@availability", MySqlDbType.UInt64).Value = storeroom.Availability;
return sqlComm.ExecuteNonQuery();
}
public int addNewVehicle(Vehicle vehicle)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " vehicle(name,serial_number,buy_date,last_service_date,remark)" +
" VALUES" + " (@name,@serial_number,@buy_date,@last_service_date,@remark)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@name", MySqlDbType.Text).Value = vehicle.Name;
sqlComm.Parameters.Add("@serial_number", MySqlDbType.UInt32).Value = vehicle.Serial_number;
sqlComm.Parameters.Add("@buy_date", MySqlDbType.Date).Value = vehicle.Buy_date;
sqlComm.Parameters.Add("@last_service_date", MySqlDbType.Date).Value = vehicle.Last_service_date;
sqlComm.Parameters.Add("@remark", MySqlDbType.Text).Value = vehicle.Remark;
return sqlComm.ExecuteNonQuery();
}
public int addNewOrder(Order order)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " orders(description,product_id,quantity_box,weight,palletAllocation,customer_id,order_date,collection,price,status,remark)" +
" VALUES" + " (@description,@product_id,@quantity_box,@weight,@palletAllocation,@customer_id,@order_date,@collection,@price,@status,@remark)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = order.Description;
sqlComm.Parameters.Add("@product_id", MySqlDbType.UInt32).Value = order.Product_id;
sqlComm.Parameters.Add("@quantity_box", MySqlDbType.UInt32).Value = order.Quantity_box;
sqlComm.Parameters.Add("@weight", MySqlDbType.Decimal).Value = order.Weight;
sqlComm.Parameters.Add("@palletAllocation", MySqlDbType.UInt32).Value = order.PalletAllocation;
sqlComm.Parameters.Add("@customer_id", MySqlDbType.UInt32).Value = order.Customer_id;
sqlComm.Parameters.Add("@order_date", MySqlDbType.Date).Value = order.Order_date;
sqlComm.Parameters.Add("@collection", MySqlDbType.Date).Value = order.Collection_date;
sqlComm.Parameters.Add("@price", MySqlDbType.Decimal).Value = order.Price;
sqlComm.Parameters.Add("@status", MySqlDbType.Text).Value = order.Status;
sqlComm.Parameters.Add("@remark", MySqlDbType.Text).Value = order.Remark;
return sqlComm.ExecuteNonQuery();
}
public int addNewProduct(Product product)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " product(name,type,quantity_box,weight,box_id)" +
" VALUES" + " (@name,@type,@quantity_box,@weight,@box_id)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@name", MySqlDbType.Text).Value = product.Name;
sqlComm.Parameters.Add("@type", MySqlDbType.Text).Value = product.Type;
sqlComm.Parameters.Add("@quantity_box", MySqlDbType.UInt32).Value = product.Quantity_box;
sqlComm.Parameters.Add("@weight", MySqlDbType.Decimal).Value = product.Weight;
sqlComm.Parameters.Add("@box_id", MySqlDbType.UInt32).Value = product.Box_id;
return sqlComm.ExecuteNonQuery();
}
public int addNewFarm(Farm farm)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " farm(description,area,utilize_area)" +
" VALUES" + " (@description,@area,@utilize_area)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = farm.Description;
sqlComm.Parameters.Add("@area", MySqlDbType.Int32).Value = farm.Area;
sqlComm.Parameters.Add("@utilize_area", MySqlDbType.Int32).Value = farm.Utilize_area;
return sqlComm.ExecuteNonQuery();
}
public int addNewEmployee(Employee employee)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " employee(first_name,last_name,username,password,dob,mobile,email,admin,status,remark)" +
" VALUES" + " (@first_name,@last_name,@username,@password,@dob,@mobile,@email,@admin,@status,@remark)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@first_name", MySqlDbType.Text).Value = employee.First_name;
sqlComm.Parameters.Add("@last_name", MySqlDbType.Text).Value = employee.Last_name;
sqlComm.Parameters.Add("@username", MySqlDbType.Text).Value = employee.Username;
sqlComm.Parameters.Add("@password", MySqlDbType.Text).Value = employee.Password;
sqlComm.Parameters.Add("@dob", MySqlDbType.Date).Value = employee.Dob;
sqlComm.Parameters.Add("@mobile", MySqlDbType.Text).Value = employee.Mobile;
sqlComm.Parameters.Add("@email", MySqlDbType.Text).Value = employee.Email;
sqlComm.Parameters.Add("@admin", MySqlDbType.UInt32).Value = employee.Admin;
sqlComm.Parameters.Add("@status", MySqlDbType.Text).Value = employee.Status;
sqlComm.Parameters.Add("@remark", MySqlDbType.Text).Value = employee.Remark;
return sqlComm.ExecuteNonQuery();
}
public int addNewCrop(Crop crop)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " crop(name, type, quantity_plot, remark)" +
"VALUES" + "(@name, @type, @quantity_plot, @remark)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@name", MySqlDbType.Text).Value = crop.Name;
sqlComm.Parameters.Add("@type", MySqlDbType.Text).Value = crop.Type;
sqlComm.Parameters.Add("@quantity_plot", MySqlDbType.UInt32).Value = crop.Quantity_plot;
sqlComm.Parameters.Add("@remark", MySqlDbType.Text).Value = crop.Remark;
return sqlComm.ExecuteNonQuery();
}
public int addNewBox(Box box)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " box(name, width, height, length, max_weight, quantity, status)" +
"VALUES" + "(@name, @width, @height, @length, @max_weight, @quantity, @status)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@name", MySqlDbType.Text).Value = box.Name;
sqlComm.Parameters.Add("@Width", MySqlDbType.Decimal).Value = box.Width;
sqlComm.Parameters.Add("@Height", MySqlDbType.Decimal).Value = box.Height;
sqlComm.Parameters.Add("@Length", MySqlDbType.Decimal).Value = box.Length;
sqlComm.Parameters.Add("@max_weight", MySqlDbType.Decimal).Value = box.Max_weight;
sqlComm.Parameters.Add("@quantity", MySqlDbType.UInt32).Value = box.Quantity;
sqlComm.Parameters.Add("@status", MySqlDbType.Text).Value = box.Status;
return sqlComm.ExecuteNonQuery();
}
public int addNewBoxStorage(BoxStorage boxstorage)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " box(storingJob_id, product_id, box_id, nettWeight, storeroom_id, add_date, best_before, out_date, order_id)" +
"VALUES" + "(@storingJob_id, @product_id, @box_id, @nettWeight, @storeroom_id, @add_date, @best_before, @out_date, @order_id)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@storingJob_id", MySqlDbType.UInt32).Value = boxstorage.StoringJob_id;
sqlComm.Parameters.Add("@product_id", MySqlDbType.UInt32).Value = boxstorage.Product_id;
sqlComm.Parameters.Add("@box_id", MySqlDbType.UInt32).Value = boxstorage.Box_id;
sqlComm.Parameters.Add("@nettWeight", MySqlDbType.Decimal).Value = boxstorage.NettWeight;
sqlComm.Parameters.Add("@storeroom_id", MySqlDbType.UInt32).Value = boxstorage.Storeroom_id;
sqlComm.Parameters.Add("@add_date", MySqlDbType.Date).Value = boxstorage.Storeroom_id;
sqlComm.Parameters.Add("@best_before", MySqlDbType.Date).Value = boxstorage.Storeroom_id;
sqlComm.Parameters.Add("@out_date", MySqlDbType.Date).Value = boxstorage.Storeroom_id;
sqlComm.Parameters.Add("@order_id", MySqlDbType.UInt32).Value = boxstorage.Storeroom_id;
return sqlComm.ExecuteNonQuery();
}
public int addNewSowingJob(SowingJob sowingjob)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " sowingjob(description, crop_id, quantity_prop, farm_id, used_area, vehicle_id, employee_id, date_start, date_end)" +
"VALUES" + "(@description, @crop_id, @quantity_prop, @farm_id, @used_area, @vehicle_id, @employee_id, @date_start, @date_end)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = sowingjob.Description;
sqlComm.Parameters.Add("@crop_id", MySqlDbType.UInt32).Value = sowingjob.Crop_id;
sqlComm.Parameters.Add("@quantity_prop", MySqlDbType.UInt32).Value = sowingjob.Quantity_prop;
sqlComm.Parameters.Add("@farm_id", MySqlDbType.UInt32).Value = sowingjob.Farm_id;
sqlComm.Parameters.Add("@used_area", MySqlDbType.Text).Value = sowingjob.Used_area;
sqlComm.Parameters.Add("@vehicle_id", MySqlDbType.UInt32).Value = sowingjob.Vehicle_id;
sqlComm.Parameters.Add("@employee_id", MySqlDbType.UInt32).Value = sowingjob.Employee_id;
sqlComm.Parameters.Add("@date_start", MySqlDbType.Date).Value = sowingjob.Date_start;
sqlComm.Parameters.Add("@date_end", MySqlDbType.Date).Value = sowingjob.Date_end;
return sqlComm.ExecuteNonQuery();
}
public int addNewHarvestingJob(HarvestingJob harvestingjob)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " harvestingjob(description, sowingJob_id, farm_id, crop_id, vehicle_id, est_quantity, harvested_quantity, employee_id, date_start, date_end)" +
" VALUES" + " (@description, @sowingJob_id, @farm_id, @crop_id, @vehicle_id, @est_quantity, @harvested_quantity, @employee_id, @date_start, @date_end)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = harvestingjob.Description;
sqlComm.Parameters.Add("@sowingJob_id", MySqlDbType.UInt32).Value = harvestingjob.Crop_id;
sqlComm.Parameters.Add("@farm_id", MySqlDbType.UInt32).Value = harvestingjob.Farm_id;
sqlComm.Parameters.Add("@crop_id", MySqlDbType.UInt32).Value = harvestingjob.Crop_id;
sqlComm.Parameters.Add("@vehicle_id", MySqlDbType.UInt32).Value = harvestingjob.Vehicle_id;
sqlComm.Parameters.Add("@est_quantity", MySqlDbType.Text).Value = harvestingjob.Est_quantity;
sqlComm.Parameters.Add("@harvested_quantity", MySqlDbType.Text).Value = harvestingjob.Harvested_quantity;
sqlComm.Parameters.Add("@employee_id", MySqlDbType.UInt32).Value = harvestingjob.Employee_id;
sqlComm.Parameters.Add("@date_start", MySqlDbType.Date).Value = harvestingjob.Date_start;
sqlComm.Parameters.Add("@date_end", MySqlDbType.Date).Value = harvestingjob.Date_end;
return sqlComm.ExecuteNonQuery();
}
public int addNewStoringJob(StoringJob storingjob)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " storingjob(description, harvest_id, crop_id, box_id, quantity, vehicle_id, employee_id, date_start, date_end)" +
"VALUES" + "(@description, @harvest_id, @crop_id, @box_id, @quantity, @vehicle_id, @employee_id, @date_start, @date_end)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = storingjob.Description;
sqlComm.Parameters.Add("@harvest_id", MySqlDbType.UInt32).Value = storingjob.Harvest_id;
sqlComm.Parameters.Add("@crop_id", MySqlDbType.UInt32).Value = storingjob.Crop_id;
sqlComm.Parameters.Add("@box_id", MySqlDbType.UInt32).Value = storingjob.Box_id;
sqlComm.Parameters.Add("@quantity", MySqlDbType.UInt32).Value = storingjob.Quantity;
sqlComm.Parameters.Add("@vehicle_id", MySqlDbType.UInt32).Value = storingjob.Vehicle_id;
sqlComm.Parameters.Add("@employee_id", MySqlDbType.UInt32).Value = storingjob.Employee_id;
sqlComm.Parameters.Add("@date_start", MySqlDbType.Date).Value = storingjob.Date_start;
sqlComm.Parameters.Add("@date_end", MySqlDbType.Date).Value = storingjob.Date_end;
return sqlComm.ExecuteNonQuery();
}
public int addNewFertilisingJob(FertilisingJob fertilisingjob)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " fertilisingjob(description, fertiliser_id, quantity_kg, sowingJob_id, farm_id, crop_id, vehicle_id, employee_id, date_start, date_end)" +
"VALUES" + "(@description, @fertiliser_id, @quantity_kg, @sowingJob_id, @farm_id, @crop_id, @vehicle_id, @employee_id, @date_start, date_end)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = fertilisingjob.Description;
sqlComm.Parameters.Add("@fertiliser_id", MySqlDbType.UInt32).Value = fertilisingjob.Fertiliser_id;
sqlComm.Parameters.Add("@quantity_kg", MySqlDbType.UInt32).Value = fertilisingjob.Quantity_kg;
sqlComm.Parameters.Add("@sowingJob_id", MySqlDbType.UInt32).Value = fertilisingjob.SowingJob_id;
sqlComm.Parameters.Add("@farm_id", MySqlDbType.UInt32).Value = fertilisingjob.Farm_id;
sqlComm.Parameters.Add("@crop_id", MySqlDbType.UInt32).Value = fertilisingjob.Crop_id;
sqlComm.Parameters.Add("@vehicle_id", MySqlDbType.UInt32).Value = fertilisingjob.Vehicle_id;
sqlComm.Parameters.Add("@employee_id", MySqlDbType.UInt32).Value = fertilisingjob.Employee_id;
sqlComm.Parameters.Add("@date_start", MySqlDbType.Date).Value = fertilisingjob.Date_start;
sqlComm.Parameters.Add("@date_end", MySqlDbType.Date).Value = fertilisingjob.Date_end;
return sqlComm.ExecuteNonQuery();
}
public int addNewPesticideJob(PesticideJob pesticidejob)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " pesticidejob(description, pesticide_id, quantity_kg, sowingJob_id, farm_id, crop_id, vehicle_id, employee_id, date_start, date_end)" +
"VALUES" + "(@description, @pesticide_id, @quantity_kg, @sowingJob_id, @farm_id, @rop_id, @vehicle_id, @employee_id, @date_start, @date_end)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@description", MySqlDbType.Text).Value = pesticidejob.Description;
sqlComm.Parameters.Add("@pesticide_id", MySqlDbType.UInt32).Value = pesticidejob.Pesticide_id;
sqlComm.Parameters.Add("@quantity_kg", MySqlDbType.Decimal).Value = pesticidejob.Quantity_kg;
sqlComm.Parameters.Add("@sowingJob_id", MySqlDbType.UInt32).Value = pesticidejob.SowingJob_id;
sqlComm.Parameters.Add("@farm_id", MySqlDbType.UInt32).Value = pesticidejob.Farm_id;
sqlComm.Parameters.Add("@crop_id", MySqlDbType.UInt32).Value = pesticidejob.Crop_id;
sqlComm.Parameters.Add("@vehicle_id", MySqlDbType.UInt32).Value = pesticidejob.Vehicle_id;
sqlComm.Parameters.Add("@employee_id", MySqlDbType.UInt32).Value = pesticidejob.Employee_id;
sqlComm.Parameters.Add("@date_start", MySqlDbType.Date).Value = pesticidejob.Date_start;
sqlComm.Parameters.Add("@date_end", MySqlDbType.Date).Value = pesticidejob.Date_end;
return sqlComm.ExecuteNonQuery();
}
public int addNewFertiliser(Fertiliser fertiliser)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " fertiliser(name, quantity_kg, remark)" +
" VALUES" + " (@name, @quantity_kg, @remark)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@name", MySqlDbType.Text).Value = fertiliser.Name;
sqlComm.Parameters.Add("@quantity_kg", MySqlDbType.UInt32).Value = fertiliser.Quantity_kg;
sqlComm.Parameters.Add("@remark", MySqlDbType.Text).Value = fertiliser.Remark;
return sqlComm.ExecuteNonQuery();
}
public int addNewPesticide(Pesticide pesticide)
{
MySqlCommand sqlComm = new MySqlCommand("INSERT INTO" + " pesticide(name, quantity_kg, remark)" +
" VALUES" + " (@name, @quantity_kg, @remark)", MysqlDbc.Instance.getConn());
sqlComm.Parameters.Add("@name", MySqlDbType.Text).Value = pesticide.Name;
sqlComm.Parameters.Add("@quantity_kg", MySqlDbType.UInt32).Value = pesticide.Quantity_kg;
sqlComm.Parameters.Add("@remark", MySqlDbType.Text).Value = pesticide.Remark;
return sqlComm.ExecuteNonQuery();
}
}
/// <summary>
/// SAMPLE
/// </summary>
public class TestSQL
{
public bool addNewSowingJob(DateTime dt/*SowingJob sj*/)
{
// can test at main screen "btnTestSql"
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = MysqlDbc.Instance.getConn();
cmd.CommandText = "INSERT INTO sowingjob VALUES(@id, @description, @crop_id, @quantity_prop, @farm_id, @used_area, @vehicle_id, @employee_id, @date, @time_start, @time_end)";
cmd.Prepare();
cmd.Parameters.AddWithValue("@id" , 0);
cmd.Parameters.AddWithValue("@description" , "sowing at helpcat"/*sj.Description*/);
cmd.Parameters.AddWithValue("@crop_id" , 1/*sj.Crop_id*/);
cmd.Parameters.AddWithValue("@quantity_prop", 213/*sj.Quantity_prop*/);
cmd.Parameters.AddWithValue("@farm_id" , 2/*sj.Farm_id*/);
cmd.Parameters.AddWithValue("@used_area" , "please change to int"/*sj.Used_area*/);
cmd.Parameters.AddWithValue("@vehicle_id" , 3/*sj.Vehicle_id*/);
cmd.Parameters.AddWithValue("@employee_id" , 4/*sj.Employee_id*/);
cmd.Parameters.AddWithValue("@date" , dt.ToString("yyyy-MM-dd")/*sj.Date.ToString("yyyy-MM-dd")*/);
cmd.Parameters.AddWithValue("@time_start" , dt.ToString("HH:mm:ss")/*sj.Time_start.ToString("HH:mm:ss")*/);
cmd.Parameters.AddWithValue("@time_end" , dt.ToString("HH:mm:ss")/*sj.Time_end.ToString("HH:mm:ss")*/);
cmd.ExecuteNonQuery();
Console.WriteLine("MySQL addNewSowingJob: success");
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("MySQL Error: {0}", ex.ToString());
}
return false;
}
// can test at form sowing job
// access through operation -> sowing job -> new sowing
public List<Crop> GetCropList()
{
List<Crop> cropLists = new List<Crop>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM crop";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Crop cr = new Crop();
cr.Id = rdr.GetInt32("id");
cr.Name = rdr.GetString("name");
cr.Type = rdr.GetString("type");
cr.Quantity_plot = rdr.GetInt32("quantity_plot");
cr.Remark = rdr.GetString("remark");
Console.WriteLine("crop => " + cr);
cropLists.Add(cr);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return cropLists;
}
public List<Employee> GetEmployeeList()
{
List<Employee> employeeLists = new List<Employee>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM employee";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee emp = new Employee();
emp.Id = rdr.GetInt32("id");
emp.First_name = rdr.GetString("first_name");
emp.Last_name = rdr.GetString("last_name");
emp.Username = rdr.GetString("username");
emp.Password = rdr.GetString("password");
emp.Dob = rdr.GetDateTime("dob");
emp.Mobile = rdr.GetString("mobile");
emp.Email = rdr.GetString("email");
emp.Admin = rdr.GetBoolean("admin");
emp.Status = rdr.GetString("status");
emp.Remark = rdr.GetString("remark");
employeeLists.Add(emp);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return employeeLists;
}
public List<Farm> GetFarmList()
{
List<Farm> farmLists = new List<Farm>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM farm";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Farm far = new Farm();
far.Id = rdr.GetInt32("id");
far.Description = rdr.GetString("description");
far.Area = rdr.GetInt32("area");
far.Utilize_area = rdr.GetInt32("utilize_area");
//Console.WriteLine("crop => " + cr);
farmLists.Add(far);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return farmLists;
}
public List<Vehicle> GetVehicleList()
{
List<Vehicle> vehicleLists = new List<Vehicle>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM vehicle";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Vehicle vehc = new Vehicle();
vehc.Id = rdr.GetInt32("id");
vehc.Name = rdr.GetString("name");
vehc.Serial_number = rdr.GetString("serial_number");
vehc.Buy_date = rdr.GetDateTime("buy_date");
vehc.Last_service_date = rdr.GetDateTime("last_service_date");
vehc.Remark = rdr.GetString("remark");
//Console.WriteLine("crop => " + cr);
vehicleLists.Add(vehc);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return vehicleLists;
}
public List<SowingJob> GetSowingJobList() //string employee_id
{
List<SowingJob> sowingLists = new List<SowingJob>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM sowingjob";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
SowingJob sj1 = new SowingJob();
sj1.Id = rdr.GetInt32("id"); ;
sj1.Description = rdr.GetString("description");
sj1.Crop_id = rdr.GetInt32("crop_id");
sj1.Quantity_prop = rdr.GetInt32("quantity_prop");
sj1.Farm_id = rdr.GetInt32("farm_id");
sj1.Used_area = rdr.GetString("used_area");
sj1.Vehicle_id = rdr.GetInt32("vehicle_id");
sj1.Employee_id = rdr.GetInt32("employee_id");
sj1.Date_start = rdr.GetDateTime("date_start");
sj1.Date_end = rdr.GetDateTime("date_end");
sowingLists.Add(sj1);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return sowingLists;
}
public List<HarvestingJob> GetHarvestingJobList() //string employee_id
{
List<HarvestingJob> harvestLists = new List<HarvestingJob>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM harvestingjob";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
HarvestingJob sj1 = new HarvestingJob();
sj1.Id = rdr.GetInt32("id"); ;
sj1.Description = rdr.GetString("description");
sj1.SowingJob_id = rdr.GetInt32("sowingJob_id");
sj1.Farm_id = rdr.GetInt32("farm_id");
sj1.Crop_id = rdr.GetInt32("crop_id");
sj1.Vehicle_id = rdr.GetInt32("vehicle_id");
sj1.Est_quantity = rdr.GetInt32("est_quantity");
sj1.Harvested_quantity = rdr.GetInt32("harvested_quantity");
sj1.Employee_id = rdr.GetInt32("employee_id");
sj1.Date_start = rdr.GetDateTime("date_start");
sj1.Date_end = rdr.GetDateTime("date_end");
harvestLists.Add(sj1);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return harvestLists;
}
public List<Box> GetBoxList() //string employee_id
{
List<Box> boxLists = new List<Box>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM box";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Box sj1 = new Box();
sj1.Id = rdr.GetInt32("id"); ;
sj1.Name = rdr.GetString("name");
sj1.Width = rdr.GetDouble("width");
sj1.Height = rdr.GetDouble("height");
sj1.Length = rdr.GetDouble("length");
sj1.Max_weight = rdr.GetDouble("max_weight");
sj1.Quantity = rdr.GetInt32("quantity");
sj1.Status = rdr.GetString("status");
boxLists.Add(sj1);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return boxLists;
}
public List<Pesticide> GetPesticideList() //string employee_id
{
List<Pesticide> pesticideLists = new List<Pesticide>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM pesticide";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Pesticide sj1 = new Pesticide();
sj1.Id = rdr.GetInt32("id"); ;
sj1.Name = rdr.GetString("name");
sj1.Quantity_kg = rdr.GetInt32("quantity_kg");
sj1.Remark = rdr.GetString("remark");
pesticideLists.Add(sj1);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return pesticideLists;
}
public List<Fertiliser> GetFertiliserList() //string employee_id
{
List<Fertiliser> fertiliserLists = new List<Fertiliser>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM fertiliser";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Fertiliser sj1 = new Fertiliser();
sj1.Id = rdr.GetInt32("id"); ;
sj1.Name = rdr.GetString("name");
sj1.Quantity_kg = rdr.GetInt32("quantity_kg");
sj1.Remark = rdr.GetString("remark");
fertiliserLists.Add(sj1);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return fertiliserLists;
}
public List<FertilisingJob> GetFertilisingJobList() //string employee_id
{
List<FertilisingJob> fertiliserLists = new List<FertilisingJob>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM fertilisingjob";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
FertilisingJob sj1 = new FertilisingJob();
sj1.Id = rdr.GetInt32("id"); ;
sj1.Description = rdr.GetString("description");
sj1.Fertiliser_id = rdr.GetInt32("fertiliser_id");
sj1.Quantity_kg = rdr.GetInt32("quantity_kg");
sj1.SowingJob_id = rdr.GetInt32("sowingJob_id");
sj1.Farm_id = rdr.GetInt32("farm_id");
sj1.Crop_id = rdr.GetInt32("crop_id");
sj1.Vehicle_id = rdr.GetInt32("vehicle_id");
sj1.Employee_id = rdr.GetInt32("employee_id");
sj1.Date_start = rdr.GetDateTime("date_start");
sj1.Date_end = rdr.GetDateTime("date_end");
fertiliserLists.Add(sj1);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return fertiliserLists;
}
public List<PesticideJob> GetPesticideJobList() //string employee_id
{
List<PesticideJob> pesticideLists = new List<PesticideJob>();
MySqlDataReader rdr = null;
try
{
string stm = "SELECT * FROM pesticidejob";
MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn());
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
PesticideJob sj1 = new PesticideJob();
sj1.Id = rdr.GetInt32("id"); ;
sj1.Description = rdr.GetString("description");
sj1.Pesticide_id = rdr.GetInt32("pesticide_id");
sj1.Quantity_kg = rdr.GetInt32("quantity_kg");
sj1.SowingJob_id = rdr.GetInt32("sowingJob_id");
sj1.Farm_id = rdr.GetInt32("farm_id");
sj1.Crop_id = rdr.GetInt32("crop_id");
sj1.Vehicle_id = rdr.GetInt32("vehicle_id");
sj1.Employee_id = rdr.GetInt32("employee_id");
sj1.Date_start = rdr.GetDateTime("date_start");
sj1.Date_end = rdr.GetDateTime("date_end");
pesticideLists.Add(sj1);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (rdr != null)
{
rdr.Close();
}
}
return pesticideLists;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using University.Data;
namespace University.UI.Areas.Admin.Models
{
public class CategoryMappingModel
{
public int ID { get; set; }
[Required, Range(1, int.MaxValue, ErrorMessage = "Please Select user")]
public int UserID { get; set; }
public Nullable<int> AdminID { get; set; }
//public string FullName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required, Range(1, int.MaxValue, ErrorMessage = "Please Select Category")]
public decimal CategoryId { get; set; }
public string CategoryName { get; set; }
public List<Login_tbl> Logintbllst { get; set; }
public List<SubCategoryMaster> SubCategoryMasterlst { get; set; }
public List<CategoryUserMapping> CategoryUserMapping { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace IRAP.WebAPI.Enums
{
/// <summary>
/// 报文类别枚举类型
/// </summary>
[Flags()]
public enum TContentType
{
/// <summary>
/// JSON 格式的报文
/// </summary>
[Description("JSON 格式的报文")]
JSON = 1,
/// <summary>
/// XML 格式的报文
/// </summary>
[Description("XML 格式的报文")]
XML
}
}
|
using FluentValidation;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit;
namespace SFA.DAS.ProviderCommitments.Web.Validators
{
public class ViewApprenticeshipUpdatesViewModelValidator : AbstractValidator<ViewApprenticeshipUpdatesViewModel>
{
public ViewApprenticeshipUpdatesViewModelValidator()
{
RuleFor(r => r.UndoChanges).NotNull()
.WithMessage("Confirm if you want to undo these changes");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio1
{
class LeituraEEscritaNElementos
{
static void Main(string[] args)
{
{
Console.Write("Quantos elementos tem o vector? ");
int N = Convert.ToInt16(Console.ReadLine());
int[] A = new int[N];
for (int I = 0; I <= N - 1; I++)
{ Console.Write("Elemento {0}=", I + 1);
A[I] = Convert.ToInt16(Console.ReadLine());
}
foreach (int Elemento in A) Console.WriteLine("{0, 4}", Elemento);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
/// <summary>
/// Descripción breve de cPomocionTipoAlimentacion
/// </summary>
[DataContract]
public class cPomocionTipoAlimentacion
{
public cPomocionTipoAlimentacion()
{
//
// TODO: Agregar aquí la lógica del constructor
//
}
[DataMember(IsRequired=true)]
public int PromocionTipoAlimentacionID {get;set;}
[DataMember(IsRequired=true)]
public int PromocionID {get;set;}
[DataMember(IsRequired=true)]
public string PromocionStr {get;set;}
[DataMember(IsRequired=true)]
public int TipoAlimentacionID {get;set;}
[DataMember(IsRequired=true)]
public string TipoAlimentacionStr{get;set;}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Advantage.API.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Advantage.API.Controllers
{
[ApiController]
public class ApiController : ControllerBase
{
private ApiContext _context;
public ApiController(ApiContext context)
{
_context = context;
}
[HttpGet("/orders")]
public IEnumerable<Order> GetOrders()
{
return _context.Orders
.OrderBy(o => o.Id)
.Include(c => c.Customer)
.Include(o => o.Product)
.ToList();
}
[HttpGet("/customer")]
public IEnumerable<object> GetOrdersByCustomer()
{
return _context
.Orders
.Include(o => o.Customer)
.GroupBy(o => o.Customer)
.Select(o => new { Customer = o.Key, OrderCount = o.Sum(t => t.Id) })
.Take(5).ToList();
}
[HttpGet("/servers")]
public IEnumerable<Server> GetServers()
{
return _context.Servers.ToList();
}
[HttpPost("/change")]
public bool ChangeServerStatus([FromBody]Server serverParam)
{
try
{
var server = _context.Servers.FirstOrDefault(s => s.Id == serverParam.Id);
server.IsOnline = !server.IsOnline;
_context.SaveChanges();
}
catch (Exception ex)
{
return false;
}
return true;
}
[HttpGet("/monthly")]
public IEnumerable<object> MonthlySalesByProduct()
{
var monthlySalesByProduct = _context.Orders
.Include(o => o.Product)
.GroupBy(o => new { o.Product.Id, o.Placed.Month })
.Select(o => new { ProductId = o.Key.Id, SaleCount = o.Sum(p => p.Total), Month = o.Key.Month })
.OrderBy(o => o.Month).ToList();
return monthlySalesByProduct
.Select(m => new
{
label = _context.Products.FirstOrDefault(p => p.Id == m.ProductId).Name,
data = monthlySalesByProduct.Where(s => s.ProductId == m.ProductId).Select(s => s.SaleCount).ToArray()
})
.ToList();
}
}
} |
namespace P00Introduction
{
using System;
using System.Collections.Generic;
using System.Linq;
using BasicTree.Trees.Tree;
public class EntryPoint
{
private static readonly Dictionary<int, Tree<int>> nodeByValue =
new Dictionary<int, Tree<int>>();
public static void Main()
{
ReadTreeValues(int.Parse(Console.ReadLine()));
int searchedValue = int.Parse(Console.ReadLine());
var root = GetRootNode();
foreach (var tree in GetPathsWithSum(root, searchedValue))
{
PrintInPreOrder(tree);
Console.WriteLine();
}
}
private static void PrintInPreOrder(Tree<int> tree)
{
Console.Write($"{tree.TreeValue} ");
foreach (var child in tree.TreeChildren)
{
PrintInPreOrder(child);
}
}
private static List<Tree<int>> GetPathsWithSum(Tree<int> root, int searchedValue)
{
Console.WriteLine($"Subtrees of sum {searchedValue}: ");
var roots = new List<Tree<int>>();
GetSubtreePathsWithSum(root, searchedValue, 0, roots);
return roots;
}
private static int GetSubtreePathsWithSum(
Tree<int> node,
int searchedValue,
int current,
List<Tree<int>> roots)
{
if (node == null)
{
return 0;
}
current = node.TreeValue;
foreach (var treeChild in node.TreeChildren)
{
current += GetSubtreePathsWithSum(treeChild, searchedValue, current, roots);
}
if (current == searchedValue)
{
roots.Add(node);
}
return current;
}
private static Tree<int> GetRootNode()
{
return nodeByValue?
.Values?
.Where(nv => nv.Parent == null)
.FirstOrDefault();
}
private static void ReadTreeValues(int nodesCount)
{
for (int i = 0; i < nodesCount - 1; i++)
{
int[] couple = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int parent = couple[0];
int child = couple[1];
Tree<int> parentNode = CreateNewNode(parent);
Tree<int> childNode = CreateNewNode(child);
parentNode.TreeChildren.Add(childNode);
childNode.Parent = parentNode;
}
}
private static Tree<int> CreateNewNode(int nodeValue)
{
if (!nodeByValue.ContainsKey(nodeValue))
{
nodeByValue.Add(nodeValue, new Tree<int>(nodeValue));
}
return nodeByValue[nodeValue];
}
}
} |
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.DraftApprenticeship
{
public class PostAddDraftApprenticeshipRequest : IPostApiRequest
{
private readonly long _cohortId;
public object Data { get; set; }
public PostAddDraftApprenticeshipRequest(long cohortId)
{
_cohortId = cohortId;
}
public string PostUrl => $"cohorts/{_cohortId}/draft-apprenticeships";
}
}
|
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace RU.Tinkoff.Acquiring.Sdk {
// Metadata.xml XPath interface reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/interface[@name='OnPaymentListener']"
[Register ("ru/tinkoff/acquiring/sdk/OnPaymentListener", "", "RU.Tinkoff.Acquiring.Sdk.IOnPaymentListenerInvoker")]
public partial interface IOnPaymentListener : IJavaObject {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/interface[@name='OnPaymentListener']/method[@name='onCancelled' and count(parameter)=0]"
[Register ("onCancelled", "()V", "GetOnCancelledHandler:RU.Tinkoff.Acquiring.Sdk.IOnPaymentListenerInvoker, Tinkoff.UI")]
void OnCancelled ();
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/interface[@name='OnPaymentListener']/method[@name='onError' and count(parameter)=1 and parameter[1][@type='java.lang.Exception']]"
[Register ("onError", "(Ljava/lang/Exception;)V", "GetOnError_Ljava_lang_Exception_Handler:RU.Tinkoff.Acquiring.Sdk.IOnPaymentListenerInvoker, Tinkoff.UI")]
void OnError (global::Java.Lang.Exception p0);
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/interface[@name='OnPaymentListener']/method[@name='onSuccess' and count(parameter)=1 and parameter[1][@type='long']]"
[Register ("onSuccess", "(J)V", "GetOnSuccess_JHandler:RU.Tinkoff.Acquiring.Sdk.IOnPaymentListenerInvoker, Tinkoff.UI")]
void OnSuccess (long p0);
}
[global::Android.Runtime.Register ("ru/tinkoff/acquiring/sdk/OnPaymentListener", DoNotGenerateAcw=true)]
internal class IOnPaymentListenerInvoker : global::Java.Lang.Object, IOnPaymentListener {
static IntPtr java_class_ref = JNIEnv.FindClass ("ru/tinkoff/acquiring/sdk/OnPaymentListener");
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (IOnPaymentListenerInvoker); }
}
IntPtr class_ref;
public static IOnPaymentListener GetObject (IntPtr handle, JniHandleOwnership transfer)
{
return global::Java.Lang.Object.GetObject<IOnPaymentListener> (handle, transfer);
}
static IntPtr Validate (IntPtr handle)
{
if (!JNIEnv.IsInstanceOf (handle, java_class_ref))
throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.",
JNIEnv.GetClassNameFromInstance (handle), "ru.tinkoff.acquiring.sdk.OnPaymentListener"));
return handle;
}
protected override void Dispose (bool disposing)
{
if (this.class_ref != IntPtr.Zero)
JNIEnv.DeleteGlobalRef (this.class_ref);
this.class_ref = IntPtr.Zero;
base.Dispose (disposing);
}
public IOnPaymentListenerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer)
{
IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle);
this.class_ref = JNIEnv.NewGlobalRef (local_ref);
JNIEnv.DeleteLocalRef (local_ref);
}
static Delegate cb_onCancelled;
#pragma warning disable 0169
static Delegate GetOnCancelledHandler ()
{
if (cb_onCancelled == null)
cb_onCancelled = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_OnCancelled);
return cb_onCancelled;
}
static void n_OnCancelled (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Acquiring.Sdk.IOnPaymentListener __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.IOnPaymentListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnCancelled ();
}
#pragma warning restore 0169
IntPtr id_onCancelled;
public unsafe void OnCancelled ()
{
if (id_onCancelled == IntPtr.Zero)
id_onCancelled = JNIEnv.GetMethodID (class_ref, "onCancelled", "()V");
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onCancelled);
}
static Delegate cb_onError_Ljava_lang_Exception_;
#pragma warning disable 0169
static Delegate GetOnError_Ljava_lang_Exception_Handler ()
{
if (cb_onError_Ljava_lang_Exception_ == null)
cb_onError_Ljava_lang_Exception_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnError_Ljava_lang_Exception_);
return cb_onError_Ljava_lang_Exception_;
}
static void n_OnError_Ljava_lang_Exception_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::RU.Tinkoff.Acquiring.Sdk.IOnPaymentListener __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.IOnPaymentListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Exception p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Exception> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnError (p0);
}
#pragma warning restore 0169
IntPtr id_onError_Ljava_lang_Exception_;
public unsafe void OnError (global::Java.Lang.Exception p0)
{
if (id_onError_Ljava_lang_Exception_ == IntPtr.Zero)
id_onError_Ljava_lang_Exception_ = JNIEnv.GetMethodID (class_ref, "onError", "(Ljava/lang/Exception;)V");
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onError_Ljava_lang_Exception_, __args);
}
static Delegate cb_onSuccess_J;
#pragma warning disable 0169
static Delegate GetOnSuccess_JHandler ()
{
if (cb_onSuccess_J == null)
cb_onSuccess_J = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, long>) n_OnSuccess_J);
return cb_onSuccess_J;
}
static void n_OnSuccess_J (IntPtr jnienv, IntPtr native__this, long p0)
{
global::RU.Tinkoff.Acquiring.Sdk.IOnPaymentListener __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.IOnPaymentListener> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnSuccess (p0);
}
#pragma warning restore 0169
IntPtr id_onSuccess_J;
public unsafe void OnSuccess (long p0)
{
if (id_onSuccess_J == IntPtr.Zero)
id_onSuccess_J = JNIEnv.GetMethodID (class_ref, "onSuccess", "(J)V");
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_onSuccess_J, __args);
}
}
public partial class ErrorEventArgs : global::System.EventArgs {
public ErrorEventArgs (global::Java.Lang.Exception p0)
{
this.p0 = p0;
}
global::Java.Lang.Exception p0;
public global::Java.Lang.Exception P0 {
get { return p0; }
}
}
public partial class SuccessEventArgs : global::System.EventArgs {
public SuccessEventArgs (long p0)
{
this.p0 = p0;
}
long p0;
public long P0 {
get { return p0; }
}
}
[global::Android.Runtime.Register ("mono/ru/tinkoff/acquiring/sdk/OnPaymentListenerImplementor")]
internal sealed partial class IOnPaymentListenerImplementor : global::Java.Lang.Object, IOnPaymentListener {
object sender;
public IOnPaymentListenerImplementor (object sender)
: base (
global::Android.Runtime.JNIEnv.StartCreateInstance ("mono/ru/tinkoff/acquiring/sdk/OnPaymentListenerImplementor", "()V"),
JniHandleOwnership.TransferLocalRef)
{
global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V");
this.sender = sender;
}
#pragma warning disable 0649
public EventHandler OnCancelledHandler;
#pragma warning restore 0649
public void OnCancelled ()
{
var __h = OnCancelledHandler;
if (__h != null)
__h (sender, new EventArgs ());
}
#pragma warning disable 0649
public EventHandler<ErrorEventArgs> OnErrorHandler;
#pragma warning restore 0649
public void OnError (global::Java.Lang.Exception p0)
{
var __h = OnErrorHandler;
if (__h != null)
__h (sender, new ErrorEventArgs (p0));
}
#pragma warning disable 0649
public EventHandler<SuccessEventArgs> OnSuccessHandler;
#pragma warning restore 0649
public void OnSuccess (long p0)
{
var __h = OnSuccessHandler;
if (__h != null)
__h (sender, new SuccessEventArgs (p0));
}
internal static bool __IsEmpty (IOnPaymentListenerImplementor value)
{
return value.OnCancelledHandler == null && value.OnErrorHandler == null && value.OnSuccessHandler == null;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2._4_Base
{
class Program
{
static void Main(string[] args)
{
Order ordem = new Order();
ordem.Id = 33;
IEnumerable<Order> ie = new List<Order>() {ordem};
OrderRepository repository = new OrderRepository(ie);
var result = repository.FindById(33);
repository.FilterOrdersOnAmount(33m);
}
}
}
|
namespace Airelax.Application.Members.Request
{
public class MembersInput
{
}
} |
namespace Forca.Repositorio.Migrations
{
using Dominio;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Forca.Repositorio.ContextoDeDados.ContextoBaseDeDados>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Forca.Repositorio.ContextoDeDados.ContextoBaseDeDados context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
context.Palavra.AddOrUpdate(
p => p.Composicao,
new Palavra { Composicao = "atividade", Dica = "começa com a" },
new Palavra { Composicao = "atitude", Dica = "começa com a" },
new Palavra { Composicao = "regra", Dica = "começa com r" },
new Palavra { Composicao = "diferente", Dica = "não é igual" },
new Palavra { Composicao = "setor", Dica = "começa com s" },
new Palavra { Composicao = "estabelecimento", Dica = "começa com e" },
new Palavra { Composicao = "relacionamento", Dica = "namoro, vínculo" },
new Palavra { Composicao = "vertical", Dica = "não é horizontal" },
new Palavra { Composicao = "hierarquia", Dica = "começa com h" },
new Palavra { Composicao = "tudo", Dica = "nada" },
new Palavra { Composicao = "fundamental", Dica = "começa com f" },
new Palavra { Composicao = "dificuldade", Dica = "javascript" },
new Palavra { Composicao = "grupo", Dica = "começa com g" },
new Palavra { Composicao = "retorno", Dica = "começa com r" },
new Palavra { Composicao = "longo", Dica = "começa com l" },
new Palavra { Composicao = "prazo", Dica = "começa com p" },
new Palavra { Composicao = "diretriz", Dica = "começa com d" },
new Palavra { Composicao = "objetivo", Dica = "meta" },
new Palavra { Composicao = "desenvolvimento", Dica = "começa com d" },
new Palavra { Composicao = "futuro", Dica = "passado" },
new Palavra { Composicao = "incentivo", Dica = "estímulo" },
new Palavra { Composicao = "mercado", Dica = "começa com m" },
new Palavra { Composicao = "mundial", Dica = "começa com m" },
new Palavra { Composicao = "postura", Dica = "começa com p" },
new Palavra { Composicao = "dirigente", Dica = "começa com d" },
new Palavra { Composicao = "complexidade", Dica = "começa com c" },
new Palavra { Composicao = "capacidade", Dica = "começa com c" },
new Palavra { Composicao = "forma", Dica = "começa com f" },
new Palavra { Composicao = "prazo", Dica = "começa com p" },
new Palavra { Composicao = "abertura", Dica = "começa com a" },
new Palavra { Composicao = "resultado", Dica = "começa com r" },
new Palavra { Composicao = "hegemonia", Dica = "começa com h" },
new Palavra { Composicao = "ambiente", Dica = "começa com a" },
new Palavra { Composicao = "departamento", Dica = "começa com d" },
new Palavra { Composicao = "crescente", Dica = "começa com c" },
new Palavra { Composicao = "alcance", Dica = "começa com a" },
new Palavra { Composicao = "inovador", Dica = "começa com i" },
new Palavra { Composicao = "constante", Dica = "começa com c" },
new Palavra { Composicao = "convencional", Dica = "começa com c" },
new Palavra { Composicao = "competitividade", Dica = "começa com c" },
new Palavra { Composicao = "comercial", Dica = "começa com c" },
new Palavra { Composicao = "valor", Dica = "começa com v" },
new Palavra { Composicao = "ortodoxo", Dica = "começa com o" },
new Palavra { Composicao = "empenho", Dica = "começa com e" },
new Palavra { Composicao = "julgamento", Dica = "começa com j" },
new Palavra { Composicao = "imparcial", Dica = "começa com i" },
new Palavra { Composicao = "costume", Dica = "começa com c" },
new Palavra { Composicao = "papel", Dica = "começa com p" },
new Palavra { Composicao = "promise", Dica = "ninguém entende" },
new Palavra { Composicao = "conhecimento", Dica = "começa com c" },
new Palavra { Composicao = "prova", Dica = "começa com p" },
new Palavra { Composicao = "acompanhamento", Dica = "começa com a" },
new Palavra { Composicao = "consumo", Dica = "começa com c" },
new Palavra { Composicao = "correto", Dica = "começa com c" },
new Palavra { Composicao = "fluxo", Dica = "começa com f" },
new Palavra { Composicao = "metodologia", Dica = "começa com m" },
new Palavra { Composicao = "equipe", Dica = "começa com e" },
new Palavra { Composicao = "distinto", Dica = "começa com d" },
new Palavra { Composicao = "corrente", Dica = "começa com c" },
new Palavra { Composicao = "pensamento", Dica = "começa com p" },
new Palavra { Composicao = "significado", Dica = "começa com s" },
new Palavra { Composicao = "problema", Dica = "começa com p" },
new Palavra { Composicao = "atividade", Dica = "começa com a" },
new Palavra { Composicao = "interessante", Dica = "começa com i" },
new Palavra { Composicao = "quadro", Dica = "começa com q" },
new Palavra { Composicao = "relatividade", Dica = "começa com r" },
new Palavra { Composicao = "fim de semana", Dica = "começa com f" },
new Palavra { Composicao = "beija flor", Dica = "passarinho" },
new Palavra { Composicao = "criado mudo", Dica = "criado sem voz" },
new Palavra { Composicao = "estrela do mar", Dica = "patrick" },
new Palavra { Composicao = "dente de leite", Dica = "dente que pode virar queijo" },
new Palavra { Composicao = "dedo duro", Dica = "inverno sem luvas" },
new Palavra { Composicao = "boto cor de rosa", Dica = "golfinho wannabe" },
new Palavra { Composicao = "sangue frio", Dica = "bernardo com trabalho de js" },
new Palavra { Composicao = "longa metragem", Dica = "filme" },
new Palavra { Composicao = "puro sangue", Dica = "cavalo" },
new Palavra { Composicao = "mata moscas", Dica = "anos 90" },
new Palavra { Composicao = "louva a deus", Dica = "kung fu" },
new Palavra { Composicao = "maria vai com as outras", Dica = "maria algo" },
new Palavra { Composicao = "guarda chuva", Dica = "agua guardada" },
new Palavra { Composicao = "alto falante", Dica = "galalau que não para de falar" },
new Palavra { Composicao = "afro americano", Dica = "dois continentes" },
new Palavra { Composicao = "ama de leite", Dica = "coisa antiga" },
new Palavra { Composicao = "asa delta", Dica = "coxa alfa" },
new Palavra { Composicao = "banho maria", Dica = "maria sai do banho" },
new Palavra { Composicao = "guarda costas", Dica = "i got ur back" },
new Palavra { Composicao = "porquinho da india", Dica = "little pig from india" },
new Palavra { Composicao = "quero quero", Dica = "guardiões da coruja" },
new Palavra { Composicao = "salva vidas", Dica = "David Hasselhoff" },
new Palavra { Composicao = "maria mole", Dica = "doce ruim" },
new Palavra { Composicao = "tatu bola", Dica = "tira do nariz e faz uma bolinha" },
new Palavra { Composicao = "montanha russa", Dica = "montes urais" });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameTiles;
using GameTiles.Tiles;
using GameTiles.Enums;
using GameTiles.Spawns;
namespace MapEditor
{
class MapEditor
{
static void Main(string[] args)
{
var Editor = new MapEditor();
}
public MapFile mapInfo;
public TileTypeDictionary TileDictionary;
public int CursorXPosition;
public int CursorYPosition;
public int WindowXPosition;
public int WindowYPosition;
public const int ScreenWidth = 21;
public const int ScreenHeight = 21;
private int _cursorSize;
public MapEditor()
{
CursorXPosition = 0;
CursorYPosition = 0;
WindowXPosition = 0;
WindowYPosition = 0;
_cursorSize = 1;
mapInfo = new MapFile(new Tile[50, 50], new List<Spawn>());
for (int y = 0; y < mapInfo.TileSet.GetLength(1); y++)
{
for (int x = 0; x < mapInfo.TileSet.GetLength(0); x++)
{
mapInfo.TileSet[x, y].TileType = EnumTileTypes.Snow;
}
}
TileDictionary = new TileTypeDictionary();
MainLoop();
}
public void MainLoop()
{
DrawMap();
ConsoleKeyInfo keyPressed;
keyPressed = Console.ReadKey(true);
while (keyPressed.Key != ConsoleKey.Escape)
{
if (keyPressed.Key == ConsoleKey.W)
{
WindowYPosition--;
}
else if (keyPressed.Key == ConsoleKey.S)
{
WindowYPosition++;
}
else if (keyPressed.Key == ConsoleKey.A)
{
WindowXPosition--;
}
else if (keyPressed.Key == ConsoleKey.D)
{
WindowXPosition++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow)
{
if (CursorYPosition > 0) CursorYPosition--;
if (CursorYPosition < WindowYPosition) WindowYPosition--;
}
else if (keyPressed.Key == ConsoleKey.DownArrow)
{
if (CursorYPosition < mapInfo.TileSet.GetLength(1) - 1) CursorYPosition++;
if (CursorYPosition >= WindowYPosition + ScreenWidth) WindowYPosition++;
}
else if (keyPressed.Key == ConsoleKey.LeftArrow)
{
if (CursorXPosition > 0) CursorXPosition--;
if (CursorXPosition < WindowXPosition) WindowXPosition--;
}
else if (keyPressed.Key == ConsoleKey.RightArrow)
{
if (CursorXPosition < mapInfo.TileSet.GetLength(0) - 1) CursorXPosition++;
if (CursorXPosition >= WindowXPosition + ScreenWidth) WindowXPosition++;
}
else if (keyPressed.Key == ConsoleKey.Add)
{
if (_cursorSize < 2)
{
_cursorSize++;
}
}
else if (keyPressed.Key == ConsoleKey.Subtract)
{
if (_cursorSize > 0)
{
_cursorSize--;
}
}
else if (keyPressed.Key == ConsoleKey.B)
{
Console.Clear();
// Create new map with specified
Console.WriteLine("Enter the new map width (in tiles)");
var newX = Console.ReadLine();
Console.WriteLine("Enter the new map height (in tiles)");
var newY = Console.ReadLine();
mapInfo = new MapFile(new Tile[int.Parse(newX), int.Parse(newY)], new List<Spawn>());
ResetMap();
}
else if (keyPressed.Key == ConsoleKey.M)
{
var newFileMenu = new MapFileHandler.MapFileHandler(ref mapInfo);
}
else if (keyPressed.Key == ConsoleKey.N)
{
ResetMap();
}
else
{
HandleTileChangeKeyPressed(keyPressed.Key);
}
DrawMap();
keyPressed = Console.ReadKey(true);
}
}
public void ResetMap()
{
//Reset/Clear map to all snow
for (int yIndex = 0; yIndex < mapInfo.TileSet.GetLength(1); yIndex++)
{
for (int xIndex = 0; xIndex < mapInfo.TileSet.GetLength(0); xIndex++)
{
mapInfo.TileSet[xIndex, yIndex].TileType = EnumTileTypes.Snow;
}
}
}
public void DrawMap()
{
Console.Clear();
var windowYPosition = CursorYPosition - (ScreenHeight - 1) / 2;
var windowXPosition = CursorXPosition - (ScreenWidth - 1) / 2;
for (int y = windowYPosition; y < windowYPosition + ScreenHeight; y++)
{
for (int x = windowXPosition; x < windowXPosition + ScreenWidth; x++)
{
//If the position is out of bounds for the map don't draw anything there
if (x < 0 || y < 0 || x >= mapInfo.TileSet.GetLength(0) || y >= mapInfo.TileSet.GetLength(1))
{
Console.Write(" ");
continue;
}
Console.ForegroundColor = TileDictionary[mapInfo.TileSet[x, y].TileType].Color;
if (IsCoordInCursor(x, y)) Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write(TileDictionary[mapInfo.TileSet[x, y].TileType].Character + " ");
}
Console.WriteLine("");
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(mapInfo.TileSet[CursorXPosition, CursorYPosition].TileType);
Console.WriteLine("CursorX\t" + CursorXPosition);
Console.WriteLine("CursorY\t" + CursorYPosition);
Console.WriteLine("WindowX\t" + windowXPosition);
Console.WriteLine("WindowY\t" + windowYPosition);
Console.WriteLine("CursorSize\t" + _cursorSize);
}
private bool IsCoordInCursor(int x, int y)
{
var xDiff = Math.Abs(x - CursorXPosition);
var yDiff = Math.Abs(y - CursorYPosition);
if (xDiff <= _cursorSize && yDiff <= _cursorSize)
{
return true;
}
return false;
}
public void HandleTileChangeKeyPressed(ConsoleKey keyPressed)
{
if (keyPressed == ConsoleKey.D1)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.Snow);
}
else if (keyPressed == ConsoleKey.D2)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.SnowWalked);
}
else if (keyPressed == ConsoleKey.D3)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.Road);
}
else if (keyPressed == ConsoleKey.D4)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.Grass);
}
else if (keyPressed == ConsoleKey.D5)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.CabinFloor);
}
else if (keyPressed == ConsoleKey.D6)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.CabinWall);
}
else if (keyPressed == ConsoleKey.D7)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.CabinDoor);
}
else if (keyPressed == ConsoleKey.D8)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.Tree);
}
else if (keyPressed == ConsoleKey.D9)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.River);
}
else if (keyPressed == ConsoleKey.D0)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.CabinWindow);
}
else if (keyPressed == ConsoleKey.Q)
{
PaintSpecifiedTileType(CursorXPosition, CursorYPosition, EnumTileTypes.Mountain);
}
else if (keyPressed == ConsoleKey.Z)
{
mapInfo.SpawnPoints.Add(new Spawn(EnumSpawnTypes.Player, CursorXPosition, CursorYPosition));
}
}
private void PaintSpecifiedTileType(int xMid, int yMid, EnumTileTypes tileType)
{
for (int y = yMid - _cursorSize; y <= yMid + _cursorSize; y++)
{
for (int x = xMid - _cursorSize; x <= xMid + _cursorSize; x++)
{
mapInfo.TileSet[x, y].TileType = tileType;
}
}
}
}
}
|
namespace Jypeli
{
/// <summary>
/// Kalibrointi puhelimen kallistuksen nollakohdalle.
/// (Asento missä puhelinta ei ole kallistettu yhtään)
/// </summary>
public enum AccelerometerCalibration
{
/// <summary>
/// Puhelin on vaakatasossa näyttö ylöspäin.
/// </summary>
ZeroAngle,
/// <summary>
/// Puhelin on 45-asteen kulmassa.
/// </summary>
HalfRightAngle,
/// <summary>
/// Puhelin on pystysuorassa.
/// </summary>
RightAngle,
/// <summary>
/// Vaihtaa X ja Y akselit toisinpäin.
/// </summary>
InvertXY
}
}
|
using System.Collections.Generic;
namespace Zesty.Core.Business
{
static class ClientSettings
{
private static IStorage storage = StorageManager.Storage;
internal static Dictionary<string, string> All()
{
return storage.GetClientSettings();
}
}
}
|
using System.Windows.Forms;
namespace SHSchool.Behavior.StuAdminExtendControls
{
internal class RowStudent : DataGridViewRow
{
private Student _student;
public Student Student
{
get { return _student; }
}
}
} |
using System.Collections.Generic;
using System.Linq;
using GalaSoft.MvvmLight;
using JeopardySimulator.Ui.Commands;
using JeopardySimulator.Ui.Commands.Base;
using JeopardySimulator.Ui.Messages;
using JeopardySimulator.Ui.Models;
namespace JeopardySimulator.Ui.Controls.ViewModels
{
public class QuestionGroupViewModel : ViewModelBase
{
private readonly QuestionGroup _model;
private bool _isFinished;
private IEnumerable<QuestionViewModel> _questions;
public QuestionGroupViewModel(QuestionGroup questionGroup)
{
_model = questionGroup;
LoadQuestionCommand = new LoadQuestionCommand(this, _model.Id);
MessengerInstance.Register<CancelQuestionMessage>(this, OnCancelQuestion);
MessengerInstance.Register<UnloadQuestionMessage>(this, msg =>
{
IsFinished =
_questions.All(rec => rec.IsAnswered);
});
}
public int Id
{
get { return _model.Id; }
}
public string Name
{
get { return _model.Name; }
}
public bool IsFinished
{
get { return _isFinished; }
private set
{
_isFinished = value;
RaisePropertyChanged(() => IsFinished);
}
}
public IEnumerable<QuestionViewModel> Questions
{
get
{
if (_questions == null)
{
_questions = new List<QuestionViewModel>(
_model.Questions.Select(question => new QuestionViewModel(question)));
}
return _questions;
}
}
public CommandBase<int> LoadQuestionCommand { get; private set; }
private void OnCancelQuestion(CancelQuestionMessage message)
{
if (message.Content.QuestionGroupId == _model.Id)
{
Questions.First(rec => rec.Model == message.Content).IsAnswered = false;
MessengerInstance.Send(new UnloadQuestionMessage());
}
}
}
} |
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
namespace HW05.ViewModels
{
public class MainPageViewModel : BindableBase, INavigationAware
{
private string _title;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
#region WhoLabel
private string _WhoLabel;
/// <summary>
/// PropertyDescription
/// </summary>
public string WhoLabel
{
get { return this._WhoLabel; }
set { this.SetProperty(ref this._WhoLabel, value); }
}
#endregion
public DelegateCommand WhoCommand { get; private set; }
public IWho _IWho;
public MainPageViewModel(IWho iWho)
{
_IWho = iWho;
WhoCommand = new DelegateCommand(Who);
}
private void Who()
{
WhoLabel = _IWho.Hello();
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public void OnNavigatedTo(NavigationParameters parameters)
{
if (parameters.ContainsKey("title"))
Title = (string)parameters["title"] + " and Prism";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems.AdventOfCode.Y2020 {
public class Problem23 : AdventOfCodeBase {
private Cup _cups;
private Dictionary<int, Cup> _hash;
private int _lowest = int.MaxValue;
private int _highest = 0;
public override string ProblemName => "Advent of Code 2020: 23";
public override string GetAnswer() {
//return Answer2("389125467").ToString();
return Answer2("368195742").ToString();
}
private string Answer1(string input) {
CreateCups(input, false);
PlayGame(100);
return GetResult1();
}
private ulong Answer2(string input) {
CreateCups(input, true);
PlayGame(10000000);
return GetResult2();
}
private string GetResult1() {
var result = "";
var current = _hash[1].Next;
do {
result += current.Value;
current = current.Next;
} while (current.Value != 1);
return result;
}
private ulong GetResult2() {
var one = _hash[1].Next;
return (ulong)one.Value * (ulong)one.Next.Value;
}
private void PlayGame(int moves) {
var current = _cups;
for (int turn = 1; turn <= moves; turn++) {
var removedFirst = current.Next;
var removedLast = removedFirst.Next.Next;
current.Next = removedLast.Next;
removedFirst.InList = false;
removedFirst.Next.InList = false;
removedLast.InList = false;
var next = current.Value - 1;
if (next < _lowest) {
next = _highest;
}
while (!_hash[next].InList) {
next--;
if (next < _lowest) {
next = _highest;
}
}
removedFirst.InList = true;
removedFirst.Next.InList = true;
removedLast.InList = true;
var destination = _hash[next];
removedLast.Next = destination.Next;
destination.Next = removedFirst;
current = current.Next;
}
}
private Cup _lastCup = null;
private void CreateCups(string input, bool addRemainingMillion) {
_hash = new Dictionary<int, Cup>();
foreach (var digit in input) {
var num = Convert.ToInt32(digit.ToString());
AddCup(num);
}
for (int num = _highest + 1; num <= 1000000; num++) {
AddCup(num);
}
_lastCup.Next = _cups;
}
private void AddCup(int num) {
var cup = new Cup() {
Value = num,
InList = true
};
if (_lastCup != null) {
_lastCup.Next = cup;
} else {
_cups = cup;
}
_lastCup = cup;
_hash.Add(num, cup);
if (num < _lowest) {
_lowest = num;
}
if (num > _highest) {
_highest = num;
}
}
private class Cup {
public Cup Next { get; set; }
public int Value { get; set; }
public bool InList { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using EnduroLibrary;
namespace EnduroCalculator.Calculators
{
public class SpeedCalculator : TrackCalculator
{
private readonly List<double> _speeds = new List<double>();
private readonly List<double> _climbingSpeeds = new List<double>();
private readonly List<double> _descentSpeeds = new List<double>();
private readonly List<double> _flatSpeeds = new List<double>();
public override void Calculate(TrackPoint nextPoint)
{
base.Calculate(nextPoint);
var timeSpanSeconds = (nextPoint.DateTime - CurrentPoint.DateTime).TotalSeconds;
if (timeSpanSeconds > TimeFilter || timeSpanSeconds == 0)
return;
var deltaS = CurrentPoint.GetGeoCoordinate().GetDistanceTo(nextPoint.GetGeoCoordinate());
var deltaT = (nextPoint.DateTime - CurrentPoint.DateTime).TotalSeconds;
var speed = deltaS / deltaT;
_speeds.Add(speed);
switch (CurrentDirection)
{
case AltitudeDirection.Climbing:
_climbingSpeeds.Add(speed);
break;
case AltitudeDirection.Descent:
_descentSpeeds.Add(speed);
break;
case AltitudeDirection.Flat:
_flatSpeeds.Add(speed);
break;
default:
throw new ArgumentOutOfRangeException();
}
CurrentPoint = nextPoint;
}
public override void PrintResult()
{
var minSpeed = _speeds.Min();
var maxSpeed = _speeds.Max();
var averageSpeed = _speeds.Average();
var averageClimbing = _climbingSpeeds.Average();
var averageDescent = _descentSpeeds.Average();
var averageFlat = _flatSpeeds.Average();
Console.WriteLine("Speed");
Console.WriteLine("----------------------------------");
Console.WriteLine("Minimum Speed: " + minSpeed.ToKilometersPerHour().ToString("##.00 'km/h'"));
Console.WriteLine("Maximum Speed: " + maxSpeed.ToKilometersPerHour().ToString("##.00 'km/h'"));
Console.WriteLine("Average Speed: " + averageSpeed.ToKilometersPerHour().ToString("##.00 'km/h'"));
Console.WriteLine("Average Climbing Speed: " + averageClimbing.ToKilometersPerHour().ToString("##.00 'km/h'"));
Console.WriteLine("Average Descent Speed: " + averageDescent.ToKilometersPerHour().ToString("##.00 'km/h'"));
Console.WriteLine("Average Flat Speed: " + averageFlat.ToKilometersPerHour().ToString("##.00 'km/h'"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Cajero1Parcial.Controllers
{
public class MontoController : Controller
{
// GET: Monto
public ActionResult Index()
{
return View();
}
public ActionResult Procesar(int Monto)
{
{
if ((Monto % 5) == 0)
{
return Redirect("/Monto/MostrarMonto");
}
else
return Redirect("/Monto/Error");
}
}
public ActionResult MostrarMonto()
{
return View();
}
public ActionResult Error()
{
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using pjank.BossaAPI.Fixml;
namespace pjank.BossaAPI.DemoConsole.Modules
{
class BosMarketDataEx : IDemoModule
{
public char MenuKey { get { return '8'; } }
public string Description { get { return "BossaAPI+NolClient, combined with low-level Fixml events"; } }
public void Execute()
{
try
{
// podpięcie zdarzenia zmiany notowań
Bossa.OnUpdate += HandleBossaUpdate;
// włączenie odbioru notowań dla wybranych instrumentów
// (wystarczy samo odwołanie się do konkretnego obiektu 'Bossa.Instruments[...]')
Bossa.Instruments["KGHM"].UpdatesEnabled = true;
Bossa.Instruments["WIG20"].UpdatesEnabled = true;
Bossa.Instruments["FW20M12"].UpdatesEnabled = true;
// własnoręczne przygotowanie obiektu do komunikacji z NOL'em...
var client = new NolClient();
// i podpięcie się bezpośrednio do jednego z jego wewnętrznych zdarzeń
client.SessionStatusMsgEvent += HandleSessionStatusMsgEvent;
// uruchomienie połączenia (to zamiast standardowego "ConnectNOL3")
Bossa.Connect(client);
// w tle odbieramy zdarzenia i wyświetlamy bieżące notowania
Console.WriteLine("Press any key... to exit");
Console.ReadKey(true);
}
finally
{
Bossa.OnUpdate -= HandleBossaUpdate;
Bossa.Disconnect();
Bossa.Clear();
}
}
// wywoływane przy aktualizacji danych rynkowych lub stanu rachunku.
void HandleBossaUpdate(object obj, EventArgs e)
{
var ins = obj as BosInstrument;
// wyświetlenie bieżących notowań: nalepsze oferty, parametry ostatniej transakcji
if (ins != null)
{
Trace.WriteLine(string.Format("{0,-10} [ {1,-8} {2,8} ] {3}",
ins.Symbol, ins.BuyOffers.BestPrice, ins.SellOffers.BestPrice, ins.Trades.Last));
}
}
// wywoływane przez NolClient po otrzymaniu komunikatu 'TrdgSesStat'
void HandleSessionStatusMsgEvent(TradingSessionStatusMsg msg)
{
var symbol = msg.Instrument != null ? msg.Instrument.Symbol : null;
Trace.WriteLine(string.Format("{0,-10} {1}", symbol, msg.SessionPhase));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SnowBLL.Models.Users
{
public class UserDetailModel
{
public string Name { get; set; }
public string Email { get; set; }
public int RoutesCount { get; set; }
public Dictionary<int, string> Routes{ get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Work.HTTP.Response
{
public class HtmlResponse : HttpResponse
{
public HtmlResponse(string html)
{
this.Code = HttpResponseCode.Ok;
byte[] byteData = Encoding.UTF8.GetBytes(html);
this.Body = byteData;
this.Headers.Add(new Header("Content-Type", "text/html"));
this.Headers.Add(new Header("Content-Length",this.Body.Length.ToString()));
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Witsml.Xml
{
public static class XmlHelper
{
public static string Serialize<T>(T item, Boolean indentXml = false)
{
var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = indentXml };
using var textWriter = new StringWriter();
using var writer = XmlWriter.Create(textWriter, settings);
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", "http://www.witsml.org/schemas/1series");
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, item, namespaces);
return textWriter.ToString();
}
public static T Deserialize<T>(string xmlString)
{
var bytes = Encoding.UTF8.GetBytes(xmlString);
using var stream = new MemoryStream(bytes);
var serializer = new XmlSerializer(typeof(T));
return (T) serializer.Deserialize(stream);
}
}
}
|
using Cosmos.HAL;
using FrameOS.Systems.CommandSystem;
using FrameOS.Systems.Encryption;
using System;
using System.Collections.Generic;
using System.Text;
namespace FrameOS.Commands
{
class DecryptCommand : ICommand
{
public string description { get => "Decrypt an encrypted text."; }
public string command => "decrypt";
public void Run(CommandArg[] commandArgs)
{
Terminal.WriteLine(Hashing.verifyHash("hi", "8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4".ToUpper()).ToString());
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ReturnBook : MonoBehaviour
{
public GameObject Panel;
public GameObject SuccessPanel;
public InputField userField;
public InputField titleField;
public void ReturnBookPanel()
{
Panel.gameObject.SetActive(true);
}
public void ExitReturnBookPanel()
{
Panel.gameObject.SetActive(false);
}
public void ExitSuccessPanel()
{
SuccessPanel.gameObject.SetActive(false);
}
public void Return()
{
StartCoroutine(BookReturn());
}
IEnumerator BookReturn()
{
WWWForm form = new WWWForm();
form.AddField("username", userField.text);
form.AddField("title", titleField.text);
WWW www = new WWW("https://organizacijaradaknjiznice.000webhostapp.com/ReturnBook.php", form);
yield return www;
if (www.text == "0")
{
Debug.Log("Book returned seccessfully");
Panel.gameObject.SetActive(false);
SuccessPanel.gameObject.SetActive(true);
}
else
{
Debug.Log("Returning book faild");
Panel.gameObject.SetActive(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Ajax.Utilities;
namespace WebQLKhoaHoc.Models
{
public class totalChartViewModel
{
public int MaDVQL { get; set; }
public int GSDD { get; set; }
public int GS { get; set; }
public int PGS { get; set; }
public int TSKH { get; set; }
public int TS { get; set; }
public int ThS { get; set; }
public int GV { get; set; }
public int NCV { get; set; }
public static totalChartViewModel Mapping(int madvql,int gsdd,int gs,int pgs,int tskh,int ts,int ths,int gv,int ncv)
{
totalChartViewModel totalvm = new totalChartViewModel();
totalvm.MaDVQL = madvql;
totalvm.GSDD = gsdd;
totalvm.GS = gs;
totalvm.PGS = pgs;
totalvm.TSKH = tskh;
totalvm.TS = ts;
totalvm.ThS = ths;
totalvm.GV = gv;
totalvm.NCV = ncv;
return totalvm;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kadastr.Data.Model
{
/// <summary>
/// Тип и наименование адресных параметров
/// </summary>
class NameAndType
{
public int Id { get; set; }
/// <summary>
/// Наименование
/// </summary>
public string Name { get; set; }
/// <summary>
/// Тип
/// </summary>
public string Type { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AboHassansFart.ParkingLot
{
class Vehicle
{
//Fält överst i klassen
private string color;
private string brand;
private string type;
private int price;
private int ammountOfTires;
public virtual void TestVehicle()
{
Console.WriteLine("Testing...");
}
public virtual void InspectVehicle()
{
Console.WriteLine($"Brand: {this.brand} Type: {this.type} Color: {this.color} Price: {this.price}");
}
public virtual void Honk()
{
Console.WriteLine("Toot toot");
}
public override string ToString()
{
return $"{this.Color} {this.Brand}";
}
//Gettters och setters i botten
public string Color { get => color; set => color = value; }
public string Brand { get => brand; set => brand = value; }
public string Type { get => type; set => type = value; }
public int Price { get => price; set => price = value; }
public int AmmountOfTires { get => ammountOfTires; set => ammountOfTires = value; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrabalhoDoAntoanne_Builder
{
internal class ReiDoCachorro4 : IConstrutorAbstrato4
{
Produto4 _produto;
public ReiDoCachorro4()
{
_produto = new Produto4("ReiDoCachorro");
}
public void SetItemPrincipal()
{
_produto.Itemprincipal = ItemPrincipal.CachorroQuente;
}
public void SetAcompanhamento()
{
_produto.Acompanhamento = Acompanhamento.BatataFrita;
}
public void SetBebida()
{
_produto.Bebida = Bebida.Guarana;
}
public void SetBrinde()
{
_produto.Brinde = Brinde.BichoDePelucia;
}
public Produto4 Produto
{
get { return _produto; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ASPNETCOREJSON.Repository;
using ASPNETCOREJSON.Models;
namespace ASPNETCOREJSON.Controllers
{
[Produces("application/json")]
[Route("api/Ozones")]
public class OzonesController : Controller
{
public IOzonesRepository OzonesRepo { get; set; }
public OzonesController(IOzonesRepository _repo)
{
OzonesRepo = _repo;
}
[HttpGet]
public IEnumerable<Ozone> GetAll()
{
return OzonesRepo.GetAll().Take(500);
}
[HttpGet("{id}", Name = "GetOzones")]
public IActionResult GetById(string id)
{
var item = OzonesRepo.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
[HttpPut("{id}")]
public IActionResult Create([FromBody] Ozone item)
{
if (item == null)
{
return BadRequest();
}
OzonesRepo.Add(item);
return CreatedAtRoute("GetOzones", new { Controller = "Ozones", id = item.Ozone_Id }, item);
}
[HttpPut]
public IActionResult Update(string id, [FromBody] Ozone item)
{
if (item == null)
{
return BadRequest();
}
var ozoneObj = OzonesRepo.Find(id);
if (ozoneObj == null)
{
return NotFound();
}
OzonesRepo.Update(item);
return new NoContentResult();
}
[HttpDelete("{id}")]
public void Delete(string id)
{
OzonesRepo.Remove(id);
}
}
}
|
using CYJ.DingDing.Application.IAppService;
namespace CYJ.DingDing.Application.AppService
{
public class ProcessAppService : IProcessAppService
{
}
} |
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using NetCore.Model.Models;
using NetCore.Model.SqlLog;
using NetCore.Utlity;
namespace NetCore.Model
{
public partial class CustomeContext : DbContext
{
private IConfiguration _IConfiguration = null;
public CustomeContext(IConfiguration configuration)
{
this._IConfiguration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// 1 new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build().GetConnectionString("CustomersConnectionString");
//2
optionsBuilder.UseSqlServer(this._IConfiguration.GetConnectionString("CustomersConnectionString"));
optionsBuilder.UseLoggerFactory(new CustomLoggerFactory());
// 3 optionsBuilder.UseSqlServer("Server=.;Database=Customers;User id=sa;password=123456;");
// 4 如果是静态类,无法使用IOC的注入IConfiguration
//optionsBuilder.UseSqlServer(StaticConstraint.CustomConnection);
}
public virtual DbSet<Company> Companies { get; set; }
public virtual DbSet<School> Schools { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<CityEntity> CityEntitys { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DBDriverEntity>().ToTable("DBDrivers");
modelBuilder.Entity<School>()
.Property(e => e.SchoolName)
.IsFixedLength();
modelBuilder.Entity<User>()
.Property(e => e.Name)
.IsFixedLength();
modelBuilder.Entity<User>()
.Property(e => e.Account)
.IsFixedLength();
modelBuilder.Entity<User>()
.Property(e => e.Password)
.IsFixedLength();
modelBuilder.Entity<User>()
.Property(e => e.Email)
.IsFixedLength();
modelBuilder.Entity<User>()
.Property(e => e.Mobile)
.IsFixedLength();
modelBuilder.Entity<User>()
.Property(e => e.CompanyName)
.IsFixedLength();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Zombies3
{
static class Constants
{
//Pickups
public static int ChanceOfPickup = 100;
public static int PickupRange = 50;
//Waves
public static int WaveMaxIncrement = 1;
public static int WaveSpawnPerSecondIncrement = 1;
public static float WaveEnemyStartSpeed = 2f; //Has to be able to be split into integer length components!
public static float WaveEnemySpeedMultiplier = 1.1f;
//Enemy AI
public static int EnemyPlayerSightBuffer = 10;
}
}
|
using System;
using System.Collections.Generic;
namespace EPI.StacksAndQueues
{
/// <summary>
/// A straight line program (SLP) for computing x^n is a finite sequence {x, x^i1, x^i2,...,x^n}
/// where each element after the first is either a product of any previous two elements or square
/// of some previous element.
/// Given a positive integer, n, compute a shortest straight line program to evaluate x^n.
/// </summary>
public static class ShortestStraightLine
{
// Iterate the sequence like BFS (breadth first search) of a graph starting with power 1.
// Find the first sequence containing the power of n and since we use BFS, it will be
// guaranteed to be the shortest path from power of 1.
// Use a queue to manage BFS
public static List<int> GetShortestStraightLine(int n)
{
if (n == 1)
{
return new List<int>() { 1 };
}
// initialize the queue for BFS traversal with 1
Queue<List<int>> sequence = new Queue<List<int>>();
sequence.Enqueue(new List<int>() { 1 });
while (sequence.Count > 0)
{
// read the next sequence to process
List<int> currentSequence = sequence.Dequeue();
int lastPower = currentSequence[currentSequence.Count - 1];
// Iterate all possible children sequences
foreach (int item in currentSequence)
{
// x^i1 + x^in
int power = item + lastPower;
if (power > n)
{
break;
}
List<int> newSequence = new List<int>(currentSequence);
newSequence.Add(power);
if (power == n)
{
return newSequence;
}
sequence.Enqueue(newSequence);
}
}
throw new InvalidOperationException("No solution found");
}
}
}
|
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class CrewPaidWageEvent : Event
{
public const string NAME = "Crew paid wage";
public const string DESCRIPTION = "Triggered when npc crew receives a profit share";
public const string SAMPLE = "{\"timestamp\":\"2019-03-09T18:46:52Z\", \"event\":\"NpcCrewPaidWage\", \"NpcCrewName\":\"Xenia Hoover\", \"NpcCrewId\":236064708, \"Amount\":0}";
[PublicAPI("The name of the crewmember")]
public string name { get; private set; }
[PublicAPI("The ID of the crewmember")]
public long crewid { get; private set; }
[PublicAPI("The amount paid to the crewmember")]
public long amount { get; private set; }
public CrewPaidWageEvent(DateTime timestamp, string name, long crewid, long amount) : base(timestamp, NAME)
{
this.name = name;
this.crewid = crewid;
this.amount = amount;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.InputSystem;
public class InputUIMissionsController : MonoBehaviour {
private DialogueScript dialogueScript;
private MissionComponent mission;
void Start() {
dialogueScript = GetComponent<DialogueScript>();
mission = GetComponent<MissionComponent>();
}
public void Move(InputAction.CallbackContext context) {
}
public void onClick(InputAction.CallbackContext context) {
if (context.started) {
var startGame = dialogueScript.Submit();
if (startGame) {
mission = GetComponent<MissionComponent>();
mission.StartMission();
}
}
}
} |
using System;
using System.Linq;
using System.ComponentModel;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
namespace SciVacancies.WebApp.Controllers
{
public class BindArgumentFromClaimsAttribute : ActionFilterAttribute
{
protected string Key;
protected string ArguName;
protected Type ArgumentType;
public BindArgumentFromClaimsAttribute() { }
public BindArgumentFromClaimsAttribute(string keys, string arguName) : this(keys, arguName, typeof(Guid)) { }
public BindArgumentFromClaimsAttribute(string keys, string arguName, Type argumentType)
{
Key = keys;
ArguName = arguName;
ArgumentType = argumentType;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var idClaim = ((Controller)context.Controller).User.Claims.FirstOrDefault(c => c.Type == Key);
if (idClaim != null)
context.ActionArguments[ArguName] = TypeDescriptor.GetConverter(ArgumentType).ConvertFrom(idClaim.Value);
base.OnActionExecuting(context);
}
}
public class BindResearcherIdFromClaimsAttribute : BindArgumentFromClaimsAttribute
{
public BindResearcherIdFromClaimsAttribute() : base(ConstTerms.ClaimTypeResearcherId, "researcherGuid", typeof(Guid)) { }
public BindResearcherIdFromClaimsAttribute(string argumentName) : base(ConstTerms.ClaimTypeResearcherId, argumentName, typeof(Guid)) { }
}
public class BindOrganizationIdFromClaimsAttribute : BindArgumentFromClaimsAttribute
{
public BindOrganizationIdFromClaimsAttribute(string argumentName) : base(ConstTerms.ClaimTypeOrganizationId, argumentName, typeof(Guid)) { }
public BindOrganizationIdFromClaimsAttribute() : base(ConstTerms.ClaimTypeOrganizationId, "organizationGuid", typeof(Guid)) { }
}
} |
using System;
namespace ConsoleApp1
{
class Shape
{
protected double width, height;
public Shape(){}
public Shape(double width, double height)
{
this.width = width;
this.height = height;
}
public void input()
{
Console.WriteLine("input of width: ");
width = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("input of height: ");
height = Convert.ToDouble(Console.ReadLine());
}
}
public interface Square
{
void Min();
}
class Restangle : Shape,Square
{
public Restangle() : base() { }
public Restangle(double width, double height) : base(width, height) { }
public double getArea()
{
return width * height;
}
public void Min()
{
Console.WriteLine("The maximum area of restangle is square");
}
}
class Program
{
static void Main(string[] args)
{
Restangle reg = new Restangle(10,8);
/* reg.input();*/
Console.WriteLine("the output of program is: " + reg.getArea());
reg.Min();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EpisodeRenaming {
public class NameDescription {
}
}
|
namespace WinterGrass
{
//A slimmed down version of SDV's Grass class with the relevant information needed to re-create it
internal class GrassSave
{
public readonly int GrassType;
public readonly int NumWeeds;
public GrassSave(int w, int n)
{
this.GrassType = w;
this.NumWeeds = n;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackgroundMusic : MonoBehaviour
{
[Tooltip("Is the scene that this gameobject is part of one of the menu scenes or not? " +
"The only exception should be the PlayScene.")]
public bool isMenu;
public bool PrintDebug = false;
void OnEnable() {
if (isMenu) {
SoundManager.StopLooping("playscene_music", PrintDebug);
SoundManager.PlaySound("menu_music");
}
else {
SoundManager.StopLooping("menu_music", PrintDebug);
SoundManager.PlaySound("playscene_music");
}
}
void OnDisable() {
if (!isMenu) {
SoundManager.StopAll();
}
}
}
|
namespace BetterSlingshots.Slingshot
{
internal interface IActionButtonAware
{
void SetActionButtonDownState(bool which);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace pjank.BossaAPI.DemoConsole.Modules
{
class BosAccountDataEx : IDemoModule
{
public char MenuKey { get { return '6'; } }
public string Description { get { return "BossaAPI basics, account info using OnUpdate event"; } }
public void Execute()
{
// połączenie z NOLem, zalogowanie użytkownika
Bossa.ConnectNOL3();
try
{
// podpięcie zdarzenia, po którym będziemy mogli odczytać nowy stan rachunku
Bossa.OnUpdate += HandleBossaUpdate;
// w tle odbieramy zdarzenia i wyświetlamy informacje o zmienionym stanie rachunku
Console.WriteLine("Press any key... to exit");
Console.ReadKey(true);
}
finally
{
Bossa.OnUpdate -= HandleBossaUpdate;
Bossa.Disconnect();
Bossa.Clear();
}
}
void HandleBossaUpdate(object obj, EventArgs e)
{
var account = obj as BosAccount;
if (account != null)
{
Trace.WriteLine("");
Trace.WriteLine(string.Format("Account: {0}", account.Number));
Trace.WriteLine(string.Format("- porfolio value: {0}", account.PortfolioValue));
Trace.WriteLine(string.Format("- deposit blocked: {0}", account.DepositBlocked));
Trace.WriteLine(string.Format("- available funds: {0}", account.AvailableFunds));
Trace.WriteLine(string.Format("- available cash: {0}", account.AvailableCash));
// spis papierów wartościowych na danym rachunku
if (account.Papers.Count > 0)
{
Trace.WriteLine("- papers: ");
foreach (var paper in account.Papers)
Trace.WriteLine(string.Format(" {0,5} x {1}", paper.Quantity, paper.Instrument));
}
// spis aktywnych zleceń na tym rachunku
if (account.Orders.Count > 0)
{
Trace.WriteLine("- orders: ");
foreach (var order in account.Orders)
Trace.WriteLine(string.Format(" {0}: {1} {2} x {3} - {4}",
order.Instrument, order.Side, order.Quantity, order.Price, order.StatusReport));
}
Trace.WriteLine("");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.