blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
3a591e9065bac6c4138ba505e2eb0be881c38c38
|
C#
|
PlumpMath/FusionPInvoke
|
/src/FusionPInvoke/CreateAssemblyCacheItemFlags.cs
| 2.546875
| 3
|
namespace FusionPInvoke
{
/// <summary>
/// Flags used in <see cref="IAssemblyCache.CreateAssemblyCacheItem"/>.
/// </summary>
public enum CreateAssemblyCacheItemFlags
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// If the assembly is already installed in the GAC and the file version numbers of the assembly being installed are the same or later, the files are replaced.
/// </summary>
Refresh = 1,
/// <summary>
/// The files of an existing assembly are overwritten regardless of their version number.
/// </summary>
ForceRefresh = 2
}
}
|
e6788eafe2e42743a1e5824a6cc48bc4c41bf9b0
|
C#
|
m2idotnet/CoursSharpGit
|
/CoursSharp/CoursAdoNetDeconnecte/Program.cs
| 3.203125
| 3
|
using CoursAdoNet;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace CoursAdoNetDeconnecte
{
class Program
{
static void Main(string[] args)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM personne", Connection.Instance);
//Création de commande d'insertion
SqlCommand commandInsert = new SqlCommand("INSERT INTO personne ( Nom, Prenom) Values (@nom,@prenom)", Connection.Instance);
//commandInsert.Parameters.Add("@id", SqlDbType.Int, 11, "Id");
commandInsert.Parameters.Add("@nom", SqlDbType.VarChar, 50, "Nom");
commandInsert.Parameters.Add("@prenom", SqlDbType.VarChar, 50, "Prenom");
SqlCommand commandUpdate = new SqlCommand("UPDATE personne set nom = @nom, prenom = @prenom WHERE id=@id",Connection.Instance);
commandUpdate.Parameters.Add("@id", SqlDbType.Int, 11, "Id");
commandUpdate.Parameters.Add("@nom", SqlDbType.VarChar, 50, "Nom");
commandUpdate.Parameters.Add("@prenom", SqlDbType.VarChar, 50, "Prenom");
SqlCommand commandDelete = new SqlCommand("DELETE FROM personne where id = @id", Connection.Instance);
commandDelete.Parameters.Add("@id", SqlDbType.Int, 11, "Id");
//Attacher la commande a l'adapter
adapter.InsertCommand = commandInsert;
adapter.UpdateCommand = commandUpdate;
adapter.DeleteCommand = commandDelete;
DataSet data = new DataSet();
Connection.Instance.Open();
adapter.Fill(data, "Personnes");
Connection.Instance.Close();
//Stocker la table Personnes du DataSet dans une variable
DataTable tablePersonne = data.Tables["Personnes"];
//indiquer que la column ID est autoIncrementer
tablePersonne.Columns["Id"].AutoIncrement = true;
//indiquer le pas
tablePersonne.Columns["Id"].AutoIncrementStep = 1;
//indiquer le début
tablePersonne.Columns["Id"].AutoIncrementSeed = (int)tablePersonne.Rows[tablePersonne.Rows.Count - 1]["Id"] + 1;
Console.WriteLine("----Avant-----");
foreach(DataRow r in data.Tables["Personnes"].Rows)
{
Console.WriteLine("Nom : " + r["Nom"] + " id : " + r["Id"]);
}
//Creer une nouvelle ligne
DataRow ro = data.Tables["Personnes"].NewRow();
ro["Nom"] = "Coucou1";
ro["Prenom"] = "CoucouPrénom";
data.Tables["Personnes"].Rows.Add(ro);
ro = data.Tables["Personnes"].NewRow();
ro["Nom"] = "Coucou2";
ro["Prenom"] = "CoucouPrénom";
//ro["Id"] = (int)tablePersonne.Rows[tablePersonne.Rows.Count - 1]["Id"] + 1;
data.Tables["Personnes"].Rows.Add(ro);
Console.WriteLine("----Après-----");
foreach (DataRow r in data.Tables["Personnes"].Rows)
{
Console.WriteLine("Nom : " + r["Nom"] + " id : "+r["Id"]);
}
//modification d'une ligne
tablePersonne.Rows[3]["Nom"] = "New Value of name at index number 3";
Connection.Instance.Open();
//suppression d'une ligne à l'interieur d'une table du DataSet
//tablePersonne.Rows[5].Delete();
for(int i=0; i< tablePersonne.Rows.Count; i++)
{
if((string)tablePersonne.Rows[i]["Nom"] == "tata")
{
tablePersonne.Rows[i].Delete();
}
}
//Mettre à jour la base de donnée à partir de la table du DataSet en utilisant les commandes du adapter
adapter.Update(tablePersonne);
Connection.Instance.Close();
Console.ReadLine();
}
}
}
|
902b6a6490b13b058f868006f38be10e2d0a640e
|
C#
|
wirachai/MirrorFetcher
|
/TerraFetcher/Services/AppService.cs
| 2.859375
| 3
|
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using TerraFetcher.Models;
namespace TerraFetcher.Services
{
public class AppService
{
private readonly MirrorService mirrorService;
private readonly LogService logService;
public AppService()
{
mirrorService = new MirrorService();
logService = new LogService();
}
public void Run()
{
Setting setting = GetSetting();
var prices = mirrorService.GetCurrentPrice().Data.SelectMany(x => x.Assets);
List<LogModel> logs = logService.GetLogs();
StringBuilder message = ComposeNotifyMessage(setting, prices, logs);
var sendingMessage = message.ToString();
SendLineNotify(setting, sendingMessage);
WriteLog(prices);
}
private static Setting GetSetting()
{
var settings = File.ReadAllText("setting.json");
var setting = JsonConvert.DeserializeObject<Setting>(settings);
return setting;
}
private static StringBuilder ComposeNotifyMessage(Setting setting, IEnumerable<Asset> prices, List<LogModel> logs)
{
var favorites = prices.Where(x => setting.SymbolFavorites.Contains(x.Symbol))
.OrderBy(x => x.Prices.Spread)
.ToList();
var filtereds = prices.Where(x => setting.SymbolFilters.Contains(x.Symbol) == false)
.OrderBy(x => x.Prices.Spread)
.ToList();
var buys = filtereds.Where(x => x.Prices.Spread <= setting.Low && x.Prices.Spread >= 0.00M).ToList();
var sells = filtereds.Where(x => x.Prices.Spread >= setting.High).ToList();
var message = new StringBuilder("\n");
if (favorites.Any())
{
ComposeMessage("Mirror Favorites:", favorites, logs, message);
}
if (buys.Any())
{
ComposeMessage("Mirror Buy:", buys, logs, message);
}
if (sells.Any())
{
ComposeMessage("Mirror Sell:", sells, logs, message);
}
return message;
}
private static void ComposeMessage(string header, List<Asset> assets, List<LogModel> logs, StringBuilder message)
{
message.AppendLine(header);
foreach (var asset in assets)
{
var change = "";
var log = logs.FirstOrDefault(x => x.Symbol == asset.Symbol);
if (log != null)
{
if (asset.Prices.PriceAt > log.Price)
{
change = " (+)";
}
if (asset.Prices.PriceAt < log.Price)
{
change = " (-)";
}
}
message.AppendLine($"- {asset.Symbol} {asset.Prices.Spread * 100:F}%: {asset.Prices.PriceAt:F}{change}");
}
message.AppendLine();
}
private static void SendLineNotify(Setting setting, string sendingMessage)
{
if (string.IsNullOrWhiteSpace(sendingMessage) == false)
{
var line = new LineNotify();
foreach (var token in setting.LineTokens)
{
line.Send(token, sendingMessage);
}
}
}
private void WriteLog(IEnumerable<Asset> prices)
{
var newLogs = prices.Select(x => new LogModel
{
Symbol = x.Symbol,
Price = x.Prices.PriceAt
}).ToList();
logService.WriteLogs(newLogs);
}
}
}
|
2e077ad52855af19915bd2b0bf49aeabdbab690c
|
C#
|
supertask/ChainX
|
/tmp/Example.cs
| 2.765625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
public class Example {
public static Object thisLock = new Object();
public ChainVoxel cv;
public Example() {
this.cv = new ChainVoxel();
}
public static void Main(string[] args) {
Voxel.Test();
StructureTable.Test();
ChainVoxel.Test();
Example ex = new Example();
string posID = "";
string destPosID = "1:1:1";
Random r = new Random(1000);
int receiveOperationNumber = 400;
int receiveOperationSleepMillisecond = 12;
int updateSelectObjectNumber = 500;
int updateSelectObjectSleepMillisecond = 15;
Thread thread = new Thread(
() => {
for(int i = 0; i < receiveOperationNumber; i++) {
/*
* Receiveした後の処理
*/
lock(Example.thisLock) {
string[] xyz_str = destPosID.Split (':');
int[] xyz = new int[3];
for(int j=0; j<3; j++) { xyz[j] = int.Parse(xyz_str[j]); }
posID = String.Format("{0}:{1}:{2}", xyz[0], xyz[1], xyz[2]);
xyz[r.Next(3)]++;
destPosID = String.Format("{0}:{1}:{2}", xyz[0], xyz[1], xyz[2]);
Console.WriteLine("別スレッドだよ: posID=" + posID + ", destPosID=" + destPosID);
ex.cv.apply(new Operation(0, Operation.MOVE, posID, destPosID, "Group2"));
}
//Thread.Sleep(500); //ユーザのキー操作の速度で処理
//Thread.Sleep(25); //25のときバグが起こりやすい
Thread.Sleep(receiveOperationSleepMillisecond); //ユーザのキー操作の速度で処理
}
}
);
thread.Start();
/*
* Receiveにて更新されたmovedPosIDsを元にdestPosIDを更新
*/
for (int i = 0; i < updateSelectObjectNumber; i++) {
//send()、ここでの処理は省く
//sendされた後、receiveで受け取られる。そこから記述している
lock(Example.thisLock) {
foreach (KeyValuePair<string,string> aPair in ChainVoxel.movedPosIDs) {
string posID_tmp = aPair.Key;
string destPosID_tmp = aPair.Value;
destPosID = destPosID_tmp;
//Console.WriteLine("本体スレッドだよ: destPosID="+ destPosID);
}
ChainVoxel.movedPosIDs.Clear();
}
Thread.Sleep(updateSelectObjectSleepMillisecond);
}
}
}
|
4b88bfa26cb90334409867a86ecdb6d73cb2c311
|
C#
|
andreaolivotto/ValutazioneAlunni
|
/ValutazioneAlunni/MVVMviewmodels/ExportViewModel.cs
| 2.515625
| 3
|
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ValutazioneAlunni.MVVMmodels;
using ValutazioneAlunni.MVVMutils;
using ValutazioneAlunni.Utilities;
using System.Windows;
using ValutazioneAlunni.Data;
using System.Diagnostics;
using NPOI.OpenXmlFormats.Wordprocessing;
namespace ValutazioneAlunni.MVVMviewmodels
{
class ExportViewModel : BaseViewModel
{
#region private fields
private static readonly Log _log = Log.Instance;
private ApplicationSettings _settings = ApplicationSettings.Instance;
private bool _edit_mode;
#endregion
#region init and deinit
public ExportViewModel()
{
EditMode = true;
messenger_init();
}
#endregion
#region messenger
private void messenger_init()
{
Messenger.Default.Register<StudentData>(this, messenger_export_student_word, "ExportStudentWord");
}
private void messenger_export_student_word(StudentData s)
{
word_export_student(s);
}
#endregion
#region private functions - word
private ulong mm_to_twip(int mm)
{
return (ulong)((1440.0f * mm) / 25.4f);
}
private bool word_export_student(StudentData s)
{
XWPFParagraph p;
XWPFRun r;
int chapter_idx;
int section_idx;
try
{
_log.Info("Esportazione sudente in Word...");
_log.Info(s.Dump());
_log.Info("Cartella di esportazione: " + _settings.ExportFolder);
if (Directory.Exists(_settings.ExportFolder) == false)
{
_log.Error("Errore! La cartella di esportazione non esiste!");
return false;
}
// see https://github.com/tonyqus/npoi/blob/master/examples/xwpf/SimpleDocument/Program.cs
XWPFDocument doc = new XWPFDocument();
doc.Document.body.sectPr = new CT_SectPr();
CT_PageMar margin = doc.Document.body.sectPr.pgMar;
margin.top = mm_to_twip(15).ToString();
margin.bottom = mm_to_twip(15).ToString();
margin.left = mm_to_twip(15);
margin.right = mm_to_twip(15);
string font_family = "Courier New";
// Title
p = doc.CreateParagraph();
p.Alignment = ParagraphAlignment.CENTER;
p.VerticalAlignment = NPOI.XWPF.UserModel.TextAlignment.CENTER;
p.SpacingAfter = 500;
r = p.CreateRun();
r.IsBold = true;
r.FontSize = 16;
r.FontFamily = font_family;
r.SetText(_settings.EvaluationTitle);
// Header: teacher, data
p = doc.CreateParagraph();
p.Alignment = ParagraphAlignment.LEFT;
r = p.CreateRun();
r.FontSize = 12;
r.FontFamily = font_family;
r.SetText("Insegnante: " + _settings.TeacherFirstName + " " + _settings.TeacherLastName);
p = doc.CreateParagraph();
p.Alignment = ParagraphAlignment.LEFT;
p.SpacingAfter = 500;
r = p.CreateRun();
r.FontSize = 12;
r.FontFamily = font_family;
r.SetText("Data : " + DateStringName);
// Student
p = doc.CreateParagraph();
p.Alignment = ParagraphAlignment.LEFT;
r = p.CreateRun();
r.FontSize = 12;
r.FontFamily = font_family;
r.SetText("Studente : " + s.FirstName + " " + s.LastName);
p = doc.CreateParagraph();
p.SpacingAfter = 500;
p.Alignment = ParagraphAlignment.LEFT;
r = p.CreateRun();
r.FontSize = 12;
r.FontFamily = font_family;
r.SetText("Data di nascita: " + s.BirthDate.ToString("dd/MM/yyyy"));
// Evaluation
chapter_idx = 0;
foreach (EvaluationChapter chapter in DataContainer.Instance.EvaluationScheme.Chapters)
{
// Student
p = doc.CreateParagraph();
p.Alignment = ParagraphAlignment.LEFT;
p.SpacingAfter = 200;
r = p.CreateRun();
r.FontSize = 16;
r.IsBold = true;
r.FontFamily = font_family;
r.SetText(chapter.Name);
section_idx = 0;
StringBuilder sb = new StringBuilder();
foreach (EvaluationSection section in chapter.Sections)
{
int level = s.GetEvaluationLevel(chapter_idx, section_idx);
if (level >= 0)
{
sb.Append(DataContainer.Instance.EvaluationScheme.GetLevelDescription(chapter_idx, section_idx, level) + " ");
}
section_idx++;
}
p = doc.CreateParagraph();
p.Alignment = ParagraphAlignment.LEFT;
p.SpacingAfter = 400;
r = p.CreateRun();
r.FontSize = 12;
r.FontFamily = font_family;
r.SetText(sb.ToString());
chapter_idx++;
}
// Save to disk
string word_file_name = s.LastName + "_" + s.FirstName + "_" + DateTime.Now.ToString("dd-MM-yyyy_hh-mm") + ".docx";
_log.Info("Nome file : " + word_file_name);
string complete_word_file_name = Path.Combine(_settings.ExportFolder, word_file_name);
FileStream out1 = new FileStream(complete_word_file_name, FileMode.Create);
doc.Write(out1);
out1.Close();
if (_settings.OpenAfterExport)
{
Process.Start(complete_word_file_name);
}
else
{
MessageBoxResult result = MessageBox.Show("Valutazione studente esportata in formato Word!", "Esportazione riuscita!", MessageBoxButton.OK);
}
return true;
}
catch (Exception exc)
{
_log.Error("Exception in export_student_word(): " + exc.Message);
return false;
}
}
#endregion
#region public properties
public bool EditMode
{
get
{
return _edit_mode;
}
private set
{
_edit_mode = value;
RaisePropertyChanged("ReadOnlyMode");
RaisePropertyChanged("EditMode");
}
}
public bool ReadOnlyMode
{
get
{
return !EditMode;
}
}
public string TeacherFirstName
{
get
{
return _settings.TeacherFirstName;
}
set
{
if (EditMode == true)
{
_settings.TeacherFirstName = value;
}
RaisePropertyChanged("TeacherFirstName");
}
}
public string TeacherLastName
{
get
{
return _settings.TeacherLastName;
}
set
{
if (EditMode == true)
{
_settings.TeacherLastName = value;
}
RaisePropertyChanged("TeacherLastName");
}
}
public string EvaluationTitle
{
get
{
return _settings.EvaluationTitle;
}
set
{
if (EditMode == true)
{
_settings.EvaluationTitle = value;
}
RaisePropertyChanged("EvaluationTitle");
}
}
private string _date = DateTime.Now.ToString("dd/MM/yyyy");
public string DateStringName
{
get
{
return _date;
}
set
{
if (EditMode == true)
{
_date = value;
}
RaisePropertyChanged("DateStringName");
}
}
public string ExportFolder
{
get
{
return _settings.ExportFolder;
}
private set
{
_settings.ExportFolder = value;
RaisePropertyChanged("ExportFolder");
}
}
public bool OpenAfterExport
{
get
{
return _settings.OpenAfterExport;
}
set
{
_settings.OpenAfterExport = value;
RaisePropertyChanged("OpenAfterExport");
}
}
#endregion
#region commands
private ICommand _set_export_folder_cmd;
public ICommand SetExportFolderCmd
{
get
{
if (_set_export_folder_cmd == null)
{
_set_export_folder_cmd = new RelayCommand(
param => this.set_export_folder(),
param => this.can_set_export_folder()
);
}
return _set_export_folder_cmd;
}
}
private bool can_set_export_folder()
{
return true;
}
private void set_export_folder()
{
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
ExportFolder = dialog.SelectedPath;
}
}
}
private ICommand _export_all_word_cmd;
public ICommand ExportAllWordCmd
{
get
{
if (_export_all_word_cmd == null)
{
_export_all_word_cmd = new RelayCommand(
param => this.export_all_word(),
param => this.can_export_all_word()
);
}
return _export_all_word_cmd;
}
}
private bool can_export_all_word()
{
return false;
}
private void export_all_word()
{
// TODO
}
#endregion
}
}
|
6bed8acab4d059a57a1ec84861a693e672ca9b9c
|
C#
|
felixsoum/hostile-mind
|
/HM2/Source/Level/RoomTransition.cs
| 2.609375
| 3
|
using System;
using Microsoft.Xna.Framework;
namespace HostileMind
{
public class RoomTransition
{
public string NextRoom { get; private set; }
public Vector2 NextPlayerPosition { get; private set; }
public bool IsActive { get; private set; }
public RoomTransition()
{
NextRoom = "";
NextPlayerPosition = Vector2.Zero;
IsActive = false;
}
public void Activate(string nextRoom, Vector2 nextPlayerPosition)
{
NextRoom = nextRoom;
NextPlayerPosition = nextPlayerPosition;
IsActive = true;
}
public void Deactivate()
{
IsActive = false;
}
}
}
|
4a3f483de0f24456024fb707e4a99d988ee21ad9
|
C#
|
AntonyBaasan/lsbasi-csharp
|
/Part9/Interpreter/Var.cs
| 2.578125
| 3
|
namespace Interpreter
{
public class Var: AST
{
public Token Token { get; }
public string Value { get; }
public Var(Token token)
{
Token = token;
Value = token.Value;
}
}
}
|
56bde09a6d35ccb74aa9f93934c140d6e70146fb
|
C#
|
meltaway/csharp
|
/serialization/Program.cs
| 2.859375
| 3
|
using System.Reflection.Metadata;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
class Program {
static void Main(string[] args) {
DateTime worldTime = DateTime.Now;
List<Animal> animals = new List<Animal>();
animals.Add(new Dolphin());
foreach (var animal in animals) {
animal.Death += Globals.animalDeathLogger;
}
System.Timers.ElapsedEventHandler onWorldTimeUpdate = delegate (object sender, System.Timers.ElapsedEventArgs e)
{
worldTime = worldTime.AddYears(1);
animals[0].Live(worldTime);
Console.WriteLine($"[{worldTime}] Updating...");
};
System.Timers.Timer worldTimer = new System.Timers.Timer(1000);
worldTimer.AutoReset = true;
worldTimer.Elapsed += onWorldTimeUpdate;
worldTimer.Start();
Console.ReadKey();
Humanity h = new Humanity(5);
int c = h.CurrentJobCount("dev");
Human human = new Human();
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream("data.bin", FileMode.Create)) {
formatter.Serialize(stream, human);
}
Human dp;
using (Stream stream = new FileStream("data.bin", FileMode.Open)) {
dp = (Human) formatter.Deserialize(stream);
}
dp.ShowInfo();
Dolphin d = new Dolphin();
using (Stream stream = new FileStream("data.json", FileMode.Create)) {
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Dolphin));
ser.WriteObject(stream, d);
stream.Position = 0;
}
using (Stream stream = new FileStream("data.json", FileMode.Open)) {
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Dolphin));
stream.Position = 0;
d = (Dolphin)ser.ReadObject(stream);
}
d.ShowInfo();
Humanity list = new Humanity(5);
Console.WriteLine(list.CurrentJobCount("cook"));
}
}
|
36e44f20f391af40d44bfdc830f2a48e08a2595f
|
C#
|
pobiega/Sniffer
|
/src/Sniffer/Data/ESIClient.cs
| 2.515625
| 3
|
using Serilog;
using Sniffer.Data.ESI.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace Sniffer.Data
{
public class ESIClient : IESIClient
{
public ESIClient(
ILogger logger,
IHttpClientFactory httpClientFactory
)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
}
private const string HTTP_CLIENT_NAME = "ESICLIENT";
private const string ESI_BASE_URL = "https://esi.evetech.net/latest";
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger _logger;
private async Task<TResponse> GetAsync<TResponse>(Uri requestUri)
{
var client = _httpClientFactory.CreateClient(HTTP_CLIENT_NAME);
var response = await client.GetAsync(requestUri).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
_logger.Error("ESI returned non-success code {statusCode} when requesting resource at {requestUri}", response.StatusCode, requestUri);
return default;
}
return await response.Content.ReadFromJsonAsync<TResponse>().ConfigureAwait(false);
}
public virtual Task<SystemData> GetSystemDataAsync(int systemId)
{
if (systemId == default)
{
return Task.FromResult<SystemData>(null);
}
var requestUri = new Uri($"{ESI_BASE_URL}/universe/systems/{systemId}/?datasource=tranquility&language=en");
return GetAsync<SystemData>(requestUri);
}
public virtual async Task<AllianceData> GetAllianceDataAsync(int allianceId)
{
if (allianceId == default)
{
return null;
}
var requestUri = new Uri($"{ESI_BASE_URL}/alliances/{allianceId}/?datasource=tranquility&language=en");
var response = await GetAsync<AllianceData>(requestUri);
response.Id = allianceId;
return response;
}
public virtual async Task<CorporationData> GetCorporationDataAsync(int corpId)
{
if (corpId == default)
{
return null;
}
var requestUri = new Uri($"{ESI_BASE_URL}/corporations/{corpId}/?datasource=tranquility&language=en");
var response = await GetAsync<CorporationData>(requestUri);
response.Id = corpId;
return response;
}
public virtual async Task<CharacterData> GetCharacterDataAsync(int characterId)
{
if (characterId == default)
{
return null;
}
var requestUri = new Uri($"{ESI_BASE_URL}/characters/{characterId}/?datasource=tranquility&language=en");
var response = await GetAsync<CharacterData>(requestUri);
response.Id = characterId;
return response;
}
public virtual Task<List<int>> GetRouteDataAsync(int originSystemId, int destinationSystemId)
{
var requestUri = new Uri($"{ESI_BASE_URL}/route/{originSystemId}/{destinationSystemId}/?datasource=tranquility&language=en");
return GetAsync<List<int>>(requestUri);
}
}
}
|
13baca14f5f26558e19eceae8b3eb3572b03a535
|
C#
|
max619/OnScreenKeyboard
|
/OnScreenKeyboard/Helpers/DebugKeyboardInputContext.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnScreenKeyboard.Helpers
{
class DebugKeyboardInputContext : IKeyboardInputContext
{
public IKeyboardInputContext TargetContext { get; set; }
public DebugKeyboardInputContext(IKeyboardInputContext context)
{
TargetContext = context;
}
public bool IsFocused()
{
var res = TargetContext != null ? TargetContext.IsFocused() : true;
Debug.WriteLine($"IsFocused returned {res}");
return res;
}
public void PushChar(char c)
{
Debug.WriteLine($"Pushing char {c} to the context");
TargetContext?.PushChar(c);
}
public void PushKeyCode(int keyCode)
{
Debug.WriteLine($"Pushing keycode {keyCode} to the context");
TargetContext?.PushKeyCode(keyCode);
}
}
}
|
dc5ff068ce2893a053a3d6073bdd824fff862403
|
C#
|
shendongnian/download4
|
/code8/1336667-36069943-113495476-2.cs
| 2.6875
| 3
|
foreach (var item in fileDictionary)
{
var tempFileList = new List<string>();
foreach (var file in fileArray)
{
if (!Array.Exists(item.Value, element => element.Contains(file + today)))
{
tempFileList.Add(file + today);
}
}
resultDictionary.Add(item.Key, tempFileList);
}
|
bd51ee5c191026d509e40cbda19269caa3134faf
|
C#
|
pleasenophp/mindi-demo
|
/Implementations/Human.cs
| 2.96875
| 3
|
using MinDI;
namespace Custom.Demo.Implementations {
public class Human : ContextObject, IHuman {
[Injection] public ISky sky { get; set; }
[Injection] public ILog log { get; set; }
[Requirement] public string name { get; set; }
public void Act() {
log.LogLine("I will act and will try to touch the sky right now");
sky.Touch();
}
public void Say() {
log.LogLine(string.Format("Hi, I'm {0}", name));
}
}
}
|
758dd75d0af834b6699471b18febdd9917840929
|
C#
|
ShiroYacha/Planact
|
/Planact.App/Planact.App/Converters/StringToColorConverter.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI;
using Windows.UI.Xaml.Data;
namespace Planact.App.Converters
{
public class StringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
{
return ColorHelper.FromArgb(255, 63, 78, 149);
}
else
{
var hexString = GenerateSHA1HexStringFromString(value as string);
return CreateColorFromHexString(hexString);
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
private string GenerateSHA1HexStringFromString(string rawString)
{
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(rawString, BinaryStringEncoding.Utf8);
HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
IBuffer hashBuffer = hashAlgorithm.HashData(buffer);
return CryptographicBuffer.EncodeToHexString(hashBuffer);
}
private Color CreateColorFromHexString(string hexString)
{
var hexColorString = hexString.Substring(0, 6);
return ColorHelper.FromArgb(255,
byte.Parse(hexColorString.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
byte.Parse(hexColorString.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
byte.Parse(hexColorString.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
}
}
}
|
218d5fe14ea435a19c5ed7f6bc7c8e3ae5fb04bc
|
C#
|
charlierobson/M6
|
/M6/Classes/RawFloatPCMFileConverter.cs
| 2.859375
| 3
|
using System;
using System.IO;
using ProtoBuf;
namespace M6.Classes
{
public class RawFloatPCMFileConverter : IFileConverter
{
private readonly string _path;
private readonly IFileSystemHelper _fileSystemHelper;
public RawFloatPCMFileConverter(string path, IFileSystemHelper fileSystemHelper)
{
_path = path;
_fileSystemHelper = fileSystemHelper;
}
public IFrameData ProcessFile()
{
FrameData frameData = null;
try
{
using (var rawFile = File.OpenRead(_path))
{
frameData = Serializer.Deserialize<FrameData>(rawFile);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return frameData;
}
//public IFrameData ProcessFile()
//{
// var bytes = _fileSystemHelper.ReadAllBytes(_path);
// var frames = bytes.Length/4;
// var left = new float[frames];
// var right = new float[frames];
// var j = 0;
// for (var i = 0; i < bytes.Length; i += 4)
// {
// var l = BitConverter.ToInt16(bytes, i);
// left[j] = l / 32768f;
// var r = BitConverter.ToInt16(bytes, i + 2);
// right[j] = r / 32768f;
// ++j;
// }
// return new FrameData(left, right);
//}
}
}
|
fd9029b4ff9251bd4a077bc8ebf8f120eb8b7c6f
|
C#
|
ignatovasashka/FinalExam-Tech-Module
|
/02OnTheWay/Program.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _02OnTheWay
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, List<string>> storeAndItems = new Dictionary<string, List<string>>();
string[] input = Console.ReadLine().Split("->");
string command = input[0];
while (command != "END")
{
string storeName = input[1];
List<string> itemsInStore = new List<string>();
if (command == "Add")
{
string[] tokensItems = input[2].Split(",");
foreach (var item in tokensItems)
{
itemsInStore.Add(item);
}
if (!storeAndItems.ContainsKey(storeName))
{
storeAndItems.Add(storeName, itemsInStore);
}
else
{
foreach (var item in tokensItems)
{
storeAndItems[storeName].Add(item);
}
}
}
else if(storeAndItems.ContainsKey(storeName))
{
storeAndItems.Remove(storeName);
}
input = Console.ReadLine().Split("->");
command = input[0];
}
Console.WriteLine("Stores list:");
foreach (var kvp in storeAndItems
.OrderByDescending(x=>x.Value.Count)
.ThenByDescending(x=>x.Key))
{
Console.WriteLine($"{kvp.Key}");
foreach (var item in storeAndItems[kvp.Key])
{
Console.WriteLine($"<<{item}>>");
}
}
}
}
}
|
1a7f9356ad7625e8fafc47cc099768cd69723695
|
C#
|
irongut/CarouselView
|
/Demo/Pages/Bug168.xaml.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using PropertyChanged;
using Xamarin.Forms;
namespace Demo
{
public partial class Bug168 : ContentPage
{
public Bug168()
{
InitializeComponent();
BindingContext = new CarouselPageViewModel();
}
}
[AddINotifyPropertyChangedInterface]
public class CarouselPageViewModel
{
#region private
private ObservableCollection<String> _items = new ObservableCollection<String>();
//private Boolean _isVisible = false;
#endregion
public ObservableCollection<String> Items
{
get { return _items; }
}
public Boolean IsVisible
{
get;
set;
}
public Command UpdateCarouselCommand
{
get
{
return new Command(() => Items.Add(String.Format("Item {0}", Items.Count + 1)));
}
}
public Command ToggleVisibilityCommand
{
get
{
return new Command(() => IsVisible = !IsVisible);
}
}
}
}
|
070fc95660870ad7a451d021c50951836d315804
|
C#
|
blounty/XB1
|
/XboxOne.Core.WP8/Services/TwitterService.cs
| 2.578125
| 3
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using XboxOne.Core.Models;
namespace XboxOne.Core.WP8.Services
{
public class TwitterService
{
const string TWEET_AUTH_URL = "https://api.twitter.com/oauth2/token";
private string twitterAccessToken = "";
private long maxId = default(long);
public string SearchTerm { get; set; }
public int ReturnCount { get; set; }
public TwitterService(string searchTerm, int returnCount)
{
this.SearchTerm = searchTerm;
this.ReturnCount = returnCount;
}
public void ResetFilters()
{
this.maxId = default(long);
}
public async Task<bool> AuthorizeTwitter()
{
if (!string.IsNullOrEmpty(this.twitterAccessToken))
return true;
try
{
var authTokens = "QUZksaqAdqZFxefaQ5cPQ:9vNnFn1SrtUAoWa1eNXjTFNpySQN2b5icTs10uDE4g";
var base64AuthTokens = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(authTokens));
var twitterAuthClient = new HttpClient();
twitterAuthClient.DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", base64AuthTokens));
var content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await twitterAuthClient.PostAsync(TWEET_AUTH_URL, content);
var responseJson = JValue.Parse(await response.Content.ReadAsStringAsync());
this.twitterAccessToken = responseJson["access_token"].ToString();
}
catch (Exception)
{
return false;
}
return true;
}
public async Task<List<TwitterItem>> LoadTweets()
{
var twitterItems = new List<TwitterItem>();
if (string.IsNullOrEmpty(this.twitterAccessToken))
{
return twitterItems;
}
var tweetClient = new HttpClient();
tweetClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + this.twitterAccessToken);
try
{
var response = await tweetClient.GetAsync(this.GenerateTwitterUrl());
var jsonString = await response.Content.ReadAsStringAsync();
var resultsJson = JObject.Parse(jsonString);
var tweetArrayJson = (JArray)resultsJson["statuses"];
foreach (JObject tweetJson in tweetArrayJson)
{
var twitterItem = new TwitterItem
{
Author = tweetJson["user"]["screen_name"].Value<string>(),
AvatarUrl = tweetJson["user"]["profile_image_url"].Value<string>(),
Tweet = tweetJson["text"].Value<string>(),
Id = tweetJson["id"].Value<string>()
};
var createdDateString = tweetJson["created_at"].Value<string>();
twitterItem.PublishDate = createdDateString.Remove(createdDateString.Length - 11);
twitterItems.Add(twitterItem);
}
}
catch (Exception)
{
var twitterItem = new TwitterItem
{
Author = "",
AvatarUrl = "",
Tweet = "error, please retry...",
Id = ""
};
twitterItems.Add(twitterItem);
return twitterItems;
}
this.maxId = Convert.ToInt64(twitterItems.Last().Id) - 1;
return twitterItems;
}
private string GenerateTwitterUrl()
{
var url = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}&count={1}", this.SearchTerm, this.ReturnCount);
if (this.maxId != default(long))
{
url = string.Format("{0}&max_id={1}", url, this.maxId);
}
return url;
}
}
}
|
61b3c1105199704aaecd83c2f3e42508db5d03be
|
C#
|
WilliamCopland/optimusprime
|
/YellowstonePathology.OptimusPrime/HPV1618ResultHandler.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace YellowstonePathology.OptimusPrime
{
public class HPV1618ResultHandler
{
public async Task<object> Invoke(object input)
{
var payload = (IDictionary<string, object>)input;
return await HandleResult(payload);
}
public async Task<string> HandleResult(IDictionary<string, object> payload)
{
var connectionString = "Server = 10.1.2.26; Uid = sqldude; Pwd = 123Whatsup; Database = lis;";
string testName = (string)payload["testName"];
string aliquotOrderId = (string)payload["aliquotOrderId"];
string hpv16Result = (string)payload["hpv16Result"];
string hpv18Result = (string)payload["hpv1845Result"];
HPV1618Result hpv1618Result = HPV1618Result.GetResult(hpv16Result, hpv18Result);
string sql = hpv1618Result.GetSqlStatement(aliquotOrderId);
using (var cnx = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand(sql, cnx))
{
await cnx.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
return "Optimus Prime updated result: " + aliquotOrderId + " - " + testName + " on " + DateTime.Now.ToString();
}
}
}
|
955652ccf03d558c1f8772d9a6f3ea30f73396fe
|
C#
|
Azure/China-Data-Solutions
|
/Marketing/CRDAnalytics/src/Common/Pipelines/Models/SentenceSentimentResult.cs
| 2.609375
| 3
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ChinaDataSolution.CrdAnalytics.Common.Pipelines.Models
{
using System;
/// <summary>
/// Defines the sentence sentiment result class.
/// </summary>
[Serializable]
public sealed class SentenceSentimentResult
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SentenceSentimentResult"/> class.
/// </summary>
/// <param name="sentenceIndex">Index of the sentence.</param>
/// <param name="sentence">The sentence.</param>
/// <param name="polarity">The polarity.</param>
/// <param name="sentimentScore">The sentiment score.</param>
public SentenceSentimentResult(int sentenceIndex, string sentence, string polarity, double sentimentScore)
{
this.SentenceIndex = sentenceIndex;
this.Sentence = sentence;
this.Polarity = polarity;
this.SentimentScore = sentimentScore;
}
#endregion
#region Properties
/// <summary>
/// Gets the index of the sentence.
/// </summary>
/// <value>
/// The index of the sentence.
/// </value>
public int SentenceIndex { get; }
/// <summary>
/// Gets the sentence.
/// </summary>
/// <value>
/// The sentence.
/// </value>
public string Sentence { get; }
/// <summary>
/// Gets the polarity.
/// </summary>
/// <value>
/// The polarity.
/// </value>
public string Polarity { get; }
/// <summary>
/// Gets the sentiment score.
/// </summary>
/// <value>
/// The sentiment score.
/// </value>
public double SentimentScore { get; }
#endregion
}
}
|
2439097fc32715c1283bd5f7f36f79b6f730e8d5
|
C#
|
exiton3/AppFactory
|
/Source/Framework.Domain/Specifications/DateGreaterThanOrEqualSpecificationDecorator.cs
| 2.6875
| 3
|
using System;
using System.Data.SqlTypes;
using System.Linq.Expressions;
using System.Reflection;
namespace Framework.Domain.Specifications
{
public class DateGreaterThanOrEqualSpecificationDecorator<T> : SpecificationBase<T> where T : class
{
private readonly string _property;
private readonly DateTime? _value;
private readonly ISpecification<T> _specification;
public DateGreaterThanOrEqualSpecificationDecorator(ISpecification<T> specification, object value, string propertyName)
{
_specification = specification;
_property = propertyName;
_value = (DateTime?)value;
}
public override Expression<Func<T, bool>> GetExpression()
{
ParameterExpression paramExp = Expression.Parameter(typeof(T), "x");
var prop = Expression.Property(paramExp, _property);
var propType = ((PropertyInfo)prop.Member).PropertyType;
MemberExpression memberExp = Expression.Property(paramExp, _property);
Expression gtExpression = null;
if (propType == typeof(DateTime?))
{
var nullCheck = Expression.NotEqual(memberExp, Expression.Constant(null, typeof(object)));
var condition = Expression.GreaterThanOrEqual(Expression.Constant(_value),
Expression.Convert(memberExp, typeof(DateTime)));
gtExpression = Expression.AndAlso(nullCheck, condition);
}
if (propType == typeof(DateTime))
{
gtExpression = Expression.GreaterThanOrEqual(Expression.Constant(_value ?? (DateTime)SqlDateTime.MinValue), memberExp);
}
return gtExpression == null
? _specification.GetExpression()
: Expression.Lambda<Func<T, bool>>(gtExpression, paramExp);
}
}
}
|
64fb81e61399027a9f83f04e3463abbfe83ce595
|
C#
|
Vizivul360/TestTask_3
|
/Assets/Src/Game/Systems/LookSystem.cs
| 2.65625
| 3
|
using UnityEngine;
using Ecs.Systems;
using Ecs;
namespace Game
{
public class LookSystem : Executor
{
private Group stayPlayer, stayBots, allBots, player;
public LookSystem(Context context)
{
var moves = new Moves();
stayPlayer = context.GetGroup(new LookSelect(new PickPlayer(), moves));
stayBots = context.GetGroup(new LookSelect(new PickBot(), moves));
player = context.GetGroup(new PickPlayer());
allBots = context.GetGroup(new PickBot());
}
public void Exec()
{
playerLook();
botsLook();
}
private void playerLook()
{
var p = stayPlayer.First();
if (p != null) setLook(p, nearestBot(p.position));
}
private Entity nearestBot(Vector3 from)
{
float dist = 0;
Entity bot = null;
foreach(var obj in allBots.Select())
{
var d = (from - obj.position).magnitude;
if (d < dist || bot == null)
{
dist = d;
bot = obj;
}
}
return bot;
}
private void botsLook()
{
var p = player.First();
if (p == null) return;
foreach (var obj in stayBots.Select())
setLook(obj, p);
}
private void setLook(Entity obj, Entity to)
{
if (to == null)
{
obj.unsetLook(false);
return;
}
obj.setLook(to.position.value - obj.position);
}
private class LookSelect : Selector
{
private Selector basic, exclude;
public LookSelect(Selector basic, Selector exclude)
{
this.basic = basic;
this.exclude = exclude;
}
public bool check(Entity obj)
{
return basic.check(obj) && exclude.check(obj) == false;
}
}
}
public class PickPlayer : Selector
{
public bool check(Entity obj)
{
return obj.hasIdentity && obj.identity.id == UID.PLAYER;
}
}
public class PickBot : Selector
{
public bool check(Entity obj)
{
return obj.hasIdentity && obj.identity.id != UID.PLAYER;
}
}
}
|
6ce417cbabdaa7b7ee81d693297d97cdfd514c92
|
C#
|
war-man/movie-recommendations
|
/MovieRecommendations/MovieRecommendations/Components/CurrentRabbitHole.cs
| 2.546875
| 3
|
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MovieRecommendations.ViewModels;
using MoviesDataAccessLibrary.Entities;
using MoviesDataAccessLibrary.Repositories;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
namespace MovieRecommendations.Components
{
public class CurrentRabbitHole : ViewComponent
{
private readonly IRepository _repository;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IMapper _mapper;
public CurrentRabbitHole(IRepository repository,
IHttpContextAccessor httpContextAccessor,
IMapper mapper)
{
_repository = repository;
_httpContextAccessor = httpContextAccessor;
_mapper = mapper;
}
public IViewComponentResult Invoke()
{
List<MovieViewModel> currentRabbitHole = new List<MovieViewModel>();
// get the currently connected user email
string userEmail = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value.ToString();
// based on email, get the latest movie the user watched
History latestWatchedHistoryItem = _repository.GetLatestFromHistory(userEmail);
if (latestWatchedHistoryItem == null)
{
return View(currentRabbitHole);
}
Movie latestWatchedMovie = _repository.GetMovieByMovieId(latestWatchedHistoryItem.MovieId);
// map and add the Rabbit Hole entry point - the last movie in the History of the user
MovieViewModel latestWatchedMovieViewModel = _mapper.Map<Movie, MovieViewModel>(latestWatchedMovie);
currentRabbitHole.Add(latestWatchedMovieViewModel);
// while there are next movies, always get the strongest nextMovie for each and add it to the Rabbit Hole
List<NextMovie> nextMovies = _repository.GetNextMoviesForMovieById(latestWatchedMovie.Id);
// based on the latest movie, get the list of nextMovies
int counter = 0;
while (nextMovies.Count() > 0 && counter < 9)
{
Movie tempMovie = _repository.GetMovieByMovieId(nextMovies[0].NextMovieId);
MovieViewModel tempMovieViewModel = _mapper.Map<Movie, MovieViewModel>(tempMovie);
currentRabbitHole.Add(tempMovieViewModel);
nextMovies.Clear();
nextMovies = _repository.GetNextMoviesForMovieById(tempMovie.Id);
counter++;
}
return View(currentRabbitHole);
}
}
}
|
91dfac8ed5e65dda1960b545cd5b032656e5d7df
|
C#
|
brookpatten/MrGibbs
|
/src/MrGibbs.Models/State.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MrGibbs.Models
{
/// <summary>
/// the current state of all sensor data and calculated values
/// TODO: refactor this to allow plugins to add/remove things as needed, it's kind of a
/// god class right now
/// </summary>
public class State
{
//enum Tack : byte { Port = 0, Starboard = 1 }
//enum Leg : byte { Windward = 0, Leeward = 1 }
//provided by system clock or gps
public DateTime SystemTime { get; set; }
//gps provided data
public DateTime? GpsTime { get; set; }
public CoordinatePoint Location { get; set; }
public IDictionary<StateValue, double> StateValues { get; set; }
public static void Run()
{
throw new NotImplementedException();
}
public void Clear()
{
GpsTime = null;
Location = null;
StateValues.Clear ();
}
//race state
public DateTime? StartTime { get; set; }
public ICourse Course { get; set; }
private int? _targetMarkIndex;
private int? _previousMarkIndex;
public bool RaceStarted { get; set; }
public IList<Tack> Tacks { get; set; }
//system state
private List<Message> _messages;
public State()
{
_messages = new List<Message>();
StateValues = new Dictionary<StateValue, double> ();
Course = null;
Tacks = new List<Tack> ();
}
public Message Message
{
get;
private set;
}
public TimeSpan? Countdown
{
get
{
if (StartTime.HasValue)
{
if (StartTime.Value > BestTime)
{
return StartTime.Value - BestTime;
}
else
{
return null;
}
}
else
{
return null;
}
}
}
public Mark TargetMark
{
get
{
if (_targetMarkIndex.HasValue
&& Course!=null
&& Course is CourseByMarks
&& _targetMarkIndex.Value < (Course as CourseByMarks).Marks.Count)
{
return (Course as CourseByMarks).Marks[_targetMarkIndex.Value];
}
else
{
return null;
}
}
set
{
if (value == null)
{
_targetMarkIndex = null;
}
else if (Course !=null && Course is CourseByMarks && (Course as CourseByMarks).Marks.Contains(value))
{
_targetMarkIndex = (Course as CourseByMarks).Marks.IndexOf(value);
}
else
{
throw new InvalidDataException("Unknown mark");
}
}
}
public Mark PreviousMark
{
get
{
if (_previousMarkIndex.HasValue
&& Course != null
&& Course is CourseByMarks
&& _previousMarkIndex.Value < (Course as CourseByMarks).Marks.Count)
{
return (Course as CourseByMarks).Marks[_previousMarkIndex.Value];
}
else
{
return null;
}
}
set
{
if (value == null)
{
_previousMarkIndex = null;
}
else if (Course != null && Course is CourseByMarks && (Course as CourseByMarks).Marks.Contains(value))
{
_previousMarkIndex = (Course as CourseByMarks).Marks.IndexOf(value);
}
else
{
throw new InvalidDataException("Unknown mark");
}
}
}
public DateTime BestTime
{
get
{
if (GpsTime.HasValue)
{
return GpsTime.Value;
}
else
{
return SystemTime;
}
}
}
public void AddMessage(Message message)
{
lock (_messages)
{
message.ShownAt = null;
_messages.Add(message);
}
//if we're not showing anything right now, we can go ahead and show it
if(Message==null)
{
CycleMessages();
}
}
public void AddMessage(MessageCategory category, MessagePriority priority, int secondsDuration, string text)
{
var message = new Message();
message.CreatedAt = BestTime;
message.Text = text;
message.Priority = priority;
message.Duration = new TimeSpan(0,0,0,secondsDuration);
AddMessage(message);
}
public int MessageCount
{
get
{
if(_messages!= null)
{
return _messages.Count;
}
else
{
return 0;
}
}
}
public void CycleMessages()
{
lock (_messages)
{
if (Message == null || Message.HideAt < BestTime)
{
if (_messages.Any())
{
var highest = _messages.OrderBy(x => (int)x.Priority).First();
Message = highest;
Message.ShownAt = BestTime;
_messages.Remove(highest);
}
else
{
Message = null;
}
}
else
{
//Message = null;
}
}
}
}
}
|
94d29236ff4f848c82b6521582831146cb564c36
|
C#
|
kimsk/RegExpose
|
/RegExpose.Tests/CompilerTests/AlternationParsingTests.cs
| 2.5625
| 3
|
using System.Linq;
using NUnit.Framework;
using RegExpose.Nodes.Alternation;
using RegExpose.Nodes.Character;
using RegExpose.Nodes.Parens;
namespace RegExpose.Tests.CompilerTests
{
public class AlternationParsingTests
{
[Test]
public void AnAlternationWithTwoCharacterLiteralChoicesParsesCorrectly()
{
const string pattern = @"a|b";
var sut = new RegexCompiler();
var result = sut.Compile(pattern);
var nodes = result.Children.ToList();
Assert.That(nodes.Count, Is.EqualTo(1));
Assert.That(nodes[0], Is.InstanceOf<Alternation>());
var alternation = (Alternation) nodes[0];
var choices = alternation.Choices.ToList();
Assert.That(choices.Count, Is.EqualTo(2));
Assert.That(choices[0], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[1], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[0].Children.Count, Is.EqualTo(1));
Assert.That(choices[1].Children.Count, Is.EqualTo(1));
Assert.That(choices[0].Children[0], Is.InstanceOf<CharacterLiteral>());
Assert.That(choices[1].Children[0], Is.InstanceOf<CharacterLiteral>());
}
[Test]
public void AnAlternationWithAllCharacterNodesChoicesParsesCorrectly()
{
const string pattern = @"abc|[0-9]|\s|.";
var sut = new RegexCompiler();
var result = sut.Compile(pattern);
var nodes = result.Children.ToList();
Assert.That(nodes.Count, Is.EqualTo(1));
Assert.That(nodes[0], Is.InstanceOf<Alternation>());
var alternation = (Alternation) nodes[0];
var choices = alternation.Choices.ToList();
Assert.That(choices.Count, Is.EqualTo(4));
Assert.That(choices[0], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[1], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[2], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[3], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[0].Children.Count, Is.EqualTo(3));
Assert.That(choices[1].Children.Count, Is.EqualTo(1));
Assert.That(choices[2].Children.Count, Is.EqualTo(1));
Assert.That(choices[3].Children.Count, Is.EqualTo(1));
Assert.That(choices[0].Children[0], Is.InstanceOf<CharacterLiteral>());
Assert.That(choices[0].Children[1], Is.InstanceOf<CharacterLiteral>());
Assert.That(choices[0].Children[2], Is.InstanceOf<CharacterLiteral>());
Assert.That(choices[1].Children[0], Is.InstanceOf<CharacterClass>());
Assert.That(choices[2].Children[0], Is.InstanceOf<CharacterClassShorthand>());
Assert.That(choices[3].Children[0], Is.InstanceOf<Dot>());
}
[Test]
public void CapturedChoices()
{
const string pattern = @"(a)(b)|(c)(d)|(e)(f)";
var sut = new RegexCompiler();
var result = sut.Compile(pattern);
var nodes = result.Children.ToList();
Assert.That(nodes.Count, Is.EqualTo(1));
Assert.That(nodes[0], Is.InstanceOf<Alternation>());
var alternation = (Alternation)nodes[0];
var choices = alternation.Choices.ToList();
Assert.That(choices.Count, Is.EqualTo(3));
Assert.That(choices[0], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[1], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[2], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[0].Children.Count, Is.EqualTo(2));
Assert.That(choices[1].Children.Count, Is.EqualTo(2));
Assert.That(choices[2].Children.Count, Is.EqualTo(2));
Assert.That(choices[0].Children[0], Is.InstanceOf<CapturingParens>());
Assert.That(((CapturingParens)choices[0].Children[0]).Number, Is.EqualTo(1));
Assert.That(choices[0].Children[1], Is.InstanceOf<CapturingParens>());
Assert.That(((CapturingParens)choices[0].Children[1]).Number, Is.EqualTo(2));
Assert.That(choices[1].Children[0], Is.InstanceOf<CapturingParens>());
Assert.That(((CapturingParens)choices[1].Children[0]).Number, Is.EqualTo(3));
Assert.That(choices[1].Children[1], Is.InstanceOf<CapturingParens>());
Assert.That(((CapturingParens)choices[1].Children[1]).Number, Is.EqualTo(4));
Assert.That(choices[2].Children[0], Is.InstanceOf<CapturingParens>());
Assert.That(((CapturingParens)choices[2].Children[0]).Number, Is.EqualTo(5));
Assert.That(choices[2].Children[1], Is.InstanceOf<CapturingParens>());
Assert.That(((CapturingParens)choices[2].Children[1]).Number, Is.EqualTo(6));
}
[Test]
public void CapturedAlternation()
{
const string pattern = @"(a|b)";
var sut = new RegexCompiler();
var result = sut.Compile(pattern);
var nodes = result.Children.ToList();
Assert.That(nodes.Count, Is.EqualTo(1));
Assert.That(nodes[0], Is.InstanceOf<CapturingParens>());
var parens = (CapturingParens)nodes[0];
var parensChildren = parens.Children.ToList();
Assert.That(parensChildren.Count, Is.EqualTo(1));
Assert.That(parensChildren[0], Is.InstanceOf<Alternation>());
var alternation = (Alternation)parensChildren[0];
var choices = alternation.Choices.ToList();
Assert.That(choices.Count, Is.EqualTo(2));
Assert.That(choices[0], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[1], Is.InstanceOf<AlternationChoice>());
Assert.That(choices[0].Children.Count, Is.EqualTo(1));
Assert.That(choices[1].Children.Count, Is.EqualTo(1));
Assert.That(choices[0].Children[0], Is.InstanceOf<CharacterLiteral>());
Assert.That(choices[1].Children[0], Is.InstanceOf<CharacterLiteral>());
}
}
}
|
5d2f184f3a56bf2509523eba59491170581c47bb
|
C#
|
khoanguyen84/C1020K1
|
/APC/Collection/QueueDemo.cs
| 3.03125
| 3
|
using System;
using System.Collections;
namespace Collection
{
class QueueDemo
{
static void Main(string[] args)
{
Queue q = new Queue();
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
while(q.Count > 0){
Console.WriteLine(q.Dequeue());
}
}
}
}
|
7883795e852b640f0dca5f6b31f492c5218247ef
|
C#
|
felixlapierre/CostumeCurse
|
/Assets/Scripts/Combat/TargetSelector.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using UnityEngine;
public enum CombatantType { Enemy, Ally };
public enum SelectorType { Self, All, Number };
public struct TargetSchema
{
public int NumberOfTargets;
public CombatantType CombatantType;
public SelectorType SelectorType;
public TargetSchema(int numberOfTargets, CombatantType combatantType, SelectorType selectorType)
{
NumberOfTargets = numberOfTargets;
CombatantType = combatantType;
SelectorType = selectorType;
}
}
// TODO let's make this virtual: one for allies; one for enemies, cuz they're pretty different
public class TargetSelector : MonoBehaviour
{
public CombatSystem CombatSystem;
private GameObject[] CurrentTargetedCombatants;
private Ability CallingAbility;
private TargetSchema CurrentTargetSchema;
public void Start()
{
CombatSystem = GameObject.FindGameObjectWithTag("CombatSystem").GetComponent<CombatSystem>();
}
public void Target(Ability callingAbility, bool userTargeting = true)
{
CallingAbility = callingAbility;
CurrentTargetSchema = callingAbility.TargetSchema;
if (CurrentTargetSchema.SelectorType == SelectorType.All)
{
if (CurrentTargetSchema.CombatantType == CombatantType.Enemy)
TargetAllEnemies(userTargeting);
else if (CurrentTargetSchema.CombatantType == CombatantType.Ally)
TargetAllAllies(userTargeting);
}
if (CurrentTargetSchema.SelectorType == SelectorType.Number)
{
// TODO do something else, add rest of options
if (CurrentTargetSchema.CombatantType == CombatantType.Enemy)
TargetAllEnemies(userTargeting);
else if (CurrentTargetSchema.CombatantType == CombatantType.Ally)
TargetAllAllies(userTargeting);
}
}
private void TargetSingleEnemy(bool userTargeting = true)
{
// TODO
}
private void TargetAllEnemies(bool userTargeting = true)
{
GameObject[] enemies = CombatSystem.Combatants.
Where(combatant => combatant.CompareTag("Enemy") && combatant.GetComponent<Combatant>().IsAlive).ToArray();
if (userTargeting)
{
// TODO highlight each enemy, wait for user selection
Thread.Sleep(500); // Fake the UI selection
}
CurrentTargetedCombatants = enemies;
ReplyToCallingAbility();
}
private void TargetAllAllies(bool userTargeting = true)
{
GameObject[] allies = CombatSystem.Combatants.
Where(combatant => combatant.CompareTag("Player") && combatant.GetComponent<Combatant>().IsAlive).ToArray();
if (userTargeting)
{
// TODO highlight each enemy, wait for user selection
Thread.Sleep(500); // Fake the UI selection
}
CurrentTargetedCombatants = allies;
ReplyToCallingAbility();
}
private void ReplyToCallingAbility()
{
CallingAbility.SetTargetedCombatants(CurrentTargetedCombatants);
}
}
|
df9b6bf4cf610b2619a5c068fcaadfb4413d3bd7
|
C#
|
aldundur-Mansour/Project04_Auth_CRUD_ASP.NET
|
/Backend/Induction/Induction/Repositories/ChapterChunkRepository.cs
| 2.875
| 3
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Induction.Data;
using Induction.Models;
using Microsoft.EntityFrameworkCore;
namespace Induction.Repositories
{
public class ChapterChunkRepository : IChapterChunkRepository
{
private readonly AppDbContext _context;
public ChapterChunkRepository(AppDbContext context)
{
this._context = context;
}
public async Task<IEnumerable<ChapterChunkModel>> Get()
{
return await _context.ChapterChunks.ToListAsync();
}
public async Task<ChapterChunkModel> Get(int id)
{
return await _context.ChapterChunks.FindAsync(id);
}
public async Task<ChapterChunkModel> Create(ChapterChunkModel ChapterChunk)
{
_context.ChapterChunks.Add(ChapterChunk);
await _context.SaveChangesAsync();
return ChapterChunk;
}
public async Task Update(ChapterChunkModel ChapterChunk)
{
_context.Entry(ChapterChunk).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
public async Task Delete(int id)
{
var ChapterChunkToDelete = await _context.ChapterChunks.FindAsync(id);
_context.ChapterChunks.Remove(ChapterChunkToDelete);
await _context.SaveChangesAsync(); }
}
}
|
69159a3a783f03885cb2bfe83f067b5f2fa0a691
|
C#
|
rcruzeiro/Accounts
|
/Accounts.Services.Entity/ProfileEntityService.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Accounts.Entities;
using Accounts.Repository;
namespace Accounts.Services.Entity
{
public sealed class ProfileEntityService
{
readonly IProfileRepository _repository;
public ProfileEntityService(IProfileRepository repository)
{
_repository = repository;
}
~ProfileEntityService()
{
_repository.Dispose();
}
public List<Profile> GetProfiles(string clientID)
{
try
{
return _repository.Get(p => p.ClientID == clientID)
.ToList();
}
catch (Exception ex)
{ throw ex; }
}
public Profile GetProfile(string clientID, int id)
{
try
{
return _repository.Get(p => p.ClientID == clientID && p.ID == id)
.SingleOrDefault();
}
catch (Exception ex)
{ throw ex; }
}
public async Task Save(Profile profile)
{
try
{
if (profile.ID == default(int))
await _repository.AddAsync(profile);
else
_repository.Update(profile);
await _repository.SaveAsync();
}
catch (Exception ex)
{ throw ex; }
}
public async Task Delete(Profile profile)
{
try
{
_repository.Remove(profile);
await _repository.SaveAsync();
}
catch (Exception ex)
{ throw ex; }
}
public async Task Delete(string clientID, int id)
{
try
{
_repository.Remove(p => p.ClientID == clientID && p.ID == id);
await _repository.SaveAsync();
}
catch (Exception ex)
{ throw ex; }
}
}
}
|
8ee010b5eb39b755181bc4d3d700e4b624b1c3c9
|
C#
|
nickky2010/Epam_Gomel_Training_Task_05-Database
|
/Database/Program.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Configuration;
namespace Database
{
class Program
{
static void Main(string[] args)
{
string connectionString = ConfigurationManager.ConnectionStrings["DictionaryAccess"].ConnectionString;
Dictionary<int, int> dictionaryLenght = new Dictionary<int, int>();
OleDbConnection connection = null;
OleDbCommand command = null;
OleDbDataReader dataReader = null;
try
{
connection = new OleDbConnection(connectionString);
command = connection.CreateCommand();
command.CommandText = "select (int(abs(x2-x1)+0.5)) as len, Count(*) as num from Coordinates group by (int(abs(x2-x1)+0.5)) ORDER BY 1";
//открываем соединение и читаем из таблицы Coordinates в Dictionary
connection.Open();
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
dictionaryLenght.Add((int)dataReader.GetDouble(0), dataReader.GetInt32(1));
}
dataReader.Close();
//удаляем записи в таблице Frequencies
command.CommandText = "delete from Frequencies";
command.ExecuteNonQuery();
//запись коллекции в таблицу Frequencies используя параметры, чтобы избежать внедрения
command.CommandText = "insert into Frequencies (len, num) values (@len, @num)";
command.Parameters.Add("@len", OleDbType.Integer);
command.Parameters.Add("@num", OleDbType.Integer);
foreach (int len in dictionaryLenght.Keys)
{
command.Parameters["@len"].Value = len;
command.Parameters["@num"].Value = dictionaryLenght[len];
command.ExecuteNonQuery();
}
// поиск записей в Frequencies в которых len>num
command.CommandText = "select * from Frequencies where len>num";
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Console.WriteLine("{0};{1}\n", dataReader.GetInt32(1), dataReader.GetInt32(2));
}
dataReader.Close();
connection.Close();
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Application configuration error has occurred.");
}
catch (InvalidCastException)
{
Console.WriteLine("Database contains invalid data type. Conversion of an instance of one type to another type is not supported.");
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
catch (OleDbException ex)
{
string errorMessages = "";
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages += $"Number #{i+1}\n" +
$"Message: {ex.Errors[i].Message}\n" +
$"NativeError: {ex.Errors[i].NativeError}\n" +
$"Source: {ex.Errors[i].Source}\n" +
$"SQLState: {ex.Errors[i].SQLState}\n";
}
Console.WriteLine("Error!!!\n"+errorMessages+ "\nPlease contact your system administrator.");
}
finally
{
if (dataReader != null)
dataReader.Dispose();
if (command != null)
command.Dispose();
if (connection != null)
connection.Dispose();
}
Console.Write("\nFor exit press any key...");
Console.ReadKey();
}
}
}
|
5896d2acba7bd5e096aefd9d484e7144daf4a524
|
C#
|
prince-nto/TenderSystem
|
/TenderSystem/Configurations/CompanyConfiguration.cs
| 2.515625
| 3
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using TenderSystem.Models;
namespace TenderSystem.Configurations
{
public class CompanyConfiguration : IEntityTypeConfiguration<Company>
{
public void Configure(EntityTypeBuilder<Company> builder)
{
builder.ToTable("Companies");
builder.Property(p => p.CompanyId).UseIdentityColumn();
builder.Property(p => p.Name).HasMaxLength(50).IsRequired();
builder.Property(p => p.VatNo).HasMaxLength(50).IsRequired();
builder.Property(p => p.Registration).HasMaxLength(50).IsRequired();
builder.Property(p => p.PhysicalAddress1).HasMaxLength(50).IsRequired();
builder.Property(p => p.PhysicalAddress2).HasMaxLength(50));
builder.Property(p => p.Suburb).HasMaxLength(50).IsRequired();
builder.Property(p => p.Province).HasMaxLength(50);
builder.Property(p => p.PostalCode).HasMaxLength(50).IsRequired();
}
}
}
|
250447d992167d3149d9de481239cc7a3eb244f4
|
C#
|
konstantin1304/Safe
|
/WindowsFormsApp2/Form1.cs
| 2.8125
| 3
|
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 WindowsFormsApp2
{
public partial class MyForm : Form
{
bool enableClosing = false;
MyLock @lock = new MyLock("123456789");
public MyForm()
{
@lock.Unlock += lock_Unlock;
@lock.LockAll += BlockAllButtons;
InitializeComponent();
}
/// <summary>
/// Разблокирование сейфа
/// </summary>
private void lock_Unlock()
{
enableClosing = true;
Close();
}
private void button_Click(object sender, EventArgs e)
{
Button b = sender as Button;
@lock.Check(b.Text[0]);
}
/// <summary>
/// Закрытие формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (enableClosing) return;
e.Cancel = true;
}
/// <summary>
/// Блокировка всех кнопок
/// </summary>
private void BlockAllButtons()
{
foreach (Control control in this.Controls)
{
var but = control as Button;
if (but == null)
continue;
but.Enabled = false;
}
}
}
}
|
37cdef5f0d1653dd9b2d9be0767c5dc969376035
|
C#
|
SVemulapalli/resin
|
/src/Sir.Store/Term.cs
| 2.515625
| 3
|
using Sir.Store;
using System;
namespace Sir
{
/// <summary>
/// A query term.
/// </summary>
public class Term
{
public IComparable Key { get; private set; }
public AnalyzedString TokenizedString { get; private set; }
public ulong KeyHash { get; private set; }
public int Index { get; private set; }
public long? KeyId { get; private set; }
public VectorNode Node { get; private set; }
public Term(IComparable key, AnalyzedString tokenizedString, int index)
{
Key = key;
KeyHash = key.ToHash();
TokenizedString = tokenizedString;
Index = index;
}
public Term(long keyId, AnalyzedString tokenizedString, int index)
{
KeyId = keyId;
TokenizedString = tokenizedString;
Index = index;
}
public Term(IComparable key, VectorNode node)
{
Key = key;
KeyHash = key.ToHash();
Node = node;
}
private string GetDebugString()
{
if (Node != null)
return Node.ToString();
var token = TokenizedString.Tokens[Index];
return TokenizedString.Original.Substring(token.offset, token.length);
}
public override string ToString()
{
return string.Format("{0}:{1}", Key, GetDebugString());
}
}
}
|
8a253b833b0b7c270fff22dc7678dffceebde69f
|
C#
|
atulsagarEngaze/SearchService
|
/CampusPulse.SearchService.Manager/SearchManager.cs
| 2.765625
| 3
|
using CampusPulse.CacheManager;
using CampusPulse.Core.Domain;
using CampusPulse.SearchService.Domain.Model;
using System.Collections.Generic;
namespace CampusPulse.SearchService.Manager
{
public class SearchManager :ISearchManager
{
private readonly ICacheManager<Book> cacheManager;
public SearchManager(ICacheManager<Book> cacheManager)
{
this.cacheManager = cacheManager;
}
public ICollection<Book> GetBooks(BookFilter bookFilter)
{
return cacheManager.get(bookFilter.Acedamics);
}
public void SaveBook()
{
List<Book> books = new List<Book>();
Book book = new Book()
{
Acedamics = "A1",
Author = "auth1",
Description = "desc",
Year = 1990
};
Book book1 = new Book()
{
Acedamics = "A1",
Author = "auth1",
Description = "desc",
Year = 1990
};
books.Add(book);
books.Add(book1);
cacheManager.save(books as IReadOnlyCollection<Book>);
}
}
}
|
5d98d937a085651c95e9d4e80754b39445b74b31
|
C#
|
GinoCubeddu/NanoEngine
|
/NanoEngine/Collision/Manager/ICollisionManager.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NanoEngine.ObjectTypes.Assets;
namespace NanoEngine.Collision.Manager
{
public interface ICollisionManager
{
/// <summary>
/// Checks to see if there is a collsion between an asset and a list
/// of assets
/// </summary>
/// <param name="asset">A tuple of an asset and its mind</param>
/// <param name="possibleCollisions">A list containingt tuples of assets and their minds</param>
void CheckCollision(
Tuple<IAsset, IAiComponent> asset,
IList<Tuple<IAsset, IAiComponent>> possibleCollisions
);
/// <summary>
/// Updates the collision manager against the passed in objects
/// </summary>
/// <param name="assets">All assets that are on scene</param>
/// <param name="aiComponents">All AiComponents that belong to the assets</param>
void Update(IDictionary<string, IAsset> assets, IDictionary<string, IAiComponent> aiComponents);
}
}
|
e56c04026548a832b1ec46be64401a7fe9ab325b
|
C#
|
romuloalvesbm/projetoapiddd
|
/ProjetoDDD/Projeto.Domain/Aggregates/Usuarios/Services/PerfilDomainService.cs
| 2.59375
| 3
|
using Projeto.Domain.Aggregates.Usuarios.Contracts.Repositories;
using Projeto.Domain.Aggregates.Usuarios.Contracts.Services;
using Projeto.Domain.Aggregates.Usuarios.Exceptions;
using Projeto.Domain.Aggregates.Usuarios.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Projeto.Domain.Aggregates.Usuarios.Services
{
public class PerfilDomainService : IPerfilDomainService
{
//atributo
private readonly IPerfilRepository perfilRepository;
//construtor para injeção de dependência
public PerfilDomainService(IPerfilRepository perfilRepository)
{
this.perfilRepository = perfilRepository;
}
public void Create(Perfil obj)
{
//verificando se ja existe um perfil cadastrado com o nome informado
if (perfilRepository.Count(p => p.Nome.Equals(obj.Nome)) > 0)
throw new PerfilUnicoException();
//cadastrar o perfil
perfilRepository.Create(obj);
}
public void Update(Perfil obj)
{
perfilRepository.Update(obj);
}
public void Delete(Perfil obj)
{
perfilRepository.Delete(obj);
}
public List<Perfil> GetAll()
{
return perfilRepository.GetAll();
}
public Perfil GetById(Guid id)
{
return perfilRepository.GetById(id);
}
}
}
|
5c007f5c6ceda278dce3e5cf15773785febd2709
|
C#
|
Ljubo6/SoftUni-1
|
/CSharp-Advanced/05-FUNCTIONAL-PROGRAMMING_Exercise/P11.PRFM/PFRM.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace P11.PRFM
{
class PFRM
{
static void Main(string[] args)
{
Predicate<string> predicate;
var invitedGuests = Console.ReadLine().Split().ToList();
var filters = new Dictionary<string, List<string>>();
string[] input = Console.ReadLine().Split(';');
while (input[0] != "Print")
{
string filter = input[1];
string criteria = input[2];
if (input[0] == "Add filter")
{
if (!filters.ContainsKey(filter))
{
filters.Add(filter, new List<string> { criteria });
}
else
{
if (!filters[filter].Contains(criteria))
{
filters[filter].Add(criteria);
}
}
}
else if (input[0] == "Remove filter")
{
if (filters.ContainsKey(filter))
{
filters[filter].RemoveAll(x => x == criteria);
}
}
input = Console.ReadLine().Split(';');
}
foreach (var filter in filters)
{
foreach (var criteria in filter.Value)
{
predicate = GetPredicate(filter, criteria);
invitedGuests.RemoveAll(predicate);
}
}
Console.WriteLine(string.Join(' ', invitedGuests));
}
private static Predicate<string> GetPredicate(KeyValuePair<string, List<string>> filter, string criteria)
{
if (filter.Key == "Starts with")
{
return name => name.StartsWith(criteria);
}
else if (filter.Key == "Ends with")
{
return name => name.EndsWith(criteria);
}
else if (filter.Key == "Length")
{
return name => name.Length == int.Parse(criteria);
}
else if (filter.Key == "Contains")
{
return name => name.Contains(criteria);
}
return null;
}
}
}
|
b9621c3a6c291712e3734c02f1d834b437e001c6
|
C#
|
OctopusDeploy/Nevermore
|
/source/Nevermore/Mapping/DocumentMapRegistry.cs
| 2.625
| 3
|
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Nevermore.Mapping
{
public class DocumentMapRegistry : IDocumentMapRegistry
{
readonly IPrimaryKeyHandlerRegistry primaryKeyHandlerRegistry;
readonly ConcurrentDictionary<Type, DocumentMap> mappings = new ConcurrentDictionary<Type, DocumentMap>();
readonly ConcurrentDictionary<string, List<string>> mappingColumnNamesSortedWithJsonLastCache = new();
public DocumentMapRegistry(IPrimaryKeyHandlerRegistry primaryKeyHandlerRegistry)
{
this.primaryKeyHandlerRegistry = primaryKeyHandlerRegistry;
}
public List<DocumentMap> GetAll()
{
return new List<DocumentMap>(mappings.Values);
}
public void Register(DocumentMap map)
{
map.Validate();
mappings[map.Type] = map;
}
public void Register(IDocumentMap map)
{
Register(new List<IDocumentMap> { map });
}
public void Register(params IDocumentMap[] mappingsToAdd)
{
Register(mappingsToAdd.AsEnumerable());
}
public void Register(IEnumerable<IDocumentMap> mappingsToAdd)
{
foreach (var mapping in mappingsToAdd)
{
Register(mapping.Build(primaryKeyHandlerRegistry));
}
}
public bool ResolveOptional(Type type, out DocumentMap map)
{
var maps = new List<DocumentMap>();
// Walk up the inheritance chain and make sure there's only one map for the document.
var currentType = type;
while (true)
{
if (mappings.TryGetValue(currentType, out var m))
{
maps.Add(m);
}
currentType = currentType.GetTypeInfo().BaseType;
if (currentType == typeof(object) || currentType == null)
break;
}
if (maps.Count > 1)
throw new InvalidOperationException($"More than one document map is registered against the type '{type.FullName}'. The following maps could apply: " + string.Join(", ", maps.Select(m => m.GetType().FullName)));
map = maps.SingleOrDefault();
return map != null;
}
public DocumentMap Resolve<TDocument>()
{
return Resolve(typeof(TDocument));
}
public DocumentMap Resolve(object instance)
{
var mapping = Resolve(instance.GetType());
return mapping;
}
public DocumentMap Resolve(Type type)
{
if (!ResolveOptional(type, out var mapping))
{
throw NotRegistered(type);
}
return mapping;
}
public object? GetId(object instance)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
var type = instance.GetType();
if (!ResolveOptional(type, out var map))
throw NotRegistered(type);
return map.GetId(instance);
}
static Exception NotRegistered(Type type)
{
return new InvalidOperationException($"To be used for this operation, the class '{type.FullName}' must have a document map that is registered with this relational store. Types without a document map cannot be used for this operation.");
}
}
}
|
c2caf9ef7ee2f04f0d9a5ea4470195d8982d5d77
|
C#
|
bubdm/System.Extensions
|
/Samples/BasicSample/JsonWriterSample.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Buffers;
using System.Runtime.Serialization;
using System.Linq.Expressions;
using System.Collections;
namespace BasicSample
{
public class JsonWriterSample
{
public static void Run()
{
JsonWriter.Register<long>((value, writer) =>
{
writer.WriteString(value.ToString());
});
//OR
//JsonWriter.Register(typeof(long), (value, writer) => {
// var writeString = typeof(JsonWriter).GetMethod("WriteString", new[] { typeof(string) });
// var toString = typeof(long).GetMethod("ToString", Type.EmptyTypes);
// return Expression.Call(writer, writeString, Expression.Call(value, toString));
//});
//OR
//JsonWriter.Register((type, value, writer) =>
//{
// if (type != typeof(long))
// return null;
// var writeString = typeof(JsonWriter).GetMethod("WriteString", new[] { typeof(string) });
// var toString = typeof(long).GetMethod("ToString", Type.EmptyTypes);
// return Expression.Call(writer, writeString, Expression.Call(value, toString));
//});
//=>String
Console.WriteLine(JsonWriter.ToJson<int>(int.MaxValue));
Console.WriteLine(JsonWriter.ToJson<bool>(true));
Console.WriteLine(JsonWriter.ToJson<string>("ZhangHe"));
Console.WriteLine(JsonWriter.ToJson<long>(long.MaxValue));
Console.WriteLine(JsonWriter.ToJson(typeof(int), int.MaxValue));
Console.WriteLine(JsonWriter.ToJson(typeof(bool), true));
Console.WriteLine(JsonWriter.ToJson(typeof(string), "ZhangHe"));
Console.WriteLine(JsonWriter.ToJson(typeof(long), long.MaxValue));
Console.WriteLine(JsonWriter.ToJson<object>(int.MaxValue));
Console.WriteLine(JsonWriter.ToJson<object>(true));
Console.WriteLine(JsonWriter.ToJson<object>("ZhangHe"));
Console.WriteLine(JsonWriter.ToJson<object>(long.MaxValue));
//JsonWriter.RegisterProperty((property) => StringExtensions.ToSnakeCase(property.Name));
JsonWriter.RegisterProperty<Guid>((format) => format == "My", (value, writer) => {
writer.WriteString(value.ToString("N"));
});
var c1 = new TestClass1()
{
String = "ZhangHe{}[]\r\n",
Int = int.MaxValue,
Bool = true,
Double = double.NaN,
Long = long.MinValue,
DateTime=DateTime.Now,
Guid=Guid.NewGuid(),
ExtensionData = new Dictionary<string, object>()
{
{ "E1" ,long.MaxValue},
{ "E2",double.PositiveInfinity}
}
};
JsonWriter.Register(typeof(TestClass1), Expression.Parameter(typeof(TestClass1), "value"), Expression.Parameter(typeof(JsonWriter), "writer"), out var expression, out _);
Console.WriteLine(expression);//Use Lib To See Code
Console.WriteLine(JsonWriter.ToJson<TestClass1>(c1));
Console.WriteLine(JsonWriter.ToJson<List<TestClass1>>(new List<TestClass1>() { c1 ,c1}));
Console.WriteLine(JsonWriter.ToJsonIndent<TestClass1>(c1));
Console.WriteLine(JsonWriter.ToJsonIndent<List<TestClass1>>(new List<TestClass1>() { c1 ,c1}));
var s1 = Buffer<char>.Create(1);
JsonWriter.ToJson<TestClass1>(c1, s1);//BufferWriter<char>
Console.WriteLine(s1);
var t1 = new StringWriter();//new StreamWriter(new FileStream())
JsonWriter.ToJson<TestClass1>(c1, t1);//TextWriter
Console.WriteLine(t1);
//var t2 = new StringWriter();
//var writer1 = JsonWriter.Create(s1);
//var writer1 = JsonWriter.CreateIndent(s1, "\t", Environment.NewLine);
var s2 = Buffer<char>.Create(1);
var writer1 = JsonWriter.Create(s2);
//var writer1 = JsonWriter.CreateIndent(s2, "\t", Environment.NewLine);
writer1.WriteStartArray();
writer1.WriteNull();
writer1.WriteBoolean(true);
writer1.WriteString("ABCDEF");
writer1.WriteNumber(int.MaxValue);
writer1.WriteNumber(decimal.MaxValue);
writer1.WriteStartObject();
writer1.WriteProperty("Name");
writer1.WriteString("ZhangHe".AsSpan());
writer1.WriteProperty("Double");
writer1.WriteNumber(1.22);
writer1.WriteEndObject();
writer1.WriteEndArray();
Console.WriteLine(s2.ToString());
//------------------------------------------------------------------------
Console.WriteLine(JsonWriter.ToJsonIndent(new TestClass2() {
Code=0,
Message="ok",
Data=new[] {"A","B","C" },
ExtensionData=new PageData()
{
PageSize=10,
PagetNumber=1,
Records=100
}
}));
}
public class TestClass1
{
[DataMember(Name ="String1")]
public string String { get; set; }
public int Int { get; set; }
public bool Bool { get; set; }
public double Double { get; set; }
[DataMember(Order = 100)]//bigger forward (default 0)
public long Long { get; set; }
public long? NullLong { get; set; }
[DataFormat("yyyy-MM-dd HH:mm:ss")]
public DateTime DateTime { get; set; }
[DataFormat("My")]
public Guid Guid { get; set; }
[DataMember(EmitDefaultValue = false)]
public object NullObject { get; set; }
//如果是普通属性加上[DataMember]
//If it is a normal property add [DataMember]
//能遍历KeyValuePair<TKey, TValue>的类型都是支持的
//Type that can Foreach KeyValuePair<TKey, TValue> is supported
public Dictionary<string, object> ExtensionData { get; set; }
}
public class TestClass2
{
public int Code { get; set; }
public string Message { get; set; }
public object Data { get; set; }
public PageData ExtensionData { get; set; }
}
public class PageData//Or :IEnumerable<KeyValuePair<>>
{
public int Records { get; set; }
public int PageSize { get; set; }
public int PagetNumber { get; set; }
public Enumerator GetEnumerator() => new Enumerator(this);
public struct Enumerator
{
public Enumerator(PageData pageData)
{
_pageData = pageData;
_state = 0;
_current = default;
}
private PageData _pageData;
private int _state;
private KeyValuePair<string, int> _current;
public KeyValuePair<string, int> Current => _current;
public bool MoveNext()
{
switch (_state)
{
case 0:
_current = new KeyValuePair<string, int>("Records", _pageData.Records);
break;
case 1:
_current = new KeyValuePair<string, int>("PageSize", _pageData.PageSize);
break;
case 2:
_current = new KeyValuePair<string, int>("PagetNumber", _pageData.PagetNumber);
break;
default:
return false;
}
_state += 1;
return true;
}
}
}
}
}
|
7e78e4055e7ee4a78a472b225a454baf47ee8b75
|
C#
|
lulzzz/3DpointCloud
|
/Framework/Rendering/Renderables/BezierPathRenderer.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Magic.Common.Path;
using System.Drawing;
using Magic.Common;
using Magic.Common.Splines;
namespace Magic.Rendering.Renderables
{
public class BezierPathRenderer : IRender
{
IPath currentPath;
public BezierPathRenderer()
{
}
public void SetPath(IPath p)
{
currentPath = p;
}
#region IRender Members
public string GetName()
{
throw new NotImplementedException();
}
public void Draw(Renderer r)
{
if (currentPath == null) return;
CubicBezier bezier;
foreach (IPathSegment seg in currentPath)
{
if (!(seg is BezierPathSegment)) return;
bezier = ((BezierPathSegment) seg).Bezier;
GLUtility.DrawCircle(new GLPen(Color.Green, 1.0f), seg.Start.ToPointF(), 0.25f);
GLUtility.DrawCircle(new GLPen(Color.Green, 1.0f), seg.End.ToPointF(), 0.25f);
GLUtility.DrawBezier(new GLPen(Color.Green, 1.0f), bezier.P0, bezier.P1, bezier.P2, bezier.P3);
}
}
public void ClearBuffer()
{
}
public bool VehicleRelative
{
get { return false; }
}
public int? VehicleRelativeID
{
get { return null; }
}
#endregion
}
}
|
a633ad3fe6d7eec647e1bb1158593f30b6b13959
|
C#
|
sedc-codecademy/skwd8-06-csharpadv
|
/g1/Class04/Adv.Class02/Adv.Class02.Structs/Program.cs
| 3.90625
| 4
|
using System;
namespace Adv.Class03.Structs
{
// For most of our entities that might:
// Use inheritance to create a business logic tree ( Inheritance )
// Use overriding to use a method in different scenarios ( polymorphism )
// That it has more responsibilities than just storing data
// Have members that are a refference type ( object )
// We would always use a Class
public class User
{
public string Username { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
// Since we created this constructor and we don't have a default one, we can't create User without paramteres
public User(string username, int age, Address address)
{
Username = username;
Age = age;
Address = address;
}
public string GetInfo()
{
return $"{Username} ({Age})";
}
}
// A struct can be used:
// When the only reason we need the entity is to store some data
// When we want to pass the data by value instead of by reference
// When we know that we will never use the entity as a business logic tree ( Inheritance )
// When all members are a value type ( int, string, bool etc. )
public struct Address
{
public string Street { get; set; }
public int Number { get; set; }
// We can create a constructor in a struct
// We can't create an empty ( default ) constructor, we must provide all the members
// Unlike the classes, even tho we don't have a default constructor Address struct can still be created without parameters
public Address(string street, int number)
{
Street = street;
Number = number;
}
public string GetFullAddress()
{
return $"{Street} No. {Number}";
}
}
class Program
{
static void Main(string[] args)
{
Address address = new Address("Bob Street", 11);
// Address address = new Address() { Street = "Bob Street", Number = 11 }; // This also works
User bob = new User("BobBest", 21, address);
// User bob = new User() { Username = "BobBest", Age = 21, Address = address }; // This does not work
Console.WriteLine(bob.GetInfo());
Console.WriteLine(address.GetFullAddress());
Address newAddress = address;
newAddress.Number = 50;
newAddress.Street = "New Street";
User bobTwin = bob;
bobTwin.Username = "BobSuper";
bobTwin.Age = 45;
Console.WriteLine("----------after changes-----------");
Console.WriteLine(bob.GetInfo());
Console.WriteLine(address.GetFullAddress());
Console.ReadLine();
}
}
}
|
1a0548c6be1c267956d68d2dff4b81cb116f6d32
|
C#
|
bodyquest/SoftwareUniversity-Bulgaria
|
/Entity Framework Core Oct2019/4.EF Code First/P01_HospitalDatabase/Data/HospitalContext.cs
| 2.625
| 3
|
namespace P01_HospitalDatabase.Data
{
using Microsoft.EntityFrameworkCore;
using P01_HospitalDatabase.Data.Models;
public class HospitalContext : DbContext
{
public HospitalContext()
{
}
public HospitalContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Patient> Patients { get; set; }
public DbSet<Visitation> Visitations { get; set; }
public DbSet<Diagnose> Diagnoses { get; set; }
public DbSet<Medicament> Medicaments { get; set; }
public DbSet<PatientMedicament> PatientsMedicaments { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(DataSettings.DefaultConection);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
this.OnModelCreatingDoctor(modelBuilder);
this.OnModelCreatingDoctor(modelBuilder);
this.OnModelCreatingDiagnose(modelBuilder);
this.OnModelCreatingVisitation(modelBuilder);
this.OnModelCreatingMedicament(modelBuilder);
this.OnModelCreatingPatientMedicament(modelBuilder);
}
private void OnModelCreatingDoctor(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Doctor>(entity =>
{
entity.HasKey(d => d.DoctorId);
entity
.HasMany(d => d.Visitations)
.WithOne(v => v.Doctor);
entity
.Property(d => d.Name)
.HasMaxLength(100)
.IsRequired(true)
.IsUnicode(true);
entity
.Property(d => d.Specialty)
.HasMaxLength(100)
.IsRequired(true)
.IsUnicode(true);
});
}
private void OnModelCreatingDiagnose(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Diagnose>(entity =>
{
entity.HasKey(d => d.DiagnoseId);
entity
.Property(d => d.Name)
.HasMaxLength(50)
.IsRequired(true)
.IsUnicode(true);
entity
.Property(d => d.Comments)
.HasMaxLength(250)
.IsUnicode(true)
.IsRequired(true);
entity
.HasOne(p => p.Patient)
.WithMany(d => d.Diagnoses)
.HasForeignKey(k => k.PatientId);
});
}
private void OnModelCreatingVisitation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Visitation>(entity =>
{
entity.HasKey(v => v.VisitationId);
entity
.Property(v => v.Comments)
.HasMaxLength(250)
.IsUnicode(true);
entity
.HasOne(p => p.Patient)
.WithMany(v => v.Visitations)
.HasForeignKey(k => k.PatientId);
});
}
private void OnModelCreatingMedicament(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Medicament>(entity =>
{
entity.HasKey(m => m.MedicamentId);
entity
.Property(m => m.Name)
.HasMaxLength(50)
.IsRequired(true)
.IsUnicode(true);
entity
.HasMany(p => p.Prescriptions)
.WithOne(m => m.Medicament)
.HasForeignKey(k => k.MedicamentId);
});
}
private void OnModelCreatingPatientMedicament(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PatientMedicament>(entity =>
{
entity.HasKey(pm => new { pm.PatientId, pm.MedicamentId });
entity
.HasOne(pm => pm.Patient)
.WithMany(p => p.Prescriptions)
.HasForeignKey(pm => pm.PatientId);
entity
.HasOne(pm => pm.Medicament)
.WithMany(m => m.Prescriptions)
.HasForeignKey(pm => pm.MedicamentId);
});
}
}
}
|
cb5f586df9460c8264a6aa38e8453662b9edb884
|
C#
|
kabessao/Atividade_11_10
|
/SemNomeAinda/MainWindow.xaml.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SemNomeAinda
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region construtor
public MainWindow()
{
InitializeComponent();
}
#endregion
private void Somar(object sender, RoutedEventArgs e)
{
double numero1 = double.Parse(txtPrimeiro.Text), numero2 = double.Parse(txtSegundo.Text), resultado = numero1 + numero2;
lblResultado.Text = $"{resultado}";
}
#region botão de limpar
bool teste1 = false, teste2 = false;
private void Teste1(object sender, TextChangedEventArgs e)
{
double t;
teste1 = double.TryParse((sender as TextBox).Text, out t);
Testar();
}
private void Teste2(object sender, TextChangedEventArgs e)
{
double t;
teste2 = double.TryParse((sender as TextBox).Text, out t);
Testar();
}
private void Testar()
{
btnSomar.IsEnabled = (teste1 && teste2);
}
#endregion
}
}
|
1b17bf4ddf9a63cdfc38347831a4018524bf0d18
|
C#
|
JamieFletcher92/Year2BiometricSystem
|
/Temperature_Chart_Display/Temperature Chart/FormRecords.cs
| 2.96875
| 3
|
//---NAMESPACES---
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace Temperature_Chart
{
public partial class FormRecords : Form
{
public FormRecords()
{
InitializeComponent();
}
//---VARIABLES FOR USE WITHIN THIS FORM---
string PatientID, Surname, Forename, Age, Temperature, GSR, Pulse, dateTime, idInput;
int counter = 0, arrayCounter = 0, clickCount = 0;
//---DECLARING STRING ARRAYS THAT WILL BE NEEDED TO STORE DATA WITHIN THIS FORM---
string[,] Records = new string[50000, 8];
string[,] foundRecords = new string[50000, 8];
//---DECLARING A STRING LIST USED TO HOLD THE ID NUMBERS OF CLIENTS FOUND LATER ON---
List<string> idList = new List<string>();
//---NEW XMLDOCUMENT INSTANCE, USED TO LOAD THE XML DOCUMENT INTO THE PROGRAM LATER ON---
XmlDocument addDoc = new XmlDocument();
//---METHOD EXECUTED WHEN THE FORM LOADS---
private void FormRecords_Load(object sender, EventArgs e)
{
//---THE RECORDS XML FILE IS LOADED INTO THE PROGRAM---
addDoc.Load("Records.xml");
//---MOVING INSIDE OF THE ROOT NODES OF THE FILE---
XmlNodeList nodeList = addDoc.SelectNodes("/records/Patient");
//---FOR EACH NODE WITHIN THE ROOT NODES, EXECUTE THE FOLLOWING CODE---
foreach (XmlNode xmlNode in nodeList)
{
//---ASSIGNING THE VALUE WITHIN THE "DATETIME" TAGS TO THE ARRAY WITHIN COLLUMN 0---
dateTime = xmlNode["DateTime"].InnerText;
Records[counter, 0] = dateTime;
//---ASSIGNING THE VALUE WITHIN THE "ID" TAG TO THE 1ST COLLUMN OF THE ARRAY---
PatientID = xmlNode["ID"].InnerText;
Records[counter, 1] = PatientID;
//---STORING THE "FORENAME" VALUE TO THE 2ND COLLUMN IN THE ARRAY---
Forename = xmlNode["Forename"].InnerText;
Records[counter, 2] = Forename;
//---ASSIGNING THE VALUE OF THE "SURNAME" TAG TO COLLUMN 3 IN THE ARRAY---
Surname = xmlNode["Surname"].InnerText;
Records[counter, 3] = Surname;
//---STORING THE VALUE WITHIN THE "AGE" TAG TO COLLUMN 4 OF THE ARRAY "RECORDS"---
Age = xmlNode["Age"].InnerText;
Records[counter, 4] = Age;
//---STORING THE "TEMPERATURE" TAGS VALUE TO COLLUMN 5 OF THE ARRAY---
Temperature = xmlNode["Temperature"].InnerText;
Records[counter, 5] = Temperature;
//---ASSIGNING THE VALUE WITHIN THE "PULSE" TAGS TO COLLUMN 6 OF THE ARRAY---
Pulse = xmlNode["Pulse"].InnerText;
Records[counter, 6] = Pulse;
//---STORING THE VALUE FOUND WITHIN THE "GSR" TAGS TO COLLUMN 7 OF THE ARRAY---
GSR = xmlNode["GSR"].InnerText;
Records[counter, 7] = GSR;
//---ADDING 1 TO THE VALUE OF COUNTER, THIS MEANS THAT THE CODE WITHIN THIS TAG WILL BE EXECUTED AGAIN, BUT THE NEW DATA WILL BE STORED IN THE NEXT ROW OF ARRAY---
counter = counter + 1;
}
//---ASSIGNING VARIABLE "I" WITH VALUE OF 0, EXECUTING FOLLOWING CODE, AND ADDING 1 TO "I" UNTILL IT REACHES THE VALUE OF COUNTER---
for (int i = 0; i < counter; i++)
{
//---ADDING THE VALUE IN COLLUMN 1 OF THE ARRAY TO THE LIST "IDLIST", SO ALL CLIENT ID'S ARE STORED IN THIS LIST---
idList.Add(Records[i, 1]);
}
}
//---METHOD EXECUTED WHENEVER THE USER CLICKS THE "VIEW" BUTTON---
private void btnView_Click(object sender, EventArgs e)
{
//---MOVING INSIDE OF THE ROOT NODES OF THE FILE AGAIN---
XmlNodeList nodeList = addDoc.SelectNodes("/records/Patient");
//---ASSIGNING THE USER INPUT ID TO THE VARIABLE "IDINPUT"---
idInput = txtID.Text;
//---ENABLING BOTH "NEXT" AND "PREVIOUS" BUTTONS---
btnNext.Enabled = true;
btnPrevious.Enabled = true;
//---NEW VARIABLE "T" WITH VALUE OF 0, USED LATER ON---
int t = 0;
//---IF THE USER INPUT ID IS WITHIN THE LIST CONTAINING ALL THE CLIENT IDS RECORDED, EXECUTE THE FOLLOWING CODE---
if (idList.Contains(idInput))
{
//---EXECUTE THIS CODE AND ADD 1 TO "I", WHILE "I" IS LESS THAN THE VALUE OF "COUNTER"---
for (int i = 0; i < counter; i++)
{
//---THE VALUE IN COLLUMN 1 OF THE ARRAY IS ASSIGNED TO "IDRECORDS"---
string idRecords = Records[i, 1];
//---IF THE VALUE OF "IDRECORDS" JUST ASSIGNED, MATCHES THE USER INPUT VALUE, DO THE FOLLOWING---
if (idRecords == idInput)
{
//---STORING ALL FOUND DATA FOR THIS CLIENT WITHIN THE "FOUNDRECORDS" ARRAY, TO BE DEALED WITH AND DISPLAYED TO THE USER LATER---
foundRecords[t, 0] = Records[i, 0];
foundRecords[t, 1] = Records[i, 1];
foundRecords[t, 2] = Records[i, 2];
foundRecords[t, 3] = Records[i, 3];
foundRecords[t, 4] = Records[i, 4];
foundRecords[t, 5] = Records[i, 5];
foundRecords[t, 6] = Records[i, 6];
foundRecords[t, 7] = Records[i, 7];
//---ADDING 1 TO THE VALUE OF "T" SO THAT THIS CODE WILL MOVE THROUGH THE ARRAY STORING ALL THE DATA FOR THE GIVEN CLIENT ID WITHIN THE ARRAY---
t = t + 1;
}
}
//---LET THE USER KNOW THAT THE RECORDS HAVE BEEN FOUND FOR THIS CLIENT---
MessageBox.Show("Records have been found for client " + idInput);
}
//---IF THE USER INPUT CLIENT ID HAS NO RECORDED DATA FOR IT, LET THE USER KNOW AND ASK THEM TO TRY AGAIN WITH A NEW ID---
else
{
MessageBox.Show("No readings were found for that client, please try again!");
}
}
//---METHOD EXECUTED WHEN THE USER CLICKS THE "NEXT" BUTTON", THIS CODE SHOULD DISPLAY THE NEXT AVAILABLE DATA FOR THE GIVEN CLIENT---
private void btnNext_Click(object sender, EventArgs e)
{
//---ADDING 1 TO THE VALUE OF CLICKCOUNT, USED TO SEARCH THE INDEX OF THE ARRAY---
clickCount = clickCount + 1;
//---ASSIGNING THE CERTAIN VALUES OF THE ARRAY TO VARIABLES, THIS IS USED TO CHECK IF THERE ARE ANY MORE RECORDS FOR THE GIVEN CLIENT ID---
string searchedID = foundRecords[clickCount, 1];
string nextID = foundRecords[clickCount + 1, 1];
//---ASSIGNING THE USER INPUT ID TO THE VARIABLE "IDTOMATCH"---
string idToMatch = txtID.Text;
//---IF THE ID WITHIN THE ARRAY MATCHES THE ID THE USER HAS INPUT, THEN DO THE FOLLOWING---
if (searchedID == idToMatch)
{
//---ASSIGNING ALL THE FOUND RECORDS AND DATA FOR THE GIVEN CLIENT ID TO THE LABELS, SO THAT THEY ARE DISPLAYED TO THE USER---
lblDate.Text = foundRecords[clickCount, 0];
lblID.Text = foundRecords[clickCount, 1];
lblForename.Text = foundRecords[clickCount, 2];
lblSurname.Text = foundRecords[clickCount, 3];
lblAge.Text = foundRecords[clickCount, 4];
lblTemp.Text = foundRecords[clickCount, 5];
lblPulse.Text = foundRecords[clickCount, 6];
lblGSR.Text = foundRecords[clickCount, 7];
}
//---IF THE NEXT ID IN THE ARRAY DOESN'T MATCH THE ID THE USER INPUT, DISABLE THE "NEXT" BUTTON AS THERE ARE NO MORE RECORDS TO VIEW---
if (nextID != idToMatch)
{
btnNext.Enabled = false;
}
//---HOWEVER IS THERE ARE MORE RECORDS TO VEIW, KEEP THE "NEXT" BUTTON ENABLED---
else if (nextID == idToMatch)
{
btnNext.Enabled = true;
}
//---IF THE VALUE OF "CLICKCOUNT" IS 0, DISABLE THE "PREVIOUS" BUTTON---
if (clickCount == 0)
{
btnPrevious.Enabled = false;
}
//---HOWEVER, IF THE VALUE OF "CLICKCOUNT IS NOT 0, ENABLE THE "PREVIOUS" BUTTON---
else
{
btnPrevious.Enabled = true;
}
}
//---THIS CODE IS EXECUTED WHEN THE USER CLICKS THE "PREVIOUS" BUTTON---
private void btnPrevious_Click(object sender, EventArgs e)
{
//---DECREASE THE VALUE OF "CLICKCOUNT" BY 1 AND ASSIGN THIS NEW VALUE TO "CLICKCOUNTDOWN"---
int clickCountDown = clickCount - 1;
//---ASSIGN THE VALUE FOUND IN THE 1ST COLLUMN OF THE ARRAY TO "SEARCHEDID"---
string searchedID = foundRecords[clickCountDown, 1];
//---ASSIGN THE VALUE OF THE USER INPUT TEXTBOX TO "IDTOMATCH"---
string idToMatch = txtID.Text;
//---ASSIGN THE VALUE OF THE NEXT ID IN THE ARRAY TO "NEXTID"---
string nextID = foundRecords[clickCount + 1, 1];
//---IF THE ID FOUND IN THE ARRAY MATCHES THE ID THAT THE USER HAS INPUT, THE EXECUTE THIS CODE---
if (searchedID == idToMatch)
{
//---DISPLAYING THE FOUND RECORDS FOR THE USER SEARCHED ID TO THE USER VIA THE LABELS WITHIN THE FORM---
lblDate.Text = foundRecords[clickCountDown, 0];
lblID.Text = foundRecords[clickCountDown, 1];
lblForename.Text = foundRecords[clickCountDown, 2];
lblSurname.Text = foundRecords[clickCountDown, 3];
lblAge.Text = foundRecords[clickCountDown, 4];
lblTemp.Text = foundRecords[clickCountDown, 5];
lblPulse.Text = foundRecords[clickCountDown, 6];
lblGSR.Text = foundRecords[clickCountDown, 7];
}
//--DECREASING THE VALUE OF CLICKCOUNT BY 1---
clickCount = clickCount - 1;
//---IF CLICKCOUNT IS 0, DISABLE THE "PREVIOUS" BUTTON---
if (clickCount == 0)
{
btnPrevious.Enabled = false;
}
//---OTHERWISE KEEP THIS BUTTON ENABLED---
else
{
btnPrevious.Enabled = true;
}
//---IF THE NEXT ID WITHINT HE ARRAY DOESN'T MATCH THE ID THE USER HAS INPUT, THEN DISABLE THE "NEXT" BUTTON---
if (nextID != idToMatch)
{
btnNext.Enabled = false;
}
//---OTHERWISE, ENABLE THE "NEXT" BUTTON---
else if (nextID == idToMatch)
{
btnNext.Enabled = true;
}
}
}
}
|
7649e8d878570f179d0fddf2652679d53478458c
|
C#
|
shaykhullinsergey/Shaykhullin.ObjectOrientedProgramming
|
/Shaykhullin.Lab4/Shaykhullin.Lab4/Operations/Binary/BinaryDivideOperation.cs
| 2.796875
| 3
|
namespace Shaykhullin.Operations
{
public class BinaryDivideOperation
: BinaryOperation<double, double>
{
public override double Calculate(double arg1, double arg2)
{
return arg1 / arg2;
}
}
}
|
678d3ea7efb5091e722cff62a1e7d7ee2a33b3ae
|
C#
|
Daoting/dt
|
/Infras/Dt.Xls/Base/ExcelTableBorder.cs
| 2.84375
| 3
|
#region 文件描述
/******************************************************************************
* 创建: Daoting
* 摘要:
* 日志: 2014-07-01 创建
******************************************************************************/
#endregion
#region 引用命名
using System;
#endregion
namespace Dt.Xls
{
/// <summary>
/// Represent the excel table border settings
/// </summary>
public class ExcelTableBorder : ExcelBorder, IExcelTableBorder, IExcelBorder, IEquatable<IExcelBorder>
{
private IExcelBorderSide _horizontal;
private IExcelBorderSide _vertical;
/// <summary>
/// Create a new <see cref="T:Dt.Xls.ExcelBorder" /> based on the current item.
/// </summary>
/// <returns>
/// An <see cref="T:Dt.Xls.ExcelBorder" /> represent a cloned <see cref="T:Dt.Xls.ExcelBorder" /> instance.
/// </returns>
public override IExcelBorder Clone()
{
ExcelTableBorder border = new ExcelTableBorder();
ExcelBorderSide side = new ExcelBorderSide {
Color = base.Left.Color,
LineStyle = base.Left.LineStyle
};
border.Left = side;
ExcelBorderSide side2 = new ExcelBorderSide {
Color = base.Right.Color,
LineStyle = base.Right.LineStyle
};
border.Right = side2;
ExcelBorderSide side3 = new ExcelBorderSide {
Color = base.Top.Color,
LineStyle = base.Top.LineStyle
};
border.Top = side3;
ExcelBorderSide side4 = new ExcelBorderSide {
Color = base.Bottom.Color,
LineStyle = base.Bottom.LineStyle
};
border.Bottom = side4;
border.Vertical = (this.Vertical != null) ? new ExcelBorderSide() : null;
border.Horizontal = (this.Horizontal != null) ? new ExcelBorderSide() : null;
return border;
}
/// <summary>
/// Determine whether the specified ExcelBorder object is equal to this instance
/// </summary>
/// <param name="other"> An <see cref="T:Dt.Xls.ExcelBorder" /> instance used to compared with the current instance.</param>
/// <returns>
/// <see langword="true" /> if the specified <see cref="T:Dt.Xls.ExcelBorder" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(IExcelTableBorder other)
{
if (object.ReferenceEquals(this, other))
{
return true;
}
if (other == null)
{
return false;
}
bool flag = ((base.Left.Equals(other.Left) && base.Right.Equals(other.Right)) && base.Top.Equals(other.Top)) && base.Bottom.Equals(other.Bottom);
if (!flag)
{
return false;
}
if ((this.Horizontal != null) && !this.Horizontal.Equals(other.Horizontal))
{
return false;
}
if (other.Horizontal != null)
{
return false;
}
if ((this.Vertical != null) && !this.Vertical.Equals(other.Vertical))
{
return false;
}
if (other.Vertical != null)
{
return false;
}
return flag;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object" /> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object" /> to compare with this instance.</param>
/// <returns>
/// <see langword="true" /> if the specified <see cref="T:System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this.Equals((IExcelTableBorder) (obj as ExcelTableBorder));
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int num = ((base.Left.GetHashCode() ^ (base.Right.GetHashCode() << 8)) ^ (base.Top.GetHashCode() << 0x10)) ^ (base.Bottom.GetHashCode() << 0x18);
if (this.Horizontal != null)
{
num ^= this.Horizontal.GetHashCode() << 10;
}
if (this.Vertical != null)
{
num ^= this.Vertical.GetHashCode() << 20;
}
return num;
}
/// <summary>
/// Gets or sets the horizontal border line
/// </summary>
/// <value>The horizontal border line</value>
public IExcelBorderSide Horizontal
{
get { return this._horizontal; }
set { this._horizontal = value; }
}
/// <summary>
/// Gets or sets the vertical border line
/// </summary>
/// <value>The vertical border line</value>
public IExcelBorderSide Vertical
{
get { return this._vertical; }
set { this._vertical = value; }
}
}
}
|
cf74001d51c18d557f84cef04f582b5d77cb2b56
|
C#
|
ethedy/Curso2016_PTR
|
/Resoluciones/Ana Laura/ConsoleApplication1/Ejercicio_1.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace ConsoleApplication1
{
public class Ejercicio_1
{
public static void EjecutarEjercicio1()
{
DateTime fecha = DateTime.Today;
Console.WriteLine("Fines de semana del año {0}", fecha.Year);
DateTime inicio = new DateTime(fecha.Year, 1, 1);
String txtInicio = inicio.ToShortDateString();
DateTime fin = new DateTime(fecha.Year, 12, 31);
String txtFin = fin.ToShortDateString();
Console.WriteLine("Fecha inicio {0} y fecha fin {1}", txtInicio, txtFin);
#region Comentarios
/* bool bisiesto = DateTime.IsLeapYear(fecha.Year);
int diasDelAnio =0;
int diasFeb = 0;
if (bisiesto)
{
diasDelAnio = 366;
diasFeb = 29;
}
else
{
diasDelAnio = 365;
diasFeb = 28;
}*/
#endregion
int i = 0;
DateTime temporal = inicio;
while (temporal <= fin)
{
//Console.WriteLine("Entró al While");
//Console.WriteLine(temporal.DayOfWeek);
if (temporal.DayOfWeek == DayOfWeek.Saturday)
{
i++;
string dia = "Sábado";
int mesNro = temporal.Month;
string txtMes = getNombreMes(mesNro);
// Console.WriteLine("Fin de semana #{0} - {1} {2} de {3} ", i,dia,temporal.Day,txtMes);
Console.WriteLine("Fin de semana #{0} - {1:dddd} {1:dd} de {1:MMMM} ", i, temporal);
}
temporal = temporal.AddDays(1);
if(temporal.DayOfWeek == DayOfWeek.Sunday && temporal <= fin)
{
string dia = "Domingo";
int mesNro = temporal.Month;
string txtMes = getNombreMes(mesNro);
Console.WriteLine("Fin de semana #{0} - {1} {2} de {3} ", i, dia, temporal.Day, txtMes);
}
}
Console.ReadKey();
Console.ReadKey();
Console.ReadKey();
}
private static string getNombreMes(int mesNro)
{
try
{
DateTimeFormatInfo formatoFecha = CultureInfo.CurrentCulture.DateTimeFormat;
string nombreMes = formatoFecha.GetMonthName(mesNro);
return nombreMes;
}
catch
{
return "No se encontró el mes";
}
}
}
}
|
af83f4269dc4070d438c51ecd238827e4282566d
|
C#
|
stefanandy/VendingMachine
|
/Persistance/SoldItemRepository.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Business;
using Microsoft.EntityFrameworkCore;
namespace Persistance
{
public class SoldItemRepository : ISoldItemRepository
{
private readonly VendingDbContext Context;
public SoldItemRepository(VendingDbContext context) {
Context = context;
}
public async Task Add(SoldItem item)
{
await Context.SoldItem.AddAsync(item);
await Context.SaveChangesAsync();
}
public async Task<SoldItem> Get(int Id)
{
var item = await Context.SoldItem.Include(t => t.Item).FirstOrDefaultAsync(x => x.Id == Id);
return item;
}
public async Task<List<SoldItem>> GetAll()
{
var items = await Context.SoldItem.Include(t=>t.Item).Select(x => x).ToListAsync();
return items;
}
public async Task<List<SoldItem>> GetSoldLast30Days() {
var firstDay = DateTime.Today.AddDays(-30);
var items = await Context.SoldItem.Include(t => t.Item).Where(x => x.TimeStamp >= firstDay)
.ToListAsync();
return items;
}
public async Task<List<SoldItem>> GetSoldLast7Days()
{
var firstDay = DateTime.Today.AddDays(-7);
var items = await Context.SoldItem.Include(t => t.Item).Where(x => x.TimeStamp >= firstDay)
.ToListAsync();
return items;
}
public async Task<List<SoldItem>> GetSoldLast1Days()
{
var firstDay = DateTime.Today.AddDays(-1);
var items = await Context.SoldItem.Include(t => t.Item).Where(x => x.TimeStamp >= firstDay)
.ToListAsync();
return items;
}
public async Task<List<SoldItem>> GetTopFiveSoldItems() {
var items = await Context.SoldItem
.Include(t => t.Item)
.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Take(5)
.Select(g=>g.Key).ToListAsync();
return items;
}
}
}
|
70285238eafcb48dde07a37654f6e4d287be9b6f
|
C#
|
cometchuck/spnati
|
/editor source/SPNATI Character Editor/DataStructures/Definitions.cs
| 2.875
| 3
|
using Desktop;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace SPNATI_Character_Editor
{
public class Definitions
{
private static Definitions _instance;
public static Definitions Instance
{
get
{
if (_instance == null)
{
_instance = new Definitions();
}
return _instance;
}
set { _instance = value; }
}
public void Destroy()
{
_instance = null;
}
private DualKeyDictionary<Type, string, IRecord> _definitions = new DualKeyDictionary<Type, string, IRecord>();
#region General definitions
public void Clear()
{
_definitions.Clear();
}
public void Add<T>(T definition) where T : IRecord, new()
{
_definitions.Set(typeof(T), definition.Key, definition);
}
/// <summary>
/// Adds a definition to the correct subclass dictionary
/// </summary>
/// <param name="definition"></param>
public void Add(IRecord definition)
{
_definitions.Set(definition.GetType(), definition.Key, definition);
}
public void Remove<T>(T definition) where T : IRecord
{
_definitions.Remove(typeof(T), definition.Key);
}
public void Remove(Type type, IRecord definition)
{
_definitions.Remove(type, definition.Key);
}
/// <summary>
/// Enumerates through all definitions of a certain type
/// </summary>
/// <typeparam name="T">Asset definition type</typeparam>
/// <returns></returns>
public IEnumerable<T> Get<T>() where T : IRecord
{
Dictionary<string, IRecord> assets = _definitions[typeof(T)];
if (assets != null)
{
foreach (IRecord asset in assets.Values)
{
yield return (T)asset;
}
}
}
public IEnumerable<IRecord> Get(Type type)
{
Dictionary<string, IRecord> assets = _definitions[type];
if (assets != null)
{
foreach (IRecord asset in assets.Values)
{
yield return asset;
}
}
}
/// <summary>
/// Gets a definition with the given key
/// </summary>
/// <typeparam name="T">Definition type</typeparam>
/// <param name="key">Key identifier</param>
/// <returns></returns>
public T Get<T>(string key) where T : IRecord
{
if (key == null)
{
return default(T);
}
IRecord asset = _definitions.Get(typeof(T), key);
return (T)asset;
}
#endregion
}
}
|
ca5b3dabecdb7df359b498bbb67cf9034c2ba974
|
C#
|
gsimion/SlimXUnitDb
|
/Core.Test/BaseFactoryTest.cs
| 2.734375
| 3
|
using Bogus;
using SlimXUnitDb.Test.Core;
using SlimXUnitDb.Test.Core.Generators;
using System;
using System.Collections.Generic;
using Xunit;
namespace Core.Test
{
public class BaseFactoryTest
{
public static int Counter;
public class SimpleObj
{
public int Hash { get; set; }
public SimpleObj()
{
}
public SimpleObj(int hash)
: this()
{
Hash = hash;
}
}
private class SimpleObjFaker : BaseFactory<SimpleObj>
{
public SimpleObjFaker(BaseTest testContest) : base(testContest)
{
}
protected override SimpleObj GenerateNew(Action<Faker<SimpleObj>> action)
{
var faker = new Faker<SimpleObj>();
faker.RuleFor(u => u.Hash, 1);
action(faker);
return faker;
}
protected override SimpleObj GenerateNew()
{
var faker = new Faker<SimpleObj>();
faker.RuleFor(u => u.Hash, 1);
return faker;
}
protected override void SyncDb(IReadOnlyList<SimpleObj> list)
{
Counter += list.Count;
}
}
public static IEnumerable<object[]> GetSimpleObjects()
{
yield return new object[] { new Faker<SimpleObj>().RuleFor(u => u.Hash, 1) };
}
[Theory(DisplayName = "Bogus :: assumption on override rule.")]
[MemberData(nameof(GetSimpleObjects))]
public void Bogus_Faker_Override_Hash(dynamic faker)
{
Assert.IsType<Faker<SimpleObj>>(faker);
(faker as Faker<SimpleObj>).RuleFor(x => x.Hash, 100);
SimpleObj o = faker;
Assert.Equal(100, o.Hash);
}
[Fact(DisplayName = "BaseFactory :: create new assert on inheritedn properties.")]
public void BaseFactory_Constructor_Properties()
{
var generator = new SimpleObjFaker(null);
Assert.NotNull(generator);
Assert.Equal(0, generator.Count);
}
[Fact(DisplayName = "BaseFactory :: generate default output.")]
public void BaseFactory_Generate_Defult_Output()
{
var generator = new SimpleObjFaker(null);
var generated = generator.Generate();
int expectedHash = 1;
Assert.NotNull(generated);
Assert.IsType<SimpleObj>(generated);
Assert.Equal(expectedHash, generated.Hash);
}
[Fact(DisplayName = "BaseFactory :: generate override output.")]
public void BaseFactory_Generate_Override_Output()
{
int expectedHash = 1234;
var generator = new SimpleObjFaker(null);
var generated = generator.Generate(u => u.RuleFor(x => x.Hash, expectedHash));
Assert.NotNull(generated);
Assert.IsType<SimpleObj>(generated);
Assert.Equal(expectedHash, generated.Hash);
}
[Fact(DisplayName = "BaseFactory :: sync db count.")]
public void BaseFactory_Sync_CorrectCall_Count()
{
int initialCount = Counter;
var generator = new SimpleObjFaker(null);
generator.Generate();
generator.Generate();
generator.Sync();
Assert.Equal(2, Counter - initialCount);
}
[Fact(DisplayName = "BaseFactory :: sync db after accepting changes count.")]
public void BaseFactory_AcceptChanges_Sync_CorrectCall_NothingToSync_Count()
{
int initialCount = Counter;
var generator = new SimpleObjFaker(null);
generator.Generate();
generator.Generate();
generator.AcceptChanges();
generator.Sync();
Assert.Equal(0, Counter - initialCount);
}
[Fact(DisplayName = "BaseFactory :: sync db after accepting changes count.")]
public void BaseFactory_AcceptChanges_Sync_CorrectCall_Count()
{
int initialCount = Counter;
var generator = new SimpleObjFaker(null);
generator.Generate();
generator.AcceptChanges();
generator.Generate();
generator.Generate();
generator.Sync();
Assert.Equal(2, Counter - initialCount);
Assert.Equal(3, generator.Count);
}
}
}
|
a2feda84c56270f799fbcc20e6ff18625f82cdeb
|
C#
|
narc0tiq/dotnet-temp
|
/ConsoleConfigThing/Program.cs
| 3.109375
| 3
|
using System;
using System.Configuration;
namespace ConsoleConfigThing
{
class Program
{
static Random rand = new Random();
static void Main(string[] args)
{
Console.WriteLine("Your hostname is {0}", System.Net.Dns.GetHostName());
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["SomeThingy"].Value = rand.Next().ToString();
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");
}
}
}
|
3d9ebf91f93dd5c131508cdd383c75f28fb082f5
|
C#
|
PowerDG/DDDgP2018
|
/4.6.0/aspnet-core/dgOcelot/MicroDg/queryconsul1/Program.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Consul;
namespace queryconsul1
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello World!");
using (ConsulClient consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
{
//consulClient.Agent.Services()获取consul中注册的所有的服务
Dictionary<String, AgentService> services = consulClient.Agent.Services().Result.Response;
foreach (KeyValuePair<String, AgentService> kv in services)
{
Console.WriteLine($"key={kv.Key},{kv.Value.Address},{kv.Value.ID},{kv.Value.Service},{kv.Value.Port}");
}
//获取所有服务名字是"apiservice1"所有的服务
var agentServices = services.Where(s => s.Value.Service.Equals("apiservice1", StringComparison.CurrentCultureIgnoreCase))
.Select(s => s.Value);
//根据当前TickCount对服务器个数取模,“随机”取一个机器出来,避免“轮询”的负载均衡策略需要计数加锁问题
var agentService = agentServices.ElementAt(Environment.TickCount % agentServices.Count());
Console.WriteLine($"{agentService.Address},{agentService.ID},{agentService.Service},{agentService.Port}");
}
Console.ReadKey();
}
}
}
|
cbdbfc19688ef58b3940cba8692ad5521e4852fa
|
C#
|
quimaruanomed/ExerciciVideos_Fase2_y_Fase3
|
/ExerciciVideosFase_3/clases/User.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Exercici3VideosFases_3.Clases
{
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public DateTime DatRegister { get; set; }
public User()
{
}
//Metodo que valida si los campos están vacíos
public static void DatesEmptys(string resp)
{
if (resp == "")
{
Console.WriteLine("Error!!! No has introducido ningún valor");
Console.WriteLine();
}
}
public static void Login()
{
Console.WriteLine("Introduce tu usuario/Username: ");
string login = Console.ReadLine();
Console.WriteLine("Introduce el Password: ");
string pass = Console.ReadLine();
Console.WriteLine();
var fUser = User.uList.Exists(x => x.Username.Equals(login));
var fpas = User.uList.Exists(x => x.Password.Equals(pass));
Console.WriteLine();
// Comprobamos que valor tienen las variables fUser y fpas para poder programar las condiciones que comprueben que los datos introducidos son correctos
Console.WriteLine("Usuario :" + fUser);
Console.WriteLine("Password : " + fpas);
if ((fUser == true) && (fpas == true))
{
Console.WriteLine("Validacion correcta");
}
else
{
Console.WriteLine("**************************************");
Console.WriteLine("******** Prueba de nuevo: ***********");
do
{
Console.WriteLine("Introduce tu usuario/Username: ");
login = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Introduce el Password: ");
pass = Console.ReadLine();
Console.WriteLine();
fUser = User.uList.Exists(x => x.Username.Equals(login));
Console.WriteLine("Usuario :" + fUser);
fpas = User.uList.Exists(x => x.Password.Equals(pass));
Console.WriteLine();
Console.WriteLine("Password : " + fpas);
} while ((fUser != true) && (fpas != true));
Console.WriteLine("Validacion correcta");
}
{
var newR = new List<Video>();
var conVideo = Video.vList.ToList();
List<Video> newVideo = new List<Video>();
List<bool> vT = new List<bool>().ToList();
// Variable que utilizaremos para las dif. opciones del swtich
ConsoleKeyInfo op;
do
{
Console.WriteLine("**************************");
Console.WriteLine(" Bienvenido a : Videos ");
Console.WriteLine();
Console.WriteLine("***************************");
Console.WriteLine("============================");
Console.WriteLine(" MENU ");
Console.WriteLine("============================");
Console.WriteLine("Opciones:" +
"\n A.-Listar mis video" +
"\n B.-Crear video " +
"\n C.-Buscar Video : y accdiones sobre el video: " +
"\n D.-Para Salir pulsa ESC dos veces "
);
op = Console.ReadKey(true);
switch (op.Key)
{
case ConsoleKey.A:
Console.Clear();
Console.WriteLine();
Console.WriteLine("LISTADO DE VIDEOS DEL USUARIO LOGEADO : " + login);
Console.WriteLine();
if (login == "admin")
{
Console.WriteLine("Pearl harbor sound track");
}
if (login == "jruanomed")
{
Console.WriteLine("Gladiator - Now We Are Free Super Theme Song");
Console.WriteLine(" Sarah Mclachlan - In The Arms Of The Angel");
}
if (login == "jperez")
{
Console.WriteLine(" One day We Had Today");
Console.WriteLine(" John Barry - The Old Woman");
}
break;
case ConsoleKey.B:
Console.Clear();
Console.WriteLine("Introduce su Url: ");
string nUrl = Console.ReadLine();
Console.WriteLine("Introduce el título del video que quieres crear: ");
string nVideo = Console.ReadLine();
Video.vList.Add(new Video() { Url = nVideo, Title = nUrl });
List<Video> newVi = new List<Video>();
newVi.Add(new Video() { Url = nVideo, Title = nUrl });
// Comprobamos que los registros nuevos se han guardado
Console.WriteLine("####################################################################################");
Console.WriteLine("Listado de Video : Comprobación de que el video creado se ha guardado en la lista ");
Console.WriteLine("######################################################################################");
Console.WriteLine();
for (int i = 0; i < Video.vList.Count; i++)
{
Console.WriteLine("Titulo: " + "\n" + Video.vList[i].Title + "\n" + "Url: " + "\n" + Video.vList[i].Url);
}
Console.WriteLine();
Console.WriteLine("###########");
Console.WriteLine("TAGS");
Console.WriteLine("############");
Console.WriteLine("1.- Crear un Tag: " + "Si: 1 " + " " + "No :2");
string resp = Console.ReadLine();
DatesEmptys(resp);
do
{
if (resp == "2")
{
break;
}
if (resp == "1")
{
Console.WriteLine("Introduce el nombre del Tag/etiqueta : ");
string nTag = Console.ReadLine();
List<string> newTags = new List<string>();
newTags.Add(nTag);
Console.WriteLine("Quieres añadir otro Tag ");
resp = Console.ReadLine();
DatesEmptys(resp);
if ((resp == "2") || (resp != "1"))
{
break;
}
}
} while ((resp != "2") || (resp != ""));
break;
case ConsoleKey.C:
Console.Clear();
Console.WriteLine("Introduce el titulo del video que quieres buscar: ");
string xVideo = Console.ReadLine();
string findVideo = Video.vList.ToString();
DatesEmptys(xVideo);
if (login == "admin")
{
if (xVideo == "Pearl harbor sound track")
{
Console.WriteLine("Resultado de la busqueda: " + xVideo);
Console.WriteLine("\n 1.- Reproducir video" +
"\n 2- Pausar video " +
"\n 3 - Parar video");
string respSub = Console.ReadLine();
DatesEmptys(respSub);
if (respSub == "1")
{
Console.WriteLine("El video se está reproduciendo");
}
if (respSub == "2")
{
Console.WriteLine("Video Pausado");
}
if (respSub == "3")
{
Console.WriteLine("Video detenido");
}
}
}
if (login == "jruanomed")
{
if (xVideo == "Gladiator - Now We Are Free Super Theme Song" || xVideo == "Sarah Mclachlan - In The Arms Of The Angel")
{
Console.WriteLine("Resultado de la busqueda : " + xVideo);
Console.WriteLine("\n 1.- Reproducir video" +
"\n 2- Pausar video " +
"\n 3 - Parar video");
string respSubm = Console.ReadLine();
DatesEmptys(respSubm);
if (respSubm == "1")
{
Console.WriteLine("El video se está reproduciendo");
}
if (respSubm == "2")
{
Console.WriteLine("Video Pausado");
}
if (respSubm == "3")
{
Console.WriteLine("Video detenido");
}
}
}
if (login == "jperez")
{
if (xVideo == "One day We Had Today" || xVideo == "John Barry - The Old Woman")
{
Console.WriteLine("Resultado de la busqueda : " + xVideo);
Console.WriteLine("\n 1.- Reproducir video" +
"\n 2- Pausar video " +
"\n 3 - Parar video");
string respSubmn = Console.ReadLine();
DatesEmptys(respSubmn);
if (respSubmn == "1")
{
Console.WriteLine("El video se está reproduciendo");
}
if (respSubmn == "2")
{
Console.WriteLine("Video Pausado");
}
if (respSubmn == "3")
{
Console.WriteLine("Video detenido");
}
}
}
break;
default:
Console.WriteLine();
Console.WriteLine("Opción no valida");
Console.WriteLine();
break;
case ConsoleKey.Escape:
break;
}
} while (op.Key != ConsoleKey.Escape);
}
Console.ReadKey();
}
public static List<User> uList = new List<User>
{
new User {Name="Joaquina", Surname="Ruano",Username="jruanomed",Password="jruanomed" },
new User {Name= "Javier", Surname= "Perez", Username= "jperez", Password= "jperez" },
new User {Name= "admin", Surname= "admin", Username= "admin", Password= "admin"}};
}
}
|
7efdf3fae9c37c06560c7d8734af83876c8ef4da
|
C#
|
HFisher1212/halfisher1212
|
/HW6/Counter.cs
| 4.15625
| 4
|
/** Define a class called Counter whose objects count things.
* An object of this class records a count that is a nonnegative
* integer.Include methods to set the counter to 0, to increase
* the count by 1, and to decrease the count by 1. Be sure that
* no method allows the value of the counter to become negative.
* Include a getter method that returns the current count value
* and a method that outputs the count to the screen.There should
* be no input method or other setter methods. The only method
* that can set the counter is the one that sets it to 0. Include
* a ToString methods and a Equals method. Write a driver program
* that include a menu to interactively test each method in your
* program. For example, the menu should have an option that test
* each method and operates on 1 object for example you should be
* able to select the increment method which would increment your
* Counter.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HW6
{
class Counter
{
// CLASS VARIABLES
private int count = 0;
// DEFAULT CONSTRUCTOR
public Counter()
{
count = 0;
}
// RESET METHOD
public void zeroCount()
{
count = 0;
}
// GETTER METHODS
public int getCount()
{
return count;
}
// SETTER METHODS
// ADDONECOUNT METHOD
// Precondition- Counter object must be instantiated
// Postcondition- Counter object incremented by 1
public void addOneCount()
{
count++;
}
// SUBTRACTONECOUNT METHOD
// Precondition- counter object must be instantiated
// Postcondition- counter object decremented by 1 unless zero
public void subtractOneCount()
{
if (count != 0)
{
count--;
}
}
// REQUIRED METHODS
// TOSTRING METHOD
// Precondition- counter object must be instantiated
// Postcondition- returns string containing counter variable
public override string ToString()
{
return "The Count is: " + count;
}
// EQUALS METHOD
// Precondition- counter object must be instantiated
// Postcondition- returns boolean true false when comparing other object
public bool Equals(Counter other)
{
return this.getCount() == other.getCount();
}
}
}
|
9e1409362aa2dc8a7030a76e4a04d64be8bb5008
|
C#
|
olekstra/Olekstra.Sdk.LikePharma
|
/Olekstra.LikePharma.Server.Demo/SampleLikePharmaService.cs
| 2.5625
| 3
|
namespace Olekstra.LikePharma.Server.Demo
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Olekstra.LikePharma.Client;
// <inheritdocs />
public class SampleLikePharmaService : ILikePharmaService<string>
{
private readonly ILogger logger;
public SampleLikePharmaService(ILogger<SampleLikePharmaService> logger)
{
this.logger = logger;
}
// <inheritdocs />
public Task<string?> AuthorizeAsync(string authorizationToken, string authorizationSecret, HttpRequest httpRequest)
{
if (string.IsNullOrEmpty(authorizationToken) || string.IsNullOrEmpty(authorizationSecret))
{
return Task.FromResult<string?>(null);
}
#pragma warning disable CA1308 // Normalize strings to uppercase - как хочу так и проверяю пароль
var validSecret = authorizationSecret.ToLowerInvariant();
#pragma warning restore CA1308 // Normalize strings to uppercase
if (string.Equals(authorizationSecret, validSecret, StringComparison.Ordinal))
{
logger.LogInformation("Успешная авторизация: " + authorizationToken);
return Task.FromResult<string?>(authorizationToken.ToUpperInvariant());
}
else
{
logger.LogWarning("Неуспешная авторизация: " + authorizationToken);
return Task.FromResult<string?>(null);
}
}
// <inheritdocs />
public Task<RegisterResponse> RegisterAsync(RegisterRequest request, string user)
{
throw new NotImplementedException();
}
// <inheritdocs />
public Task<ConfirmCodeResponse> ConfirmCodeAsync(ConfirmCodeRequest request, string user)
{
throw new NotImplementedException();
}
// <inheritdocs />
public Task<GetDiscountResponse> GetDiscountAsync(GetDiscountRequest request, string user)
{
throw new NotImplementedException();
}
// <inheritdocs />
public Task<ConfirmPurchaseResponse> ConfirmPurchaseAsync(ConfirmPurchaseRequest request, string user)
{
throw new NotImplementedException();
}
// <inheritdocs />
public Task<CancelPurchaseResponse> CancelPurchaseAsync(CancelPurchaseRequest request, string user)
{
throw new NotImplementedException();
}
// <inheritdocs />
public Task<GetProductsResponse> GetProductsAsync(GetProductsRequest request, string user)
{
throw new NotImplementedException();
}
// <inheritdocs />
public Task<GetProgramsResponse> GetProgramsAsync(GetProgramsRequest request, string user)
{
var resp = new GetProgramsResponse
{
Status = Globals.StatusSuccess,
ErrorCode = 0,
Message = "Данные сформированы",
Programs = new List<GetProgramsResponse.Program>
{
new GetProgramsResponse.Program
{
Code = "SAMPLE1",
Name = "Программа 1",
},
new GetProgramsResponse.Program
{
Code = "SAMPLE2",
Name = "Программа 2",
},
},
};
return Task.FromResult(resp);
}
}
}
|
2605e54ba9b015ec1068480a00f14325729f65bf
|
C#
|
DashaPavlova/CI
|
/задача 6 лр5/задача 6 лр5/Program.cs
| 3.703125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace задача_6_лр5
{
class Program
{
static StackT<int> Input(int n)
{
StackT<int> tmp = new StackT<int>();
Random rnd = new Random();
for (int i = 0; i < n; i++)
tmp.PushTail(rnd.Next(0, 10));
return tmp;
}
static void Output(StackT<int> tmp)
{
StackT<int> a = new StackT<int>();
while (tmp.Count > 0)
{
int n = (int)tmp.PopHead();
Console.WriteLine(n);
a.PushTail(n);
}
while (a.Count > 0)
{
tmp.PushTail((int)a.PopHead());
}
}
/// <summary>
/// Вставка в дек перед предыдущим элементом, равным введенному числу с клавиатуры, число равное произведению предыдущего и элемента
/// </summary>
/// <param name="tmp">Исходный дек</param>
/// <param name="tmp3">Новый дек</param>
/// <param name="K">Искомый элемент</param>
/// <returns>Исходный дек</returns>
static StackT<int> Vstavka(StackT<int> tmp, int K)
{
StackT<int> tmp3 = new StackT<int>();
StackT<int> tmp1 = new StackT<int>();
foreach(int y in tmp)
{
tmp1.PushTail(y);
}
while (tmp1.Count>1)
{
int x = (int)tmp1.PopHead();//Предыдущий элемент
//Console.WriteLine("x={0}",x);
int c = (int)tmp1.PopHead();// Элемент, который сравниваем
//Console.WriteLine("c={0}",c);
if (c==K)
{
tmp3.PushTail(x*K);
tmp3.PushTail(x);
}
else
{
tmp3.PushTail(x);
}
tmp1.PushHead(c);//Возвращаем элемент в дек
//Console.WriteLine("--------------------------");
}
tmp3.PushTail(tmp1.PopHead());//Записываем самый последний элемент, перед которым уже пусто
return tmp3;
}
static void Main(string[] args)
{
try
{
Console.WriteLine("Введите количество элементов дека");
int C = int.Parse(Console.ReadLine());
if (C > 0)
{
StackT<int> st = new StackT<int>();
st = Input(C);
Console.WriteLine("Исходный дек:");
Output(st);
Console.WriteLine("Введите число для сравнения");
int K = int.Parse(Console.ReadLine());
StackT<int> tmp3 = new StackT<int>();
tmp3 = Vstavka(st, K);
Console.WriteLine("Новый дек:");
Output(tmp3);
//Console.WriteLine("------------");
//Output(st);
}
else
{
Console.WriteLine("Размерность не может быть меньше или равна нуля");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
|
6d428be97e5223df5f5b8aa7503e0346d03cf225
|
C#
|
sarincr/Basics-of-C-Sharp-Programming
|
/20_ArrayFun/src/main.cs
| 3.859375
| 4
|
using System;
namespace ArrayApplication {
class MyArray {
double getAverage(int[] arr, int size) {
int i;
double avg;
int sum = 0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
static void Main(string[] args) {
MyArray app = new MyArray();
/* an int array with 5 elements */
int [] balance = new int[]{1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = app.getAverage(balance, 5 ) ;
/* output the returned value */
Console.WriteLine( "Average value is: {0} ", avg );
Console.ReadKey();
}
}
}
|
ad826c5e8cb2590f272e099c61fd036f80b869f9
|
C#
|
DouglasWait/Assignments
|
/FIFO/FIFO/Shortest Job First.cs
| 3
| 3
|
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 FIFO
{
public partial class Shortest_Job_First : Form
{
public Shortest_Job_First()
{
InitializeComponent();
}
int[] arr = new int[5] {5,3,8,1,6 };
int[] arrpositions = new int[5] { 0, 1, 2,3, 4 };
private void button1_Click(object sender, EventArgs e)
{
int smallest = 10;
int smalindex=0 ;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i+1; j < arr.Length; j++)
{
if (arr[j] < arr[i])
{
int temp = arrpositions[j];
arrpositions[j] = arrpositions[i];
arrpositions[i] = temp;
}
}
// textBox1.AppendText("Execution time of process " + (smalindex + 1) + " :\t" + arr[i] + "\n");
}
for (int i = 0; i < arr.Length; i++)
{
textBox1.AppendText("Execution time of process " + (arrpositions[i]+1) + " :\t" + arr[arrpositions[i]] + "\n");
}
}
private void Shortest_Job_First_Load(object sender, EventArgs e)
{
for (int i = 0; i < arr.Length; i++)
{
textBox1.AppendText("Execution time of process " + (i + 1) + " :\t" + arr[i]+"\n");
}
textBox1.AppendText("\n\n");
}
}
}
|
96ddfb0fa9fd4f83402395a221b621b129975b75
|
C#
|
panncakemahogany/The-Griddle.github.io
|
/Flooring.UI/Flooring.Data/FlooringIO/OrderRepository.cs
| 2.96875
| 3
|
using Flooring.Models.Interfaces;
using Flooring.Models;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Flooring.Data.FlooringIO
{
public class OrderRepository : IOrderRepository
{
public List<Order> LoadOrders(string date)
{
List<Order> ordersFromFile = new List<Order>();
TaxesRepository taxRepo = new TaxesRepository();
ProductRepository productRepo = new ProductRepository();
List<Taxes> allTaxes = taxRepo.LoadTaxes();
List<Product> allProducts = productRepo.LoadProducts();
using (StreamReader reader = new StreamReader(Settings.GetOrderDateFilePath(date)))
{
reader.ReadLine();
string line;
while((line = reader.ReadLine()) != null)
{
Order order = new Order();
string[] newOrder = line.Split(',');
order.OrderNumber = int.Parse(newOrder[0]);
order.CustomerName = newOrder[1];
foreach (Product p in allProducts)
{
if (p.ProductType == newOrder[4])
{
order.Product = p;
}
else continue;
}
foreach (Taxes t in allTaxes)
{
if (t.StateAbbreviation == newOrder[2])
{
order.Taxes = t;
}
else continue;
}
order.Area = decimal.Parse(newOrder[5]);
order.CalculateOrderValues(order.CustomerName, order.Area, order.Product, order.Taxes);
ordersFromFile.Add(order);
}
}
return ordersFromFile;
}
public void SaveOrders(List<Order> orders, string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("OrderNumber,CustomerName,State,TaxRate,ProductType,Area,CostPerSquareFoot,LaborCostPerSquareFoot,MaterialCost,LaborCost,Tax,Total");
foreach (Order o in orders)
{
writer.WriteLine(o.ToString());
}
}
}
}
}
|
ca09a69c4b3781944a1cd4c83897629e0937cfa5
|
C#
|
jschneiderhan15/oregon-road-83
|
/Oregon Road/Oregon Road/Assets/Scripts/HungerManager.cs
| 2.921875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//script that allows the player to change how fast their characters are eating
public class HungerManager : MonoBehaviour
{
//three options for feeding
static Button tiny, meager, full;
void Start(){
//initiating each button
tiny = GameObject.Find("Tiny").GetComponent<Button>();
meager = GameObject.Find("Meager").GetComponent<Button>();
full = GameObject.Find("Full").GetComponent<Button>();
//full.Select();
}
//the following three methods just change the game's overall "eating rate" of each player
public void changeToTiny(){
GameLogic.EatRate = 1;
Debug.Log("Changing eating!");
}
public void changeToMeager(){
GameLogic.EatRate = 2;
Debug.Log("Changing eating!");
}
public void changeToFull(){
GameLogic.EatRate = 3;
Debug.Log("Changing eating!");
}
//way to keep the buttons pressed down even if you click off of them
public static void loadButtons(){
if(GameLogic.EatRate == 1){
tiny.Select();
}
else if(GameLogic.EatRate == 2){
meager.Select();
}
else{
full.Select();
}
}
}
|
f20a8b3ab87277f35ef23d73efdcbf0a9745e3b0
|
C#
|
matt-comeaux/DemoQA_AutomatedUITest
|
/Page_Object_Models/AlertsFramesWindows/BrowserWindowsPage.cs
| 2.640625
| 3
|
/*
Name: BrowserWindows.cs
Purpose: Contains the Page Object Model for the browser windows page on www.demoqa.com.
Author: Matthew Comeaux. Github: https://www.github.com/matt-comeaux Linkedin: https://www.linkedin.com/in/matthew-comeaux
Created On: 5/3/2021
First Uploaded To Github On: 5/4/2021
MIT License
Copyright (c) [2021] [Matthew H. Comeaux]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
using Xunit;
namespace AutomatedUITest_DemoQA.Page_Object_Models.AlertsFramesWindows
{
class BrowserWindowsPage
{
private readonly IWebDriver Driver;
private readonly string url = "https://demoqa.com/browser-windows";
private readonly string mainHeader = "Browser Windows";
//Create instance of POM.
public BrowserWindowsPage(IWebDriver driver)
{
this.Driver = driver;
}
//Loads page.
public void LoadPage()
{
Driver.Navigate().GoToUrl(url);
EnsurePageLoaded();
}
//Validate that the correct page loaded.
public void EnsurePageLoaded()
{
bool isLoaded = (Driver.Url == url) && (Driver.FindElement(By.ClassName("main-header")).Text == mainHeader);
if (!isLoaded)
{
throw new Exception($"The requested page did not load correctly. The page url is: '{url}' The page source is: \r\n '{Driver.PageSource}'");
}
}
public void ClickButton_NewTab()
{
//Click new tab button, create collection of all tabs, switch to tab and store its data in a variable.
Driver.FindElement(By.Id("tabButton")).Click();
ReadOnlyCollection<String> allTabs = Driver.WindowHandles;
var createdTab = Driver.SwitchTo().Window(allTabs[1]);
//Assert correct tab was created on button click.
var pageHeader = Driver.FindElement(By.Id("sampleHeading")).Text;
Assert.True(createdTab.Url == "https://demoqa.com/sample", "The button with id of: 'tabButton' did not open to the correct url.");
Assert.True(pageHeader == "This is a sample page", "The button with id of: 'tabButton' did not open to the page with the correct heading.");
}
public void ClickButton_NewWindow()
{
//Click new window button, create collection of all windows, switch to created window and store its data in a variable.
Driver.FindElement(By.Id("windowButton")).Click();
ReadOnlyCollection<String> allWindows = Driver.WindowHandles;
var createdWindow = Driver.SwitchTo().Window(allWindows[1]);
//Verify the window loaded to the correct page.
Assert.True(createdWindow.Url == "https://demoqa.com/sample", "The button with id of: 'windowButton' did not open the correct window.");
Assert.True(Driver.FindElement(By.Id("sampleHeading")).Text == "This is a sample page", "The button with id of: 'windowButton' did not open the correct window.");
}
public void ClickButton_NewWindowMessage()
{
//Store current window Id and click new window message button.
var mainWindowHandle = Driver.CurrentWindowHandle;
Driver.FindElement(By.Id("messageWindowButton")).Click();
//create collection of all windows, switch to created window message and store its data in a variable.
ReadOnlyCollection<String> allWindows = Driver.WindowHandles;
var windowMessage = Driver.SwitchTo().Window(allWindows[1]);
//Validate window message appeared.
Assert.True(windowMessage.CurrentWindowHandle != mainWindowHandle, "The message window failed to load.");
}
}
}
|
e3fc6551986e02118723653a826020a6827f8aa6
|
C#
|
kirkenskorshaer/crm
|
/SystemInterface/SystemInterface/Mailrelay/Logic/UpdateReport.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SystemInterface.Mailrelay.Logic
{
public class UpdateReport<ReportType>
{
public List<ReportType> Failed = new List<ReportType>();
public List<ReportType> Updated = new List<ReportType>();
public List<ReportType> AlreadyUpToDate = new List<ReportType>();
public void CollectUpdate(UpdateResultEnum updateResult, ReportType reportValue)
{
switch (updateResult)
{
case UpdateResultEnum.Failed:
Failed.Add(reportValue);
break;
case UpdateResultEnum.Updated:
Updated.Add(reportValue);
break;
case UpdateResultEnum.AlreadyUpToDate:
AlreadyUpToDate.Add(reportValue);
break;
default:
throw new Exception($"unknown UpdateResult {updateResult}");
}
}
public string AsLogText(string logTextName)
{
StringBuilder logTextBuilder = new StringBuilder();
logTextBuilder.AppendLine(logTextName);
logTextBuilder.AppendLine($" Failed:{ListToLogText(Failed)}");
logTextBuilder.AppendLine($" Updated:{ListToLogText(Updated)}");
logTextBuilder.AppendLine($" AlreadyUpToDate:{ListToLogText(AlreadyUpToDate)}");
return logTextBuilder.ToString();
}
private string ListToLogText(List<ReportType> reportList)
{
return string.Join(",", reportList);
}
}
}
|
b89800d8dfb26657b51091a3ea6effbe90611aec
|
C#
|
zhangleipku/Unity-UI-Cookbook-files
|
/Unity UI Cookbook files/Chapter 02/7 - HealthBar with armor/HealthbarWithArmorScript.cs
| 2.890625
| 3
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HealthbarWithArmorScript : MonoBehaviour {
public GameObject[] armor;
private int piecesOfArmor;
private Image healthbarFilling;
public int maxHealth = 100;
private int health;
void Start () {
healthbarFilling = this.GetComponent<Image> ();
health = maxHealth;
piecesOfArmor = armor.Length;
}
public void addArmor(){
if (piecesOfArmor < armor.Length) {
piecesOfArmor++;
updateArmor();
}
}
public bool damage(int value){
if (piecesOfArmor > 0) {
piecesOfArmor--;
updateArmor();
return false;
}else{
return damageIgnoringArmor(value);
}
}
//Returns true if the player is die
public bool damageIgnoringArmor(int value){
health -= value;
if (health <= 0){
health = 0;
updateHealthbar ();
return true;
}
updateHealthbar ();
return false;
}
public void addHealth(int value){
health += value;
if (health > maxHealth)
health = maxHealth;
updateHealthbar ();
}
public void updateHealthbar(){
healthbarFilling.fillAmount = health / maxHealth;
}
public void updateArmor(){
for (int i=0; i<armor.Length; i++) {
if(i<piecesOfArmor){
armor[i].SetActive(true);
}else{
armor[i].SetActive(false);
}
}
}
}
|
24a12c57c6f6ba97094aa1b195a9c274e483d552
|
C#
|
cr0393/C-Sharp-Drills
|
/ClassObjectAssignment/ClassObjectAssignment/Program.cs
| 4.03125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassObjectAssignment
{
class Number
{
public int firstNumber = 200;
public void Add(int val)
{
Console.WriteLine(firstNumber + val);
}
public void Subtact(int val)
{
Console.WriteLine(firstNumber - val);
}
public void Multiply (int val)
{
Console.WriteLine(firstNumber * val);
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Pick a whole number number to do various math operations on");
int valueOne = Convert.ToInt32(Console.ReadLine());
Number example = new Number();
example.Add(valueOne);
example.Subtact(valueOne);
example.Multiply(valueOne);
Console.ReadKey();
}
}
}
|
39dfdc35281ea41db888406981cf57e0642e9b94
|
C#
|
Ren7851/FlutterC
|
/GUI/FlutterCGUI/FlutterCLib/FlutterCConsole/Nodes/Sizeof.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Sizeof : NativeFunctionBody
{
public Sizeof()
{
FunctionBodyStringNames fbsn = new FunctionBodyStringNames();
int argNumber = 1;
List<string> l = new List<string>();
l.Add("int");
fbsn.argsTypes.Add(l);
fbsn.argNames.Add("size");
fbsn.setReturnType(l);
string functionName = "sizeof";
init(argNumber, functionName, fbsn);
}
public override void execute()
{
Value q = Memory.instance.peek();
Memory.instance.pop();
int size = 0;
if(q.isPointer()){
size = Memory.instance.cellMemory.sizes[(int)q.value];
}
else
{
size = 1;
}
Value g = new Value("int", false);
g.value = size;
Memory.instance.push(g);
}
}
|
201f1a391627682b6817c54309f5e3e0c474d4cf
|
C#
|
garnhold/CrunchyBox
|
/CrunchyKitchen/Project/Project.cs
| 2.625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace Crunchy.Kitchen
{
using Dough;
using Noodle;
public abstract class Project<FILE, DIRECTORY, PROJECT>
where FILE : ProjectFile<FILE, DIRECTORY, PROJECT>
where DIRECTORY : ProjectDirectory<FILE, DIRECTORY, PROJECT>
where PROJECT : Project<FILE, DIRECTORY, PROJECT>
{
private StreamSystem stream_system;
private ProjectItemCreator<FILE> project_file_creator;
private ProjectItemCreator<DIRECTORY> project_directory_creator;
private DIRECTORY root;
protected virtual void UpdateInternal() { }
public Project(StreamSystem s, ProjectItemCreator<FILE> f, ProjectItemCreator<DIRECTORY> d)
{
stream_system = s;
project_file_creator = f;
project_directory_creator = d;
root = project_directory_creator.Create("");
root.InitializeAsRoot((PROJECT)this);
}
public void Update()
{
root.Update();
UpdateInternal();
}
public DIRECTORY GetRoot()
{
return root;
}
public StreamSystem GetStreamSystem()
{
return stream_system;
}
public ProjectItemCreator<FILE> GetProjectFileCreator()
{
return project_file_creator;
}
public ProjectItemCreator<DIRECTORY> GetProjectDirectoryCreator()
{
return project_directory_creator;
}
}
}
|
bb4a8b6fe671dbd9929b602f3915dba848432fea
|
C#
|
aceunlonely/fastdfs-client-net
|
/code/fastdfs-client-net/fastdfs-client-net/fastdfs/Client.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace fastdfs_client_net.fastdfs
{
/// <summary>
/// fastdfs 客户端
/// </summary>
public class Client
{
/// <summary>
/// 根据groupName获取可用的storage节点
/// </summary>
/// <param name="groupName"></param>
/// <returns></returns>
public static StorageNodeInfo GetAvailableStorageNode(string groupName)
{
return new TrackerCmds().QUERY_STORE_WITH_GROUP_ONE(groupName);
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="groupName"></param>
/// <param name="content"></param>
/// <param name="fileExt">后缀</param>
/// <returns>文件名</returns>
public static string Upload(string groupName, byte[] content, string fileExt)
{
StorageNodeInfo storage = GetAvailableStorageNode(groupName);
if (fileExt.StartsWith("."))
fileExt = fileExt.TrimStart(new char[] { '.' });
return new StorageCmds().UPLOAD_FILE(storage.EndPoint, storage.StorePathIndex, content.Length, fileExt, content);
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="groupName">组名</param>
/// <param name="fileName">文件名</param>
public static void Remove(string groupName, string fileName)
{
StorageNodeInfo storage = new TrackerCmds().QUERY_UPDATE(groupName, fileName);
new StorageCmds().DELETE_FILE(storage.EndPoint, groupName, fileName);
}
//download 不实现,fastdfs建议nginx方式获取文件
}
}
|
981a657795ce53bc74fdcb34df41fc663a78309f
|
C#
|
jsmale/dotPlumbing
|
/src/app/Plumbing.Core/DataAccess/EntityFrameworkDataContext.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Reflection;
namespace Plumbing.DataAccess
{
public class EntityFrameworkDataContext : IDataContext
{
readonly ObjectContext context;
readonly IDictionary<Type, PropertyInfo> queries;
readonly IDictionary<Type, MethodInfo> inserts;
readonly IDictionary<Type, object> queryCache;
public EntityFrameworkDataContext(ObjectContext context)
{
this.context = context;
queries = new Dictionary<Type, PropertyInfo>();
inserts = new Dictionary<Type, MethodInfo>();
queryCache = new Dictionary<Type, object>();
var queryType = typeof (ObjectQuery<>);
var contextType = context.GetType();
var queryProperties = contextType.GetProperties().Where(p => IsGenericType(p.PropertyType, queryType));
foreach (var queryProperty in queryProperties)
{
var genericType = queryProperty.PropertyType.GetGenericArguments().First();
queries[genericType] = queryProperty;
var addMethod = contextType.GetMethods().FirstOrDefault(m => IsAddToMethod(m, genericType));
if (addMethod != null)
{
inserts[genericType] = addMethod;
}
}
}
static bool IsGenericType(Type type, Type genericType)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == genericType;
}
static bool IsAddToMethod(MethodInfo method, Type genericType)
{
if (!method.Name.StartsWith("AddTo")) return false;
var paramaters = method.GetParameters();
if (paramaters.Count() != 1) return false;
return paramaters[0].ParameterType == genericType;
}
public IQueryable<T> Query<T>() where T : class
{
var type = typeof (T);
if (queryCache.ContainsKey(type))
{
return (ObjectQuery<T>)queryCache[type];
}
if (!queries.ContainsKey(type))
{
throw new NotImplementedException();
}
var queryProperty = queries[type];
var query = queryProperty.GetGetMethod().Invoke(context, new object[0]);
queryCache[type] = query;
return (ObjectQuery<T>)query;
}
public void Insert<T>(T entity) where T : class
{
var type = typeof(T);
if (!inserts.ContainsKey(type))
{
throw new NotImplementedException();
}
var insertMethod = inserts[type];
insertMethod.Invoke(context, new object[] { entity });
}
public void Delete<T>(T entity) where T : class
{
context.DeleteObject(entity);
}
public void SubmitChanges()
{
context.SaveChanges();
}
public int ExecuteCommand(string command, params object[] parameters)
{
throw new NotImplementedException();
}
public IEnumerable<TResult> ExecuteQuery<TResult>(string query, params object[] parameters)
{
throw new NotImplementedException();
}
public void Dispose()
{
context.Dispose();
}
}
}
|
dff5700aee2078287bb71305d69fdc75a809834f
|
C#
|
dimaserd/Runtasker
|
/UI.Settings/Settings/Models/AtroposHeaderSettings.cs
| 2.84375
| 3
|
using System.ComponentModel.DataAnnotations;
using UI.Settings.Entities;
namespace UI.Settings
{
/// <summary>
/// Статический класс настроек шаблона Atropos Responsive
/// </summary>
public static class AtroposHeaderSettings
{
#region Поля
public static int HeaderHeight = 60;
public static bool UseMyColor = false;
public static RGBAColor HeaderColor = null;
public static bool HasFirstLine = true;
public static bool UseLeftLineHtml = false;
public static string LeftLineHtml = "";
public static bool UseRightLineHtml = false;
public static string RightLineHtml = "";
#endregion
#region Методы
public static void ChangeSettings(AtroposHeaderSettingsModel model)
{
UseMyColor = model.UseMyColor;
HeaderColor = model.HeaderColor;
HeaderHeight = model.HeaderHeight;
HasFirstLine = model.HasFirstLine;
UseLeftLineHtml = model.UseLeftLineHtml;
LeftLineHtml = model.LeftLineHtml;
UseRightLineHtml = model.UseRightLineHtml;
RightLineHtml = model.RightLineHtml;
}
public static AtroposHeaderSettingsModel GetSettings()
{
return new AtroposHeaderSettingsModel
{
HeaderHeight = HeaderHeight,
UseMyColor = UseMyColor,
HeaderColor = HeaderColor,
HasFirstLine = HasFirstLine,
LeftLineHtml = LeftLineHtml,
UseLeftLineHtml = UseLeftLineHtml,
UseRightLineHtml = UseRightLineHtml,
RightLineHtml = RightLineHtml
};
}
public static string GetStylesString()
{
string styleString = string.Empty;
if (UseMyColor)
{
styleString += $"background:rgba({HeaderColor.R}, {HeaderColor.G}, {HeaderColor.B}, {HeaderColor.A});";
}
return styleString;
}
#endregion
}
public class AtroposHeaderSettingsModel
{
[Display(Name = "Высота шапки")]
public int HeaderHeight { get; set; }
public bool UseMyColor { get; set; }
public RGBAColor HeaderColor { get; set; }
[Display(Name = "Показывать верхний кусок")]
public bool HasFirstLine { get; set; }
[Display(Name = "Использовать свой HTML слева")]
public bool UseLeftLineHtml { get; set; }
[Display(Name = "HTML слева")]
public string LeftLineHtml { get; set; }
[Display(Name = "Использовать свой HTML справа")]
public bool UseRightLineHtml { get; set; }
[Display(Name = "HTML справа")]
public string RightLineHtml { get; set; }
}
}
|
eb1d0d9f07ac782ec99571535041c451d0161b81
|
C#
|
gustavobruder/Curso-CSharp
|
/A.Logica.Programacao/Aula02/VariaveisEspeciais.cs
| 2.875
| 3
|
using System;
namespace A.Logica.Programacao.Aula02
{
public class VariaveisEspeciais
{
public static void Executar()
{
char letra = '\u0041';
string nome = "Gustavo";
object obj1 = "Alex Brown";
object obj2 = 4.5F;
Console.WriteLine(letra);
Console.WriteLine(nome);
Console.WriteLine(obj1);
Console.WriteLine(obj2);
}
}
}
|
fc20ca6b4219c113376febad176e61668fcee8a0
|
C#
|
VBonapartov/SoftUni-Studies
|
/CSharp OOP Advanced/02. SOLID - Exercise/01. Logger/Program.cs
| 2.671875
| 3
|
namespace _01._Logger
{
using System.Collections.Generic;
using _01._Logger.Controllers;
using _01._Logger.Entities;
using _01._Logger.Factories;
using _01._Logger.Interfaces;
public class Program
{
public static void Main(string[] args)
{
IList<IAppender> appenders = new List<IAppender>();
LayoutFactory layoutFactory = new LayoutFactory();
AppenderFactory appenderFactory = new AppenderFactory(layoutFactory);
ErrorFactory errorFactory = new ErrorFactory();
Controller controller = new Controller(appenders, appenderFactory, errorFactory);
controller.ReadAppendersFromConsole();
ILogger logger = new Logger(new List<IAppender>(controller.Appenders).ToArray());
controller.ExecuteCommands(logger);
}
}
}
|
c95a4f003e3bf76619a7bb8e4e679cf5479debac
|
C#
|
OdooBulgaria/ErpNet.FP
|
/ErpNet.FP.Core/Drivers/BgDatecs/BgDatecsXIslFiscalPrinter.Frame.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ErpNet.FP.Core.Drivers.BgDatecs
{
/// <summary>
/// Fiscal printer using the ISL implementation of Datecs Bulgaria.
/// </summary>
/// <seealso cref="ErpNet.FP.Drivers.BgIslFiscalPrinter" />
public partial class BgDatecsXIslFiscalPrinter : BgIslFiscalPrinter
{
protected override byte[] BuildHostFrame(byte command, byte[]? data)
{
// Frame header
var frame = new List<byte>();
frame.Add(MarkerPreamble);
frame.AddRange(UInt16To4Bytes((UInt16)(MarkerSpace + 10 + (data != null ? data.Length : 0))));
frame.Add((byte)(MarkerSpace + FrameSequenceNumber));
frame.AddRange(UInt16To4Bytes((UInt16)command));
// Frame data
if (data != null)
{
frame.AddRange(data);
}
// Frame footer
frame.Add(MarkerPostamble);
frame.AddRange(ComputeBCC(frame.Skip(1).ToArray()));
frame.Add(MarkerTerminator);
return frame.ToArray();
}
protected override (string, DeviceStatus) ParseResponse(byte[]? rawResponse)
{
if (rawResponse == null)
{
throw new InvalidResponseException("no response");
}
var (preamblePos, separatorPos, postamblePos, terminatorPos) = (0u, 0u, 0u, 0u);
for (var i = 0u; i < rawResponse.Length; i++)
{
var b = rawResponse[i];
switch (b)
{
case MarkerPreamble:
preamblePos = i;
break;
case MarkerSeparator:
separatorPos = i;
break;
case MarkerPostamble:
postamblePos = i;
break;
case MarkerTerminator:
terminatorPos = i;
break;
}
}
if (preamblePos + 10 <= separatorPos && separatorPos + 8 < postamblePos && postamblePos + 4 < terminatorPos)
{
var data = rawResponse.Slice(preamblePos + 10, separatorPos);
var status = rawResponse.Slice(separatorPos + 1, postamblePos);
var bcc = rawResponse.Slice(postamblePos + 1, terminatorPos);
var computedBcc = ComputeBCC(rawResponse.Slice(preamblePos + 1, postamblePos + 1));
if (bcc.SequenceEqual(computedBcc))
{
// For debugging purposes only (to view status bits)
var deviceID = (Info == null ? "" : Info.SerialNumber);
System.Diagnostics.Debug.WriteLine($"Status of device {deviceID}");
for (var i = 0; i < status.Length; i++)
{
byte mask = 0b10000000;
byte b = status[i];
// Ignore j==0 because bit 7 is always reserved and 1
for (var j = 1; j < 8; j++)
{
mask >>= 1;
if ((mask & b) == mask)
{
System.Diagnostics.Debug.Write($"{i}.{7 - j} ");
}
}
}
System.Diagnostics.Debug.WriteLine("");
var response = Encoding.UTF8.GetString(data);
System.Diagnostics.Debug.WriteLine($"Response: {response}");
return (response, ParseStatus(status));
}
}
throw new InvalidResponseException("the response is invalid");
}
}
}
|
333e292fd968950b7782140d8d67fb50d0b2342e
|
C#
|
OneLuminare/Compiler-Design-Class
|
/Compiler/NFLanguageCompiler/NFLanguageCompiler/ExprASTNode.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NFLanguageCompiler
{
// Abstract base class for expression type ASTNodes.
//
// Base: ASTNode
public abstract class ExprASTNode : ASTNode
{
#region Constructors
// Default constructor
public ExprASTNode()
:base(ASTNodeType.ASTTYPE_EXPR)
{
}
public ExprASTNode(ASTNodeType nodeType)
: base(nodeType)
{
}
#endregion
#region Object Overrides
public override string ToString()
{
String ret = null;
ret = "Base EXPR AST node.";
return ret;
}
#endregion
}
}
|
e161e35c168d7268510e706a1ff50679f2a1fb73
|
C#
|
unibuc-cs/pet-owner-api
|
/Controllers/TipController.cs
| 2.703125
| 3
|
using Microsoft.AspNetCore.Mvc;
using PetOwner.Models;
using PetOwner.Repository.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace PetOwner.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TipController : ControllerBase
{
private readonly ITipRepository _tipRepository;
public TipController(ITipRepository tipRepository)
{
_tipRepository = tipRepository;
}
// GET: api/<TipController>
[HttpGet]
public ActionResult<List<Tip>> Get()
{
var tips = _tipRepository.GetAll();
if (tips != null)
return Ok(tips);
return Ok("eroare");
}
// GET api/<TipController>/5
[HttpGet("{id}")]
public ActionResult<Tip> Get(int id)
{
return Ok(_tipRepository.Get(id));
}
[HttpGet("title/{title}")]
public ActionResult<List<Tip>> GetByTitle(string title)
{
var tip = _tipRepository.GetByTitle(title);
if (tip != null)
return Ok(tip);
return Ok("Not Found");
}
// POST api/<TipController>
[HttpPost]
public ActionResult Post([FromBody] Tip value)
{
_tipRepository.Insert(value);
if (_tipRepository.Save())
{
var id = _tipRepository.GetByTitle(value.Title).FirstOrDefault().TipId;
return Ok(new {tipid = id });
}
return Ok("eroare");
}
// PUT api/<TipController>/5
[HttpPut("{id}")]
public ActionResult Put(int id, [FromBody] Tip value)
{
var T = _tipRepository.Get(id);
if (T == null) return Ok("eroare");
if (value.Title != null) T.Title = value.Title;
if (value.Description != null) T.Description = value.Description;
if (value.Category != null) T.Category = value.Category;
if (value.Race != null) T.Race = value.Race;
if (value.Species != null) T.Species = value.Species;
if (_tipRepository.Save()) return Ok();
return Ok("eroare");
}
// DELETE api/<TipController>/5
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
_tipRepository.Delete(_tipRepository.Get(id));
if (_tipRepository.Save()) return Ok();
return Ok("eroare");
}
}
}
|
2c1e29e1b9ad9c9b9ea08f96b36c1d57969011b6
|
C#
|
PavelAnufriev/-
|
/7 ZADACHA.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Globalization;
namespace _7_zadacha
{
class Program
{
static string Hamming(string text, int degree = 4)//7 800
{
//degree - степень двойки, т е 2^degree == разряд
for (int i = 0, j = 0; i < degree + 1; j += (int)Math.Pow(2, i), i++)
{
text = text.Insert(j, "0");
}
//Console.WriteLine(text);
int n = text.Length;
char[] buff = text.ToCharArray();
for (int i = 0, N = 0; i < degree + 1; N += (int)Math.Pow(2, i), i++)
{
int sum = 0;
for (int j = N; j < n; j += N + 1)
{
for (int c = 0; c < N + 1; c++, j++)
{
if (j < n)
{
sum += int.Parse($"{ buff[j]}");
}
else
break;
}
}
buff[N] = char.Parse($"{sum % 2}");
//Console.WriteLine(buff);
}
return new string(buff);
}
static string Hamming2(string text = "01000100001111010011111001001000", int degree = 4)
{
string result = "";
char[] buff = new char[(int)Math.Pow(2, degree)];
for (int i = 0; i < text.Length;)
{
for (int j = 0; j < buff.Length; j++, i++)
{
if (i > text.Length - 1)
return "неверная степень";
buff[j] = text[i];
}
result += Hamming(new string(buff), degree);
}
return result;
}
static double Сheck(bool mod = true, double inf = 1000)//проверка ввода числа ?????
{
double to = 0;
bool flag = true;
IFormatProvider formatter = new NumberFormatInfo { NumberDecimalSeparator = "." };
while (flag)
{
try
{
string from = Console.ReadLine();
to = Double.Parse(from.Replace(',', '.'), CultureInfo.InvariantCulture);
flag = false;
if (to < 0 && mod)
{
flag = true;
}
}
catch (Exception e)
{
Console.WriteLine("ошибка ввода. введите число (цифру)");
}
if (to > inf)
{
flag = true;
Console.WriteLine("число больше заданного диапазона");
}
}
return to;
}
static void Main(string[] args)
{
Console.WriteLine("Задание 7");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Задано содержимое информационных разрядов кодового слова кода Хэмминга");
Console.WriteLine("Добавить контрольные разряды и заполнить их");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("пример ввода 01000100001111010011111001001000, 4");
Console.ResetColor();
Console.ResetColor();
Console.WriteLine("введите число 0 и 1 не меньше 8 и более (обязательно кратно 8)");
Console.WriteLine("а затем количество разрядов ()");
string t = Hamming2(Console.ReadLine(), (int)Сheck());
Console.WriteLine("введите количество контрольных разрядов");
Console.WriteLine(t);
Console.ReadKey();
}
}
}
|
d48242c85b281ecaa920402d369c42b53a2e519e
|
C#
|
ePayment/account
|
/DAL/SqlServer/Errors.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Account.Common.Entities;
namespace Account.Data.SqlServer
{
public partial class D_Error:SqlServerHelper
{
private Error_Info GenerateObject(DataRow row)
{
Error_Info ei = new Error_Info();
if (row == null)
throw new Exception("obj invalid");
if (row["Code"] != DBNull.Value)
ei.Code = Convert.ToInt32(row["Code"]);
if (row["EN"] != DBNull.Value)
ei.EN_Message = Convert.ToString(row["EN"]);
if (row["VN"] != DBNull.Value)
ei.VN_Message = Convert.ToString(row["VN"]);
if (row["ISO8583"] != DBNull.Value)
ei.ISO8583 = Convert.ToString(row["ISO8583"]);
return ei;
}
public List<Error_Info> GetAllErrors()
{
DataSet ds = new DataSet();
SqlConnection objconn = new SqlConnection(GetConnectionString());
SqlCommand command = new SqlCommand("Select * From Error_Detail", objconn);
command.CommandType = CommandType.Text;
try
{
objconn.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
return null;
List<Error_Info> list = new List<Error_Info>();
foreach (DataRow row in ds.Tables[0].Rows)
{ list.Add(GenerateObject(row)); }
return list;
}
catch (System.Exception ex)
{
Logger.Error(ex);
throw ex;
}
finally
{
objconn.Close();
}
}
public Error_Info GetOneError(int code)
{
{
DataSet ds = new DataSet();
SqlConnection objconn = new SqlConnection(GetConnectionString());
SqlCommand command = new SqlCommand("Select * From Error_Detail Where Code = @Code", objconn);
command.CommandType = CommandType.Text;
command.Parameters.Clear();
command.Parameters.Add("@Code", SqlDbType.Int).Value = code;
try
{
objconn.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
return null;
return GenerateObject(ds.Tables[0].Rows[0]);
}
catch (System.Exception ex)
{
Logger.Error(ex);
throw ex;
}
finally
{
objconn.Close();
}
}
}
}
}
|
ffc92342d16d00f0455ca7f5f89f2e488b894ff6
|
C#
|
CommunityToolkit/WindowsCommunityToolkit
|
/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/IObjectSerializer.cs
| 2.609375
| 3
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.Toolkit.Uwp.Helpers
{
/// <summary>
/// A basic serialization service.
/// </summary>
[Obsolete("IObjectSerializer has been migrated to the Microsoft.Toolkit (CommunityToolkit.Common) package.")]
public interface IObjectSerializer
{
/// <summary>
/// Serialize an object into a string. It is recommended to use strings as the final format for objects if you plan to use the <see cref="BaseObjectStorageHelper.SaveFileAsync{T}(string, T)"/> method.
/// </summary>
/// <typeparam name="T">The type of the object to serialize.</typeparam>
/// <param name="value">The object to serialize.</param>
/// <returns>The serialized object.</returns>
object Serialize<T>(T value);
/// <summary>
/// Deserialize a primitive or string into an object of the given type.
/// </summary>
/// <typeparam name="T">The type of the deserialized object.</typeparam>
/// <param name="value">The string to deserialize.</param>
/// <returns>The deserialized object.</returns>
T Deserialize<T>(object value);
}
}
|
08afd8f35b6f056b77b5084c1bf730d27743b066
|
C#
|
EnsarErayAkkaya/Only-Shield
|
/Assets/Scripts/Enemy/RangeEnemy.cs
| 2.6875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RangeEnemy : EnemyBase
{
Transform target;
public GameObject projectile;
public float shootingDist;
public bool canShoot;
public float timeBetweenShots;
public float projectileDistanceToCenter;
float remainingtTmeBetweenShots;
private void Start()
{
target = FindObjectOfType<Player>().transform;
remainingtTmeBetweenShots = timeBetweenShots;
}
private void Update()
{
Shoot();
}
void Shoot()
{
if ( canShoot && Vector3.Distance(target.position, transform.position) < shootingDist )
{
if(remainingtTmeBetweenShots <= 0)
{
Vector2 dir = (target.position - transform.position).normalized * projectileDistanceToCenter;
Vector2 pos = new Vector2(transform.position.x + dir.x,transform.position.y+ dir.y);
Instantiate(projectile, pos, Quaternion.identity);
remainingtTmeBetweenShots = timeBetweenShots;
}
else
{
remainingtTmeBetweenShots -= Time.deltaTime;
}
}
}
}
|
49cb5f22d36509c1bef27569160313de3ae8dea2
|
C#
|
tanqinliang/Shopping-Mall
|
/CoreDemo/DBAccess/DbFactory.cs
| 2.875
| 3
|
/******************************************************************
* Author :谭清亮
* Date :2017-12-26
* Description :获取数据库对象
******************************************************************/
using System;
namespace DBAccess
{
public class DbFactory
{
/// <summary>
/// 返回数据库对象
/// </summary>
/// <param name="sCacheKey">数据库类型</param>
/// <returns></returns>
public static IDatabase Create(string sCacheKey)
{
//根据传入的不同数据库类型,反射到不同的工具类
object obj = Activator.CreateInstance(Type.GetType(sCacheKey));
return (IDatabase)obj;
}
}
}
|
7131991f81e586d1c56ce64d3b5c7e454af776c2
|
C#
|
bogdansimion31/University
|
/Semester3/Advanced Programming Methods/Labs/StudentsManagementAppC#/StudentsManagementApp/domain/validator/GradeValidator.cs
| 3.1875
| 3
|
using System;
using StudentsManagementApp.domain.entities;
namespace StudentsManagementApp.domain.validator
{
public class GradeValidator : IValidator<Grade>
{
/// <inheritdoc />
/// <summary>
/// Function to validate a grade
/// </summary>
/// <param name="entity">Grade to be validated</param>
/// <exception cref="ValidatorException">Throws exception if grade fields are incorrect!</exception>
public void Validate(Grade entity)
{
var errs = "";
if (entity.GetStudId() < 0)
{
errs += "Student id must be a positive integer!\n";
}
if (entity.GetHwId().Equals(""))
{
errs += "Homework Id can't be an empty string!\n";
}
if (entity.GradeValue < 0.0 || entity.GradeValue > 10.0)
{
errs += "Grade value must be a real number between 0 and 10\n";
}
if (entity.Professor.Equals(""))
{
errs += "Professor field can't be empty!\n";
}
if (entity.FeedBack.Equals(""))
{
errs += "Feedback field can't be empty!\n";
}
if (!string.IsNullOrEmpty(errs))
{
throw new ValidatorException(errs);
}
}
}
}
|
4a21a8f1d1610fdbef795a77a3b18709856021ad
|
C#
|
martin-chambers/AzureBlobDemo
|
/AzureBlobDemo/Program.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System.IO;
using System.Configuration;
namespace AzureBlobDemo
{
// illustration of writing to Azure BLOB storage based on this blog:
// https://www.simple-talk.com/cloud/cloud-data/an-introduction-to-windows-azure-blob-storage-/
class Program
{
static void Main(string[] args)
{
string accountName = ConfigurationManager.AppSettings["AccountName"];
string accountKey = ConfigurationManager.AppSettings["AccountKey"];
string uploadPath = @"C:\test\azb\cliff_drop.jpg";
string blobRef = "APictureFile.jpg";
string downloadPath = @"C:\test\azb\download\cliff_drop.jpg";
// (1) upload
Upload(uploadPath, blobRef, accountName, accountKey);
// (2) download
Download(downloadPath, blobRef, accountName, accountKey);
Console.WriteLine("Done... press a key to end.");
Console.ReadKey();
}
static public void Upload(string filepath, string blobname, string accountName, string accountKey)
{
try
{
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer sampleContainer = client.GetContainerReference("public-samples");
sampleContainer.CreateIfNotExists();
// for public access ////
BlobContainerPermissions permissions = new BlobContainerPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
sampleContainer.SetPermissions(permissions);
/////////////////////////
CloudBlockBlob blob = sampleContainer.GetBlockBlobReference(blobname);
using (Stream file = File.OpenRead(filepath))
{
blob.UploadFromStream(file);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
static public void Download(string filepath, string blobname, string accountName, string accountKey)
{
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer sampleContainer = client.GetContainerReference("public-samples");
CloudBlockBlob blob = sampleContainer.GetBlockBlobReference(blobname);
blob.DownloadToFile(filepath, FileMode.Create);
}
}
}
|
9913a1420f8ad9f88bf2436be0bad73cb5b05c2f
|
C#
|
go-green/PayRoll
|
/PayRoll.Core/Tax/TaxBandTwo.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PayRoll.Core.Tax
{
public class TaxBandTwo : TaxBase
{
public TaxBandTwo()
{
this.RuleID = 2;
this.LowerLimit = 18200;
this.UpperLimit = 37000;
this.FixedRate = 0.19M;
this.FixedAmount = 0;
this.LimitDifference = UpperLimit - LowerLimit;
}
public override uint Calculate(uint amount)
{
if (!FallsUnderCurrentBand(amount)) return 0;
var rawIncomeTax = (FixedRate * GetPayAmountOverLowerLimit(amount))/12;
var roundedIncomeTax = Math.Round(rawIncomeTax, MidpointRounding.AwayFromZero);
return Convert.ToUInt32(roundedIncomeTax);
}
}
}
|
43bee0296b1bd7243a99e5bf83e76f2d12dee69c
|
C#
|
WellFiredDevelopment/WellFired.Direct
|
/unity/Assets/WellFired/WellFired.Direct/Platform/Uncompiled/Runtime/Sequencer Events/Object/USEnableComponentEvent.cs
| 2.53125
| 3
|
using UnityEngine;
using System.Collections;
namespace WellFired
{
/// <summary>
/// A custom event that will set a GameObject's specific component enable state at a given time.
/// </summary>
[USequencerFriendlyName("Toggle Component")]
[USequencerEvent("Object/Toggle Component")]
[USequencerEventHideDuration()]
public class USEnableComponentEvent : USEventBase
{
/// <summary>
/// Should we enable the object at the given time.
/// </summary>
public bool enableComponent = false;
private bool prevEnable = false;
[HideInInspector]
[SerializeField]
private string componentName;
public string ComponentName
{
get { return componentName; }
set { componentName = value; }
}
public override void FireEvent()
{
var component = AffectedObject.GetComponent(ComponentName) as Behaviour;
if(!component)
return;
prevEnable = component.enabled;
component.enabled = enableComponent;
}
public override void ProcessEvent(float deltaTime)
{
}
public override void StopEvent()
{
UndoEvent();
}
public override void UndoEvent()
{
if(!AffectedObject)
return;
var component = AffectedObject.GetComponent(ComponentName) as Behaviour;
if(!component)
return;
component.enabled = prevEnable;
}
}
}
|
c0b5b6ff82525237951eea2870ce1fc91a645f00
|
C#
|
eeee386/CrackTheCodingInterview
|
/Solutions/StacksAndQueues/SetOfStacks.cs
| 3.84375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Solutions.StacksAndQueues
{
public class SetOfStacks<T>
{
private Stack<T> _activeStack = new Stack<T>();
private readonly HashSet<Stack<T>> setOfStacks = new HashSet<Stack<T>>();
private int _activeStackNumberOfItems = 0;
private readonly int capacity = 10;
public SetOfStacks()
{
setOfStacks.Add(_activeStack);
}
public void Add(T data)
{
if (_activeStackNumberOfItems == capacity)
{
Stack<T> newStack = new Stack<T>();
newStack.Push(data);
setOfStacks.Add(newStack);
_activeStack = newStack;
}
else
{
_activeStack.Push(data);
_activeStackNumberOfItems++;
}
}
public T Pop()
{
T data = _activeStack.Pop();
if (_activeStackNumberOfItems != 0) return data;
if (setOfStacks.Count == 1) return data;
setOfStacks.Remove(_activeStack);
_activeStack = setOfStacks.Last();
return data;
}
//For this the set could be changed for Array for easier access.
public T PopAtSpecifiedStack(int index)
{
if (setOfStacks.Count - 1 < index)
{
throw new Exception("You cannot pop from a non-existent Stack!");
}
int counter = 0;
foreach (Stack<T> stack in setOfStacks)
{
if (counter == index)
{
return stack.Pop();
}
counter++;
}
throw new Exception("Invalid execution of method.");
}
}
}
|
c32096aa2e0b153f843361e137046c880d2179bb
|
C#
|
shendongnian/download4
|
/code6/974008-24722183-69237063-2.cs
| 2.875
| 3
|
class Model : INotifyPropertyChanged
{
private int _Name = default(int);
public int Name
{
get { return _Name; }
set
{
SetValue(ref this._Name, value);
}
}
private void SetValue<T>(ref T property, T value, [CallerMemberName]string propertyName = null)
{
if (object.Equals(property, value) == false)
{
property = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
|
f9b47d2b0a2d55814f1840170ea7bf8f8b00e288
|
C#
|
RoseHlahane/UltraManufacturing
|
/UltraManufacturing/Services/Cryptography.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace UltraManufacturing.Services
{
public class Cryptography
{
public string HashSHA256(string value)
{
var stringBuilder = new StringBuilder();
using (var hash = SHA256.Create())
{
var encrypt = Encoding.UTF8;
var result = hash.ComputeHash(encrypt.GetBytes(value));
foreach (var b in result)
stringBuilder.Append(b.ToString("x2"));
}
return stringBuilder.ToString();
}
//MSDN code
public byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (Aes aesAlgorithm = Aes.Create())
{
aesAlgorithm.Key = Key;
aesAlgorithm.IV = IV;
// create a decryptor
ICryptoTransform encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV);
using (MemoryStream memoryStreamEncrypt = new MemoryStream())
{
using (CryptoStream cryptoStreamEncrypt = new CryptoStream(memoryStreamEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriterEncrypt = new StreamWriter(cryptoStreamEncrypt))
{
// add all the data to the stream
streamWriterEncrypt.Write(plainText);
}
encrypted = memoryStreamEncrypt.ToArray();
}
}
}
return encrypted;
}
public string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// this is the string the contains the decrypted text
string plainText = null;
using (Aes aesAlgorithm = Aes.Create())
{
aesAlgorithm.Key = Key;
aesAlgorithm.IV = IV;
ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV);
// creating the streams for decryption
using (MemoryStream memoryStreamDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream cryptoStreamDecrypt = new CryptoStream(memoryStreamDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReaderDecrypt = new StreamReader(cryptoStreamDecrypt))
{
// read the decrypted bytes and add them to a string
plainText = streamReaderDecrypt.ReadToEnd();
}
}
}
}
return plainText;
}
}
}
|
158dd51edbd9344688f72f49ccd45f92ef47d53e
|
C#
|
DokuzEylulCsc/odev2-simgeakosman
|
/Converter/Converter/Form1.cs
| 2.875
| 3
|
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 Converter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Convert.ToInt32(textBox1.Text);
if (Convert.ToInt32(textBox1.Text) <= 3999 && Convert.ToInt32(textBox1.Text) > 0)
{
ConvertRoman(Convert.ToInt32(textBox1.Text));
}
else MessageBox.Show("Sayı Limitini aştınız");
textBox1.Clear();
}
catch
{
if(textBox1.Text.Contains('ı'))
textBox1.Text.Replace('ı', 'i');
textBox1.CharacterCasing = CharacterCasing.Upper;
string[] red = new string[7]
{
"IIII",
"VVVV",
"XXXX",
"LLLL",
"CCCC",
"MMMM",
"DDDD"
};
for (int i = 0; i < red.Length; i++)
{
if (textBox1.Text.Contains(red[i]))
{
MessageBox.Show("Yan yana en fazla 3 Karakter girebilirsiniz");
textBox1.Clear();
}
}
if ((ConvertDecimal(textBox1.Text)) != 0)
MessageBox.Show(ConvertDecimal(textBox1.Text).ToString());
textBox1.Clear();
}
}
public int ConvertDecimal(string rom)
{
char[] textkarakter = new char[rom.Length];
textkarakter = rom.ToCharArray();
int result = 0;
for (int i = 0; i < rom.Length; i++)
{
if (i + 1 < rom.Length)
{
if ((RomeenListe(textkarakter[i].ToString())) == 0)
{
textBox1.Clear();
result = 0;
goto end_;
}
//Hatalı Giriş sebebleri
//Sadece I, X ve C rakamları, kendinin en fazla 10 katı büyük bir rakamdan önce yazılabilir
// (Örneğin V den önce I veya X'den önce I yazılabilir. C'den önce I olmaz.)xıc olmamalı. Olması gereken cıx
//Soldaki deger sagdaki degerden buyuk olmalı ıxc olmamalı
// V, L, D karakterleri bitişik olarak tekrar edemez.
if ((RomeenListe(textkarakter[i].ToString()) == 1))
{
if (((RomeenListe(textkarakter[i + 1].ToString()) >= 50)))
{
MessageBox.Show("Hatalı Giriş Yaptınız");
textBox1.Clear();
result = 0;
goto end_;
}
}
if ((RomeenListe(textkarakter[i].ToString()) == 5))
{
if (((RomeenListe(textkarakter[i + 1].ToString()) >= 5)))
{
MessageBox.Show("Hatalı Giriş Yaptınız");
textBox1.Clear();
result = 0;
goto end_;
}
}
if ((RomeenListe(textkarakter[i].ToString()) == 10))
{
if (((RomeenListe(textkarakter[i + 1].ToString()) >= 500)))
{
MessageBox.Show("Hatalı Giriş Yaptınız");
textBox1.Clear();
result = 0;
goto end_;
}
}
if ((RomeenListe(textkarakter[i].ToString()) == 50))
{
if (((RomeenListe(textkarakter[i + 1].ToString()) >= 50)))
{
MessageBox.Show("Hatalı Giriş Yaptınız");
textBox1.Clear();
result = 0;
goto end_;
}
}
if ((RomeenListe(textkarakter[i].ToString()) == 500))
{
if (((RomeenListe(textkarakter[i + 1].ToString()) != 500)))
{
MessageBox.Show("Hatalı Giriş Yaptınız");
textBox1.Clear();
result = 0;
goto end_;
}
}
for ( int k = 2; k <= rom.Length; k++)
{
if (RomeenListe(textkarakter[0].ToString()) < (RomeenListe(textkarakter[i].ToString())))
{
MessageBox.Show("Hatalı Giriş Yaptınız");
textBox1.Clear();
result = 0;
goto end_;
}
}
if (RomeenListe(textkarakter[i].ToString()) >= RomeenListe(textkarakter[i + 1].ToString()))
{
result = result + RomeenListe(textkarakter[i].ToString());
}
else
{
result = result + RomeenListe(textkarakter[i + 1].ToString()) - RomeenListe(textkarakter[i].ToString());
i++;
}
}
else
{
result = result + RomeenListe(textkarakter[i].ToString());
}
}
if (result > 3999)
{
result = 0;
MessageBox.Show("Limiti aştınız lütfen tekrar deneyin");
textBox1.Clear();
}
end_:
return result;
}
public int RomeenListe(string a)
{
int value=0;
switch (a)
{
case "I": value= 1; break;
case "ı": value= 1; break;
case "V": value= 5; break;
case "L": value= 50; break;
case "X": value= 10; break;
case "C": value= 100; break;
case "D": value= 500; break;
case "M": value= 1000;break;
default: value = 0; MessageBox.Show("Karakter tanımlı değil"); break;
}
return value;
}
public void ConvertRoman(int value)
{
string M, C, I, X;
M = Thousand((value / 1000) % 10);
C = hundred((value / 100) % 10);
X = ten((value / 10) % 10);
I = ones(value % 10);
MessageBox.Show(M + C + X + I);
}
public string Thousand(int k4)
{
string value = "";
switch (k4)
{
case 1: value = "M"; break;
case 2: value = "MM"; break;
case 3: value = "MMM"; break;
default: break;
}
return value;
}
public string hundred(int k1)
{
string value = "";
switch (k1)
{
case 1: value = "C"; break;
case 2: value = "CC"; break;
case 3: value = "CCC"; break;
case 4: value = "CD"; break;
case 5: value = "D"; break;
case 6: value = "DC"; break;
case 7: value = "DCC"; break;
case 8: value = "DCCC"; break;
case 9: value = "CM"; break;
default: break;
}
return value;
}
public string ten(int k2)
{
string value = "";
switch (k2)
{
case 1: value = "X"; break;
case 2: value = "XX"; break;
case 3: value = "XXX"; break;
case 4: value = "XL"; break;
case 5: value = "L"; break;
case 6: value = "LX"; break;
case 7: value = "LXX"; break;
case 8: value = "LXXX"; break;
case 9: value = "XC"; break;
default: break;
}
return value;
}
public string ones(int k3)
{
string value = "";
switch (k3)
{
case 1: value = "I"; break;
case 2: value = "II"; break;
case 3: value = "III"; break;
case 4: value = "IV"; break;
case 5: value = "V"; break;
case 6: value = "VI"; break;
case 7: value = "VII"; break;
case 8: value = "VIII"; break;
case 9: value = "IX"; break;
default: break;
}
return value;
}
private void Form1_Load(object sender, EventArgs e)
{
Form form = new Form();
form.AcceptButton = button1;
}
}
}
|
22304f87031913db90e6532bbb5f515d513dff9c
|
C#
|
giacomelli/GeneticSharp
|
/src/GeneticSharp.Benchmarks/GeneticAlgorithmsBenchmark.cs
| 2.765625
| 3
|
using System;
using BenchmarkDotNet.Attributes;
using GeneticSharp.Extensions;
namespace GeneticSharp.Benchmarks
{
[Config(typeof(DefaultConfig))]
public class GeneticAlgorithmsBenchmark
{
private const int _minPopulationSize = 50;
private const int _generations = 1000;
private const int _numberOfCities = 100;
[Benchmark]
public GeneticAlgorithm LinearTaskExecutor()
{
var ga = CreateGA();
ga.TaskExecutor = new LinearTaskExecutor();
ga.Start();
return ga;
}
[Benchmark]
public GeneticAlgorithm ParallelTaskExecutor()
{
var ga = CreateGA();
ga.TaskExecutor = new ParallelTaskExecutor();
ga.Start();
return ga;
}
[Benchmark]
public GeneticAlgorithm TplTaskExecutor()
{
var ga = CreateGA(c => new TplPopulation(_minPopulationSize, _minPopulationSize, c));
ga.OperatorsStrategy = new TplOperatorsStrategy();
ga.TaskExecutor = new TplTaskExecutor();
ga.Start();
return ga;
}
private GeneticAlgorithm CreateGA(Func<TspChromosome, Population> createPopulation = null)
{
var selection = new EliteSelection();
var crossover = new OrderedCrossover();
var mutation = new ReverseSequenceMutation();
var chromosome = new TspChromosome(_numberOfCities);
var fitness = new TspFitness(_numberOfCities, 0, 1000, 0, 1000);
var population = createPopulation == null
? new Population(_minPopulationSize, _minPopulationSize, chromosome)
: createPopulation(chromosome);
population.GenerationStrategy = new PerformanceGenerationStrategy();
var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
{
Termination = new GenerationNumberTermination(_generations)
};
return ga;
}
}
}
|
ebe8b138c038ffdb84c394c2161ddcb7379e0096
|
C#
|
jpumph029/Lab07-Collections
|
/Lab07_Collections/Classes/Card.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Lab07_Collections.Classes
{
public class Card
{
public Suit suit { get; set; }
public Value value { get; set; }
public enum Suit { Clubs, Diamonds, Heats, Spades}
public enum Value { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }
}
}
|
20ab8aa97252c078c0887b45f3d1315a05545a6a
|
C#
|
ConfirmitYaroslavlStudents/Students
|
/2015/Bolshakov/MP3_tager/FolderLib/FolderProcessor.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using Mp3Handler;
namespace FolderLib
{
public class FolderProcessor
{
public FolderProcessor(IFolderHandler folderHandler, IFileHandler fileHandler)
{
_folderHandler = folderHandler;
_lateFileHandler = new LateWriteFileHandler(fileHandler);
}
public FolderProcessor()
{
_folderHandler = new FolderHandler();
FileHandlerBuilder();
}
public LateWriteFileHandler LateFileHandler
{
get { return _lateFileHandler; }
}
public Dictionary<string,Dictionary<FrameType,TagDifference>> GetDifferences(string path, string pattern)
{
var files = _folderHandler.GetAllMp3s(path);
if (files.Count == 0)
return null;
var mp3Processor = new Mp3FileProcessor(_lateFileHandler);
var differences = new Dictionary<string, Dictionary<FrameType, TagDifference>>();
foreach (var file in files)
{
_lateFileHandler.FilePath = file;
var diff = mp3Processor.Difference(pattern);
if(diff != null)
differences.Add(file,diff);
}
return differences;
}
public bool PrepareSynch(string path, string pattern)
{
if (!_synchInProgres)
{
var mp3Processor = new Mp3FileProcessor(_lateFileHandler);
var files = _folderHandler.GetAllMp3s(path);
if (files.Count == 0)
return false;
_synchInProgres = true;
foreach (var file in files)
{
_lateFileHandler.FilePath = file;
mp3Processor.Synchronize(pattern);
}
return true;
}
return false;
}
public bool CompleteSych(int[] notToWrite)
{
if (_synchInProgres)
{
_synchInProgres = false;
_lateFileHandler.WriteFiles(notToWrite);
_lateFileHandler = null;
return true;
}
return false;
}
private void FileHandlerBuilder()
{
var fileHandler = new Id3LibFileHandler();
_lateFileHandler = new LateWriteFileHandler(fileHandler);
}
private LateWriteFileHandler _lateFileHandler;
private IFolderHandler _folderHandler;
private bool _synchInProgres;
}
}
|
e118a85213d1d8901182fdbf5a3ff197c83600ce
|
C#
|
Laikos38/SimulacionMontecarlo
|
/SimulacionMontecarlo/Simulator.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimulacionMontecarlo;
namespace SimulacionMontecarlo
{
class Simulator
{
public IList<StateRow> simulate(int quantity, int from, int maxReservations)
{
Random random = new Random();
IList<StateRow> stateRows = new List<StateRow>();
int currentPassengers;
long acumProfit = 0;
int deniedSeats;
int totalProfit;
int extraPassengersCost;
for (int i=0; i<quantity; i++)
{
deniedSeats = 0;
totalProfit = 0;
extraPassengersCost = 0;
double rndNumber = random.NextDouble();
currentPassengers = this.getCurrentPassengers(rndNumber, maxReservations);
if (currentPassengers > 30)
{
deniedSeats = currentPassengers - 30;
extraPassengersCost = deniedSeats * 150;
}
totalProfit = (currentPassengers * 100) - (extraPassengersCost);
acumProfit += totalProfit;
if ((i >= from-1 && i <= from + 99) || i == (quantity - 1))
{
StateRow row = new StateRow { currentPassengers = currentPassengers, deniedSeats = deniedSeats, iterationNum = i + 1, extraPassengersCost = extraPassengersCost, rndNumber = Math.Truncate(rndNumber * 10000) / 10000, totalEarnings = currentPassengers * 100, totalProfit = totalProfit, acumProfit = acumProfit};
stateRows.Add(row);
}
}
return stateRows;
}
private int getCurrentPassengers(double rnd, int maxReservations)
{
switch (maxReservations)
{
case 31:
//Para el caso de 31 reservaciones máx
if (rnd < 0.10) return 28;
if (rnd < 0.35) return 29;
if (rnd < 0.85) return 30;
return 31;
case 32:
//Para el caso de 32 reservaciones máx
if (rnd < 0.05) return 28;
if (rnd < 0.3) return 29;
if (rnd < 0.8) return 30;
if (rnd < 0.95) return 31;
return 32;
case 33:
//Para el caso de 33 reservaciones máx
if (rnd < 0.05) return 29;
if (rnd < 0.25) return 30;
if (rnd < 0.70) return 31;
if (rnd < 0.90) return 32;
return 33;
case 34:
//Para el caso de 34 reservaciones máx
if (rnd < 0.05) return 29;
if (rnd < 0.15) return 30;
if (rnd < 0.55) return 31;
if (rnd < 0.85) return 32;
if (rnd < 0.95) return 33;
return 34;
}
return 30;
}
}
}
|
fc901c37d086e3bb9ee17c252a966f44f846ebc3
|
C#
|
Hydrofluoric0/Stump
|
/src/Stump.DofusProtocol.D2OClasses/Tools/Bin/Direction.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stump.DofusProtocol.D2oClasses.Tools.Bin
{
public enum DirectionEnum
{
INVALID = -1,
EAST = 0,
SOUTH_EAST = 1,
SOUTH = 2,
SOUTH_WEST = 3,
WEST = 4,
NORTH_WEST = 5,
NORTH = 6,
NORTH_EAST = 7,
INVALID_2 = 255,
}
public static class Direction
{
public static bool IsValidDirection(int direction)
{
return (DirectionEnum)direction >= DirectionEnum.EAST && (DirectionEnum)direction <= DirectionEnum.NORTH_EAST;
}
public static DirectionEnum FromName(string name)
{
switch (name)
{
case "EAST":
return DirectionEnum.EAST;
case "SOUTH_EAST":
return DirectionEnum.SOUTH_EAST;
case "SOUTH":
return DirectionEnum.SOUTH;
case "SOUTH_WEST":
return DirectionEnum.SOUTH_WEST;
case "WEST":
return DirectionEnum.WEST;
case "NORTH_WEST":
return DirectionEnum.NORTH_WEST;
case "NORTH":
return DirectionEnum.NORTH;
case "NORTH_EAST":
return DirectionEnum.NORTH_EAST;
default:
return DirectionEnum.INVALID;
}
}
}
}
|
ce9fe719f91190fd94240f0c8f10766b8cad3aaf
|
C#
|
MemeKeeper/TableFindBackend
|
/TableFindBackend/Forms/EditRestaurantForm.cs
| 2.6875
| 3
|
using BackendlessAPI;
using BackendlessAPI.Async;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using TableFindBackend.Global_Variables;
using TableFindBackend.Models;
using TableFindBackend.Output;
namespace TableFindBackend.Forms
{
//This form is used to change some of the settings of the program and get access to more features
public partial class EditRestaurantForm : Form
{
private MainForm _master; //An instance of the MainForm gets passed along so that is can be manipulated from this form
//This form is created with an instance of the MainForm
public EditRestaurantForm(MainForm master)
{
InitializeComponent();
_master = master;
//All textboxes are filled in with valid information
tbxName.Text = OwnerStorage.ThisRestaurant.Name;
tbxLocation.Text = OwnerStorage.ThisRestaurant.LocationString;
tbxContactNumber.Text = OwnerStorage.ThisRestaurant.ContactNumber;
dtpOpen.Value = OwnerStorage.ThisRestaurant.Open;
dtpClose.Value = OwnerStorage.ThisRestaurant.Close;
if(OwnerStorage.ThisRestaurant.Active==false)
{
btnReactivate.Visible = true;
btnDeactivate.Enabled = false;
}
//Ensures that the Reset to Defaults button is only enabled if there is a layout to replace
if (File.Exists(@"layouts\" + OwnerStorage.ThisRestaurant.objectId + "_layout.tbl"))
{
btnDefault.Enabled = true;
}
}
//Button used to close the form if the user wishes to not save changes made
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Close();
}
//A method that will appear on all forms. It simulates a loading screen by showing and hiding all necessary buttons and interface elements
private void ShowLoading(bool toggle)
{
if (toggle == true)
{
pbxLoading.Visible = true;
btnSave.Enabled = false;
btnCancel.Enabled = false;
btnClose.Enabled = false;
btnBrowseLayout.Enabled = false;
btnPrint.Enabled = false;
btnDeactivate.Enabled = false;
btnDefault.Enabled = false;
pnlRestaurantDetails.Enabled = false;
pnlRestaurantTimes.Enabled = false;
}
else
{
pbxLoading.Visible = false;
btnSave.Enabled = true;
btnCancel.Enabled = true;
btnClose.Enabled = true;
btnBrowseLayout.Enabled = true;
btnPrint.Enabled = true;
btnDeactivate.Enabled = true;
btnDefault.Enabled = true;
pnlRestaurantDetails.Enabled = true;
pnlRestaurantTimes.Enabled = true;
}
}
//Saves the changes made by the user, as well as checking if the layout has been modified or cleared
private void btnSave_Click(object sender, EventArgs e)
{
string file = ofdLayoutBrowse.FileName;
ShowLoading(true);
if (file != "")
{
try
{
//The directory has to be created first. If it does not already exist, it's created here
if (File.Exists("layouts") != true)
Directory.CreateDirectory("layouts");
//Layout was chosen or left as is
if (file.Equals("reset") != true)
{
string text = File.ReadAllText(file);
lblLayout.Text = ofdLayoutBrowse.FileName;
//If the file already exists, it has to be deleted first so that it can be replaced with the new one
if (File.Exists(@"layouts\" + OwnerStorage.ThisRestaurant.objectId + "_layout.tbl"))
{
_master.DisableLayoutImage();
File.Delete(@"layouts\" + OwnerStorage.ThisRestaurant.objectId + "_layout.tbl");
}
//The new layout image gets copied to the program files
File.Copy(ofdLayoutBrowse.FileName, @"layouts\" + OwnerStorage.ThisRestaurant.objectId + "_layout.tbl");
//Log and document the event
OwnerStorage.FileWriter.WriteLineToFile("User changed the restaurant layout image", true);
OwnerStorage.LogInfo.Add("User changed the restaurant layout image");
OwnerStorage.LogTimes.Add(System.DateTime.Now.ToString("HH:mm:ss"));
}
//Layout was reset or deleted
else
{
//Calls a method on the MainForm which disables the image so that the image can be deleted fromm the program files
_master.DisableLayoutImage();
//deletes the image file
File.Delete(@"layouts\" + OwnerStorage.ThisRestaurant.objectId + "_layout.tbl");
//documents the events
OwnerStorage.FileWriter.WriteLineToFile("User cleared the restaurant layout image", true);
OwnerStorage.LogInfo.Add("User cleared the restaurant layout image");
OwnerStorage.LogTimes.Add(System.DateTime.Now.ToString("HH:mm:ss"));
}
}
//Something went wrong, so an error message gets displayed
catch (IOException ex)
{
MessageBox.Show(this, "Error: " + ex.Message);
}
}
//Saving the rest of the restaurant information
OwnerStorage.ThisRestaurant.ContactNumber = tbxContactNumber.Text;
OwnerStorage.ThisRestaurant.Name = tbxName.Text;
OwnerStorage.ThisRestaurant.LocationString = tbxLocation.Text;
OwnerStorage.ThisRestaurant.Open = dtpOpen.Value;
OwnerStorage.ThisRestaurant.Close = dtpClose.Value;
if(btnReactivate.Enabled==false)
{
OwnerStorage.ThisRestaurant.Active = true;
}
AsyncCallback<Restaurant> updateObjectCallback = new AsyncCallback<Restaurant>(
savedRestaurant =>
{
//Success the object is now updated. the form will now close
//Runs visual aspects on a new thread because you cannot alter visual aspects on any thread other than the GUI thread
Invoke(new Action(() =>
{
ShowLoading(false);
DialogResult = DialogResult.OK;
this.Close();
}));
//Log the event
OwnerStorage.FileWriter.WriteLineToFile("User made changes to the restaurant settings", true);
OwnerStorage.LogInfo.Add("User made changes to the restaurant settings");
OwnerStorage.LogTimes.Add(System.DateTime.Now.ToString("HH:mm:ss"));
},
error =>
{
//Something went wrong, an error message will now display
//Runs visual aspects on a new thread because you cannot alter visual aspects on any thread other than the GUI thread
Invoke(new Action(() =>
{
ShowLoading(false);
MessageBox.Show(error.Message.ToString());
}));
});
AsyncCallback<Restaurant> saveObjectCallback = new AsyncCallback<Restaurant>(
savedRestaurant =>
{
//The object has to be saved first before it can be updated
Backendless.Persistence.Of<Restaurant>().Save(savedRestaurant, updateObjectCallback);
},
error =>
{
//Something went wrong, an error message will now display
//Runs visual aspects on a new thread because you can not alter visual aspects on any thread other than the GUI thread
Invoke(new Action(() =>
{
ShowLoading(false);
MessageBox.Show(error.Message.ToString());
}));
}
);
Backendless.Persistence.Of<Restaurant>().Save(OwnerStorage.ThisRestaurant, saveObjectCallback);
}
#region feature declared obsolete
//feature declared obsolete / unpractical
//private void btnBrowse_Click(object sender, EventArgs e)
//{
// long size = -1;
// ofdMenuBrowse.Filter = "pdf files (*.pdf)|*.pdf|Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG";
// DialogResult result = ofdMenuBrowse.ShowDialog(); // Show the dialog.
// if (result == DialogResult.OK) // Test result.
// {
// string file = ofdMenuBrowse.FileName;
// try
// {
// string text = File.ReadAllText(file);
// tbxMenu.Text = ofdMenuBrowse.FileName;
// size = text.Length / 1024;
// lblSize.Text = "File size: " + size+ "KB";
// btnUpload.Enabled = true;
// }
// catch (IOException)
// {
// }
// }
//}
//private void btnUpload_Click(object sender, EventArgs e)
//{
// if (tbxMenu.Text!="")
// {
// pbxLoading.Visible = true;
// btnSave.Enabled = false;
// lblSize.Text = "Removing Existing File...";
// AsyncCallback<object> deleteCallback = new AsyncCallback<object>(
// result =>
// {
// Invoke(new Action(() =>
// {
// lblSize.Text = "Uploading...";
// }));
// AsyncCallback<BackendlessAPI.File.BackendlessFile> callback = new AsyncCallback<BackendlessAPI.File.BackendlessFile>(
// success =>
// {
// OwnerStorage.ThisRestaurant.MenuLink = success.FileURL;
// Invoke(new Action(() =>
// {
// OwnerStorage.FileWriter.WriteLineToFile("User Uploaded new menu pdf", true);
// OwnerStorage.LogInfo.Add("User Uploaded new menu pdf");
// OwnerStorage.LogTimes.Add(System.DateTime.Now.ToString("HH:mm:ss"));
// pbxLoading.Visible = false;
// lblSize.Text = "Upload completed";
// btnSave.Enabled = true;
// }));
// },
// fault =>
// {
// Invoke(new Action(() =>
// {
// OwnerStorage.FileWriter.WriteLineToFile("Menu Upload Failed", true);
// pbxLoading.Visible = false;
// MessageBox.Show(this, "Error: " + fault.Message.ToString());
// lblSize.Text = "Upload failed";
// btnSave.Enabled = true;
// }));
// });
// FileStream fs = new FileStream(tbxMenu.Text, FileMode.Open, FileAccess.Read);
// BackendlessAPI.Backendless.Files.Upload(fs, "Menu/" + OwnerStorage.ThisRestaurant.objectId, callback);
// },
// fault =>
// {
// Invoke(new Action(() =>
// {
// lblSize.Text = "Uploading...";
// }));
// AsyncCallback<BackendlessAPI.File.BackendlessFile> callback = new AsyncCallback<BackendlessAPI.File.BackendlessFile>(
// success =>
// {
// OwnerStorage.ThisRestaurant.MenuLink = success.FileURL;
// Invoke(new Action(() =>
// {
// OwnerStorage.FileWriter.WriteLineToFile("User Uploaded new menu pdf", true);
// OwnerStorage.LogInfo.Add("User Uploaded new menu pdf");
// OwnerStorage.LogTimes.Add(System.DateTime.Now.ToString("HH:mm:ss"));
// pbxLoading.Visible = false;
// lblSize.Text = "Upload completed";
// btnSave.Enabled = true;
// }));
// },
// uploadFault =>
// {
// Invoke(new Action(() =>
// {
// OwnerStorage.FileWriter.WriteLineToFile("Menu Upload Failed", true);
// pbxLoading.Visible = false;
// MessageBox.Show(this, "Error: " + uploadFault.Message.ToString());
// lblSize.Text = "Upload failed";
// btnSave.Enabled = true;
// }));
// });
// FileStream fs = new FileStream(tbxMenu.Text, FileMode.Open, FileAccess.Read);
// BackendlessAPI.Backendless.Files.Upload(fs, "Menu/" + OwnerStorage.ThisRestaurant.objectId, callback);
// });
// BackendlessAPI.Backendless.Files.Remove("Menu/"+OwnerStorage.ThisRestaurant.objectId, deleteCallback);
// }
// else
// {
// MessageBox.Show(this, "Please browse for a file to upload first");
// }
//}
#endregion
//Method which displays an OpenFileDialog form in which the user can locate a layout image of format either BMP, JPG or PNG
private void btnBrowseLayout_Click(object sender, EventArgs e)
{
//If the user is advanced enough he/she can even locate the .tbl files which is what happens after a regular image is selected by the TableFind Program
ofdLayoutBrowse.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG|TableFindBackend Layout files (*.tbl)|*.tbl";
//Show the dialog
DialogResult result = ofdLayoutBrowse.ShowDialog();
//Test result
if (result == DialogResult.OK)
{
//Enables and clears the appropriate controls
string file = ofdLayoutBrowse.FileName;
lblLayout.Text = ofdLayoutBrowse.FileName;
btnDefault.Enabled = true;
}
}
//Opens the SystemReportForm where the user can generate documents containing information about the report of the day
private void btnPrint_Click(object sender, EventArgs e)
{
SystemReportForm sysReportForm = new SystemReportForm();
sysReportForm.ShowDialog();
}
//This method will clear the layout image of the restaurant on the MainForm
private void btnDefault_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you would like to reset the restaurant layout to a blank canvas?", "Reset Restaurant layout", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
lblLayout.Text = ofdLayoutBrowse.FileName;
lblLayout.Text = "Change restaurant layout image";
btnDefault.Enabled = false;
ofdLayoutBrowse.FileName = "reset"; //As long as this is empty, the layout will be reset once the user clicks 'save'
}
}
//Button used to close the form if the user wishes to not save changes made
private void btnClose_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
//Shows the ConfirmRestaurantDeactivationForm, which will allow the user to deactivate his/her restaurant
private void btnDeactivate_Click(object sender, EventArgs e)
{
ConfirmRestaurantDeactivationForm form = new ConfirmRestaurantDeactivationForm();
form.ShowDialog();
}
private void EditRestaurantForm_FormClosing(object sender, FormClosingEventArgs e)
{
//Blocks the "alt F4" capability so that the user cannot close the program while a process is running
if (e.CloseReason == System.Windows.Forms.CloseReason.UserClosing && pbxLoading.Visible == true)
{
e.Cancel = true;
}
}
//Sets the coulors in the panel to fit with the theme of the functions on the panel
private void pnlDangerZone_Paint(object sender, PaintEventArgs e)
{
Color color = Color.Red;
Panel panel = (Panel)sender;
float width = (float)4.0;
Pen pen = new Pen(color, width);
e.Graphics.DrawLine(pen, 0, 0, 0, panel.Height - 0);
e.Graphics.DrawLine(pen, 0, 0, panel.Width - 0, 0);
e.Graphics.DrawLine(pen, panel.Width - 1, panel.Height - 1, 0, panel.Height - 1);
e.Graphics.DrawLine(pen, panel.Width - 1, panel.Height - 1, panel.Width - 1, 0);
}
private void btnChangePassoword_Click(object sender, EventArgs e)
{
ChangePasswordForm passChangeForm = new ChangePasswordForm();
passChangeForm.ShowDialog();
}
private void btnReactivate_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show(this, "Are you sure would like to Activate your restaurant? This will enable users to see your restaurant on the mobile app.", "Activation", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if(result == DialogResult.Yes)
{
btnReactivate.Enabled = false;
}
}
}
}
|
f5075c480b1d53e9d4254bbafe1c9e71cec2175c
|
C#
|
Alexandros5880/ShortingAlgorithms
|
/Short/QuiqSort.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Short
{
public class QuiqSort
{
private void _swap(ref int xp, ref int yp)
{
int temp = xp;
xp = yp;
yp = temp;
}
private int _Partition(int[] nums, int low, int high)
{
int i = low - 1;
int pivot = nums[high];
for (int j = low; j < high; j++)
{
if(nums[j] <= pivot)
{
i++;
this._swap(ref nums[i], ref nums[j]);
}
}
this._swap(ref nums[i+1], ref nums[high]);
return i + 1;
}
public void Sort(int[] nums, int low, int high)
{
if (low < high)
{
int pivot = this._Partition(nums, low, high);
this.Short(nums, low, pivot - 1);
this.Short(nums, pivot + 1, high);
}
}
}
}
|
423f485699f4170ccdf9f4f85ff8f23094fc6f75
|
C#
|
8800720273/Task-Parallel
|
/Thread4.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadingApp
{
public class Wedding
{
public void Venue()
{
for(int i = 0;i < 10;i++)
{
Console.WriteLine("Venue Decesion {0} ",+i);
}
}
public void WeddingCard()
{
for(int i = 1;i<5;i++)
{
Console.WriteLine("Wedding Card Printing {0}",+ i);
}
}
public void WeddingCardDistribution()
{
for(int i = 1;i < 10;i++)
{
Console.WriteLine("Wedding card Distribution {0}",+ i);
}
}
}
class Thread4
{
static void Main(string[] args)
{
Wedding wed = new Wedding();
Thread t = new Thread(new ThreadStart(wed.Venue));
Thread th = new Thread(new ThreadStart(wed.WeddingCard));
Thread th1 = new Thread(new ThreadStart(wed.WeddingCardDistribution));
t.Name = "Venue";
th.Name = "Wedding Card Printing....";
th1.Name = "Wedding Card Distribution";
Console.WriteLine("Thread Name " +t.Name);
Console.WriteLine("Thread Name "+th.Name);
Console.WriteLine("Thread Name "+th1.Name);
t.Start();
t.Join();
th.Start();
th.Join();
th1.Start();
Thread4 ts = new Thread4();
Console.ReadKey();
}
}
}
|
0113bb33e18e3839963595da6cf51b8bd7ee43c7
|
C#
|
evgenitsn/CSharp-Entity-ASP-Web-Development
|
/1.C#-Advanced/05.Regular-Expressions/03.ExtractEmails/ExtractMails.cs
| 2.9375
| 3
|
using System;
using System.Text.RegularExpressions;
class ExtractMails
{
static void Main()
{
string text = Console.ReadLine();
string pattern = @"(?<=\s|^)([a-z0-9]+(?:[_.-][a-z0-9]+)*@(?:[a-z]+\-?[a-z]+\.)+[a-z]+\-?[a-z]+)\b";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(text);
foreach (Match email in matches)
{
Console.WriteLine(String.Format(email.Groups[1]+"" ));
}
}
}
|
927417125ec8219dbe3bcc770f13a2b1d32a8f4c
|
C#
|
khmosquera/Smart-Tech-Mintic
|
/Server/AplicationDbContext.cs
| 2.6875
| 3
|
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using PeliculaIISemanaIV.Shared.Entity;
using System;
namespace PeliculaIISemanaIV.Server
{
public class ApplicationDbContext : DbContext
{
/* Cada DbSet es una tabla que crearemos a partir de una entidad */
public DbSet<Movie> Movies { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Actor> Actors { get; set; }
public DbSet<CategoryMovie> CategoriesMovie { get; set; }
public DbSet<MovieActor> MoviesActor { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
/* Establecemos los tipos de relaciones entre las tablas que se van a crear 1 - 1, 1 - *, N -
M
Creamos una llave primaria compuesta para la tabla CategoryMovie*/
modelBuilder.Entity<CategoryMovie>().HasKey(x => new { x.CategoryId, x.MovieId });
modelBuilder.Entity<MovieActor>().HasKey(x => new { x.MovieId, x.ActorId });
base.OnModelCreating(modelBuilder);
}
}
}
|
4ae4b8fa77d815b5fb54a1eed893360287f6d4fa
|
C#
|
Hengle/HelGames.Teaching.EventManager
|
/HelGames.Teaching.EventManager/IEvent.cs
| 3.203125
| 3
|
// -----------------------------------------------------------------------
// <copyright file="IEvent.cs" company="Paul Schulze (HelGames)">
// Copyright 2014 Paul Schulze (HelGames). All rights reserved.
// </copyright>
// <author>Paul Schulze</author>
// -----------------------------------------------------------------------
namespace HelGames.Teaching.EventManager
{
/// <summary>
/// Defines the interface for an Event. This interface is provided and used by the event manager
/// to not restrict the contents, an event can have but to ensure, that the minimum of data for
/// managing the event, as well as handling it, is present. Management alone only requires the
/// <see cref="IEvent.EventType" /> field, but many events rely on additional data from the sender.
/// For this reason, <see cref="IEvent.EventData" /> was added. As <see cref="EventHandlerDelegate" />
/// event handlers will always receive an object of type IEvent as a parameter, they would otherwise
/// have to be casted to a specific type, providing that additional data for the event handler.
/// </summary>
public interface IEvent
{
/// <summary>
/// Gets the type of the event.
/// <para>
/// For convenience, this is declared as an object, providing the freedom to use any
/// type, that correctly overrides the <see cref="System.Object.Equals" /> and
/// <see cref="System.Object.GetHashCode" />, as an event type. This includes
/// <see cref="System.String" /> and <see cref="System.Int" />. However, for practical
/// applications and a maintainable code base, it is highly recommended to use enums here.
/// </para>
/// <para>
/// Please note, that this interface only requires a getter. This is intentional, as one
/// usually creates a new event using a concrete class, implementing this interface. So
/// during object creation, the type can be set. The event manager and event handlers on
/// the other hand will use this interface, intentionally preventing them from modifying
/// the type of the event.
/// </para>
/// </summary>
object EventType { get; }
/// <summary>
/// Gets the data, to send with the event or null, if the event doesn't require any data.
/// <para>
/// This can be any kind of data, system types like <see cref="System.String" /> or
/// <see cref="System.Int" />. However, experience shows that these data sets tend to
/// grow. When building editors, they also need to be reflected on, for which simple
/// types like the above usually need to be special cased. For that reason, it is a
/// very good habbit to always create a special class, containing all the values you
/// want to send with the event. When doing this, it is also very important to actually
/// store the values in properties, whose name reflects the meaning of the value, so
/// event queueing code and event handlers remain readable and maintainable.
/// </para>
/// </summary>
object EventData { get; }
}
}
|
64a6db6d7eba46e469099b022857700cb5d75a78
|
C#
|
shristoff/TelerikAcademy
|
/C#/PartI/7.Exam-Preparation/11.ShipDamage/ShipDamage.cs
| 3.5
| 4
|
/*Inside the sea (a standard Cartesian /rectangular/ coordinate system) we are given a ship S
(a rectangle whose sides are parallel to the coordinate axes), a horizontal line H (the horizon) and three catapults,
given as coordinates C1, C2 and C3 that will be used to fire the ship. When the attack starts,
each catapult shoots a projectile exactly into the positions that are symmetrical to C1, C2 and C3
with respect to the horizon H. When a projectile hits some of the corners of the ship,
it causes a damage of 25%, when it hits some of the sides of the ship, the damage caused is 50% and when it hits the internal body of the ship,
the damage is 100%. When the projectile does not reach the ship, there is no damage. The total damage is a sum of the separate damages and can exceed 100%.*/
using System;
class ShipDamage
{
static void Main()
{
string SX1str = Console.ReadLine();
int SX1 = int.Parse(SX1str);
string SY1str = Console.ReadLine();
int SY1 = int.Parse(SY1str);
string SX2str = Console.ReadLine();
int SX2 = int.Parse(SX2str);
string SY2str = Console.ReadLine();
int SY2 = int.Parse(SY2str);
string Hstr = Console.ReadLine();
int H = int.Parse(Hstr);
string CX1str = Console.ReadLine();
int CX1 = int.Parse(CX1str);
string CY1str = Console.ReadLine();
int CY1 = int.Parse(CY1str);
string CX2str = Console.ReadLine();
int CX2 = int.Parse(CX2str);
string CY2str = Console.ReadLine();
int CY2 = int.Parse(CY2str);
string CX3str = Console.ReadLine();
int CX3 = int.Parse(CX3str);
string CY3str = Console.ReadLine();
int CY3 = int.Parse(CY3str);
int Damage = 0;
int CY1mirror = H + H - CY1;
int CY2mirror = H + H - CY2;
int CY3mirror = H + H - CY3;
if ((CX1 > Math.Min(SX1, SX2) && CX1 < Math.Max(SX1, SX2)) && (CY1mirror > Math.Min(SY1, SY2) && (CY1mirror < Math.Max(SY1, SY2))))
Damage = Damage + 100;
if ((CX2 > Math.Min(SX1, SX2) && CX2 < Math.Max(SX1, SX2)) && (CY2mirror > Math.Min(SY1, SY2) && (CY2mirror < Math.Max(SY1, SY2))))
Damage = Damage + 100;
if ((CX3 > Math.Min(SX1, SX2) && CX3 < Math.Max(SX1, SX2)) && (CY3mirror > Math.Min(SY1, SY2) && (CY3mirror < Math.Max(SY1, SY2))))
Damage = Damage + 100;
if ((((CX1 == SX1 || CX1 == SX2)) && (CY1mirror > Math.Min(SY1, SY2) && (CY1mirror < Math.Max(SY1, SY2)))) ||
((CY1mirror == SY1 || CY1mirror == SY2) && (CX1 > Math.Min(SX1, SX2) && (CX1 < Math.Max(SX1, SX2)))))
Damage = Damage + 50;
if ((((CX2 == SX1 || CX2 == SX2)) && (CY2mirror > Math.Min(SY1, SY2) && (CY2mirror < Math.Max(SY1, SY2)))) ||
((CY2mirror == SY1 || CY2mirror == SY2) && (CX2 > Math.Min(SX1, SX2) && (CX2 < Math.Max(SX1, SX2)))))
Damage = Damage + 50;
if ((((CX3 == SX1 || CX3 == SX2)) && (CY3mirror > Math.Min(SY1, SY2) && (CY3mirror < Math.Max(SY1, SY2)))) ||
((CY3mirror == SY1 || CY3mirror == SY2) && (CX3 > Math.Min(SX1, SX2) && (CX3 < Math.Max(SX1, SX2)))))
Damage = Damage + 50;
if ((CX1 == SX1 || CX1 == SX2) && (CY1mirror == SY1 || CY1mirror == SY2))
Damage = Damage + 25;
if ((CX2 == SX1 || CX2 == SX2) && (CY2mirror == SY1 || CY2mirror == SY2))
Damage = Damage + 25;
if ((CX3 == SX1 || CX3 == SX2) && (CY3mirror == SY1 || CY3mirror == SY2))
Damage = Damage + 25;
Console.WriteLine(Damage + "%");
}
}
|
3a6e879757125f7a9e7b1a62114ef7ab4182a572
|
C#
|
cacmis/NETConfLatAm2021
|
/NorthWind.Entities/Exceptions/UpdateException.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NorthWind.Entities.Exceptions
{
#nullable disable
public class UpdateException : Exception
{
public IReadOnlyList<string> Entries { get; }
public UpdateException() { }
public UpdateException(string message) : base(message) { }
public UpdateException(string message, Exception innerException) :
base(message, innerException)
{ }
public UpdateException(string message,
IReadOnlyList<string> entries) :
base(message) =>
Entries = entries;
}
}
|
f97575a402e11b3ba4e4e2c113b14cd49888b42c
|
C#
|
shendongnian/download4
|
/first_version_download2/497452-45229229-152102484-2.cs
| 3.234375
| 3
|
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
|