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
|
|---|---|---|---|---|---|---|
1441fb1c23c1ca469644bad0819f3faf4de005e4
|
C#
|
creatorQuen/db_LocalDataBase_CRUD
|
/SandreyPersonBase/Form1.cs
| 2.90625
| 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;
using System.Data.SqlClient; // Добавляем пространство имен.
namespace SandreyPersonBase
{
public partial class Form1 : Form
{
// Нужные поля для работы.
private SqlConnection sqlConnection = null;
private SqlCommandBuilder sqlBuilder = null;
private SqlDataAdapter sqlDataAdapter = null;
private DataSet dataSet = null;
private bool newRowAdding = false;
public Form1()
{
InitializeComponent();
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
// Создаем метод для загрузкми данных.
private void LoadData()
{
try
{
// Созданим экземпляр класса sqlApapter. В качестве первого параметра передадим SQL запрос, второй - экземпляр класса sqlConnection.
// SELECT * выбираем все колонки и сущности из таблицы, 7 колонка таблицы это кнопки для управления insert или update.
// Это для таблицы "Users".
// Command - название ячейки.
sqlDataAdapter = new SqlDataAdapter("SELECT *, 'Delete' AS [Команда] FROM Users", sqlConnection);
// Создаем экземпляр класса sqlCommanBuilder
sqlBuilder = new SqlCommandBuilder(sqlDataAdapter);
// Создаем команды для insert, update и delete для sqlBuilder
sqlBuilder.GetInsertCommand();
sqlBuilder.GetUpdateCommand();
sqlBuilder.GetDeleteCommand();
// Создаем поле dataSet
dataSet = new DataSet();
// Заполняем dataSet и заполним при помощи sqlDataAdapter. + добавляем имя таблицы
sqlDataAdapter.Fill(dataSet, "Users");
// Устанавливаем
dataGridView1.DataSource = dataSet.Tables["Users"];
// В 7 колонке содержится linkLabel(insert,delete,update) и это у меня кнопки которые должны работать, а не быть просто текстом.
// Поэтому в цикле переопределим 7 колонку.
// Проходимся по количеству всех строк.
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewLinkCell linkCell = new DataGridViewLinkCell();
// Обращаемся к ячейка как к элементу в двумерном массиве.
// 8 это девятая колонка , а row index i.
dataGridView1[8, i] = linkCell;
}
}
// Вслучае ошибки выводим.
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Создаем метод для перезаписывания данных.
private void ReloadData()
{
try
{
// Очищение таблицы.
dataSet.Tables["Users"].Clear();
// Заполняем dataSet и заполним при помощи sqlDataAdapter. + добавляем имя таблицы.
sqlDataAdapter.Fill(dataSet, "Users");
// Устанавливаем.
dataGridView1.DataSource = dataSet.Tables["Users"];
// В 7 колонке содержится linkLabel(insert,delete,update) и это у меня кнопки которые должны работать, а не быть просто текстом .
// Поэтому в цикле переопределим 7 колонку.
for (int i = 0; i < dataGridView1.Rows.Count; i++) // проходимся по количеству всех строк.
{
DataGridViewLinkCell linkCell = new DataGridViewLinkCell();
// Обращаемся к ячейка как к элементу в двумерном массиве.
// 8 это девятая колонка , а row index i.
dataGridView1[8, i] = linkCell;
}
}
catch (Exception ex)
{
// Вслучае ошибки выводим.
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Создаем поле для подключения базы данных (см. св-во БД). Пишем через @"".
sqlConnection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\SandreyPersonBase\SandreyPersonBase\DatabaseMain.mdf;Integrated Security=True");
// Открываем соединение с БД.
// В этом же методе будет происходит загрузка данных в таблицу GridNew.
sqlConnection.Open();
LoadData();
}
// Это кнопка обновить
private void toolStripButton1_Click(object sender, EventArgs e)
{
ReloadData();
}
// sell contant click и user add the draw.
// Обрабатывается событие нажатия на ячейку и событые добавление новой строки.
// Тут узнаем при помощи 7 колонки действие котороеб будет updadte, delete или insert.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
// Определяем на какую ячейку было совершено нажатие.
if (e.ColumnIndex == 8)
{
// Получаем текст из libkLabel.
string task = dataGridView1.Rows[e.RowIndex].Cells[8].Value.ToString();
// определяем какю команду хотел выполнить пользователь.
if (task == "Delete")
{
// Если yes то удаляем.
if (MessageBox.Show("Удалить эту строку?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes)
{
int rowIndex = e.RowIndex;
// Вызываем метод remove at на объЕкт.
dataGridView1.Rows.RemoveAt(rowIndex);
// Удаляем строку из dataSet т.к. удали только с gridView.
dataSet.Tables["Users"].Rows[rowIndex].Delete();
// Обновляем БД.
sqlDataAdapter.Update(dataSet, "Users");
}
}
else if (task == "Insert")
{
// Новая переменная с индексом строки.
int rowIndex = dataGridView1.Rows.Count - 2; // - 2
// Создаем ссылку на новую строку которую создадим в dataSet в таблице Users.
DataRow row = dataSet.Tables["Users"].NewRow();
row["Имя"] = dataGridView1.Rows[rowIndex].Cells["Имя"].Value;
row["Фамилия"] = dataGridView1.Rows[rowIndex].Cells["Фамилия"].Value;
row["Отчество"] = dataGridView1.Rows[rowIndex].Cells["Отчество"].Value;
row["День_Рождения"] = dataGridView1.Rows[rowIndex].Cells["День_Рождения"].Value;
row["Адресс"] = dataGridView1.Rows[rowIndex].Cells["Адресс"].Value;
row["Отдел"] = dataGridView1.Rows[rowIndex].Cells["Отдел"].Value;
row["О_себе"] = dataGridView1.Rows[rowIndex].Cells["О_себе"].Value;
// Выведем стрку которою только что заполнили.
dataSet.Tables["Users"].Rows.Add(row);
dataSet.Tables["Users"].Rows.RemoveAt(dataSet.Tables["Users"].Rows.Count - 1); // - 1
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 2); // - 2
// Добовляем delete чтобы можно было использовать.
dataGridView1.Rows[e.RowIndex].Cells[8].Value = "Delete";
sqlDataAdapter.Update(dataSet, "Users");
newRowAdding = false;
}
else if (task == "Update")
{
// Индекс выделенной строки.
int r = e.RowIndex;
// Обновляем все данные в dataSet.
// Ячейкам, нужной нам строки по индексу в dataSet в талице Users присваеваем значение из ячеек редактируемой строки которая нужна.
dataSet.Tables["Users"].Rows[r]["Имя"] = dataGridView1.Rows[r].Cells["Имя"].Value;
dataSet.Tables["Users"].Rows[r]["Фамилия"] = dataGridView1.Rows[r].Cells["Фамилия"].Value;
dataSet.Tables["Users"].Rows[r]["Отчество"] = dataGridView1.Rows[r].Cells["Отчество"].Value;
dataSet.Tables["Users"].Rows[r]["День_Рождения"] = dataGridView1.Rows[r].Cells["День_Рождения"].Value;
dataSet.Tables["Users"].Rows[r]["Адресс"] = dataGridView1.Rows[r].Cells["Адресс"].Value;
dataSet.Tables["Users"].Rows[r]["Отдел"] = dataGridView1.Rows[r].Cells["Отдел"].Value;
dataSet.Tables["Users"].Rows[r]["О_себе"] = dataGridView1.Rows[r].Cells["О_себе"].Value;
sqlDataAdapter.Update(dataSet, "Users");
// Меняем текст последней колонки.
dataGridView1.Rows[e.RowIndex].Cells[8].Value = "Delete";
}
}
ReloadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
try
{
if(newRowAdding == false)
{
// Делаем так потому что строка добовляется.
newRowAdding = true;
// Чтобы строка изменялаять на insert или delete в последней строке.
int lastRow = dataGridView1.Rows.Count - 2; // -2
// Используя индекс последней строки в которую мы добавляем новую ячейку создаем класс.
DataGridViewRow row = dataGridView1.Rows[lastRow];
// Загружаем форму.
DataGridViewLinkCell linkCell = new DataGridViewLinkCell();
dataGridView1[8, lastRow] = linkCell;
// Меняем кнопку вместо delete на insert.
row.Cells["Команда"].Value = "Insert";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// Переминуем последнюю яйчейку на update.
try
{
// Нужен false чтобы было понятно что строка не добавляется, а изменяется.
if (newRowAdding == false)
{
// Выводим индЕкс строки выделенной ячейки.
int rowIndex = dataGridView1.SelectedCells[0].RowIndex;
// Создаем экземпляр класса dataGridviewRow.
DataGridViewRow editingRow = dataGridView1.Rows[rowIndex];
DataGridViewLinkCell linkCell = new DataGridViewLinkCell();
dataGridView1[8, rowIndex] = linkCell;
// Меняем кнопку вместо delete на update.
editingRow.Cells["Команда"].Value = "Update";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Ошикбка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
DataTable dt = new DataTable("Users");
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
if (e.KeyChar == (char)13)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("Фамилия like '%{0}%',", txtSearch.Text);
dataGridView1.DataSource = dv.ToTable();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошикбка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FindButton_Click(object sender, EventArgs e)
{
}
}
}
|
a5f1f817ab61eb0ca09a9915f1bf8f623f4a6347
|
C#
|
bobkataelittt/first-repo1
|
/zad 2.cs
| 3.546875
| 4
|
using System;
namespace zad_2
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> phonebook = new Dictionary<string, string>();
while (true)
{
var input = Console.ReadLine().Split(' ');
string comm = input[0].ToLower();
switch (comm)
{
case "a":
{
phonebook.Add(input[1], input[2]);
break;
}
case "s":
{
if (phonebook.ContainsKey(input[1]))
{
Console.WriteLine($"Name: {input[1]} -> {phonebook[1]]}");
}
else
{
Console.WriteLine($"This contact doesnt exist");
}
break;
}
case "end":
{
return;
}
}
}
}
}
}
|
dfc56e1287b664c3c27661314fc5d98b279200ec
|
C#
|
weedkiller/entra21-matutino-2019-tcc
|
/Repository/Repositories/CategoriaRepository.cs
| 3.015625
| 3
|
using Model;
using Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Repositories
{
public class CategoriaRepository : ICategoriaRepository
{
private SystemContext context;
public CategoriaRepository()
{
context = new SystemContext();
}
public bool Alterar(Categoria categoria)
{
var categoriaOriginal = context.Categorias.FirstOrDefault(x => x.Id == categoria.Id);
if (categoriaOriginal == null)
return false;
categoriaOriginal.Nome = categoria.Nome;
categoriaOriginal.Id = categoria.Id;
int quantidadeAfetada = context.SaveChanges();
return quantidadeAfetada == 1;
}
public bool Apagar(int id)
{
var categoria = context.Categorias.FirstOrDefault(x => x.Id == id);
if (categoria == null)
{
return false;
}
categoria.RegistroAtivo = false;
int quantidadeAfetada = context.SaveChanges();
return quantidadeAfetada == 1;
}
public int Inserir(Categoria categoria)
{
context.Categorias.Add(categoria);
context.SaveChanges();
return categoria.Id;
}
public Categoria ObterPeloId(int id)
{
var categoria = context.Categorias.FirstOrDefault(x => x.Id == id);
return categoria;
}
public List<Categoria> ObterTodos()
{
return context.Categorias.Where(x => x.RegistroAtivo == true).OrderBy(x => x.Id).ToList();
}
}
}
|
a1784a59ec399a940aa98bf6346c6a0f0fdea9ae
|
C#
|
neuhauser/perseus-plugins
|
/PluginMzTab/Lib/Model/MZTabFile.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
namespace PluginMzTab.Lib.Model{
/**
* In the jmzTab core model, the MZTabFile class is the central entry point to manage the internal relationships
* among the different sections in the file. It contains three key components: i) Metadata, which is a mandatory
* meta-model that provides the definitions contained in the dataset included in the file; ii) {@link MZTabColumnFactory},
* a factory class that can be used to generate stable {@link MZTabColumn} elements, and to add dynamically different
* optional columns (like e.g. protein and peptide abundance related columns). The {@link Metadata} and {@link MZTabColumnFactory}
* constitute the framework for the MZTabFile class; and iii) Consistency constraints among the different sections
* of the model. For example, the MZTabFile class supports the iterative modification of the elements ‘{@link MsRun}’,
* ‘{@link Sample}’, ‘{@link StudyVariable}’, and ‘{@link Assay}’ assigned numbers (1-n) and its location in the file,
* maintaining the internal consistency between the Metadata section and the optional elements in the table-based sections.
* These methods are particularly useful when information coming from different experiments (e.g. ms runs) is
* condensed in a single mzTab file.
*/
public class MZTabFile{
// The metadata section.
private readonly Metadata metadata;
// header line section.
private MZTabColumnFactory _proteinColumnFactory;
private MZTabColumnFactory _peptideColumnFactory;
private MZTabColumnFactory _psmColumnFactory;
private MZTabColumnFactory _smallMoleculeColumnFactory;
// The line number indexed sorted map.
private readonly SortedDictionary<int, Comment> comments = new SortedDictionary<int, Comment>();
private readonly SortedDictionary<int, Protein> proteins = new SortedDictionary<int, Protein>();
private readonly SortedDictionary<int, Peptide> peptides = new SortedDictionary<int, Peptide>();
private readonly SortedDictionary<int, PSM> psms = new SortedDictionary<int, PSM>();
private readonly SortedDictionary<int, SmallMolecule> smallMolecules =
new SortedDictionary<int, SmallMolecule>();
/**
* Create a MZTabFile with defined metadata.
*
* @param metadata SHOULD NOT set null.
*/
public MZTabFile(Metadata metadata){
if (metadata == null){
throw new NullReferenceException("Metadata should be created first.");
}
this.metadata = metadata;
}
/**
* Get all comment line in mzTab. Comment lines can be placed anywhere in an mzTab file. These lines must
* start with the three-letter code COM and are ignored by most parsers. Empty lines can also occur anywhere
* in an mzTab file and are ignored.
*
* @return a unmodifiable collection.
*/
public ReadOnlyCollection<Comment> getComments(){
return new ReadOnlyCollection<Comment>(comments.Values.ToList());
}
/**
* Get the metadata section can provide additional information about the dataset(s) reported in the mzTab file.
*/
public Metadata getMetadata(){
return metadata;
}
/**
* Get the Protein header line column factory.
*/
public MZTabColumnFactory getProteinColumnFactory(){
return _proteinColumnFactory;
}
/**
* Get the Peptide header line column factory.
*/
public MZTabColumnFactory getPeptideColumnFactory(){
return _peptideColumnFactory;
}
/**
* Get the PSM header line column factory.
*/
public MZTabColumnFactory getPsmColumnFactory(){
return _psmColumnFactory;
}
/**
* Get the Small Molecule header line column factory.
*/
public MZTabColumnFactory getSmallMoleculeColumnFactory(){
return _smallMoleculeColumnFactory;
}
/**
* Set the Protein header line column factory.
*
* @param proteinColumnFactory if null, system will ignore Protein table output.
*/
public void setProteinColumnFactory(MZTabColumnFactory proteinColumnFactory){
_proteinColumnFactory = proteinColumnFactory;
}
/**
* Set the Peptide header line column factory.
*
* @param peptideColumnFactory if null, system will ignore Peptide table output.
*/
public void setPeptideColumnFactory(MZTabColumnFactory peptideColumnFactory){
_peptideColumnFactory = peptideColumnFactory;
}
/**
* Set the PSM header line column factory.
*
* @param psmColumnFactory if null, system will ignore PSM table output.
*/
public void setPSMColumnFactory(MZTabColumnFactory psmColumnFactory){
_psmColumnFactory = psmColumnFactory;
}
/**
* Set the Small Molecule header line column factory.
*
* @param smallMoleculeColumnFactory if null, system will ignore Small Molecule table output.
*/
public void setSmallMoleculeColumnFactory(MZTabColumnFactory smallMoleculeColumnFactory){
_smallMoleculeColumnFactory = smallMoleculeColumnFactory;
}
/**
* Add a Protein record.
*
* @param protein SHOULD NOT set null.
*/
public void addProtein(Protein protein){
if (protein == null){
throw new NullReferenceException("Protein record is null!");
}
int lineNumber = proteins.Count == 0 ? 1 : proteins.Last().Key + 1;
proteins.Add(lineNumber, protein);
}
/**
* Add a Protein record.
*
* @param lineNumber SHOULD be positive integer
* @param protein SHOULD NOT set null.
*
* @throws ArgumentException if there exists Protein object for assigned lineNumber
*/
public void addProtein(int lineNumber, Protein protein){
if (protein == null){
throw new NullReferenceException("Protein record is null!");
}
if (lineNumber <= 0){
throw new ArgumentException("Line number should be positive integer");
}
if (proteins.ContainsKey(lineNumber)){
throw new ArgumentException("There already exist protein record in line number " + lineNumber);
}
proteins.Add(lineNumber, protein);
}
/**
* Add a Peptide record.
*
* @param peptide SHOULD NOT set null.
*/
public void addPeptide(Peptide peptide){
if (peptide == null){
throw new NullReferenceException("Peptide record is null!");
}
int position = peptides.Count == 0 ? 1 : peptides.Last().Key + 1;
peptides.Add(position, peptide);
}
/**
* Add a Peptide record.
*
* @param lineNumber SHOULD be positive integer
* @param peptide SHOULD NOT set null.
*
* @throws ArgumentException if there exists Peptide object for assigned lineNumber
*/
public void addPeptide(int lineNumber, Peptide peptide){
if (peptide == null){
throw new NullReferenceException("Peptide record is null!");
}
if (lineNumber <= 0){
throw new ArgumentException("Line number should be positive integer");
}
if (peptides.ContainsKey(lineNumber)){
throw new ArgumentException("There already exist peptide record in line number " + lineNumber);
}
peptides.Add(lineNumber, peptide);
}
/**
* Add a PSM record.
*
* @param psm SHOULD NOT set null.
*/
public void addPSM(PSM psm){
if (psm == null){
throw new NullReferenceException("PSM record is null!");
}
int position = psms.Count == 0 ? 1 : psms.Last().Key + 1;
psms.Add(position, psm);
}
/**
* Add a PSM record.
*
* @param lineNumber SHOULD be positive integer
* @param psm SHOULD NOT set null.
*
* @throws ArgumentException if there exists PSM object for assigned lineNumber
*/
public void addPSM(int lineNumber, PSM psm){
if (psm == null){
throw new NullReferenceException("PSM record is null!");
}
if (lineNumber <= 0){
throw new ArgumentException("Line number should be positive integer");
}
if (psms.ContainsKey(lineNumber)){
throw new ArgumentException("There already exist PSM record in line number " + lineNumber);
}
psms.Add(lineNumber, psm);
}
/**
* Add a Small Molecule record.
*
* @param smallMolecule SHOULD NOT set null.
*/
public void addSmallMolecule(SmallMolecule smallMolecule){
if (smallMolecule == null){
throw new NullReferenceException("Small Molecule record is null!");
}
int position = smallMolecules.Count == 0 ? 1 : smallMolecules.Last().Key + 1;
smallMolecules.Add(position, smallMolecule);
}
/**
* Add a SmallMolecule record.
*
* @param lineNumber SHOULD be positive integer
* @param smallMolecule SHOULD NOT set null.
*
* @throws ArgumentException if there exists SmallMolecule object for assigned lineNumber
*/
public void addSmallMolecule(int lineNumber, SmallMolecule smallMolecule){
if (smallMolecule == null){
throw new NullReferenceException("Small Molecule record is null!");
}
if (lineNumber <= 0){
throw new ArgumentException("Line number should be positive integer");
}
if (smallMolecules.ContainsKey(lineNumber)){
throw new ArgumentException("There already exist small molecule record in line number " +
lineNumber);
}
smallMolecules.Add(lineNumber, smallMolecule);
}
/**
* Add a Comment record.
*
* @param lineNumber SHOULD be positive integer
* @param comment SHOULD NOT set null.
*
* @throws ArgumentException if there exists Protein object for assigned lineNumber
*/
public void addComment(int lineNumber, Comment comment){
if (comment == null){
throw new NullReferenceException("Comment record is null!");
}
if (lineNumber <= 0){
throw new ArgumentException("Line number should be positive integer");
}
if (comments.ContainsKey(lineNumber)){
throw new ArgumentException("There already exist comment in line number " + lineNumber);
}
comments.Add(lineNumber, comment);
}
/**
* Returns all proteins identified by the given accession.
*
* @param accession The accession identifying the proteins.
* @return A unmodifiable collection of proteins identified by the given accession.
*/
public ReadOnlyCollection<Protein> getProteins(String accession){
List<Protein> result = new List<Protein>();
foreach (Protein record in proteins.Values){
if (record.Accession.Equals(accession)){
result.Add(record);
}
}
return new ReadOnlyCollection<Protein>(result);
}
/**
* Returns a Collection holding all proteins identified in this mzTabFile.
*
* @return A unmodifiable collection of proteins
*/
public ReadOnlyCollection<Protein> getProteins(){
return new ReadOnlyCollection<Protein>(proteins.Values.ToList());
}
public ReadOnlyDictionary<int, Protein> getProteinsWithLineNumber(){
return new ReadOnlyDictionary<int, Protein>(proteins);
}
/**
* Returns a Collection holding all peptides found in the mzTab file.
*
* @return A unmodifiable collection of peptides.
*/
public ReadOnlyCollection<Peptide> getPeptides(){
return new ReadOnlyCollection<Peptide>(peptides.Values.ToList());
}
/**
* Returns a Collection holding all PSMs found in the mzTab file.
*
* @return A unmodifiable collection of PSMs.
*/
public ReadOnlyCollection<PSM> getPSMs(){
return new ReadOnlyCollection<PSM>(psms.Values.ToList());
}
/**
* Returns all SmallMoleculeS identified in the mzTab file.
*
* @return A unmodifiable collection of SmallMolecules
*/
public ReadOnlyCollection<SmallMolecule> getSmallMolecules(){
return new ReadOnlyCollection<SmallMolecule>(smallMolecules.Values.ToList());
}
/**
* Judge there exists records in MZTabFile or not.
*/
public bool isEmpty(){
return proteins.Count == 0 && peptides.Count == 0 && psms.Count == 0 && smallMolecules.Count == 0;
}
/**
* Print MZTabFile into a output stream.
*
* @param out SHOULD NOT be null
*/
public void printMZTab(TextWriter output){
if (output == null){
throw new NullReferenceException("Output stream should be defined first.");
}
if (isEmpty()){
return;
}
output.Write(metadata.ToString());
output.Write(MZTabConstants.NEW_LINE);
// print comment
foreach (Comment comment in comments.Values){
output.Write(comment.ToString());
output.Write(MZTabConstants.NEW_LINE);
}
if (comments.Count != 0){
output.Write(MZTabConstants.NEW_LINE);
}
// print protein
if (_proteinColumnFactory != null && proteins.Count != 0){
output.Write(_proteinColumnFactory.ToString());
output.Write(MZTabConstants.NEW_LINE);
foreach (Protein protein in proteins.Values){
output.Write(protein.ToString());
output.Write(MZTabConstants.NEW_LINE);
}
output.Write(MZTabConstants.NEW_LINE);
}
// print peptide
if (_peptideColumnFactory != null && peptides.Count != 0){
output.Write(_peptideColumnFactory.ToString());
output.Write(MZTabConstants.NEW_LINE);
foreach (Peptide peptide in peptides.Values){
output.Write(peptide.ToString());
output.Write(MZTabConstants.NEW_LINE);
}
output.Write(MZTabConstants.NEW_LINE);
}
// print PSM
if (_psmColumnFactory != null && psms.Count != 0){
output.Write(_psmColumnFactory.ToString());
output.Write(MZTabConstants.NEW_LINE);
foreach (PSM psm in psms.Values){
output.Write(psm.ToString());
output.Write(MZTabConstants.NEW_LINE);
}
output.Write(MZTabConstants.NEW_LINE);
}
// print small molecule
if (_smallMoleculeColumnFactory != null && smallMolecules.Count != 0){
output.Write(_smallMoleculeColumnFactory.ToString());
output.Write(MZTabConstants.NEW_LINE);
foreach (SmallMolecule smallMolecule in smallMolecules.Values){
output.Write(smallMolecule.ToString());
output.Write(MZTabConstants.NEW_LINE);
}
output.Write(MZTabConstants.NEW_LINE);
}
}
/**
* Translate a MZTabFile into a string.
*/
public String toString(){
StringBuilder sb = new StringBuilder();
// print comment
foreach (Comment comment in comments.Values){
sb.Append(comment).Append(MZTabConstants.NEW_LINE);
}
if (comments.Count != 0){
sb.Append(MZTabConstants.NEW_LINE);
}
sb.Append(metadata).Append(MZTabConstants.NEW_LINE);
if (_proteinColumnFactory != null){
sb.Append(_proteinColumnFactory).Append(MZTabConstants.NEW_LINE);
foreach (Protein protein in proteins.Values){
sb.Append(protein).Append(MZTabConstants.NEW_LINE);
}
sb.Append(MZTabConstants.NEW_LINE);
}
if (_peptideColumnFactory != null){
sb.Append(_peptideColumnFactory).Append(MZTabConstants.NEW_LINE);
foreach (Peptide peptide in peptides.Values){
sb.Append(peptide).Append(MZTabConstants.NEW_LINE);
}
sb.Append(MZTabConstants.NEW_LINE);
}
if (_psmColumnFactory != null){
sb.Append(_psmColumnFactory).Append(MZTabConstants.NEW_LINE);
foreach (PSM psm in psms.Values){
sb.Append(psm).Append(MZTabConstants.NEW_LINE);
}
sb.Append(MZTabConstants.NEW_LINE);
}
if (_smallMoleculeColumnFactory != null){
sb.Append(_smallMoleculeColumnFactory).Append(MZTabConstants.NEW_LINE);
foreach (SmallMolecule smallMolecule in smallMolecules.Values){
sb.Append(smallMolecule).Append(MZTabConstants.NEW_LINE);
}
sb.Append(MZTabConstants.NEW_LINE);
}
return sb.ToString();
}
}
}
|
8fb5b670452dc7f11302eaab5d992fc3186e6c8e
|
C#
|
SMarshall08/OSFOLCrossPlatform
|
/OSFOLCrossPlatform/OSFOLCrossPlatform/Pages/AddExpenseCS.cs
| 2.609375
| 3
|
using System;
using Xamarin.Forms;
using OSFOLCrossPlatform.Model;
using OSFOLCrossPlatform.Views;
using System.Diagnostics;
namespace OSFOLCrossPlatform.Pages
{
class AddExpenseCS : ContentPage
{
public AddExpenseCS()
{
ListView customerListView;
var LogoutItem = new ToolbarItem
{
Text = "Logout"
};
LogoutItem.Clicked += OnLogoutButtonClicked;
ToolbarItems.Add(LogoutItem);
var HomeItem = new ToolbarItem
{
Text = "Home"
};
HomeItem.Clicked += OnLogoutButtonClicked;
ToolbarItems.Add(HomeItem);
// Creates a label to estbalish the title
Label Title = new Label
{
Text = "Add Expense",
Font = Font.BoldSystemFontOfSize(50),
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
// Creates a Date Picker
DatePicker datePicker = new DatePicker
{
Format = "D",
VerticalOptions = LayoutOptions.CenterAndExpand
};
Button btnAdd = new Button
{
Text = "Add",
TextColor = Color.Black
};
Label date = new Label
{
Text = "",
Font = Font.BoldSystemFontOfSize(50),
HorizontalOptions = LayoutOptions.Center
};
customerListView = new ListView();
customerListView.ItemTemplate = new DataTemplate
(typeof(Customers));
customerListView.ItemSelected += (sender, e) =>
{
//Label customerLabel = new Label
//{
// Text = "Please Select a Customer"
//};
var customer = (Customers)e.SelectedItem;
};
btnAdd.Clicked += delegate(object sender, EventArgs e)
{
int d = datePicker.Date.Day;
int mon = datePicker.Date.Month;
int year = datePicker.Date.Year;
date.Text = d + "/" + mon + "/" + year;
};
// Creates the content that will sit inside the add Expenses page
Content = new StackLayout
{
VerticalOptions = LayoutOptions.FillAndExpand,
Children =
{
Title,
datePicker,
btnAdd,
date,
customerListView
}
};
}
// On button click logout
async void OnLogoutButtonClicked(object sender, EventArgs e)
{
App.IsUserLoggedIn = false;
Navigation.InsertPageBefore(new LoginPage(), this);
await Navigation.PopAsync();
}
// On button click logout
async void OnHomeButtonClicked(object sender, EventArgs e)
{
Navigation.InsertPageBefore(new MainPage(), this);
await Navigation.PopAsync();
}
}
}
|
c14051e472fbd83f388e84837d78b58960d7998d
|
C#
|
VictorTFeng/UIProject
|
/UIProject/TelerikUI/OrderServices/OrderService.cs
| 2.90625
| 3
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TelerikUI.Models;
using TelerikUI.Repository;
namespace TelerikUI.OrderServices
{
public class OrderService : IOrder
{
private ApplicationDbContext _context;
public OrderService(ApplicationDbContext context)
{
_context = context;
}
public void Add(Order order)
{
_context.Add(order);
_context.SaveChanges();
}
public void Delete(string id)
{
_context.Orders
.Remove(GetById(id));
_context.SaveChanges();
}
public IEnumerable<Order> GetAll()
{
return _context.Orders
.Include(o => o.SystemSerials);
}
public Order GetById(string id)
{
return _context.Orders
.Include(o=>o.SystemSerials)
.SingleOrDefault(o=>o.OrderId==id);
}
public DateTime? GetFinishDate(string id)
{
return GetById(id).FinishDate;
}
public DateTime GetStartDate(string id)
{
return GetById(id).StartDate;
}
public ICollection<SystemSerial> GetSerials(string id)
{
return GetById(id).SystemSerials;
}
public void MakeFinished(string id)
{
GetById(id).FinishDate=DateTime.Now;
_context.SaveChanges();
}
public bool IsFulfilled(string id)
{
return GetById(id).FinishDate != null;
}
}
}
|
c9e95376c69987eb70121a02c7404e885d3b6a43
|
C#
|
JamesMenetrey/Matrix.NET
|
/tests/MatrixUnitTests/Operations/MatrixMultiplicationTests.cs
| 3.09375
| 3
|
using System;
using Binarysharp.Maths;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Binarysharp.Tests.Operations
{
[TestClass]
public class MatrixMultiplicationTests
{
[TestMethod]
public void Multiply2X2And2X3()
{
// Arrange
var left = new Matrix<int>(new[,]
{
{2, 1 },
{0, -1 }
});
var right = new Matrix<int>(new[,]
{
{1, 0, 3},
{-1, 1, 0 }
});
var expected = new Matrix<int>(new[,]
{
{1, 1, 6},
{1, -1, 0 }
});
// Act
var result = left * right;
// Assert
Assert.IsTrue(expected == result, "The result of the multiplication does not match with the expected result.");
}
[TestMethod]
public void Multiply3X3And3X3()
{
// Arrange
var matrix = new Matrix<int>(new[,]
{
{-1, 2, 3 },
{4, -5, 6 },
{7, 8, -9 }
});
var expected = new Matrix<int>(new[,]
{
{30, 12, -18},
{18, 81, -72 },
{-38, -98, 150 }
});
// Act
var result = matrix * matrix;
// Assert
Assert.IsTrue(expected == result, "The result of the multiplication does not match with the expected result.");
}
[TestMethod]
[ExpectedException(typeof (ArgumentException), "Incorrect dimensions for a matrix multiplication.")]
public void Multiplay3X2And3X2()
{
// Arrange
var matrix = new Matrix<int>(new[,]
{
{1, 2 },
{3, 4 },
{5, 6 }
});
// Act
Func<Matrix<int>> multiply = () => matrix * matrix;
multiply();
}
}
}
|
6264e3c46cba59bfdb608809e5d493315f2ceb81
|
C#
|
RosenUrkov/TelerikAcademyHomeworks
|
/C# OOP/DefiningClasses - Part2/GenericClass/MainClass.cs
| 3.703125
| 4
|
namespace GenericClass
{
using System;
using System.Collections.Generic;
public class MainClass
{
public static void Main(string[] args)
{
//Here i review some of the implementations
var list = new List<int>(4);
var genericList = new GenericList<int>(4);
Console.WriteLine(list.Capacity);
Console.WriteLine(genericList.Capacity);
Console.WriteLine();
list.Insert(0, 1);
genericList.InsertElement(0, 1);
Console.WriteLine(string.Join(" ", list));
Console.WriteLine(genericList);
Console.WriteLine();
list.RemoveAt(0);
genericList.RemoveElementAt(0);
for (int i = 0; i < 1000; i++)
{
list.Add(i);
genericList.Add(i);
}
Console.WriteLine(list.Count);
Console.WriteLine(genericList.Count);
Console.WriteLine();
Console.WriteLine(list.IndexOf(15));
Console.WriteLine(genericList.IndexOf(15));
Console.WriteLine();
Console.WriteLine(genericList.Min());
Console.WriteLine(genericList.Max());
Console.WriteLine();
list.Clear();
genericList.Clear();
Console.WriteLine(list.Capacity);
Console.WriteLine(genericList.Capacity);
Console.WriteLine();
}
}
}
|
7b39097b4b71ed2a72c2f5c00765f890fff71d37
|
C#
|
shendongnian/download4
|
/first_version_download2/246619-19535376-49893912-1.cs
| 3.390625
| 3
|
//You have to pass a double value into the method, because there is only one method
//and wants a double paramater:
//this is what you created:
public double getDeposit(double amount) // <-
{
double transactionAmt = 0.00;
if (amount > 0)
{
balance += amount;
transactionAmt = amount;
}
return transactionAmt;
}
//This how you should call it:
static void DumpContents(Account account)
{
Console.WriteLine(" output {0}", account.getDeposit(34.90)); //<-
}
|
be9654d70947ad4c9dab175daa6f9b33a66a7c85
|
C#
|
Orlokun/TruCounter
|
/Assets/Scripts/SaveSystem.cs
| 2.84375
| 3
|
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
public static void FormatAndSaveShameData(ShameManager sManager)
{
BinaryFormatter bFormatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/shameBytes.dog";
FileStream fStream = new FileStream(path, FileMode.Create);
bFormatter.Serialize(fStream, sManager.GetShameData());
fStream.Close();
}
public static ShameData LoadShameData()
{
string path = Application.persistentDataPath + "/shameBytes.dog";
if (File.Exists(path))
{
BinaryFormatter bFormatter = new BinaryFormatter();
FileStream fStream = new FileStream(path, FileMode.Open);
ShameData shameData = (ShameData)bFormatter.Deserialize(fStream);
fStream.Close();
return shameData;
}
else
{
Debug.LogError("Save file not found in " + path + "");
return null;
}
}
}
|
4e597092af9ff6220f9574fc19dbc00543eee886
|
C#
|
kszam/hashcode-pizza
|
/Pizza.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
namespace Pizza_Slicing
{
class Pizza
{
public int rows;
public int columns;
public int minIng;
public int maxCPS;
public string outputFileRoot = "";
public int solutionNo;
int score = 0;
public char[,] pizzaBelag;
public int[,] pizzaSlices;
Stack<Slice> slices;
int nextFreeRow=0;
int nextFreeColumn = 0;
public void findPieces()
{
// The big loop in the sky
do
{
while(!addNewPiece())
{ // Neues Stück konnte nicht hinzugefügt werden
if (!findNextFreeCell())
{ // nächste freie Zelle konnte nicht gefunden werden. Evaluiere Brett und suche dann weiter
scoreBoard();
while(!evolveLastPiece())
{
if (slices.Count == 0)
{
Console.WriteLine("=== No more solutions ==================");
return;
}
}
}
}
} while (true);
}
void scoreBoard()
{
int tempScore = 0;
foreach (Slice s in slices)
{
tempScore = tempScore + s.rows * s.columns;
}
if (tempScore > score)
{
score = tempScore;
Console.WriteLine("Solution number: " + ++solutionNo);
//foreach (Slice s in slices)
//{
// Console.WriteLine("(" + s.posRow + "," + s.posColumn + ") (" + (s.posRow + s.rows - 1) + "," + (s.columns + s.posColumn - 1) + ")");
//}
Console.WriteLine("Score: " + score);
Console.WriteLine("========================================");
writeSolutionToFile(outputFileRoot);
}
}
public void readProblemFromFile(string filename)
{
slices = new Stack<Slice>();
using (StreamReader reader = File.OpenText(filename))
{
{
nextFreeRow = 0;
nextFreeColumn = 0;
solutionNo=0;
char[] splitOnThese = {' '};
// Lese kopf
string readInputPizzaRow = reader.ReadLine();
string[] headerInf = readInputPizzaRow.Split(splitOnThese);
rows = int.Parse(headerInf[0]);
columns = int.Parse(headerInf[1]);
minIng = int.Parse(headerInf[2]);
maxCPS = int.Parse(headerInf[3]);
// Definiere Pizza-Größe
pizzaBelag = new char[rows, columns];
pizzaSlices = new int[rows, columns];
//lese Belag ein
for (int r = 0; r < rows; ++r)
{
readInputPizzaRow = reader.ReadLine();
for (int c = 0; c < columns; ++c)
{
pizzaBelag[r, c] = readInputPizzaRow.Substring(c, 1)[0];
}
}
}
}
}
public void writeSolutionToFile(string filename)
{
try
{
string filePath = filename + score.ToString();
using (StreamWriter writer = new StreamWriter(filePath))
{
// Anzahl Slices in Kopfzeile
writer.WriteLine(slices.Count.ToString());
foreach (Slice s in slices)
{
writer.WriteLine(s.posRow + " " + s.posColumn + " " + (s.posRow+s.rows - 1) + " " + (s.posColumn + s.columns - 1));
}
}
}
catch (IOException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
}
}
bool findNextFreeCell()
{
int rr = nextFreeRow;
int cc = nextFreeColumn;
for (int r = rr; r < rows; ++r)
{
for (int c = cc; c < columns; ++c)
{
if (rr != 0 || cc != 0)
{
rr = 0;
cc = 0;
}
else
if (pizzaSlices[r, c] == 0)
{
nextFreeRow = r;
nextFreeColumn = c;
return true;
}
}
}
return false;
}
public void blockCells(Slice s){
for (int r = 0; r < s.rows; ++r)
{
for (int c = 0; c < s.columns; ++c)
{
pizzaSlices[s.posRow + r, s.posColumn + c] = 1;
}
}
}
public void unblockCells(Slice s)
{
for (int r = 0; r < s.rows; ++r)
{
for (int c = 0; c < s.columns; ++c)
{
pizzaSlices[s.posRow + r, s.posColumn + c] = 0;
}
}
}
bool pieceFitsOnBoard(Slice s)
{
if (!(s.posRow + s.rows <= rows && s.posColumn + s.columns <= columns) || pieceCoversOtherPiece(s))
{
return false; // Slice geht über die Pizza hinaus
}
else
{
return true;
}
}
/*
* true: other piece is covered
* false: no other pieces covered
*/
bool pieceCoversOtherPiece(Slice s)
{
for (int r = 0; r < s.rows; ++r)
{
for (int c = 0; c < s.columns; ++c)
{
if (pizzaSlices[s.posRow + r, s.posColumn + c] == 1)
{
return true;
}
}
}
return false;
}
/*
* true = new piece added
* false = piece not added
*
*/
public bool addNewPiece()
{
Slice s = new Slice();
s.posRow = nextFreeRow;
s.posColumn = nextFreeColumn;
for (int r = 1; r <= maxCPS; ++r)
{
for (int c = 1; c <= maxCPS/r; ++c)
{
s.rows = r;
s.columns = c;
if (pieceFitsOnBoard(s))
{
if (evaluatePiece(s))
{
goto weiter;
}
}
}
}
return false;
weiter: blockCells(s);
findNextFreeCell();
slices.Push(s);
return true;
}
// true = ok, false = not ok
bool evaluatePiece(Slice s)
{
// Slice s = slices.Peek();
int m = 0;
int t = 0;
int totalCells = s.rows * s.columns;
//fits on board?
//if (!pieceFitsOnBoard(s))
//{
// return false; // Slice geht über die Pizza hinaus
//}
for (int r = 0; r < s.rows; ++r)
{
for (int c = 0; c < s.columns; ++c)
{
if (pizzaBelag[s.posRow + r, s.posColumn + c] == 'T')
{
t += 1;
}
if (pizzaBelag[s.posRow + r, s.posColumn + c] == 'M')
{
m += 1;
}
}
}
if (t >= minIng && m >= minIng && totalCells <= maxCPS)
{
return true;
}
else
{
return false;
}
}
/*
* When the last piece couldn't be evolved, it is taken from the board and I return false!
*
*/
public bool evolveLastPiece()
{
Slice s = removeLastPiece();
int rstart = s.rows;
int cstart = s.columns;
bool firstCall = true;
for (int r = rstart; r <= maxCPS; ++r)
{
for (int c = cstart; c <= maxCPS / r; ++c)
{
if (!firstCall)
{
s.rows = r;
s.columns = c;
if (pieceFitsOnBoard(s) && evaluatePiece(s))
{
goto weiter;
}
}
else
{ // Dieses ist nur um quasi in die ehemalige Generierungsschleife wieder hineinzuspringen
rstart = 1;
cstart = 1;
firstCall = false;
}
}
}
return false;
weiter: blockCells(s);
nextFreeRow = s.posRow;
nextFreeColumn = s.posColumn;
findNextFreeCell();
slices.Push(s);
return true;
}
public Slice removeLastPiece()
{
Slice s = slices.Pop();
// belegte Felder wieder freigeben
unblockCells(s);
return s;
}
}
}
|
d27aae0d25987a441818fdce42c97c14e0bb1aa0
|
C#
|
GrumpyBusted/Grumpy.RipplesMQ.Server
|
/Grumpy.RipplesMQ.Core/Infrastructure/IMessageStateRepository.cs
| 2.609375
| 3
|
using System.Collections.Generic;
using Grumpy.RipplesMQ.Entity;
namespace Grumpy.RipplesMQ.Core.Infrastructure
{
/// <summary>
/// Message/Subscriber State Repository
/// </summary>
public interface IMessageStateRepository
{
/// <summary>
/// Insert new State for Message/Subscriber
/// </summary>
/// <param name="messageState"></param>
void Insert(MessageState messageState);
/// <summary>
/// Get current state of a Message for a Subscriber
/// </summary>
/// <param name="messageId">Message Id</param>
/// <param name="subscriberName">Subscriber Name</param>
/// <returns>Message/Subscriber State</returns>
MessageState Get(string messageId, string subscriberName);
/// <summary>
/// Get all Message/Subscriber
/// </summary>
/// <returns></returns>
IEnumerable<MessageState> GetAll();
/// <summary>
/// Delete all Messages States for a specified Subscriber
/// </summary>
/// <param name="subscriberName">Subscriber Name</param>
void DeleteBySubscriber(string subscriberName);
/// <summary>
/// Delete all Subscriber States for a specified Message
/// </summary>
/// <param name="messageId">Message Id</param>
void DeleteByMessageId(string messageId);
}
}
|
6c8c227edb131375c6473992182b5ded7b79877b
|
C#
|
pedromsilvapt/miei-storage-system-backend
|
/foodss-backend/Controllers/DTO/StorageProductItemDTO.cs
| 2.625
| 3
|
using System;
using StorageSystem.Models;
using System.ComponentModel.DataAnnotations;
namespace StorageSystem.Controllers.DTO
{
public class ProductItemInputDTO
{
public bool Shared { get; set; }
public DateTime ExpiryDate { get; set; }
[Range(1, int.MaxValue)]
public int? Quantity { get; set; }
}
public class ProductItemDTO
{
public int Id { get; set; }
public int ProductId { get; set; }
public string ProductName { get; set; }
public int StorageId { get; set; }
public int OwnerId { get; set; }
public bool Shared { get; set; }
public DateTime ExpiryDate { get; set; }
public DateTime AddedDate { get; set; }
public DateTime? ConsumedDate { get; set; }
public static ProductItemDTO FromModel(ProductItem model)
=> new ProductItemDTO()
{
Id = model.Id,
ProductId = model.ProductId,
OwnerId = model.OwnerId,
Shared = model.Shared,
ExpiryDate = model.ExpiryDate,
AddedDate = model.AddedDate,
ProductName = model.Product != null ? model.Product.Name : null,
StorageId = model.Product != null ? model.Product.StorageId : 0,
ConsumedDate = null
};
public static ProductItemDTO FromModel(ConsumedProductItem model)
=> new ProductItemDTO()
{
Id = model.Id,
ProductId = model.ProductId,
OwnerId = model.OwnerId,
Shared = model.Shared,
ExpiryDate = model.ExpiryDate,
AddedDate = model.AddedDate,
ConsumedDate = model.ConsumedDate
};
}
}
|
1b5eb28f15c091d7b774d016692fcb82ad648231
|
C#
|
lyudoGO/SoftUni
|
/DataBaseApplications/06-XML/6.2.XMLProcessingInDotNet/01.MusicalAlbumsXMLFormat/Program.cs
| 3.25
| 3
|
// Problem 1. Catalog of Musical Albums in XML Format
// Create a XML file catalog.xml representing a catalog of musical albums.
// For each album you should define name, artist, year, producer, price and a list of songs.
// Each song should be described by title and duration.
// Hint: You can take sample data from https://gist.github.com/jasonbaldridge/2597611.
namespace _01.MusicalAlbumsXMLFormat
{
using System;
class Program
{
static void Main()
{
}
}
}
|
c6f1e6a27f47001f211582a21d6fed95a2ad9374
|
C#
|
evolvedmicrobe/cafe-quality
|
/src/PacBio.Consensus/GenerateMutations.cs
| 2.59375
| 3
|
#region Copyright (c) 2010, Pacific Biosciences of California, Inc.
//
// All rights reserved.
//
// THIS SOFTWARE CONSTITUTES AND EMBODIES PACIFIC BIOSCIENCES’ CONFIDENTIAL
// AND PROPRIETARY INFORMATION.
//
// Disclosure, redistribution and use of this software is subject to the
// terms and conditions of the applicable written agreement(s) between you
// and Pacific Biosciences, where “you” refers to you or your company or
// organization, as applicable. Any other disclosure, redistribution or
// use is prohibited.
//
// THIS SOFTWARE IS PROVIDED BY PACIFIC BIOSCIENCES AND ITS CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using PacBio.IO;
using PacBio.Utils;
namespace PacBio.Consensus
{
using MutationType = ConsensusCore.MutationType;
/// <summary>
/// Static methods for generating streams of candidate mutations
/// </summary>
public static class GenerateMutations
{
/// <summary>
/// Filter a stream of proposed mutations, only accepting those that fall within some range of another list of mutations
/// </summary>
/// <param name="muts">Input mutations to filter</param>
/// <param name="prev">Previous list of mutations</param>
/// <param name="spacing">Maximum spacing between an accepted mutation and a mutation in the prev list</param>
/// <returns>The filtered mutation stream</returns>
public static IEnumerable<Mutation> PrevMutationFilter(IEnumerable<Mutation> muts, List<Mutation> prev, int spacing)
{
// No previous mutations -- we won't find one now either, so bail out
if(prev.Count == 0)
yield break;
var prevs = prev.OrderBy(p => p.TemplatePosition).ToArray();
var shiftedTplPos = new int[prevs.Length];
var shift = 0;
// Shift the previous mutations to keep track of their new position in the template
for (int i = 0; i < prevs.Length; i++)
{
var m = prevs[i];
shiftedTplPos[i] = m.TemplatePosition + shift;
if (m.Type == MutationType.DELETION)
shift--;
if (m.Type == MutationType.INSERTION)
shift++;
}
// Only return templates that are in the consider regions
foreach(var m in muts)
{
// Do a binary search to find the closest previous mutation.
// Let it through if it's within spacing of the current mutation
var l = 0;
var r = prevs.Length - 1;
while (r - l > 1)
{
var mid = (r + l)/2;
if (shiftedTplPos[mid] > m.TemplatePosition)
r = mid;
else
l = mid;
}
// Find the closest previous mutation
var dist = Math.Min(Math.Abs(shiftedTplPos[l] - m.TemplatePosition),
Math.Abs(shiftedTplPos[r] - m.TemplatePosition));
if(dist < spacing)
yield return m;
}
}
/// <summary>
/// Enumerate all possible single indel or substitution mutations to the TrialTemplate tpl. The template is
/// flanked by presumed correct adapter bases that are not mutated
/// </summary>
/// <param name="tpl">The template to generate mutations of</param>
/// <param name="generateSubstitutions">Generate substitution mutations</param>
/// <returns>An enumerable of Mutation objects</returns>
public static IEnumerable<Mutation> GenerateUniqueMutations(TrialTemplate tpl, bool generateSubstitutions = true)
{
// Attempt to insert or mismatch every base at every positions.
// Don't mutate anything in the know template adapter region
var seq = tpl.GetSequence(Strand.Forward);
// Start is the first base past the adapter
var start = Math.Max(1, tpl.StartAdapterBases);
// End is the fist base of the end adapter
var end = seq.Length - Math.Max(1, tpl.EndAdapterBases);
for (int i = start; i <= end; i++)
{
// homopolyerStart is true if we are on the first base of a hp
// We will only do a matching insertion or a deletion if we're a
// the start of a homopolyer, to prevent retesting the same template
bool homopolyerStart = !(i > 2 && seq[i-1] == seq[i] && i > start);
foreach (var b in DNA.Bases)
{
if ((b != seq[i] && b != seq[i-1]) || (homopolyerStart && b != seq[i-1]))
{
// You are allowed to make an insertion before the first base of the adapter region
yield return new Mutation {Base = b, TemplatePosition = i, Type = MutationType.INSERTION};
}
// Don't generate substitutions if not requested
// Don't mutate adapter
if (generateSubstitutions && b != seq[i] && i < end)
yield return new Mutation { Base = b, TemplatePosition = i, Type = MutationType.SUBSTITUTION };
}
// Attempt to delete only the first base of a homopolymer run
// Don't delete adapter
if (homopolyerStart && i < end)
{
yield return new Mutation {TemplatePosition = i, Type = MutationType.DELETION, Base = 'A'};
}
}
}
}
}
|
6206b76bcfb1b5f0f72ec7e9dbe19fa53a16ab7d
|
C#
|
luispedrovieira30/LI4
|
/WWB/DataAccess/UserDAO.cs
| 3
| 3
|
using System;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using WorldWideBasketball.Models;
namespace WorldWideBasketball.DataAccess
{
public class UserDAO
{
private Connection connection = new Connection();
public bool isValid(Account account)
{
this.connection.open();
string query = "select * from [Utilizador] where Email='" + account.Email + "' and Password='" + account.Password + "'";
SqlDataReader dr = this.connection.executeReader(query);
if (dr.Read())
{
dr.Close();
this.connection.close();
return true;
}
else
{
dr.Close();
this.connection.close();
return false;
}
}
public int Insert(Account account)
{
if (account.Email == null || account.Email == "" || !account.Email.Contains("@"))
{
return -1;
}
if (account.Password != account.ConfirmPassword)
{
return 2;
}
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime localDate = DateTime.Now;
if (localDate < account.Data)
return 8;
TimeSpan span = localDate - account.Data;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
if (years < 18 || years > 100)
{
return 8;
}
// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);
this.connection.open();
string query = "select * from [Utilizador] where Email='" + account.Email + "'";
SqlDataReader dr = this.connection.executeReader(query);
if (dr.Read())
{
Console.WriteLine("User já Existente");
dr.Close();
this.connection.close();
return 7;
}
else
{
dr.Close();
Console.WriteLine("Registering ...");
query = "Insert into [Utilizador] VALUES('" + account.Username + "', '" + account.Password + "', '" + account.Data + "', '" + account.Email + "', '" + account.Name + "');";
try
{
this.connection.executeQuery(query);
Console.WriteLine("Sucesso");
this.connection.close();
return 1;
}
catch (SqlException)
{
Console.WriteLine("Erro no Registo");
this.connection.close();
return 6;
}
}
}
}
}
|
ebf9ef72de5da422a7fecabf5f2ec38c8a28cbfe
|
C#
|
LeonardoLDSZ/Entra21-WindowsForms
|
/Academia/Academia/Dominio/Modalidade.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Academia.Dominio
{
class Modalidade
{
}
}
//public class Modalidade : IMensalidade
//{
// public string Nome { get; set; }
// public Professor Professor { get; set; }
// public int VezesSemana { get; set; }
// public double PrecoHora { get; set; }
// public Modalidade(string nome, int vezesSemana, double precoHora, Professor professor)
// {
// Nome = nome;
// VezesSemana = vezesSemana;
// PrecoHora = precoHora;
// Professor = professor;
// }
// public double CalcularValor()
// {
// return PrecoHora * VezesSemana * 4;
// }
// public override string ToString()
// {
// return $"{Nome}";
// }
//}
|
d8cf0493cf122ccb3cae3a712aa7d2c5b37a336b
|
C#
|
iambenjamin-developer/autocor
|
/autocorapi/AutocorApi/AutocorApi.Servicios/Email/Implementation/EnviadorEmail.cs
| 2.53125
| 3
|
using System;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace AutocorApi.Servicios.Email.Implementation
{
public class EnviadorEmail : IEnviadorEmail
{
private IConfiguracionEmail configuracion;
public EnviadorEmail(IConfiguracionEmail configuracion)
{
this.configuracion = configuracion;
}
public bool EnviarEmail(string para, string asunto, string mensaje, string from = null, string cc = null, string bcc = null, string replyTo = null, bool esHtml = true)
{
if(string.IsNullOrEmpty(from))
{
from = configuracion.From;
}
using (MailMessage message = new MailMessage())
{
message.To.Add(para); // a que dirección se envía
message.From = new MailAddress(configuracion.Email, from, Encoding.UTF8); // desde dónde se envía
message.Subject = asunto;
message.Body = mensaje;
if (!string.IsNullOrEmpty(cc)) { message.CC.Add(cc); }
if (!string.IsNullOrEmpty(bcc)) { message.Bcc.Add(bcc); }
if (!string.IsNullOrEmpty(replyTo)) { message.ReplyToList.Add(replyTo); }
message.SubjectEncoding = Encoding.UTF8;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = esHtml;
SmtpClient client = new SmtpClient(configuracion.Host, configuracion.Port)
{
Credentials = new NetworkCredential(configuracion.Email, configuracion.Password),
EnableSsl = configuracion.SSL
};
try
{
client.Send(message);
return true;
}
catch (Exception ex)
{
// TODO: agregar log
}
}
return false;
}
}
}
|
84230e82e777698b55070b6f48641c3646c1a12c
|
C#
|
nikolabojovic97/InstaBazaar
|
/InstaBazaar/InstaBazaar.Data/Data/Repository/InstagramAccountRepository.cs
| 2.765625
| 3
|
using InstaBazaar.Data.Data.Repository.IRepository;
using InstaBazaar.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InstaBazaar.Data.Data.Repository
{
public class InstagramAccountRepository : Repository<InstagramAccount>, IInstagramAccountRepository
{
private new readonly ApplicationDbContext context;
public InstagramAccountRepository(ApplicationDbContext context) : base(context)
{
this.context = context;
}
public IEnumerable<InstagramAccount> GetByCategory(Category category)
{
var accounts = context.InstagramAccounts;
return GetByCategory(accounts, category);
}
public IEnumerable<InstagramAccount> GetByCategory(IEnumerable<InstagramAccount> accounts, Category category)
{
foreach (var account in accounts)
if (account.CategoryId == category.Id)
yield return account;
}
public IEnumerable<InstagramAccount> GetByCategories(IEnumerable<InstagramAccount> accounts, IEnumerable<Category> categories)
{
foreach (var category in categories)
yield return (InstagramAccount)GetByCategory(accounts, category);
}
public async Task<IEnumerable<InstagramAccount>> SearchAsync(string search)
{
return await Task.Run(() =>
{
var accounts = context.InstagramAccounts;
return Search(accounts, search).ToList();
});
}
public IEnumerable<InstagramAccount> Search(IEnumerable<InstagramAccount> accounts, string search)
{
search = search.ToLower();
return accounts.Where(x => x.IgUserName.ToLower().Contains(search) || x.Description.ToLower().Contains(search)).ToList();
}
public async Task UpdateAsync(InstagramAccount account)
{
await Task.Run( async () =>
{
var accountDb = await context.InstagramAccounts.FirstOrDefaultAsync(x => x.Id == account.Id);
accountDb.IgUserName = account.IgUserName;
accountDb.Description = account.Description;
accountDb.TotalFollowers = account.TotalFollowers;
accountDb.TotalPosts = account.TotalPosts;
accountDb.AvgComments = account.AvgComments;
accountDb.AvgLikes = account.AvgLikes;
accountDb.Services = account.Services;
});
}
public async Task UpdateAccountCategoryAsync(InstagramAccount account, Category category)
{
await Task.Run( async () =>
{
var accountDb = await context.InstagramAccounts.FirstOrDefaultAsync(x => x.Id == account.Id);
accountDb.CategoryId = category.Id;
accountDb.Category = category;
});
}
}
}
|
227d8ea66ee0c7151a44503b1019e823c333f0ef
|
C#
|
Vytur/Caesar_cipher
|
/Caesar_cipher.UnitTests/DecryptionTests.cs
| 2.9375
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Caesar_cipher.UnitTests
{
[TestClass]
public class DecryptionTests
{
[TestMethod]
public void Decryption_WithOneWord_CorrectEncryption()
{
string PlainText = "effe";
int key = 4;
string expected = "abba";
var actual = Program.Decryption(PlainText, key);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Decryption_WithManyWords_CorrectEncryptionWithSpaces()
{
string PlainText = "kllk sc k wecsm lkxn";
int key = 10;
string expected = "abba is a music band";
var actual = Program.Decryption(PlainText, key);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Decryption_WithBigKey_CorrectEncryption()
{
string PlainText = "ghhg luxskj ot 1972";
int key = 1410;
string expected = "abba formed in 1972";
var actual = Program.Decryption(PlainText, key);
Assert.AreEqual(expected, actual);
}
}
}
|
7b365d6a0e40836e39b5e1aec537298a10bf28e9
|
C#
|
roeyskoe/Jypeli
|
/Jypeli/Storage/FileManager/Directories.cs
| 3.1875
| 3
|
using System.Collections.Generic;
namespace Jypeli
{
public partial class FileManager
{
private Stack<string> prevDirs = new Stack<string>();
protected string _currentDir;
/// <summary>
/// Nykyinen tyhakemisto.
/// </summary>
public string CurrentDirectory
{
get { return _currentDir; }
set { ChDir( value ); }
}
/// <summary>
/// Vaihtaa nykyist hakemistoa.
/// </summary>
/// <param name="path">Hakemistopolku</param>
/// <returns>Vaihdettiinko hakemistoa</returns>
public abstract bool ChDir( string path );
/// <summary>
/// Luo uuden hakemiston.
/// </summary>
/// <param name="path">Luotavan hakemiston nimi.</param>
public abstract void MkDir( string path );
/// <summary>
/// Poistaa hakemiston.
/// </summary>
/// <param name="path">Poistettavan hakemiston nimi.</param>
public abstract void RmDir( string path );
/// <summary>
/// Vaihtaa tyhakemistoa jtten edellisen hakemiston muistiin.
/// Kutsu PopDir kun haluat palauttaa tyhakemiston edelliseen arvoonsa.
/// </summary>
/// <param name="dir"></param>
public void PushDir( string dir )
{
prevDirs.Push( _currentDir );
ChDir( dir );
}
/// <summary>
/// Palauttaa edellisen tyhakemiston.
/// Jos edellist tyhakemistoa ei ole tallennettu, silytetn nykyinen.
/// </summary>
public void PopDir()
{
if ( prevDirs.Count > 0 )
_currentDir = prevDirs.Pop();
}
}
}
|
87d91bf702fffcb6b78de7751926a3fa1fe28e76
|
C#
|
thiagovas/Net3s
|
/Net3Services/Models/Notificacao.cs
| 2.78125
| 3
|
using System;
using MongoDB;
namespace Models
{
//Se mudar alguma coisa neste enum, lembre-se de mudar nos metodos de montar objeto e documento na classe ClsNotificacaoDAL.
//Cria um elemento enum TipoNotificacao pra controlar o tipo da notificação. O tipo da notificação informa a classe de cadastro a
// necessidade (ou a falta dela) de se ler alguns campos.
//Junior - adicionei o tipo de notificação de denuncia, caso seje para aviso
public enum TipoNotificacao : short
{
Network = 0,
Orcamento = 1,
Denuncia = 2
}
//Se mudar alguma coisa neste enum, lembre-se de mudar nos metodos de montar objeto e documento na classe ClsNotificacaoDAL.
/// <summary>
/// Verifica qual a prioridade daquela notificação
/// </summary>
/// <by>Marcio Mansur - marciorabelom@hotmail.com</by>
public enum Prioridade : short
{
Baixa = 0,
Media = 1,
Alta = 2,
Urgente = 3
}
/// <summary>
/// Enum que serve para ajudar a identificar o status atual de uma notificação.
/// </summary>
public enum StatusNotif : short
{
Aceito,
Bloqueado, //Usado em notificações que o seu objetivo é pedir a outro usuario que ele seja adicionado a um network de outro usuário.
Pendente
}
/// <summary>
/// Classe que representa o model da notificação.
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public class Notificacao
{
private TipoNotificacao internalTipo;
/// <summary>
/// Oid da notificação. Variavel de controle interno
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public MongoDB.Oid _id { get; set; }
/// <summary>
/// Usuário que gerou a notificação ao ter requisitado um pedido de amizade ou uma solicitação de orçamento
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public Oid idRemetente { get; set; }
/// <summary>
/// Usuário que recebe a notificaçõe
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public Oid idDestinatario { get; set; }
/// <summary>
/// Titulo que aparecerá na notificação
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public string assunto { get; set; }
/// <summary>
/// Breve descrição escrita pelo remetente sobre a notificação gerada.
/// Pode ser uma mensagem escrita ao se adicionar o usuário ao network ou a
/// descrição da solicitação de orçameto.
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public string descricao { get; set; }
/// <summary>
/// Indica se a notificação já foi respondida ou se ainda deve ser respondida (ou ignorada).
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public StatusNotif status { get; set; }
/// <summary>
/// Define o tipo da notificação. O tipo será utilizado no cadastro da notificação para saber quais campos devem ou não
/// ser lidos
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public TipoNotificacao tipo
{
get { return internalTipo; }
set
{
internalTipo = value;
if (value != TipoNotificacao.Orcamento)
{
idServico = null;
qtdContratada = null;
}
}
}
//Propriedade de prioridade
public Prioridade prioridade { get; set; }
/// <summary>
/// Data em que a notificação foi gerada
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public DateTime dataNotificacao { get; set; }
/* Tudo a partir desta linha só deve ser utilizado caso a otificação seja do tipo Orcamento(1) */
/// <summary>
/// Oid do serviço que deseja ser contratado
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public Oid idServico { get; set; }
/// <summary>
/// Quantidade do serviço que será solicitada. A quantidade está de acordo com a unidade de medida informada no
/// cadastro do serviço.
/// </summary>
/// <by>Breno Pires - breno_spires@hotmail.com</by>
public double? qtdContratada { get; set; }
}
}
|
fdcb939843fc53addfab099d20a4560a64e7a102
|
C#
|
svatasoiu/OptionSimulator
|
/OptionSimulator/HestonModel.cs
| 2.71875
| 3
|
using MathNet.Numerics.LinearAlgebra;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OptionSimulator
{
class HestonModel : IStock_Simulator
{
public bool simulate_stock(Collection<Stock> stocks, Matrix<double> cov,
double r, double T, int intervals, int num_samples,
Dictionary<string, double> extra_params)
{
Matrix<double> C = Matrix<double>.Build.DiagonalIdentity(stocks.Count);
if (cov != null)
C = cov.Cholesky().Factor;
for (int i = 0; i < num_samples; ++i)
{
Matrix<double> Z = Matrix<double>.Build.Random(stocks.Count, intervals);
Matrix<double> Y;
if (cov == null)
Y = Z;
else
Y = C * Z;
for (int j = 0; j < stocks.Count; ++j)
compute_path(stocks[j], j, intervals, i, r, Y, T, extra_params);
}
return true;
}
private static object compute_path(Stock stock, int stock_index, int intervals,
int sample_num, double r, Matrix<double> Y, double T, Dictionary<string, double> extra_params)
{
// do euler scheme to compute volatility
double theta = extra_params["theta"];
double long_var = extra_params["long_var"];
double eps = extra_params["eps"];
double dt = T / intervals;
Vector<double> Z = Vector<double>.Build.Random(intervals);
Vector<double> volatilities = Vector<double>.Build.Dense(intervals);
double vol = stock.Sig;
volatilities[0] = vol;
for (int i = 0; i < intervals - 1; ++i) {
double v = Math.Max(vol,0);
vol += theta * (long_var - v) * dt + eps * Math.Sqrt(v*dt) * Z[i];
volatilities[i+1] = vol;
}
// do euler scheme to compute stock price
double price = stock.InitialPrice;
for (int i = 0; i < intervals; ++i)
{
double v = Math.Max(volatilities[i], 0);
price *= Math.Exp((r - v / 2.0) * dt + Math.Sqrt(dt * v) * Y[stock_index, i]); // not just Y
stock.price_paths[sample_num, i] = price;
}
return null;
}
public void EnableInput(MainWindow mainWindow)
{
mainWindow.theta_txt.IsEnabled = true;
mainWindow.longvar_txt.IsEnabled = true;
mainWindow.eps_txt.IsEnabled = true;
}
}
}
|
d9421e3fb624427da7a0e51d4d5d17cfe6f73768
|
C#
|
JohannesDeWet/Military-Flight-Simulator
|
/PRG282_Project_LijaniVWDV_JohannesDW/PRG282_Project_LijaniVWDV_JohannesDW/DataHandlers/TextFileDataHandler.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace PRG282_Project_LijaniVWDV_JohannesDW.DataHandlers
{
class TextFileDataHandler
{
private string filepath = @"Resources\TextFiles\MissionReport.txt";
/*
the format of the file should be as follows
(targetes identified)^(targeted locaiton)^(target damage delt)^(max possible damage to targets)^(obsticalse identified)^(obsticalse location)
^(mission time)^(Plane used)^(Distance traveled)^(feul used)^(inventory used)
*/
public List<string> ReadExternalReportFile()
{
List<string> reportdetails = new List<string>();
string fileLine;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader srReader = new StreamReader(filepath);
//Read line of text
fileLine = srReader.ReadLine();
//Continue to read until end of file
while (fileLine != null)
{
//write the line to list
reportdetails.Add(fileLine);
//Read the next line
fileLine = srReader.ReadLine();
}
//close the file
srReader.Close();
}
catch (Exception) { MessageBox.Show("Error: Reading reportdata failed, please contact developer"); }
return reportdetails;
}
public void WriteExternalReportFile(string[] targetesIdentified, string[] targetedLocaitons, int[] targetDamageDelt, int maxPossibleDamage, string[] obsticalseIdentified, string[] obsticaleLocation, string missionTime, string planeUsed, float DistanceTraveled,int MaxFeul, float feulUsed, string[] inventoryStart,string[] inventoryUsed)
{
string identifiedTargets = "";
string locationOfTarget = "";
string damageToTarget = "";
for (int i = 0; i < targetesIdentified.Length; i++)
{
identifiedTargets += targetesIdentified[i] + "*";
locationOfTarget += targetedLocaitons[i] + "*";
damageToTarget += targetDamageDelt[i] + "*";
}
string identifiedOdsticles = "";
string locationOfOdsticles = "";
for (int i = 0; i < obsticalseIdentified.Length; i++)
{
identifiedOdsticles += obsticalseIdentified[i] + "*";
locationOfOdsticles += obsticaleLocation[i] + "*";
}
string Startinventory = "";
for (int i = 0; i < inventoryStart.Length; i++)
{
Startinventory += inventoryStart[i] + "*";
}
string Usedinventory = "";
for (int i = 0; i < inventoryUsed.Length; i++)
{
Usedinventory += inventoryUsed[i] + "*";
}
try
{
using (StreamWriter writer = new StreamWriter(filepath, true))
{
writer.WriteLine(identifiedTargets + "^" + locationOfTarget + "^" + damageToTarget + "^" + maxPossibleDamage + "^" + identifiedOdsticles + "^" + locationOfOdsticles + "^" + missionTime + "^" + planeUsed + "^" + DistanceTraveled + "^" + MaxFeul + "^" + feulUsed + "^" + Startinventory + "^" + Usedinventory);
}
}
catch (Exception)
{
MessageBox.Show("An Error Occured writing to the file");
throw;
}
}
}
}
|
bc6e10bdcd3546e8bb7e451461e535fee8c96a04
|
C#
|
khalid19/MvcApplication
|
/MVCTest/MVCTest/Controllers/PersonController.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTest.DAL;
namespace MVCTest.Controllers
{
public class PersonController : Controller
{
//
// GET: /Person/
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
Test3DbContext db = new Test3DbContext();
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Image/" + ImageName);
// save image in folder
file.SaveAs(physicalPath);
//save new record in database
Person newRecord = new Person();
newRecord.FirstName = Request.Form["FirstName"];
newRecord.LastName = Request.Form["FirstName"];
newRecord.Date = Convert.ToDateTime(Request.Form["Date"]);
newRecord.Salary = Convert.ToDouble(Request.Form["Salary"]);
newRecord.ImgeURL = ImageName;
db.People.Add(newRecord);
db.SaveChanges();
}
//Display records
return RedirectToAction("Display");
}
public ActionResult Display()
{
return View();
}
}
}
|
6118e94519d74e6222bc127dd51c1b5dbb046cf6
|
C#
|
azulengine/AzulEngine
|
/GameEngine/SpriteEngine/SpriteLayer.cs
| 2.84375
| 3
|
//<AzulEngine - Game engine for monogame>
//Copyright (C) <2013>
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using AzulEngine.EngineUtils;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace AzulEngine.SpriteEngine
{
/// <summary>
/// Clase que representa una capa compuesta de varias secuencias de sprites
/// </summary>
public class SpriteLayer : AbstractLayer
{
/// <summary>
/// Obtiene o establece el catálogo de sprites
/// </summary>
public SpriteCatalog SpriteCatalog { get; set; }
/// <summary>
/// Obtiene o establece una colección de secuencias de cuadros
/// </summary>
public SpriteSequence[] SpriteSequences { get; set; }
private int currentSequenceIndex;
/// <summary>
/// Obtiene o establece el indice de la secuencia actual a dibujar
/// </summary>
public int CurrentSequence {
get
{
return this.currentSequenceIndex;
}
set
{
this.currentSequenceIndex = (int)MathHelper.Clamp(value, 0, this.SpriteSequences.Length);
}
}
/// <summary>
/// Obtiene o establece el ancla de la capa
/// </summary>
public Anchor Anchor { get; set; }
/// <summary>
/// Obtiene o establece el tiempo acumulado que se utiliza para calcular el tiempo de cambio de un cuadro en la secuencia.
/// </summary>
private float TotalElapsedTime;
/// <summary>
/// Obtiene o establece un efecto de tipo Microsoft.Xna.Framework.Graphics.SpriteEffect, que
/// rota la imagen 180 Grados
/// </summary>
public SpriteEffects SpriteEffects;
/// <summary>
/// Inicializa una nueva instancia de la clase AzulEngine.SpriteEngine.SpriteLayer que permite
/// crear una instancia completa con transparencia, visibilidad, posición,escala,velocidad, independencia de cámara y dirección de movimiento
/// </summary>
/// <param name="spriteCatalog">Catálogo de cuadros</param>
/// <param name="spriteSecuence">Colección de secuencia de cuadros</param>
/// <param name="transparency">Transparencia de la capa</param>
/// <param name="visible">Visibilidad de la capa</param>
/// <param name="position">Posición de la capa</param>
/// <param name="zoomScale">Escala inicial de la capa</param>
/// <param name="velocity">Velocidad de desplazamiento de la capa</param>
/// <param name="spriteEffects">Efecto de rotación sobre el sprite</param>
/// <param name="cameraIndependent">Indica si la capa es independiente del movimiento de la cámara</param>
/// <param name="direction">Dirección de desplazamiento de la capa cuando esta es independiente de la cámara</param>
public SpriteLayer(SpriteCatalog spriteCatalog, SpriteSequence[] spriteSecuence, float transparency, Boolean visible, Vector2 position, Vector2 zoomScale, Vector2 velocity, SpriteEffects spriteEffects, bool cameraIndependent, LayerMovementDirection direction)
: base(transparency, visible, position, zoomScale, velocity, cameraIndependent, direction)
{
this.SpriteCatalog = spriteCatalog;
this.SpriteSequences = spriteSecuence;
this.Anchor = Anchor.None;
this.SpriteEffects = spriteEffects;
this.TotalElapsedTime = 0f;
}
/// <summary>
/// Inicializa una nueva instancia de la clase AzulEngine.SpriteEngine.SpriteLayer que permite
/// crear una instancia completa con transparencia, visibilidad, posición,escala,velocidad, independencia de cámara y un anclaje de eje
/// </summary>
/// <param name="spriteCatalog">Catálogo de cuadros</param>
/// <param name="spriteSecuence">Colección de secuencia de cuadros</param>
/// <param name="transparency">Transparencia de la capa</param>
/// <param name="visible">Visibilidad de la capa</param>
/// <param name="position">Posición de la capa</param>
/// <param name="zoomScale">Escala inicial de la capa</param>
/// <param name="velocity">Velocidad de desplazamiento de la capa</param>
/// <param name="spriteEffects">Efecto de rotación sobre el sprite</param>
/// <param name="cameraIndependent">Indica si la capa es independiente del movimiento de la cámara</param>
/// <param name="anchor">Anclaje del sprite</param>
public SpriteLayer(SpriteCatalog spriteCatalog, SpriteSequence[] spriteSecuence, float transparency, Boolean visible, Vector2 position, Vector2 zoomScale, Vector2 velocity, SpriteEffects spriteEffects, bool cameraIndependent, Anchor anchor)
: base(transparency, visible, position, zoomScale, velocity, cameraIndependent, LayerMovementDirection.None)
{
this.SpriteCatalog = spriteCatalog;
this.SpriteSequences = spriteSecuence;
this.Anchor = anchor;
this.SpriteEffects = spriteEffects;
this.TotalElapsedTime = 0f;
}
/// <summary>
/// Inicializa una nueva instancia de la clase AzulEngine.SpriteEngine.SpriteLayer que permite
/// crear una instancia solo con un cátalogo y una colección de secuencias
/// </summary>
/// <param name="spriteCatalog">Cátalogo de cuadros </param>
/// <param name="spriteSecuence">Secuencia de cuadros</param>
public SpriteLayer(SpriteCatalog spriteCatalog, SpriteSequence[] spriteSecuence)
: this(spriteCatalog, spriteSecuence, 1.0f, true, Vector2.Zero, Vector2.One, Vector2.One, SpriteEffects.None, false, LayerMovementDirection.None)
{ }
/// <summary>
/// Obtiene el Tamaño de la capa
/// </summary>
public override Point Size
{
get
{
int width = this.SpriteCatalog.Size.X;
int height = this.SpriteCatalog.Size.Y;
return new Point(width, height);
}
}
/// <summary>
/// Obtiene el Tamaño de la capa con escala aplicada
/// </summary>
public override Vector2 ScaledSize
{
get
{
Point size = this.Size;
float width = size.X * this.ZoomScale.X;
float height = size.Y * this.ZoomScale.Y;
return new Vector2(width, height);
}
}
public SpriteSequence GetCurrentSequence()
{
return this.SpriteSequences[this.currentSequenceIndex - 1];
}
public bool SpriteCollide(IGameElement gameElement)
{
return false;
}
public void UpdateFrame(float elapsedTime)
{
this.TotalElapsedTime += elapsedTime;
SpriteSequence spriteSequence = this.SpriteSequences[this.CurrentSequence - 1];
if (this.TotalElapsedTime > spriteSequence.StepTime)
{
this.TotalElapsedTime -= spriteSequence.StepTime;
spriteSequence.NextFrame();
}
}
}
}
|
d8b9826a42de560cbae47a597de5331afc489549
|
C#
|
benjaminsampica/designpatterns
|
/src/DecoratorPattern/Tests/MochaTests.cs
| 2.828125
| 3
|
using DecoratorPattern.Components;
using DecoratorPattern.Decorators;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DecoratorPattern.Tests
{
[TestClass]
public class MochaTests
{
private MochaDecorator _decorator;
[TestInitialize]
public void Initialize()
{
_decorator = new MochaDecorator(new EspressoComponent());
}
[TestMethod]
public void GetDescription_IsEspressoCommaMocha() => Assert.AreEqual("Espresso, Mocha", _decorator.GetDescription());
[TestMethod]
public void GetCost_Is1Dollar19Cents() => Assert.AreEqual(1.19m, _decorator.Cost());
[TestMethod]
public void GetCost_TwoMochas_Is1Dollar39Cents() => Assert.AreEqual(1.39m, new MochaDecorator(new MochaDecorator(new EspressoComponent())).Cost());
[TestMethod]
public void GetCost_TwoMochas_IsEspressCommaMochaCommaMocha()
{
BeverageComponent espresso = new EspressoComponent();
espresso = new MochaDecorator(espresso);
espresso = new MochaDecorator(espresso);
Assert.AreEqual("Espresso, Mocha, Mocha", espresso.GetDescription());
}
}
}
|
04d5996e655ffb19d5e92347e7355776faa21040
|
C#
|
dmitrykarpenko/TeamManager
|
/TeamManager.DataLayer/Concrete/EFUnitOfWork.cs
| 2.90625
| 3
|
using TeamManager.DataLayer.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeamManager.Model.Entities;
using System.Collections.Concurrent;
namespace TeamManager.DataLayer.Concrete
{
public class EFUnitOfWork : IUnitOfWork
{
private EFTeamManagerContext _context = new EFTeamManagerContext();
private ConcurrentDictionary<Type, object> _repos = new ConcurrentDictionary<Type, object>();
//all entities which could have a repository
private static readonly List<Type> _entitiesWithRepos = new List<Type>() { typeof(Player), typeof(Team) };
public IRepository<T> GetRepositiry<T>() where T : class, IEntity
{
Type repoType = typeof(T);
if (!_entitiesWithRepos.Contains(repoType))
throw new ArgumentException("Invalid type: " + repoType.Name);
object repo = _repos.GetOrAdd(repoType, new BaseEFRepositiry<T>(_context));
return (IRepository<T>)repo;
}
public void Save()
{
_context.SaveChanges();
}
#region dispose
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed && disposing)
_context.Dispose();
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
|
24e2c2f2e210e9b423b589fe32c18307e2fd5f1c
|
C#
|
kalatchev/Celestial.UIToolkit
|
/src/Celestial.UIToolkit.Core.Tests/Converters/MathOperationConverterTests.cs
| 2.84375
| 3
|
using Celestial.UIToolkit.Converters;
using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using Xunit;
namespace Celestial.UIToolkit.Tests.Converters
{
public class MathOperationConverterTests
{
[Fact]
public void ConvertsValues()
{
var converter = new MathOperationConverter();
double l = 10.5;
double r = 5.5;
converter.Operator = MathOperator.Add;
Assert.Equal(l + r, converter.Convert(l, r, CultureInfo.CurrentCulture));
converter.Operator = MathOperator.Subtract;
Assert.Equal(l - r, converter.Convert(l, r, CultureInfo.CurrentCulture));
converter.Operator = MathOperator.Multiply;
Assert.Equal(l * r, converter.Convert(l, r, CultureInfo.CurrentCulture));
converter.Operator = MathOperator.Divide;
Assert.Equal(l / r, converter.Convert(l, r, CultureInfo.CurrentCulture));
}
[Fact]
public void InputTypeEqualsOutputType()
{
var converter = new MathOperationConverter();
Assert.IsType<string>(converter.Convert("10", 5.5, CultureInfo.CurrentCulture));
}
[Fact]
public void AcceptsConvertibles()
{
var converter = new MathOperationConverter(MathOperator.Multiply);
// I won't test every convertible here, only two very contrary types.
var result = converter.Convert("10", (decimal)10.123, CultureInfo.CurrentCulture);
Assert.IsType<string>(result);
}
[Fact]
public void SilentFailForNullValues()
{
var converter = new MathOperationConverter();
Assert.Null(converter.Convert(null, 1, CultureInfo.CurrentCulture));
Assert.Equal(10, converter.Convert(10, null, CultureInfo.CurrentCulture));
}
[Fact]
public void ThrowsForWrongInputTypes()
{
var converter = new MathOperationConverter();
Assert.Throws<NotSupportedException>(() =>
converter.Convert(10, new object(), CultureInfo.CurrentCulture));
}
[Fact]
public void SupportsMultiValueConversion()
{
IMultiValueConverter converter = new MathOperationConverter(MathOperator.Add);
object[] values = { 1, 2, 3, 4, 5, 6 };
int sum = values.Sum(val => (int)val);
Assert.Equal(
sum,
converter.Convert(values, typeof(int), null, null));
}
[Fact]
public void MultiValueConversionThrowsForEmptyValues()
{
IMultiValueConverter converter = new MathOperationConverter();
Assert.Throws<ArgumentException>(() =>
converter.Convert(new object[] { }, typeof(object), null, null));
}
[Fact]
public void MultiValueConversionThrowsForNonIConvertible()
{
IMultiValueConverter converter = new MathOperationConverter();
Assert.Throws<NotSupportedException>(() =>
converter.Convert(new object[] { new object() }, typeof(object), null, null));
}
}
}
|
9defc73786b50225d78974706ef80e5e8554e48b
|
C#
|
kevinzogg/TournamentOrganizer
|
/TournamentOrganizer/services/TeamManagement.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TournamentOrganizer.domain;
namespace TournamentOrganizer.services
{
class TeamManagement
{
public IList<Team> CreateRandomTeams(IList<Player> players)
{
if (players.Count % 2 == 1)
{
throw new InvalidNumberOfPlayersException("The number of Players available is not even.");
}
List<Team> teams = new List<Team>();
int teamSize = 0;
Team team = new Team();
foreach (Player player in players)
{
team.addPlayer(player);
if (++teamSize % 2 == 0)
{
teams.Add(team);
team = new Team();
}
}
return teams;
}
}
}
|
e7b2634625e3e60113306d6dfee64ade32dced16
|
C#
|
zyxyuanxiao/GameCompanyTechnicalCode
|
/GameClient/Framework/Assets/ThirdPartyLibraries/LogSystem/GCTools.cs
| 2.65625
| 3
|
using System;
using System.Threading;
namespace LogSystem
{
/// <summary>
/// 取自 <<NET CLR via C#>> 第 21 章托管堆和垃圾回收,垃圾回收触发条件
/// </summary>
public static class GCTools
{
//通知运行时在安排垃圾回收时应考虑分配大量的非托管内存。
//GC.AddMemoryPressure(10*1024*1024);//分配 10MB 非托管内存
//GC.RemoveMemoryPressure(10*1024*1024);//销毁 10MB 非托管内存
//强制对所有代进行即时垃圾回收
//GC.Collect();
//强制对零代到指定代进行即时垃圾回收。
//GC.Collect(0);//对 0 代进行垃圾回收,最多 3 代
//强制在 GCCollectionMode 值所指定的时间对零代到指定代进行垃圾回收
//GC.Collect(0,System.GCCollectionMode.Default);//0代默认回收
//返回已经对对象的指定代进行的垃圾回收次数。
// GC.CollectionCount(0);//对 0 代进行 GC 的次数
//返回指定对象的当前代数。
//GC.GetGeneration(obj);//obj 属于哪一代?
//返回指定弱引用的目标的当前代数。
//GC.GetGeneration(WeakReference);//弱引用对象属于哪一代
//检索当前认为要分配的字节数。 一个参数,指示此方法是否可以等待较短间隔再返回,以便系统回收垃圾和终结对象。
//GC.GetTotalMemory(true);单位是 byte
//引用指定对象,使其从当前例程开始到调用此方法的那一刻为止均不符合进行垃圾回收的条件。
//GC.KeepAlive(obj);不让其在 GC 阶段回收内存.
//指定当条件支持完整垃圾回收以及回收完成时,应引发垃圾回收通知。
//GC.RegisterForFullGCNotification(1-99, 1-99);// http://www.csref.cn/vs100/method/System-GC-RegisterForFullGCNotification.html
//请求系统调用指定对象的终结器,此前已为该对象调用 SuppressFinalize。
//GC.ReRegisterForFinalize(this);
//请求系统不要调用指定对象的终结器。
//GC.SuppressFinalize(obj);
//返回已注册通知的状态,用于确定公共语言运行时是否即将引发完整垃圾回收。
//GC.WaitForFullGCApproach();
//挂起当前线程,直到处理终结器队列的线程清空该队列为止。
//GC.WaitForPendingFinalizers();
//GCHanadle 手动监视和控制对象的生存期
//GCSettings默认是客户端模式的 GC,消耗小,可以设置为服务器模式的 GC,消耗大,垃圾回收模式
private static Action<Int32> s_gcDone = null;
public static event Action<Int32> GCDone
{
add
{
//如果之前没有登记的委托,就开始报告通知
if (s_gcDone == null)
{
new GenObject(0);
new GenObject(2);
}
s_gcDone += value;
}
remove { s_gcDone -= value; }
}
private sealed class GenObject
{
private Int32 m_generation;
public GenObject(Int32 generation)
{
m_generation = generation;
}
~GenObject() //这个是 Finalize 方法
{
//如果这个对象在我们希望的(或更高的)代中. 3>2>1>0,GC 是先将 0 代中的对象清除,再 1 代,再 2 代.最多 3 代.
//就通知委托一次 GC 刚刚完成
int g = GC.GetGeneration(this);
if (g >= m_generation)
{
Action<Int32> temp = Volatile.Read(ref s_gcDone);
//回调的次数越多,说明 GC 的次数越多,总内存越小,说明可分配的内存块越小,正常情况下 6-10 秒左右回调一次,大小7-15MB
temp(g);
}
//如果至少还有一个已登记的委托,而且 AppDomain 并非正在卸载
//而且进程并非正在关闭,就继续报告通知
if ((s_gcDone != null) &&
!AppDomain.CurrentDomain.IsFinalizingForUnload() &&
!Environment.HasShutdownStarted)
{
//对于第 0 代,创建一个新对象;对于第二代,复活对象,
//使第 2 代在下次回收时,GC 会再次调用 Finalize
if (m_generation == 0)
{
new GenObject(0);
}
else
{
GC.ReRegisterForFinalize(this);
}
}
}
}
}
}
|
d9da305ff6c3bcdc79bae338617dd65aaf5c4510
|
C#
|
Hydrofluoric0/Stump
|
/src/Stump.DofusProtocol.Types/Types/Game/Context/EntityMovementInformations.cs
| 2.5625
| 3
|
namespace Stump.DofusProtocol.Types
{
using System;
using System.Linq;
using System.Text;
using Stump.DofusProtocol.Types;
using System.Collections.Generic;
using Stump.Core.IO;
[Serializable]
public class EntityMovementInformations
{
public const short Id = 63;
public virtual short TypeId
{
get { return Id; }
}
public int ObjectId { get; set; }
public sbyte[] Steps { get; set; }
public EntityMovementInformations(int objectId, sbyte[] steps)
{
this.ObjectId = objectId;
this.Steps = steps;
}
public EntityMovementInformations() { }
public virtual void Serialize(IDataWriter writer)
{
writer.WriteInt(ObjectId);
writer.WriteShort((short)Steps.Count());
for (var stepsIndex = 0; stepsIndex < Steps.Count(); stepsIndex++)
{
writer.WriteSByte(Steps[stepsIndex]);
}
}
public virtual void Deserialize(IDataReader reader)
{
ObjectId = reader.ReadInt();
var stepsCount = reader.ReadUShort();
Steps = new sbyte[stepsCount];
for (var stepsIndex = 0; stepsIndex < stepsCount; stepsIndex++)
{
Steps[stepsIndex] = reader.ReadSByte();
}
}
}
}
|
a724715c3cb13cef6eaaf9544caca24bb66a3840
|
C#
|
ACHERIFB/ExcerciceCSHARP
|
/AnalyseMot/Program.cs
| 3.34375
| 3
|
//Etape 1 :
//• Dans la fonction Main(), faire saisir un mot à l’utilisateur.On ne fera pas de vérification du mot saisi ; on s’attend à ce qu’il ne comporte que des lettres.
//• Créer une fonction CompterLettres (vide pour l’instant) qui prend en entrée un mot, et renvoie les nombres de lettres, de voyelles et de consonnes
//• Afficher le résultat de l’appel de cette fonction sous la forme : « ”livre” comporte 5 lettres, dont 3 consonnes et 2 voyelles »
//Etape 2 : implémenter le corps de la fonction vide créée précédemment et tester.
using System;
namespace AnalyseMot
{
class Program
{
static void Main(string[] args)
{
string motutilisateur = Console.ReadLine();
CompterLettres(motutilisateur, out int nombreV, out int nombreC);
Console.WriteLine("le mot {0} contient {1} lettres dont {2} consonnes et {3} voyelles", motutilisateur,nombreC+nombreV,nombreC,nombreV );
}
static void CompterLettres(string mot, out int voyelles, out int consonnes)
{
consonnes = 0;
voyelles = 0;
for (int i = 0; i < mot.Length; i++)
{
if (mot[i] == 'a'
|| mot[i] == 'e'
|| mot[i] == 'i'
|| mot[i] == 'o'
|| mot[i] == 'u'
|| mot[i] == 'y'
)
{
voyelles++;
}
else
{
consonnes++;
}
}
}
}
}
|
22274a9806b256f9e88872e0afe48cacdb2052dc
|
C#
|
christian-vigh/sharpthrak
|
/Sources/Windows/WinAPI/DLL/Kernel32/G/GlobalAlloc.cs
| 2.515625
| 3
|
/**************************************************************************************************************
NAME
WinAPI/User32/G/GlobalAlloc.cs
DESCRIPTION
GlobalAlloc() Windows function.
AUTHOR
Christian Vigh, 08/2012.
HISTORY
[Version : 1.0] [Date : 2012/08/31] [Author : CV]
Initial version.
**************************************************************************************************************/
using System ;
using System. Runtime. InteropServices ;
using System. Text ;
using Thrak. WinAPI ;
using Thrak. WinAPI. Enums ;
using Thrak. WinAPI. Structures ;
namespace Thrak. WinAPI. DLL
{
public static partial class Kernel32
{
# region Generic version.
/// <summary>
/// Allocates the specified number of bytes from the heap.
/// <br/>
/// <para>
/// Note The global functions have greater overhead and provide fewer features than other memory management functions.
/// New applications should use the heap functions unless documentation states that a global function should be used.
/// </para>
/// </summary>
/// <param name="uFlags">
/// The memory allocation attributes. If zero is specified, the default is GMEM_FIXED.
/// This parameter can be one or more of the GMEM_Constants values, except for the incompatible combinations that are specifically noted.
/// </param>
/// <param name="dwBytes">
/// The number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies GMEM_MOVEABLE,
/// the function returns a handle to a memory object that is marked as discarded.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the newly allocated memory object.
/// <para>
/// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
/// </para>
/// </returns>
/// <remarks>
/// Windows memory management does not provide a separate local heap and global heap. Therefore, the GlobalAlloc and LocalAlloc functions are essentially the same.
/// <br/>
/// <para>
/// The movable-memory flags GHND and GMEM_MOVABLE add unnecessary overhead and require locking to be used safely.
/// They should be avoided unless documentation specifically states that they should be used.
/// </para>
/// <br/>
/// <para>
/// New applications should use the heap functions to allocate and manage memory unless the documentation specifically states that a global function should be used.
/// For example, the global functions are still used with Dynamic Data Exchange (DDE), the clipboard functions, and OLE data objects.
/// </para>
/// <br/>
/// <para>
/// If the GlobalAlloc function succeeds, it allocates at least the amount of memory requested. If the actual amount allocated is greater than
/// the amount requested, the process can use the entire amount. To determine the actual number of bytes allocated, use the GlobalSize function.
/// </para>
/// <br/>
/// <para>
/// If the heap does not contain sufficient free space to satisfy the request, GlobalAlloc returns NULL.
/// Because NULL is used to indicate an error, virtual address zero is never allocated. It is, therefore, easy to detect the use of a NULL pointer.
/// </para>
/// <br/>
/// <para>
/// Memory allocated with this function is guaranteed to be aligned on an 8-byte boundary. To execute dynamically generated code,
/// use the VirtualAlloc function to allocate memory and the VirtualProtect function to grant PAGE_EXECUTE access.
/// </para>
/// <br/>
/// <para>
/// To free the memory, use the GlobalFree function. It is not safe to free memory allocated with GlobalAlloc using LocalFree.
/// </para>
/// </remarks>
[DllImport ( KERNEL32, SetLastError = true, CharSet = CharSet. Auto )]
public static extern IntPtr GlobalAlloc ( GMEM_Constants uFlags, uint dwBytes ) ;
# endregion
}
}
|
c69bfd295a9bffdabeb277baf18ae60c690dcac2
|
C#
|
michelbelotti/Detector_Autistico
|
/Assets/Scripts/timer.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class timer : MonoBehaviour {
public Text timerText;
public bool debug = false;
private float timerCount = 0;
// Use this for initialization
void Start () {
if(!debug)
{
timerText.enabled = false;
}
else
{
timerText.enabled = true;
}
}
// Update is called once per frame
void Update () {
timerCount += Time.deltaTime;
timerText.text = "Timer = " + timerCount.ToString();
}
}
|
06c84d589ca3d17d905cef2a6b32e6a9b6679a5b
|
C#
|
berkansasmaz/oop-order-automation
|
/deneme2/YetkiliFirma.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SiparisOtomasyonu
{
public class YetkiliFirma
{
//
public Siparis Siparisler { get; set; }
public int YetkiliID { get; set; }
public List <urun> UrunListesi { get; set; }
public void stokAzalt(string u,int Miktar)
{
foreach (urun item in UrunListesi)
{
if (u == item.UrunAdi)
{
UrunListesi[item.UrunKodu - 1].UrunStokMiktarı -= Miktar;
}
}
}
public void UrunEkle(urun urn)
{
UrunListesi.Add(urn);
}
public void UrunCıkart(int index)
{
for (int i = 0; i < UrunListesi.Count; i++)
{
if (index == UrunListesi[i].UrunKodu)
{
UrunListesi.Remove(UrunListesi[i]);
}
}
}
public void UrunGüncelle(int index, string ad,int miktar, string aciklama, int fiyat)
//Gelen index parametresiyle urunlistesi içinde arama yapıp ürün bilgilerini günceller
{
for (int i = 0; i < UrunListesi.Count; i++)
{
if (index == UrunListesi[i].UrunKodu)
{
UrunListesi[i].UrunFiyat = fiyat;
UrunListesi[i].UrunAdi = ad;
UrunListesi[i].UrunStokMiktarı = miktar;
UrunListesi[i].Acıklama = aciklama;
}
}
}
public YetkiliFirma()
{
// StreamReader sınıfının nesnesini türettim.
StreamReader ItemsList = new StreamReader("ItemData.txt");
this.UrunListesi = new List<urun>();
urun u2;
string temp = "";
int i = 0;
while ((temp = ItemsList.ReadLine()) != null)// dosyanın içinde ki verileri çekip temp değişkenine atadım.
{
// temp içinde ki verileri her bir boşluk gördüğünde components dizisine atıyacak şekilde ayarladım.
string[] components = temp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
//Listbox' ta daha sonra yazdırmak için components dizisinin içindeki verilerin bazılarını \t ile ayırarak dataArray değişkenine atadım.
string dataArray = components[0] + "\t\t" + components[1] + "\t\t " + components[2] + " \n";
//Listbox' tan yazdırlan veriyi \t ile daha önce ayırmıştım şimdi ise kullanıcının listbox'tan seçtiği veriyi \t ile ayırarak aldım.
string[] selectedRow = dataArray.Split("\t\t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
// temp içinde ki verileri her bir boşluk gördüğünde components dizisine atıyacak şekilde ayarladım.
string[] components2 = temp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (components2[0] == selectedRow[0])
{
//Çektiğim verileri gerekli değişkenlere atadım.
u2 = new urun();
u2.UrunAdi = components[1];
u2.UrunKodu = Convert.ToInt32(components[0]);
u2.UrunFiyat = Convert.ToInt32(components[2]);
u2.UrunKdv = Convert.ToInt32(components2[4]);
u2.NakliyeAgırlıgı = Convert.ToDouble(components2[5]);
u2.UrunStokMiktarı = Convert.ToInt32(components[3]);
u2.Acıklama = "Ürün Adı: " + u2.UrunAdi + "Ürün Fiyatı: " + u2.UrunFiyat + "Ürün ağırlığı: " + u2.NakliyeAgırlıgı;
UrunListesi.Add(u2);
}
i++;
if (i == 1)
{
temp = "";
i = 0;
}
}
}
}
}
|
abad021a2f3fa3d4ba199529e87935e838591e9e
|
C#
|
dczychon/KlausPeterDiscordBot
|
/src/DiscordBot.Util/Commands/Attributes/CommandVerbAttribute.cs
| 3.34375
| 3
|
using System;
namespace DiscordBot.Util.Commands.Attributes
{
/// <summary>
/// Defines a command verb for a class, that implements the <see cref="ICommand"/> interface
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class CommandVerbAttribute : Attribute
{
/// <summary>
/// Verb that triggers the command when prefixed with a !
/// </summary>
public string Verb { get; }
/// <summary>
/// Description about what the command is doing for help text
/// </summary>
public string Description { get; set; }
/// <summary>
/// Specifies iof the command is hidden when printing out all supported commands
/// </summary>
public bool Hidden { get; set; } = false;
public CommandVerbAttribute(string verb)
{
Verb = verb;
}
}
}
|
56cff92a42f50998288ca56813e41fa5e78d904b
|
C#
|
nmatanski/simple-csharp-compiler-default
|
/SimpleCSharpCompiler/SimpleCSharpCompiler/TableSymbols/LocalVarSymbol.cs
| 2.796875
| 3
|
using System.Reflection;
using System.Text;
using SimpleCSharpCompiler.Tokens;
namespace SimpleCSharpCompiler.TableSymbols
{
public class LocalVarSymbol: TableSymbol
{
public LocalVariableInfo LocalVariableInfo { get; set; }
public LocalVarSymbol(IdentToken token, LocalVariableInfo localVariableInfo): base(token.line, token.column, token.value)
{
LocalVariableInfo = localVariableInfo;
}
public override string ToString()
{
var s = new StringBuilder();
s.AppendFormat("line {0}, column {1}: {2} - {3} localvartype={4} localindex={5}", line, column, value, GetType(), LocalVariableInfo.LocalType, LocalVariableInfo.LocalIndex);
return s.ToString();
}
}
}
|
098d093f5589a37be62ada49dd2b34ca8eab70b1
|
C#
|
AArnott/MessagePack-CSharp
|
/src/MessagePack.UnityClient/Assets/Scripts/Tests/Shims/XUnit.cs
| 2.625
| 3
|
// Xunit to NUnit bridge.
using NUnit.Framework;
using System.Linq;
using System.Collections.Generic;
using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace Xunit
{
public class FactAttribute : NUnit.Framework.TestAttribute
{
public string Skip { get; set; }
}
public class SkippableFactAttribute : FactAttribute
{
}
public class TheoryAttribute : FactAttribute
{
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class InlineDataAttribute : NUnit.Framework.TestCaseAttribute
{
public InlineDataAttribute(params Object[] data)
: base(data)
{
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class MemberDataAttribute : NUnit.Framework.TestCaseSourceAttribute
{
public MemberDataAttribute(string memberName)
: base(memberName)
{
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public sealed class TraitAttribute : Attribute
{
public TraitAttribute(string name, string value)
{
}
}
public static class Skip
{
public static void If(bool condition)
{
}
}
public static class Assert
{
public static T Throws<T>(Action action) where T : Exception
{
return NUnit.Framework.Assert.Throws<T>(new TestDelegate(action));
}
public static Task<T> ThrowsAsync<T>(Func<Task> action) where T : Exception
{
return Task.FromResult(Throws<T>(() => action().GetAwaiter().GetResult()));
}
public static T Throws<T>(Func<object> action) where T : Exception
{
return NUnit.Framework.Assert.Throws<T>(() => action());
}
public static void True(bool value)
{
NUnit.Framework.Assert.IsTrue(value);
}
public static void False(bool value)
{
NUnit.Framework.Assert.IsFalse(value);
}
public static void Null(object expected)
{
NUnit.Framework.Assert.IsNull(expected);
}
public static void Empty(System.Collections.IEnumerable enumerable)
{
Assert.False(enumerable.GetEnumerator().MoveNext());
}
public static void All<T>(IEnumerable<T> collection, Action<T> predicate)
{
foreach (T item in collection)
{
predicate(item);
}
}
public static T IsType<T>(object o)
{
NUnit.Framework.Assert.AreEqual(typeof(T), o.GetType());
return (T)o;
}
public static void Equal<T>(T expected, T actual)
{
NUnit.Framework.Assert.AreEqual(expected, actual);
}
public static void NotEqual<T>(T expected, T actual)
{
NUnit.Framework.Assert.AreNotEqual(expected, actual);
}
public static void NotEmpty<T>(ICollection<T> source)
{
NUnit.Framework.Assert.IsTrue(source.Count != 0);
}
public static void NotNull(object value)
{
NUnit.Framework.Assert.IsNotNull(value);
}
public static void Same(object expected, object actual)
{
NUnit.Framework.Assert.AreSame(expected, actual);
}
public static void NotSame(object expected, object actual)
{
NUnit.Framework.Assert.AreNotSame(expected, actual);
}
}
[Serializable]
public class AssertFailedException : NUnit.Framework.AssertionException
{
public AssertFailedException()
: base("")
{
}
public AssertFailedException(string message) : base(message)
{
}
public AssertFailedException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
namespace Xunit.Abstractions
{
public interface ITestOutputHelper
{
void WriteLine(String message);
void WriteLine(String format, params Object[] args);
}
}
|
37591800c1821bf6a0e93c32f56cd47ac0369ec2
|
C#
|
shendongnian/download4
|
/code1/121356-2081298-4194883-2.cs
| 2.671875
| 3
|
class SomeType {
private int length;
public int Length {
get { return length; }
protected set { length = value; }
}
}
|
959dda39a1da7a09d4b4148dc29e2ee517878cf1
|
C#
|
carlosrevespt/Exercism
|
/csharp/side exercises/armstrong-numbers/ArmstrongNumbers.cs
| 3.90625
| 4
|
using System;
public static class ArmstrongNumbers
{
public static bool IsArmstrongNumber(int number)
{
if (number < 10)
return true;
int digits = NumOfDigits(number);
int numbertoCheck = number;
int sumPowers = 0;
for (int i = 0; i < digits; i++)
{
sumPowers += (int)Math.Pow(numbertoCheck % 10, digits);
numbertoCheck /= 10;
}
return sumPowers == number;
}
private static int NumOfDigits(int number)
{
if (number < 1000000)
{
if (number < 1000)
{
return number < 100 ? 2 : 3;
}
else
{
return number < 10000 ? 4 : (number < 100000 ? 5 : 6);
}
}
else
{
if (number < 100000000)
{
return number < 10000000 ? 7 : 8;
}
else
{
return number < 1000000000 ? 9 : 10;
}
}
}
}
|
fb9249e9d5067d8e1cda63dd3feea3d3e52e83ee
|
C#
|
paul-gilbertson/libtcod-net
|
/libtcod-net/Line.cs
| 2.90625
| 3
|
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace libtcod
{
public static class Line
{
[DllImport (Constants.LibraryName)]
private extern static void TCOD_line_init (int xFrom, int yFrom, int xTo, int yTo);
public static void Setup (Point from, Point to)
{
TCOD_line_init (from.X, from.Y, to.X, to.Y);
}
[DllImport (Constants.LibraryName)]
[return: MarshalAs (UnmanagedType.I1)]
private extern static bool TCOD_line_step (ref int xCur, ref int yCur);
public static IEnumerable<Point> GetPoints (Point starting)
{
int x = starting.X;
int y = starting.Y;
while (!TCOD_line_step (ref x, ref y))
{
yield return new Point (x, y);
}
}
}
}
|
1bfe4f4c0fb17e638448f62ad0032d024ebd17ad
|
C#
|
prashant2611/C-Sharp
|
/Advance/Interface/Interface/Shape/Libraries/Concreate_Class.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Interface.Libraries
{
public class Concreate_Class
{
public double sidelength { get; set; }
public Concreate_Class(double side)
{
sidelength = side;
}
public virtual double Area()
{
throw new NotImplementedException();
}
}
}
|
2eef1ed816c41aecf33906a20879b7f0a29774e1
|
C#
|
DrJohnMelville/Melville
|
/src/Melville.Linq.Statistics/HypothesisTesting/TStatistic.cs
| 2.9375
| 3
|
using System;
using Accord.Statistics.Distributions;
using Accord.Statistics.Distributions.Univariate;
namespace Melville.Linq.Statistics.HypothesisTesting
{
public class Statistic
{
protected readonly IUnivariateDistribution Distribution;
protected readonly double innerValue;
public Statistic(IUnivariateDistribution distribution, double innerValue)
{
Distribution = distribution;
this.innerValue = innerValue;
}
public double OneSidedLessP => Distribution.DistributionFunction(innerValue);
public double OneSidedGreaterP => 1.0 - OneSidedLessP;
public double TwoTailedP
{
get
{
var absT = Math.Abs(innerValue);
return Distribution.DistributionFunction(-absT) + (1 - Distribution.DistributionFunction(absT));
}
}
}
public class TStatistic:Statistic
{
public double T => innerValue;
public double DegreesOfFreedom { get; }
public TStatistic(double t, double degreesOfFreedom):base(new TDistribution(degreesOfFreedom), t)
{
DegreesOfFreedom = degreesOfFreedom;
}
}
public class ChiSquaredStatisic
{
public double ChiSquared { get; }
public int DegreesOfFreedom { get; }
public double P => 1.0 -
new ChiSquareDistribution(DegreesOfFreedom)
.DistributionFunction(ChiSquared);
public ChiSquaredStatisic(double innerValue, int freedom)
{
ChiSquared = innerValue;
DegreesOfFreedom = freedom;
}
}
public class NormalStatistic : Statistic
{
public double Mean { get; }
public double StdDeviation { get; }
public double ZScore => innerValue;
public NormalStatistic(double mean, double stdDeviation, double value) : base(new NormalDistribution(mean, stdDeviation), value)
{
Mean = mean;
StdDeviation = stdDeviation;
}
public override string ToString() => $"T: {ZScore:0.0###} p = {TwoTailedP:0.0##}";
}
public class UStatistic : Statistic
{
public double UMax { get; }
public double UMin { get; }
public double ZScore => innerValue;
public UStatistic(double u1, double u2, double zScore) :
base(new NormalDistribution(0, 1), zScore)
{
UMax = Math.Max(u1, u2);
UMin = Math.Min(u1, u2);
}
}
}
|
9a4d9d4e9d5ec585c8b90a19fe67f8d1d0fdbdc5
|
C#
|
pegovsi/pegov.nasvyazi-api
|
/Pegov.Nasvyazi.Domains/Entities/Groups/Group.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using Pegov.Nasvyazi.Domains.Common;
using Pegov.Nasvyazi.Domains.Entities.Accounts;
using Pegov.Nasvyazi.Domains.Entities.Chats;
using Pegov.Nasvyazi.Domains.Enumerations;
namespace Pegov.Nasvyazi.Domains.Entities.Groups
{
public class Group : Entity
{
protected Group()
{
Id = Guid.NewGuid();
_chats = new List<Chat>();
_groupTypeId = GroupType.System.Id;
}
public Group(string name, Guid accountId, GroupType groupType)
: this()
{
Name = name;
AccountId = accountId;
_groupTypeId = groupType.Id;
}
public Guid AccountId { get; protected set; }
public Account Account { get; protected set; }
public string Name { get; protected set; }
private List<Chat> _chats;
public IReadOnlyCollection<Chat> Chats => _chats;
private int _groupTypeId;
public GroupType GroupType { get; protected set; }
public void AddChat(Guid chatId)
{
var chat = new Chat(chatId);
_chats.Add(chat);
}
public void AddChat(IEnumerable<Guid> chatIds)
{
foreach (var chatId in chatIds)
{
var chat = new Chat(chatId);
_chats.Add(chat);
}
}
}
}
|
e04f5fe237bb56b60f7c9f49d662cec66d5c5a5d
|
C#
|
SkillsFundingAgency/das-providerpayments
|
/src/AcceptanceTesting/SpecByExample/SFA.DAS.Payments.AcceptanceTests/Assertions/ProviderPaymentsAssertions.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.Payments.AcceptanceTests.Contexts;
using SFA.DAS.Payments.AcceptanceTests.TableParsers;
namespace SFA.DAS.Payments.AcceptanceTests.Assertions
{
static class ProviderPaymentsAssertions
{
public static void AssertEasPayments(ProviderAdjustmentsContext context, List<GenericPeriodBasedRow> paymentListForPeriods)
{
foreach (var paymentListForPeriod in paymentListForPeriods)
{
var paymentPeriod = new PeriodDefinition(paymentListForPeriod.Period);
var earningsPeriod = paymentPeriod.TransformPaymentPeriodToEarningsPeriod();
if (earningsPeriod == null)
{
AssertThatThereAreNoPaymentsForPeriod(paymentListForPeriod);
continue;
}
AssertThatPaymentsAreCorrectForPeriod(context, earningsPeriod, paymentListForPeriod);
}
}
static void AssertThatThereAreNoPaymentsForPeriod(GenericPeriodBasedRow period)
{
foreach (var row in period.Rows)
{
if (row.Amount != 0)
{
throw new ApplicationException(
$"The payment {row.Name} for period {period.Period} is made before a payment is possible for this year");
}
}
}
static void AssertThatPaymentsAreCorrectForPeriod(ProviderAdjustmentsContext context,
PeriodDefinition earningsPeriod, GenericPeriodBasedRow period)
{
var payments = context.PaymentsFor(earningsPeriod)
.Select(x => new
{
x.PaymentType,
x.PaymentTypeName,
x.Amount,
}).ToList();
foreach (var row in period.Rows)
{
var payment = payments.Where(x => x.PaymentTypeName == row.Name).Sum(x => x.Amount);
if (row.Amount != payment)
{
throw new ApplicationException(
$"expected: {row.Amount} found: {payment} for {row.Name} for period {period.Period}");
}
}
}
}
}
|
ebc494599ee99a88607ecffbcc6cf0e1ee053ffa
|
C#
|
xingx001/SiS.Communcation
|
/src/SiS.Communication/Business/ModelMessageConvert.cs
| 3.109375
| 3
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace SiS.Communication.Business
{
/// <summary>
/// Provides convert methods between GeneralMessage and model.
/// </summary>
public abstract class ModelMessageConvert
{
#region Constructor
/// <summary>
/// Create an instance of ModelMessageConvert
/// </summary>
public ModelMessageConvert()
{
Type thisType = typeof(ModelMessageConvert);
_deserializeMethod = thisType.GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Instance);
}
#endregion
#region Private Members
private MethodInfo _deserializeMethod;
#endregion
#region Abstract Functions
/// <summary>
/// Serialize model into string. The type of the model must be registered in dict. See RegisteredTypeDict.
/// </summary>
/// <param name="model">The model to serialize.</param>
/// <returns>The serialize result in string type.</returns>
protected abstract string Serialize(object model);
/// <summary>
/// Deserialize text into model.The type of T must be registered in dict. See RegisteredTypeDict.
/// </summary>
/// <param name="text">The text to deserialize.</param>
/// <returns>The deserialized model.</returns>
protected abstract T Deserialize<T>(string text);
/// <summary>
/// A dictionary representing the mapping between strings and type, which is used to serialize model and deserialize text.
/// </summary>
protected abstract Dictionary<string, Type> RegisteredTypeDict { get; }
#endregion
#region Public Functions
/// <summary>
/// Convert "GeneralMessage" into model.If the "MessageType" is not found in the mapping dictionary, an exception will be thrown out.
/// </summary>
/// <param name="message">The message to convert, see GeneralMessage.</param>
/// <returns>The converted model.</returns>
public object ToModel(GeneralMessage message)
{
if (!RegisteredTypeDict.ContainsKey(message.MessageType))
{
throw new MessageTypeNotRegisteredException($"{message.MessageType} is not registered.");
}
Type type = RegisteredTypeDict[message.MessageType];
MethodInfo deMethod = _deserializeMethod.MakeGenericMethod(type);
return deMethod.Invoke(this, new object[] { message.Body });
}
/// <summary>
/// Convert model into "GeneralMessage".If the type of the model is not found in the mapping dictionary, an exception will be thrown out.
/// </summary>
/// <param name="model">The model to convert.</param>
/// <returns>The converted message, see GeneralMessage.</returns>
public GeneralMessage ToMessage(object model)
{
string messageTypeName = null;
Type modelType = model.GetType();
foreach (string typeName in RegisteredTypeDict.Keys)
{
if (RegisteredTypeDict[typeName].Equals(modelType))
{
messageTypeName = typeName;
break;
}
}
if (messageTypeName == null)
{
throw new Exception("the model is not registered.");
}
GeneralMessage message = new GeneralMessage()
{
MessageType = messageTypeName,
Body = this.Serialize(model)
};
return message;
}
#endregion
#region Static Functions
/// <summary>
/// Get the descendants of the types in specific assembly.
/// </summary>
/// <param name="assembly">The assembly to search.</param>
/// <param name="baseTypes">The types to get descendants.</param>
/// <returns>The descendants of the input types.</returns>
public static IEnumerable<Type> GetTypeDescendants(Assembly assembly, params Type[] baseTypes)
{
List<Type> typeList = new List<Type>();
foreach (Type baseType in baseTypes)
{
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
if (type.Attributes.HasFlag(TypeAttributes.Abstract))
{
continue;
}
Type tempType = type;
while (tempType.BaseType != null)
{
if (tempType.BaseType.Equals(baseType))
{
typeList.Add(type);
break;
}
else
{
tempType = tempType.BaseType;
}
}
}
}
return typeList;
}
/// <summary>
/// Get the descendants of the type in hosted assembly.
/// </summary>
/// <param name="baseType">The type to get descendants.</param>
/// <returns>The descendants of the input type.</returns>
public static IEnumerable<Type> GetTypeDescendants(Type baseType)
{
return GetTypeDescendants(baseType.Assembly, baseType);
}
#endregion
}
}
|
338519d217f8de83eaa0d622e83ba2492bd4653a
|
C#
|
estiam/CSharp_Pokemon_MVVM
|
/PokemonMVVM/DAL/PokemonAPIDAL.cs
| 2.859375
| 3
|
using Newtonsoft.Json;
using PokemonMVVM.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace PokemonMVVM.DAL
{
public static class PokemonAPIDAL
{
const string POKEMON_API_URL = "https://pokeapi.co/api/v2/pokemon/?limit=151";
public static async Task<List<Pokemon>> LoadPokemonsAsync()
{
WebClient wc = new WebClient();
byte[] data = await wc.DownloadDataTaskAsync(new Uri(POKEMON_API_URL));
string json = Encoding.UTF8.GetString(data);
PokemonData result = JsonConvert.DeserializeObject<PokemonData>(json);
return result.Results;
}
public async static Task<Pokemon> LoadPokemonAsync(string pokeUrl)
{
WebClient wc = new WebClient();
byte[] data = await wc.DownloadDataTaskAsync(new Uri(pokeUrl));
string json = Encoding.UTF8.GetString(data);
Pokemon result = JsonConvert.DeserializeObject<Pokemon>(json);
return result;
}
}
}
|
3f1b6a0462ce4c9537e1b6bbbdbe59e00c30ed8e
|
C#
|
spsei-programming/OOP-Examples
|
/DirStats/DirStats/Extensions/DateTimeExtensions.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DirStats.Extensions
{
public class Calculator
{
public delegate double Operation(double x, double y);
public static double Add(double x, double y)
{
return x + y;
}
public static double Substract(double x, double y)
{
return x - y;
}
}
public static class DateTimeExtensionsTest
{
delegate DateTime AddDaysFunc(DateTime date, int daysToAdd);
private static Func<DateTime, int, DateTime> addFunctor = (date, daysToAdd) =>
{
return date.AddDays(daysToAdd);
};
static DateTimeExtensionsTest()
{
//AddDaysFunc f = DateTimeExtensions.AddDay;
//f(DateTime.Now, 2);
//DateTime.Now.AddDay(2);
//DateTimeExtensions.AddDay(DateTime.Now, 2);
addFunctor(DateTime.Now, 2);
List<Calculator.Operation> operations = new List<Calculator.Operation>(5);
operations.Add(Calculator.Add);
operations.Add(Calculator.Substract);
operations.Add(Calculator.Add);
operations.Add(Calculator.Add);
var x = 3;
var y = 2.1;
double res = 0;
foreach (var op in operations)
{
res += op(res, y);
}
; }
}
public static class DateTimeExtensions
{
// Add one day to date time
public static DateTime AddDay(this DateTime date, int daysToAdd)
{
return date.AddDays(daysToAdd);
}
}
}
|
d10a1d7f99ec34074b5714d710b2b1661f5dcf94
|
C#
|
Chieze-Franklin/Tril
|
/Tril.Attributes/AccessModifierAttribute.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tril.Attributes
{
/// <summary>
/// Represents an access modifier to be applied to a type
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Enum | AttributeTargets.Event|
AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Property |
AttributeTargets.Struct | AttributeTargets.Delegate,
AllowMultiple = true, Inherited = false)]
public sealed class AccessModifierAttribute : TrilAttribute
{
string _modifier = "";
/// <summary>
/// Creates a new instance of the Tril.AccessModifierAttribute class
/// </summary>
/// <param name="AccessModifier"></param>
public AccessModifierAttribute(string AccessModifier)
: this(AccessModifier, "*") { }
/// <summary>
/// Creates a new instance of the Tril.AccessModifierAttribute class
/// </summary>
/// <param name="AccessModifier"></param>
/// <param name="targetPlats"></param>
public AccessModifierAttribute(string AccessModifier, params string[] targetPlats)
: base(targetPlats)
{
_modifier = AccessModifier == null ? "" : AccessModifier.Trim();
}
/// <summary>
/// Creates a new instance of the Tril.AccessModifierAttribute class
/// </summary>
/// <param name="AccessModifier"></param>
public AccessModifierAttribute(AccessModifiers AccessModifier)
: this(AccessModifier, "*") { }
/// <summary>
/// Creates a new instance of the Tril.AccessModifierAttribute class
/// </summary>
/// <param name="AccessModifier"></param>
/// <param name="targetPlats"></param>
public AccessModifierAttribute(AccessModifiers AccessModifier, params string[] targetPlats)
: base(targetPlats)
{
if (AccessModifier == AccessModifiers.None)
_modifier = "";
else if (AccessModifier == AccessModifiers.Private)
_modifier = "private";
else if (AccessModifier == AccessModifiers.Protected)
_modifier = "protected";
else if (AccessModifier == AccessModifiers.Public)
_modifier = "public";
else if (AccessModifier == AccessModifiers.ProtectedInternal)
_modifier = "protected internal";
else if (AccessModifier == AccessModifiers.Internal)
_modifier = "internal";
else
_modifier = "";
}
/// <summary>
/// Gets the access modifier applied to a type
/// </summary>
public string AccessModifier
{
get { return _modifier; }
}
}
/// <summary>
/// Lists the recognised access modifiers
/// </summary>
public enum AccessModifiers
{
/// <summary>
/// none specified
/// </summary>
None,
/// <summary>
/// public
/// </summary>
Public,
/// <summary>
/// private
/// </summary>
Private,
/// <summary>
/// protected
/// </summary>
Protected,
/// <summary>
/// internal
/// </summary>
Internal,
/// <summary>
/// protected internal
/// </summary>
ProtectedInternal
}
}
|
eebf565d94841a5c19d3f2fb9ed41cd153da69db
|
C#
|
pr1zralll/MoleculsGame
|
/Molecule.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
// для работы с библиотекой OpenGL
using Tao.OpenGl;
// для работы с библиотекой FreeGLUT
using Tao.FreeGlut;
// для работы с элементом управления SimpleOpenGLControl
using Tao.Platform.Windows;
using System.Threading;
namespace Moleculs
{
public class Molecule
{
public bool alive;
public float r;
public float cx;
public float cy;
public float Vx;
public float Vy;
public int color=1;
public Molecule()
{
alive = false;
}
public void generate()
{
Random rand = new Random();
Vx = (float)rand.NextDouble()-0.5f;
Vy = (float)rand.NextDouble()-0.5f;
r = rand.Next(30);
Thread.Sleep(8);
alive = true;
Color(1);
}
public static float k = 12.0f * 3.14f / 360.0f;
public void move()
{
cx += Vx;
cy += Vy;
}
public void Color(int a)
{
switch(a)
{
case 1: Gl.glColor3f(0.0f, 0.0f, 1.0f); break;
case 2: Gl.glColor3f(1.0f, 0.0f, 0.0f); break;
default: Gl.glColor3f(0.0f, 1.0f, 0.0f); break;
}
}
public virtual void onDraw()
{
if(Form1.player.r>r)
Gl.glColor4f(1.0f, 1.0f, 0.5f,0.5f);
else
Gl.glColor3f(0.0f, 0.0f, 1.0f);
Gl.glBegin(Gl.GL_POLYGON);
for(int i = 0; i < 360; i++)
{
float theta = k * i;//get the current angle
float x = r * (float)Math.Cos(theta);//calculate the x component
float y = r * (float)Math.Sin(theta);//calculate the y component
Gl.glVertex2f(x + cx, y + cy);//output vertex
}
Gl.glEnd();
}
}
}
|
7e1b288e9e06d9ce91aa26ea2ee8a503cecccb2d
|
C#
|
scot140/SideProj
|
/CloneProject/Assets/Resources/UI/GameBoard/Scripts/Board.cs
| 2.765625
| 3
|
using UnityEngine;
using System.Collections;
//THis is a standard board with rows and columns that have no missing tiles
public class Board : MonoBehaviour
{
public Tile[] m_TileList;
public int Width;
public int Height;
// Use this for initialization
void Start()
{
TileConnection();
}
void TileConnection()
{
//Getting the count of the tiles
int TileCount = transform.childCount;
//Creating an array to keep track of the tiles
m_TileList = new Tile[TileCount];
//Grabbing all of the positions
for (int TileIndex = 0; TileIndex < TileCount; TileIndex++)
{
Transform ChildTransform = transform.GetChild(TileIndex);
//Grabbing a reference to the Child components tile
Tile child = m_TileList[TileIndex] = ChildTransform.GetComponent<Tile>();
//assigning the Tile index
child.TileIndex = TileIndex;
AdjacenciesGenerator(child);
}
}
void AdjacenciesGenerator(Tile NosyNeighbor)
{
//Give the tile their neighbors
UpperNeighbors(NosyNeighbor);
SameRowNeighbors(NosyNeighbor);
BottomNeighbors(NosyNeighbor);
//make sure that all neighbors are valid
ValidateNeighbor(NosyNeighbor);
}
void UpperNeighbors(Tile NosyNeighbor)
{
//Upper left Neighbor
NosyNeighbor.Nieghbor[Tile.UPPERLEFT] = NosyNeighbor.TileIndex - (Width + 1);
//Upper Neighbor
NosyNeighbor.Nieghbor[Tile.UPPER] = NosyNeighbor.TileIndex - (Width);
//Upper Right Neighbor
NosyNeighbor.Nieghbor[Tile.UPPERRIGHT] = NosyNeighbor.TileIndex - (Width - 1);
}
void SameRowNeighbors(Tile NosyNeighbor)
{
//Left Neightbor
NosyNeighbor.Nieghbor[Tile.LEFT] = NosyNeighbor.TileIndex - 1;
//Right Neighbor
NosyNeighbor.Nieghbor[Tile.RIGHT] = NosyNeighbor.TileIndex + 1;
}
void BottomNeighbors(Tile NosyNeighbor)
{
//Bottom Left Neighbor
NosyNeighbor.Nieghbor[Tile.BOTTOMLEFT] = NosyNeighbor.TileIndex + (Width - 1);
//Bottom Neighbor
NosyNeighbor.Nieghbor[Tile.BOTTOM] = NosyNeighbor.TileIndex + (Width);
//Bottome Right Neighbor
NosyNeighbor.Nieghbor[Tile.BOTTOMRIGHT] = NosyNeighbor.TileIndex + (Width + 1);
}
//Set all invalid tiles to neagtive one (-1)
void ValidateNeighbor(Tile NosyNeighbor)
{
//Left Side
if (NosyNeighbor.TileIndex % Width == 0)
{
NosyNeighbor.Nieghbor[Tile.LEFT] = -1;
NosyNeighbor.Nieghbor[Tile.UPPERLEFT] = -1;
NosyNeighbor.Nieghbor[Tile.BOTTOMLEFT] = -1;
}
//Upper
if (NosyNeighbor.TileIndex < Width)
{
NosyNeighbor.Nieghbor[Tile.UPPER] = -1;
NosyNeighbor.Nieghbor[Tile.UPPERLEFT] = -1;
NosyNeighbor.Nieghbor[Tile.UPPERRIGHT] = -1;
}
//Right side
if ((NosyNeighbor.TileIndex + 1) % Width == 0)
{
NosyNeighbor.Nieghbor[Tile.RIGHT] = -1;
NosyNeighbor.Nieghbor[Tile.UPPERRIGHT] = -1;
NosyNeighbor.Nieghbor[Tile.BOTTOMRIGHT] = -1;
}
//Bottom
//Finding the last row
int lastRow = (Width * Height) - Width;
lastRow = lastRow - 1;
if (NosyNeighbor.TileIndex > lastRow)
{
NosyNeighbor.Nieghbor[Tile.BOTTOM] = -1;
NosyNeighbor.Nieghbor[Tile.BOTTOMLEFT] = -1;
NosyNeighbor.Nieghbor[Tile.BOTTOMRIGHT] = -1;
}
}
}
|
34c512e5e7b9347c1a6ce11d0320142ee47c0a68
|
C#
|
Nicklas-Eriksson/ConsoleGameFirstC-Course
|
/Items/PowerUp.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
namespace Labb3.Items
{
[Serializable]
public class PowerUp : AbstractItem
{
private int goldCost;
public int GoldCost { get => goldCost; set => goldCost = value; }
public static PowerUp powerUp = new PowerUp();
public static List<PowerUp> staminaList = new List<PowerUp>();
public static List<PowerUp> strengthList = new List<PowerUp>();
public int Bonus { get; set; }
public void Instantiate()
{
//Stamina buff
var minorStamina = new PowerUp()
{
Name = "Minor Stamina",
GoldCost = 100,
ItemLevel = 1,
Bonus = 100,
};
var greaterStamina = new PowerUp()
{
Name = "Greater Stamina",
GoldCost = 200,
ItemLevel = 2,
Bonus = 175,
};
var majorStamina = new PowerUp()
{
Name = "Major Stamina",
GoldCost = 300,
ItemLevel = 3,
Bonus = 250,
};
//Strength buff
var minorStrength = new PowerUp()
{
Name = "Minor Strength",
GoldCost = 100,
ItemLevel = 1,
Bonus = 10,
};
var greaterStrength = new PowerUp()
{
Name = "Greater Strength",
GoldCost = 200,
ItemLevel = 2,
Bonus = 25,
};
var majorStrength = new PowerUp()
{
Name = "Major Strength",
GoldCost = 300,
ItemLevel = 3,
Bonus = 50,
};
//Stamina
staminaList.Add(minorStamina);//0
staminaList.Add(greaterStamina);//1
staminaList.Add(majorStamina);//2
//Strength
strengthList.Add(minorStrength);//0
strengthList.Add(greaterStrength);//1
strengthList.Add(majorStrength);//2
}
}
}
|
90161f330b014dfee10fcc96310341be3b8d9a82
|
C#
|
JohnAgarwal57/Telerik
|
/C# Part2/Homeworks/01. Arrays/MaximalSum/Program.cs
| 3.640625
| 4
|
/*Write a program that finds the sequence of maximal sum in given array. Example:
{2, 3, -6, -1, 2, -1, 6, 4, -8, 8} {2, -1, 6, 4}
Can you do it with only one loop (with single scan through the elements of the array)?
*/
using System;
class Program
{
static void Main()
{
Console.Write("Input array length: ");
int N = int.Parse(Console.ReadLine());
int[] array = new int[N];
for (int i = 0; i < array.Length; i++) //input elements for array
{
Console.Write("Input element {0} of array: ", i);
array[i] = int.Parse(Console.ReadLine());
}
int sum = array[0];
int currentSum = array[0];
int Start = 0;
int currentStart = 0;
int Sequence = 1;
int currentSequence = 1;
for (int i = 1; i < array.Length; i++) //only with 1 loop
{
if (array[i] + currentSum >= array[i])//for every turn we check if current element + currentsum is bigger then the current element
{
currentSum = array[i] + currentSum;//if so we add next element
currentSequence++;//and increasing the sequence by 1(we have sum of 2,3,4..N elements)
}
else
{
currentSum = array[i];//if not we start over again
currentStart = i;//getting new start element for new test
currentSequence = 1;//and sequence of 1(so far)
}
if (currentSum > sum)//check if current sum is bigger then final if so - we change the end variables
{
sum = currentSum;
Sequence = currentSequence;
Start = currentStart;
}
}
// for (int i = Start; i < Start + Sequence; i++)
// Console.Write("{0} ", array[i]);//print the part of the array we're interested in - from start N elements
Console.WriteLine(sum);//print max one
}
}
|
f7944dd33a3a3b3ca8d1a21750905ba790941968
|
C#
|
Neophear/CountDownSimple
|
/CountDownSimple/Form1.cs
| 2.75
| 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 CountDownSimple
{
public partial class Form1 : Form
{
public Settings settings = Settings.Deserialize();
private DetailedTimer timer = new DetailedTimer();
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.ResizeRedraw, true);
LoadSettings();
timer.OnSecondChange += Timer_OnSecondChange;
}
private void Timer_OnSecondChange(object sender, EventArgs e)
{
RefreshLabel();
}
private void LoadSettings(bool setWindow = true)
{
if (setWindow && settings.Location != Point.Empty)
this.Location = settings.Location;
if (setWindow && settings.WindowSize != Size.Empty)
this.Size = settings.WindowSize;
if (settings.TextFont != null)
ctlblTimer.Font = settings.TextFont;
if (settings.BackgroundColor != Color.Empty)
this.BackColor = settings.BackgroundColor;
if (settings.ForeColor != Color.Empty)
ctlblTimer.ForeColor = ctlblBottom.ForeColor = settings.ForeColor;
if (settings.TargetDate != null)
timer.Start(settings.TargetDate);
this.TopMost = settings.AlwaysOnTop;
ctlblBottom.Visible = settings.ShowBottomText;
}
private void RefreshLabel()
{
ctlblTimer.Text = GetFriendlyTime();
this.Text = GetFriendlyTime("[D]:[H]:[M]:[S]");
}
private void Form1_HelpRequested(object sender, HelpEventArgs hlpevent)
{
if (this.Focused)
{
frmSettings frm = new frmSettings(this);
if (frm.ShowDialog() == DialogResult.OK)
{
LoadSettings(false);
timer.Start(settings.TargetDate);
}
}
}
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Escape)
this.Close();
}
private const int cGrip = 4; // Grip size
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x84)
{ // Trap WM_NCHITTEST
Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
pos = this.PointToClient(pos);
if (pos.X <= cGrip && pos.Y <= cGrip)
{
m.Result = (IntPtr)13; // HTTOPLEFT
return;
}
if (pos.X >= this.ClientSize.Width - cGrip && pos.Y <= cGrip)
{
m.Result = (IntPtr)14; // HTTOPRIGHT
return;
}
if (pos.X <= cGrip && pos.Y >= this.ClientSize.Height - cGrip)
{
m.Result = (IntPtr)16; // HTBOTTOMLEFT
return;
}
if (pos.X >= this.ClientSize.Width - cGrip && pos.Y >= this.ClientSize.Height - cGrip)
{
m.Result = (IntPtr)17; // HTBOTTOMRIGHT
return;
}
m.Result = (IntPtr)2; // HTCAPTION
return;
}
base.WndProc(ref m);
}
/// <summary>
/// Returns a more userfriendly time.
/// </summary>
/// <param name="time">The DateTime to modify</param>
/// <returns></returns>
public string GetFriendlyTime(string format = "")
{
if (String.IsNullOrEmpty(format))
format = settings.TextFormat;
format = format.Replace("[D]", timer.Days.ToString());
format = format.Replace("[DT]", (timer.Days == 1 ? "dag" : "dage"));
format = format.Replace("[H]", timer.Hours.ToString());
format = format.Replace("[HT]", (timer.Hours == 1 ? "time" : "timer"));
format = format.Replace("[M]", timer.Minutes.ToString());
format = format.Replace("[MT]", (timer.Minutes == 1 ? "minut" : "minutter"));
format = format.Replace("[S]", timer.Seconds.ToString());
format = format.Replace("[ST]", (timer.Seconds == 1 ? "sekund" : "sekunder"));
format = format.Replace("[LOVE]", "❤️ Henriette ❤️");
return format;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
settings.Location = this.Location;
settings.WindowSize = this.Size;
Settings.Serialize(settings);
}
}
}
|
f8599f70cf106f7680da6b76ace1592f34ae6a66
|
C#
|
HildeDeGraeve/sbmcourse
|
/SbmCourseSolution/MyApplication.DomainModel/DeliveryAggregate/Delivery.cs
| 2.609375
| 3
|
using MySoftwareCompany.DDD;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace MyApplication.DomainModel.DeliveryAggregate
{
public class Delivery : BaseEntity
{
public string ForCustomerId { get; set; }
public string AtDeliveryAddressId { get; set; }
public string ForDate { get; set; }
public bool IsPlanned { get; set; }
private readonly List<DeliveryPart> _deliveryParts = new List<DeliveryPart>();
public IEnumerable<DeliveryPart> DeliveryParts
{
get { return new ReadOnlyCollection<DeliveryPart>(_deliveryParts); }
}
public static Delivery Create(string customerId, string deliveryAddressId, string date)
{
return new Delivery
{
Id = Guid.NewGuid().ToString(),
ForCustomerId = customerId,
AtDeliveryAddressId= deliveryAddressId,
ForDate = date,
IsPlanned = false
};
}
public void SetPlanned()
{
IsPlanned = true;
SendDomainEvent(new DeliveryPlannedEvent(Id));
}
public void AddDeliverPart(string deliveryId, double weight, double volume, List<string> productIds)
{
_deliveryParts.Add(new DeliveryPart
{
Id = Guid.NewGuid().ToString(),
//ProductIds = new List<DeliveryPartProductId>(),
Weight = weight,
Volume = volume
});
}
}
}
|
878757e384d88e7bbfbd9ca70aaf52675ff456a0
|
C#
|
Growney/GWareBase
|
/GWareBase/Gware.Common/XML/XmlResultSet.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Gware.Common.XML
{
public class XmlResultSet
{
private Dictionary<string, string> m_dataNodes;
private List<XmlRowSet> m_rowSets;
public XmlRowSet this[string name]
{
get
{
XmlRowSet retVal = null;
for(int i =0;i < m_rowSets.Count;i ++)
{
XmlRowSet rowSet = m_rowSets[i];
if (rowSet.Name.Equals(name))
{
retVal = rowSet;
break;
}
}
return retVal;
}
}
public XmlResultSet(XmlNode resultNode)
{
m_dataNodes = new Dictionary<string, string>();
m_rowSets = new List<XmlRowSet>();
LoadFromXmlNode(resultNode);
}
private void LoadFromXmlNode(XmlNode node)
{
if(node.HasChildNodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name.Equals("rowset"))
{
m_rowSets.Add(new XmlRowSet(childNode));
}
else
{
if (!m_dataNodes.ContainsKey(childNode.Name))
{
m_dataNodes.Add(childNode.Name, childNode.InnerText);
}
}
}
}
}
public static XmlResultSet GetDocumentResults(XmlDocument doc)
{
return GetDocumentResults((XmlNode)doc);
}
public static XmlResultSet GetDocumentResults(XmlNode node)
{
if (node.HasChildNodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.Name.Equals("result"))
{
return new XmlResultSet(childNode);
}
else
{
XmlResultSet retVal = GetDocumentResults(childNode);
if (retVal != null)
{
return retVal;
}
}
}
}
return null;
}
public override string ToString()
{
return String.Format("{XmlResultSet : {0} data rows {1} rowsets }", m_dataNodes.Count, m_rowSets.Count);
}
}
}
|
a8f5710a3a2f795106f10cf39706537a97f175ff
|
C#
|
gerenciaSoltic/CenturionDoc
|
/gestion_documental/DataAccessLayer/TipocomManagement.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using gestion_documental.Utils;
using gestion_documental.BusinessObjects;
using MySql.Data.MySqlClient;
using System.Data;
namespace gestion_documental.DataAccessLayer
{
public class TipocomManagement : ConnectionClass
{
#region Sql
private string DefaultSelect =
@"SELECT
*
FROM tipocom as c ";
#endregion
#region Constructors
public TipocomManagement()
{
}
#endregion
#region SELECT Commands
/// <summary>
/// Gets the whole list of Cargo
/// <returns>List of Type Cargo</returns>
/// </summary>
public List<Tipocom> GetAllTipoCom()
{
MySqlCommand cmdSelect = Connection.CreateCommand();
cmdSelect.CommandText = this.DefaultSelect+ " order by id";
try
{
if (this.Connection.State == ConnectionState.Closed)
this.Connection.Open();
MySqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
List<Tipocom> allEntes = new List<Tipocom>();
while (dr.Read())
{
Tipocom myEnte = new Tipocom();
#region Params
myEnte.TIPOCOMUNICACION = dr["TIPOCOMUNICACION"].ToString();
myEnte.ID = Convert.ToInt32(dr["ID"]);
myEnte.IDGRUPO = Convert.ToInt32(dr["IDGRUPO"]);
#endregion
allEntes.Add(myEnte);
}
return allEntes;
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
}
}
public List<Tipocom> GetTipoComById( int Idgrupo)
{
MySqlCommand cmdSelect = Connection.CreateCommand();
cmdSelect.CommandText = this.DefaultSelect + " where idgrupo = @Idgrupo order by id";
cmdSelect.Parameters.AddWithValue("@idgrupo", Idgrupo);
try
{
if (this.Connection.State == ConnectionState.Closed)
this.Connection.Open();
MySqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
List<Tipocom> allEntes = new List<Tipocom>();
while (dr.Read())
{
Tipocom myEnte = new Tipocom();
#region Params
myEnte.TIPOCOMUNICACION = dr["TIPOCOMUNICACION"].ToString();
myEnte.ID = Convert.ToInt32(dr["ID"]);
myEnte.IDGRUPO = Convert.ToInt32(dr["IDGRUPO"]);
#endregion
allEntes.Add(myEnte);
}
return allEntes;
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
}
}
public Tipocom GetTipocomIdPrincipal(int id)
{
MySqlCommand cmdSelect = Connection.CreateCommand();
cmdSelect.CommandText = "SELECT * FROM tipocom as c WHERE c.ID = @id ";
cmdSelect.Parameters.AddWithValue("@id", id);
try
{
if (this.Connection.State == ConnectionState.Closed)
this.Connection.Open();
MySqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
Tipocom myEnte = new Tipocom();
while (dr.Read())
{
#region Params
myEnte.TIPOCOMUNICACION = dr["TIPOCOMUNICACION"].ToString();
myEnte.ID = Convert.ToInt32(dr["ID"]);
myEnte.IDGRUPO = Convert.ToInt32(dr["IDGRUPO"]);
#endregion
}
return myEnte;
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
}
}
/// <summary>
/// Gets all the details of a Cargo
/// <returns>Cargo</returns>
/// </summary>
///
#endregion
/*
#region INSERT Commands
/// <summary>
/// Inserts a new Cargo
/// <param name="myEnte">Required a filled instance of Cargo</param>
/// </summary>
public int InsertTipocom(Tipocom myEnte)
{
MySqlCommand cmdInsert = Connection.CreateCommand();
cmdInsert.CommandText = "INSERT INTO tipocom (tipocom) VALUES (@tipocomunicacion);SELECT LAST_INSERT_ID()";
#region params
cmdInsert.Parameters.AddWithValue("@tipocomunicacion", myEnte.TIPOCOMUNICACION);
#endregion
int id = 0;
try
{
if (this.Connection.State == ConnectionState.Closed)
this.Connection.Open();
id = Convert.ToInt32(cmdInsert.ExecuteScalar());
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
}
return id;
}
#endregion
/*
#region UPDATE Commands
public void UpdateTipocom(Tipocom myEnte)
{
MySqlCommand cmdUpdate = Connection.CreateCommand();
cmdUpdate.CommandText = "Update tipocom SET tipocom=@tipocom where tipocom=@tipocom";
#region params
cmdUpdate.Parameters.AddWithValue("@tipocom", myEnte.TIPOCOM);
#endregion
try
{
if (this.Connection.State == ConnectionState.Closed)
this.Connection.Open();
cmdUpdate.ExecuteNonQuery();
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
}
}
#endregion
#region DELETE Commands
/// <summary>
/// Delete Cargo
/// <param name="id">Required a filled instance of Cargo</param>
/// </summary>
public bool DeleteCadenas(int id)
{
MySqlCommand cmdInsert = Connection.CreateCommand();
cmdInsert.CommandText = "DELETE FROM cadenas WHERE id=@id";
#region params
cmdInsert.Parameters.AddWithValue("@id", id);
#endregion
try
{
if (this.Connection.State == ConnectionState.Closed)
this.Connection.Open();
cmdInsert.ExecuteNonQuery();
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
}
return true;
}
#endregion
* */
}
}
|
4161d6393da53018386171f041506d92b9cbbc70
|
C#
|
ianwisely/BookStore
|
/BookStore/Services/SubClasses/Orders/PriceDeductionDiscount.cs
| 2.71875
| 3
|
using BookStore.Models;
using BookStore.Repository;
using BookStore.Repository.Repositories;
using BookStore.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookStore.Services.SubClasses.Orders
{
public class PriceDeductionDiscount : IOrderDiscount
{
public decimal GetTotalPrice(List<Book> books, int userId, int beforePoints, out int afterPoints)
{
decimal totalCost = 0;
foreach (var book in books)
{
totalCost += book.Price;
}
double discount = ((double)beforePoints * .1);
totalCost -= (decimal)discount;
var pointsDeduction = Convert.ToInt32(Math.Ceiling(discount * 10));
afterPoints = beforePoints - pointsDeduction;
if (afterPoints < 0)
{
afterPoints = 0;
}
if (totalCost < 0)
{
return 0;
}
return totalCost;
}
}
}
|
f93d035e97b2498c65bb9c7c2f9480144f2cd57f
|
C#
|
shendongnian/download4
|
/first_version_download2/407564-35584757-111574382-2.cs
| 2.828125
| 3
|
static void Main(string[] args)
{
string s;
Console.WriteLine("Hogy hívnak?");
s = Console.ReadLine();
if (s == "Zsolt")
Console.WriteLine("You are a mean guy :(((");
else Console.WriteLine("You are a nice guy! :)))))");
Console.ReadLine();
}
|
f21707a21127606ef02f8c0cc1c7588c4be84312
|
C#
|
zhou1993yu/CSharpGL
|
/CSharpGL3/0Foundations/OpenGLObjects/GLBuffers/VertexBuffers/IndexBuffers(IBO)/ZeroIndexBuffer.cs
| 2.828125
| 3
|
using System;
namespace CSharpGL
{
// 没有显式索引时的渲染方法。
/// <summary>
/// Wraps glDrawArrays(uint mode, int first, int VertexCount).
/// </summary>
public sealed partial class ZeroIndexBuffer : IndexBuffer
{
private static OpenGL.glDrawArraysInstanced glDrawArraysInstanced;
/// <summary>
/// Invalid for <see cref="ZeroIndexBuffer"/>.
/// </summary>
public override BufferTarget Target
{
get { return BufferTarget.InvalidTarget; }
}
/// <summary>
/// Wraps glDrawArrays(uint mode, int first, int VertexCount).
/// </summary>
/// <param name="mode">用哪种方式渲染各个顶点?(OpenGL.GL_TRIANGLES etc.)</param>
/// <param name="firstVertex">要渲染的第一个顶点的位置。<para>Index of first vertex to be rendered.</para></param>
/// <param name="vertexCount">要渲染多少个元素?<para>How many vertexes to be rendered?</para></param>
/// <param name="primCount">primCount in instanced rendering.</param>
internal ZeroIndexBuffer(DrawMode mode, int firstVertex, int vertexCount, int primCount = 1)
: base(mode, 0, vertexCount, vertexCount * sizeof(uint), primCount)
{
this.FirstVertex = firstVertex;
this.RenderingVertexCount = vertexCount;
//this.OriginalVertexCount = VertexCount;
}
/// <summary>
/// 要渲染的第一个顶点的位置。<para>Index of first vertex to be rendered.</para>
/// </summary>
public int FirstVertex { get; set; }
/// <summary>
/// 要渲染多少个元素?<para>How many vertexes to be rendered?</para>
/// </summary>
public int RenderingVertexCount { get; set; }
///// <summary>
///// 总共有多少个元素?<para>How many vertexes are there in total?</para>
///// </summary>
//public int OriginalVertexCount { get; private set; }
/// <summary>
/// need to do nothing.
/// </summary>
public override void Bind()
{
// need to do nothing.
}
/// <summary>
///
/// </summary>
public override void Render()
{
uint mode = (uint)this.Mode;
int primCount = this.PrimCount;
if (primCount < 1) { throw new Exception("error: primCount is less than 1."); }
else if (primCount == 1)
{
OpenGL.DrawArrays(mode, this.FirstVertex, this.RenderingVertexCount);
}
else
{
if (glDrawArraysInstanced == null)
{ glDrawArraysInstanced = OpenGL.GetDelegateFor<OpenGL.glDrawArraysInstanced>(); }
glDrawArraysInstanced(mode, this.FirstVertex, this.RenderingVertexCount, primCount);
}
}
/// <summary>
/// need to do nothing.
/// </summary>
public override void Unbind()
{
// need to do nothing.
}
/// <summary>
/// Start to read/write buffer.
/// <para>This will returns IntPtr.Zero as this buffer allocates no data in memory.</para>
/// </summary>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <param name="access"></param>
/// <param name="bind"></param>
/// <returns></returns>
public override IntPtr MapBufferRange(int offset, int length, MapBufferRangeAccess access, bool bind = true)
{
return IntPtr.Zero;
}
/// <summary>
/// Start to read/write buffer.
/// <para>This will returns IntPtr.Zero as this buffer allocates no data in memory.</para>
/// </summary>
/// <param name="access"></param>
/// <param name="bind"></param>
/// <returns></returns>
public override IntPtr MapBuffer(MapBufferAccess access, bool bind = true)
{
return IntPtr.Zero;
}
/// <summary>
/// Stop reading/writing buffer.
/// <para>need to do nothing.</para>
/// </summary>
/// <param name="unbind"></param>
public override bool UnmapBuffer(bool unbind = true)
{
// need to do nothing.
return true;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
int primCount = this.PrimCount;
if (primCount < 1)
{
return string.Format("error: primCount is less than 1.");
}
else if (primCount == 1)
{
return string.Format("OpenGL.DrawArrays({0}, {1}, {2})",
this.Mode, this.FirstVertex, this.RenderingVertexCount);
}
else
{
return string.Format("OpenGL.glDrawArraysInstanced({0}, {1}, {2}, {3})",
this.Mode, this.FirstVertex, this.RenderingVertexCount, this.PrimCount);
}
}
}
}
|
b7de35ac9937bec07388085a84b4f834782851ba
|
C#
|
shendongnian/download4
|
/first_version_download2/522828-48445431-165447057-4.cs
| 2.796875
| 3
|
public class MyClass
{
public string MyString { get; set; }
public MyClass(string someString) { this.MyString = someString; }
}
|
d30a069e41b78e6636f35d168c22ee9ecddaeed0
|
C#
|
borondy/ExamPrep_70-483
|
/ExamPrep/1.1.3.4/Program.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1._1._3._4
{
class Program
{
static void Main(string[] args)
{
var loopResult=Parallel.For(0, 100, (i, state) =>
{
if (i == 75)
state.Stop();
Console.WriteLine(i);
});
Console.WriteLine("Lowest break iteration: " + loopResult.LowestBreakIteration);
Console.ReadKey();
}
}
}
|
7e97be4d771b39bd185c24f9a82130032c80a41e
|
C#
|
fllencina/ejercicio
|
/Ejercicio 40/CentralTelefonica/Llamada.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CentralTelefonica
{
public abstract class Llamada
{
//Enumerados
public enum TipoLlamada
{
Local,
Provincial,
Todas
}
protected float duracion;
protected string nroDestino;
protected string nroOrigen;
//constructor
public Llamada(float duracion, string destino, string origen)
{
this.duracion = duracion;
this.nroDestino = destino;
this.nroOrigen = origen;
}
//propiedades
/// <summary>
/// solo lectura, retorna la duracion de la llamada
/// </summary>
public float Duracion
{
get
{
return this.duracion;
}
}
/// <summary>
/// solo lectura, retorna numero de destino de llamada
/// </summary>
public string NroDestino
{
get
{
return this.nroDestino;
}
}
/// <summary>
/// solo lectura, retorna el numero de destino de llamada
/// </summary>
public string NroOrigen
{
get
{
return this.nroOrigen;
}
}
/// <summary>
/// propiedad costo abstracta, debe ser de solo lectura
/// </summary>
/// <returns></returns>
public abstract float CostoLlamada
{
get;
}
//metodos
/// <summary>
/// retorna string con datos atributos
/// </summary>
/// <returns></returns>
protected virtual string Mostrar()
{
StringBuilder llamada = new StringBuilder();
llamada.AppendFormat("Duracion: {0},Nro Destino:{1},Nro Origen: {2} ", Duracion, NroDestino, NroOrigen);
return llamada.ToString();
}
/// <summary>
/// ordena por duracion de llamada ascendente
/// </summary>
/// <param name="llamada1"></param>
/// <param name="llamada2"></param>
/// <returns></returns>
public static int OrdenarPorDuracion(Llamada llamada1, Llamada llamada2)
{
if (llamada1.duracion > llamada2.duracion)
{
return 1;
}
if (llamada1.duracion < llamada2.duracion)
{
return -1;
}
return 0;
}
public static bool operator ==(Llamada Llamada1, Llamada Llamada2)
{
if (Llamada1.Equals(Llamada2))
{
if (Llamada1.NroDestino == Llamada2.NroDestino && Llamada2.NroOrigen == Llamada2.NroOrigen)
{
return true;
}
}
return false;
}
public static bool operator !=(Llamada Llamada1, Llamada Llamada2)
{
return !(Llamada1 == Llamada2);
}
}
}
|
e879c9229827a0a29096797494167a48cb40e0c9
|
C#
|
abelclopes/curso-dotnet-tdd
|
/src/domain/Models/Post.cs
| 3.046875
| 3
|
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace domain.Models
{
public class Post : BaseEntity
{
public Post(string title, string description, string author, DateTime datePublish, string image, Category category)
{
if (string.IsNullOrEmpty(title))
{
throw new ArgumentException("Titulo é inválido");
}
if(string.IsNullOrEmpty(description))
{
throw new ArgumentException("Descrição é inválido");
}
if(string.IsNullOrEmpty(author))
{
throw new ArgumentException("Autor é inválido");
}
Title = title;
Description = description;
Author = author;
DatePublish = datePublish;
Image = image;
Category = category ?? throw new ArgumentException("Categoria é inválido");
}
public string Title { get; }
public string Description { get; }
public string Author { get; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DatePublish { get; }
public string Image { get; }
public Category Category { get; }
}
}
|
ab54cedee2707b70cae467bd27f0007afbd8ec3e
|
C#
|
natkinnetdev/VetDirectoryTest
|
/WebApplication2/Repositories/ProductRepositoryDoc.cs
| 2.75
| 3
|
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication2.Entities;
using WebApplication2.Repositories.Interfaces;
using EFCore.BulkExtensions;
namespace WebApplication2.Repositories
{
public class ProductRepositoryDoc : IRepositoryDoc<Product>
{
private readonly DataContext _context;
private readonly ILogger<ProductRepositoryDoc> _logger;
public ProductRepositoryDoc(DataContext context, ILogger<ProductRepositoryDoc> logger)
{
this._logger = logger;
if (context == null) throw new ArgumentNullException("context");
this._context = context;
}
public async Task BulkDeleteAsync(List<Product> entities)
{
await _context.BulkDeleteAsync<Product>(entities);
await _context.SaveChangesAsync();
}
public void BulkInsert(List<Product> entities)
{
throw new NotImplementedException();
}
public async Task BulkUpsertAsync(List<Product> entities)
{
await _context.BulkInsertOrUpdateAsync<Product>(entities);
await _context.SaveChangesAsync();
}
public IEnumerable<Product> GetAll()
{
return _context.Products;
}
public Product GetItem(int id)
{
throw new NotImplementedException();
}
public void Insert(Product entity)
{
throw new NotImplementedException();
}
public void Remove(Product entity)
{
throw new NotImplementedException();
}
}
}
|
f85b878050a4f78fa66851dbd1f472156050bfc3
|
C#
|
imjoy/watermarking
|
/Watermark/Watermark/control/svd_operation.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.IntegralTransforms;
using System.Drawing;
namespace Watermark.control
{
public class svd_operation
{
public Matrix<double> Input;
public Matrix<double> Output;
public Svd<double> svd;
private double[,] src;
private int row = 0;
private int col = 0;
public svd_operation(Bitmap x, double[,] color)
{
row = x.Width >> 1;
col = x.Height >> 1;
src = new double[row, col];
src = init_src(color,row,col);
Input = DenseMatrix.OfArray(src);
svd = Input.Svd(true);
}
public double[,] init_src(double[,] color,int x, int y)
{
double[,] temp = new double[x, y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
temp[i, j] = color[i, j];
}
}
return temp;
}
public double[,] getP()
{
double[] nilai_s = svd.S.ToArray();
int count = 0;
double[,] nilai_w = new double[row, col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (i == j)
{
nilai_w[i,j] = nilai_s[count];
count++;
}
else
{
nilai_w[i, j] = 0.0;
}
}
}
//double[,] nilai_u = svd.U.ToArray();
//double[,] hasil = perkalian_matrix(nilai_u, nilai_w);
return nilai_w;
}
public double[,] recompotion(Matrix<double>u,Matrix<double>s,Matrix<double>vt)
{
double[,] temp = u.Multiply(s).Multiply(vt).ToArray();
return temp;
}
public double[,] get_w()
{
double[] nilai_s = svd.S.ToArray();
int count = 0;
double[,] nilai_w = new double[row, col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (i == j)
{
nilai_w[i, j] = nilai_s[count];
count++;
}
else
{
nilai_w[i, j] = 0.0;
}
}
}
return nilai_w;
}
public double[,] getnew_W(double[,] p)
{
double[,] nilai_w = get_w();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
nilai_w[i, j] += p[i, j];
}
}
return nilai_w;
}
public double[,] perkalian_matrix(double[,] x, double[,] y)
{
double[,] hasil = new double[row, col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < row; j++)
{
hasil[i, j] = 0;
for (int k = 0; k < col; k++)
{
hasil[i, j] += (x[i, k] * y[k, j]);
}
}
}
return hasil;
}
}
}
|
3770b2267f69fc2fce72e6e220174cd0d15cb11a
|
C#
|
AlexeyJKoshkin/Dimon_Diplom
|
/Assets/Scripts/[Core]/Extensions/SEExtensions.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace ShutEye.Extensions
{
public static class SEExtensions
{
public static T GetOrAddComponent<T>(this Component component) where T : Component
{
return component.GetComponent<T>() ?? component.gameObject.AddComponent<T>();
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T element in source)
{
action(element);
}
}
public static T GetOrAddComponent<T>(this GameObject child) where T : Component
{
T result = child.GetComponent<T>();
if (result == null)
{
result = child.gameObject.AddComponent<T>();
}
return result;
}
}
}
|
7a3593f61500c5b9f87dcebb6a1458c2030b8d34
|
C#
|
Wagsn/DotNET-WS
|
/WS.Music/Stores/SongStore.cs
| 2.765625
| 3
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WS.Core.Stores;
using WS.Music.Models;
namespace WS.Music.Stores
{
/// <summary>
/// 歌曲存储,写一些特殊的数据库存取操作
/// </summary>
public class SongStore : StoreBase<ApplicationDbContext, Song>
{
public ArtistStore _ArtistStore { get; }
/// <summary>
/// 歌曲存储
/// </summary>
/// <param name="ArtistStore"></param>
/// <param name="context"></param>
public SongStore(ArtistStore ArtistStore, ApplicationDbContext context) : base(context)
{
_ArtistStore = ArtistStore;
}
/// <summary>
/// 批量查询
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="query"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task<List<TResult>> ListAsync<TResult>(Func<IQueryable<Song>, IQueryable<TResult>> query, CancellationToken cancellationToken)
{
CheckNull(query);
return query.Invoke(Context.Songs.Where(i => i._IsDeleted == false).AsNoTracking()).ToListAsync(cancellationToken);
}
/// <summary>
/// 通过歌单ID查询歌曲
/// </summary>
/// <param name="playListId"></param>
/// <returns></returns>
public IQueryable<Song> ByPlayListId ([Required]string playListId)
{
// 操作日志
var query = from s in Context.Songs
where (from rps in Context.RelPlayListSongs
where rps.PlayListId == playListId
select rps.SongId).Contains(s.Id)
select new Song(s);
return query;
// C:\Users\wagsn\Documents\Tencent Files\850984728\FileRecv\
}
public IQueryable<Song> ById ([Required]string songId)
{
// 操作日志
var query = from s in Context.Songs
where s.Id == songId
select new Song(s);
return query;
}
/// <summary>
/// 查询ID通过歌单ID
/// </summary>
/// <param name="playListId"></param>
/// <returns></returns>
public IQueryable<string> IdsByPlayListId([Required]string playListId)
{
// 操作日志
var query = from rps in Context.RelPlayListSongs
where rps.PlayListId == playListId
select rps.SongId;
return query;
}
/// <summary>
/// 通过所有有关联的名称查询Song,模糊查询,效率较低
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IQueryable<Song> LikeAllName([Required]string name)
{
// TODO 优化查询速度
var query = from s in Context.Songs
where (s.Name.Contains(name)
|| (from rsoar in Context.RelSongArtists
where (from a in Context.Artists
where a.Name.Contains(name)
select a.Id).Contains(rsoar.ArtistId)
select rsoar.SongId).Contains(s.Id)
|| (from rsoal in Context.RelSongAlbums
where (from a in Context.Albums
where a.Name.Contains(name)
select a.Id).Contains(rsoal.AlbumId)
select rsoal.SongId).Contains(s.Id))
select new Song(s);
return query;
}
/// <summary>
/// 找到Song通过歌名,模糊查询
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IQueryable<Song> LikeName([Required]string name)
{
var query = from s in Context.Songs
where s.Name.Contains(name)
select new Song(s);
return query;
}
/// <summary>
/// 找到Song通过艺人名,模糊查询
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IQueryable<Song> LikeArtistName([Required]string name)
{
var query = from s in Context.Songs
where (from rsoar in Context.RelSongArtists
where (from a in Context.Artists
where a.Name.Contains(name)
select a.Id).Contains(rsoar.ArtistId)
select rsoar.SongId).Contains(s.Id)
select new Song(s);
return query;
}
/// <summary>
/// 通过专辑名模糊查询Song
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
public IQueryable<Song> LikeAlbumName([Required]string Name)
{
var query = from s in Context.Songs
where (from rsoal in Context.RelSongAlbums
where (from a in Context.Albums
where a.Name.Contains(Name)
select a.Id).Contains(rsoal.AlbumId)
select rsoal.SongId).Contains(s.Id)
select new Song(s);
return query;
}
}
}
|
cf3ad3375318083f5508f4bd0564b420969b3a83
|
C#
|
nickarthur/Unity-Basic-GRPC
|
/Assets/Scripts/RouteGuideUnityClient.cs
| 2.609375
| 3
|
//#define DEBUG
using System;
using System.Collections;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Routeguide;
using TMPro;
using UnityEngine;
public class RouteGuideUnityClient
{
private readonly RouteGuide.RouteGuideClient _client;
private readonly Channel _channel;
private readonly string _server;
private readonly RouteGuideUIHandler _myRouteGuideUiHandler;
private string textBuffer;
private bool isBusy;
internal RouteGuideUnityClient(string host, string port, RouteGuideUIHandler inRouteGuideUIHandler)
{
_server = host + ":" + port;
_channel = new Channel(_server, ChannelCredentials.Insecure);
_client = new RouteGuide.RouteGuideClient(_channel);
_myRouteGuideUiHandler = inRouteGuideUIHandler;
}
/// <summary>
/// This method handles the task of calling the remote gRPC Service GetFeature, passing a Message Type of
/// Point, and receiving back a single Message type of Feature (which contains a string name and its corresponding
/// Point
/// </summary>
/// <param name="pointOfInterest">A single Routeguide Point (which contains a Lat/Long value)</param>
/// <returns></returns>
public async Task GetFeature(Routeguide.Point pointOfInterest)
{
Debug.Log("GetFeature Client latitude: " + pointOfInterest.Latitude +
", longitude: " + pointOfInterest.Longitude);
try
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var returnVal = await _client.GetFeatureAsync(pointOfInterest, cancellationToken: cts.Token);
_myRouteGuideUiHandler.AddTextToUi(returnVal.Name, false);
}
catch (RpcException e)
{
_myRouteGuideUiHandler.AddTextToUi("GetFeature Service is unavailable. " + e.Message, false);
}
#if DEBUG
Debug.Log("GetFeature Finished");
#endif
}
/// <summary>
/// This method handles the task of calling the remote gRPC Service ListFeatures by passing a Message Type of
/// Rectangle which contains (2) Points. The result is a gRPC response STREAM of Feature Message Types.
/// </summary>
/// <param name="areaOfInterest">A Routeguide Rectangle containing two Points</param>
/// <returns></returns>
public async Task ListFeatures(Routeguide.Rectangle areaOfInterest)
{
Debug.Log("ListFeatures Client Lo latitude: " + areaOfInterest.Lo.Latitude +
", Lo longitude: " + areaOfInterest.Lo.Longitude + "\n" +
", Hi latitude: " + areaOfInterest.Hi.Latitude +
", Hi longitude: " + areaOfInterest.Hi.Longitude);
StringBuilder responseText = new StringBuilder();
try
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
//Sending and Receiving will be sequential - send first, then receive stream response second
var response = _client.ListFeatures(areaOfInterest, cancellationToken: cts.Token);
while (await response.ResponseStream.MoveNext())
{
var thisItemName = response.ResponseStream.Current.Name;
if (!String.IsNullOrEmpty(thisItemName))
{
_myRouteGuideUiHandler.AddTextToUi(thisItemName, false);
}
}
}
catch (RpcException e)
{
_myRouteGuideUiHandler.AddTextToUi("ListFeatures Service is unavailable. " + e.Message, false);
}
#if DEBUG
Debug.Log("async Task ListFeatures Finished");
#endif
}
/// <summary>
/// This method handles the task of calling the remote gRPC Service RecordRoute by passing a STREAM of
/// Point Message Types. Upon completion of the asynchronous stream, the remote server calculates the distance
/// between all the points and returns a single RouteSummary Message Type back.
/// </summary>
/// <param name="pointsOfInterest">An array of Routeguide Points</param>
/// <returns></returns>
public async Task RecordRoute(Routeguide.Point[] pointsOfInterest)
{
try
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
//Sending and Receiving will be sequential - send/stream all first, then receive
var thisStream = _client.RecordRoute(cancellationToken: cts.Token);
foreach (var t in pointsOfInterest)
{
await thisStream.RequestStream.WriteAsync(t);
}
await thisStream.RequestStream.CompleteAsync();
RouteSummary summary = await thisStream.ResponseAsync;
var myResultSummary = summary.ToString();
if (!String.IsNullOrEmpty(myResultSummary))
{
_myRouteGuideUiHandler.AddTextToUi(myResultSummary, false);
}
else
{
#if DEBUG
Debug.Log("async Task RecordRoute empty");
#endif
}
}
catch (RpcException e)
{
_myRouteGuideUiHandler.AddTextToUi("RecordRoute Service is unavailable. " + e.Message, false);
}
#if DEBUG
Debug.Log("async Task RecordRoute Finished");
#endif
}
/// <summary>
/// This method handles the task of calling the remote gRPC BI-Directional Service RouteChat by passing a STREAM of
/// RouteNote Message Types. A response STREAM returns a series of accumulated RouteNote Message Types.
/// </summary>
/// <param name="notesOfInterest"></param>
/// <returns></returns>
public async Task RouteChat(Routeguide.RouteNote[] notesOfInterest)
{
try
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(6));
var thisStream = _client.RouteChat(cancellationToken: cts.Token);
//Using a Task.Run(async ()...here as we essentially want (2) things to run in parallel, and
//only return when both are complete.
var responseReaderTask = Task.Run(async () =>
{
while (await thisStream.ResponseStream.MoveNext())
{
//This AddText.. method is different, its capable of getting the UI updated from a different thread.
_myRouteGuideUiHandler.AddTextToUi(thisStream.ResponseStream.Current.Message, true);
}
#if DEBUG
Debug.Log("RouteChat RECEIVE messages complete");
#endif
});
foreach (RouteNote request in notesOfInterest)
{
await thisStream.RequestStream.WriteAsync(request);
}
#if DEBUG
Debug.Log("RouteChat SEND messages complete");
#endif
await thisStream.RequestStream.CompleteAsync();
await responseReaderTask;
}
catch (RpcException e)
{
_myRouteGuideUiHandler.AddTextToUi("RouteChat Service is unavailable. " + e.Message, false);
}
#if DEBUG
Debug.Log("async Task RouteChat Finished");
#endif
}
private void OnDisable()
{
_channel.ShutdownAsync().Wait();
}
}
|
6319b575709fc467b1c9f1552a1a65510d4f6fdb
|
C#
|
rdamm/Columbia583
|
/Columbia583/Data_Access_Layer/Data_Access_Layer_View_Trail.cs
| 2.71875
| 3
|
using System;
namespace Columbia583
{
/// <summary>
/// View trail data access layer will control all requests relating to the view trail page.
/// </summary>
public class Data_Access_Layer_View_Trail
{
public Data_Access_Layer_View_Trail ()
{
}
/// <summary>
/// Gets the trail.
/// </summary>
/// <returns>The trail.</returns>
/// <param name="trailId">Trail identifier.</param>
public Trail getTrail(int trailId)
{
Data_Layer_View_Trail dataLayer = new Data_Layer_View_Trail();
return dataLayer.getTrail (trailId);
}
/// <summary>
/// Gets the activities for the trail.
/// </summary>
/// <returns>The activities.</returns>
/// <param name="trailId">Trail identifier.</param>
public Activity[] getActivities(int trailId)
{
Data_Layer_View_Trail dataLayer = new Data_Layer_View_Trail();
return dataLayer.getActivities (trailId).ToArray();
}
/// <summary>
/// Gets the amenities for the trail.
/// </summary>
/// <returns>The amenities.</returns>
/// <param name="trailId">Trail identifier.</param>
public Amenity[] getAmenities(int trailId)
{
Data_Layer_View_Trail dataLayer = new Data_Layer_View_Trail();
return dataLayer.getAmenities (trailId).ToArray();
}
/// <summary>
/// Gets the points for the trail.
/// </summary>
/// <returns>The points.</returns>
/// <param name="trailId">Trail identifier.</param>
public Point[] getPoints(int trailId)
{
Data_Layer_View_Trail dataLayer = new Data_Layer_View_Trail();
return dataLayer.getPoints (trailId).ToArray();
}
/// <summary>
/// Gets the media for the trail.
/// </summary>
/// <returns>The media.</returns>
/// <param name="trailId">Trail identifier.</param>
public Media[] getMedia(int trailId)
{
Data_Layer_View_Trail dataLayer = new Data_Layer_View_Trail ();
return dataLayer.getMedia (trailId).ToArray();
}
/// <summary>
/// Gets the comments for the trail.
/// </summary>
/// <returns>The comments.</returns>
/// <param name="trailId">Trail identifier.</param>
public Comment[] getComments(int trailId)
{
Data_Layer_View_Trail dataLayer = new Data_Layer_View_Trail();
return dataLayer.getComments (trailId).ToArray();
}
/*
public User getUserForComment(Comment c)
{
Data_Layer_View_Trail dataLayer = new Data_Layer_View_Trail();
return dataLayer.getUserForComment(c);
}
*/
}
}
|
99677e84d6d35b83240fd3cddede4418eff284ba
|
C#
|
everas7/library-api
|
/LibraryAPI/App_Start/WebApiConfig.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace LibraryAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
/* Requerimiento 4: Hacer uso de friendly routes*/
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
/*Mapea la ruta http api/{nombre del controlador}/{id}. Esta llama nuestro
metodo GetBook en BookController al utilizar api/book/2, por ejemplo.*/
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
/*Mapea la ruta http api/book/{BookID}/Page/{PageID}/{Format}. Esta llama nuestro
metodo GetPage en PageController al utilizar api/book/1/page/2/text, por ejemplo.*/
config.Routes.MapHttpRoute(
name: "PageApi",
routeTemplate: "api/book/{BookID}/Page/{PageID}/{Format}",
defaults: new { controller="Page" }
);
}
}
}
|
874a7e31993f3785fdd3157b2961bdfed09ddb0a
|
C#
|
JulianZ90/GDD2014C2
|
/FrbaHotel/Regimen.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FrbaHotel
{
public class Regimen
{
public int id { get; set; }
public decimal precio_base { get; set; }
public string descripcion { get; set; }
public bool estado { get; set; }
public override string ToString()
{
if (String.IsNullOrEmpty(descripcion))
return "";
else
return descripcion;
}
public bool esAllInclusive()
{
return this.descripcion == "All inclusive";
}
}
}
|
0304b5054edfabfdf651aa99d4218660e47c0d79
|
C#
|
diogocavassani/ExercicioPilaresOrientadaObjeto
|
/src/Cadastro.ConsoleApp/Program.cs
| 2.578125
| 3
|
using Cadastro.Models;
using System;
using System.Collections.Generic;
namespace Cadastro.ConsoleApp
{
class Program : Cliente
{
static void Main(string[] args)
{
#region Cliente1
var clienteUm = new Cliente();
var listaClienteUm = new List<string>() { "Produto 1","Produto 2","Produto 3"};
clienteUm.Nome = "Diogo";
clienteUm.Cpf = "298.737.628-68"; //CPF Valido.
clienteUm.Rg = "95.160.245-5";
clienteUm.Endereco = "Rua sobe desce, 125, centro";
clienteUm.Email = "diogo@teste.com.br";
clienteUm.HistoricoDeVenda = listaClienteUm;
if (DocumentoValido(clienteUm))
Console.WriteLine($"Ola, {clienteUm.Nome} o CPF {clienteUm.Cpf} é valido");
else
Console.WriteLine($"Ola, {clienteUm.Nome} o CPF {clienteUm.Cpf} não é valido");
#endregion
#region Cliente2
var clienteDois = new Cliente();
var listaClienteDois = new List<string>() { "Produto 4", "Produto 5", "Produto 6" };
clienteDois.Nome = "Douglas";
clienteDois.Cpf = "123.456.456-65"; //CPF invalido
clienteDois.Rg = "87.856.124-5";
clienteDois.Endereco = "Rua dobra direita, 124, centro";
clienteDois.Email = "Douglas@teste.com.br";
clienteDois.HistoricoDeVenda = listaClienteDois;
if (DocumentoValido(clienteDois))
Console.WriteLine($"Ola, {clienteDois.Nome} o CPF {clienteDois.Cpf} é valido");
else
Console.WriteLine($"Ola, {clienteDois.Nome} o CPF {clienteDois.Cpf} não é valido");
#endregion
#region Funcionario1
var funcionarioUm = new Funcionario();
funcionarioUm.Nome = "Gilberto";
funcionarioUm.Cpf = "607.936.258-90";
funcionarioUm.Rg = "78.124.576-5";
funcionarioUm.Endereco = "Rua João Pessoa";
funcionarioUm.Email = "Gilberto@teste.com.br";
funcionarioUm.DataAdminissao = DateTime.Now;
funcionarioUm.Salario = 3000D;
funcionarioUm.Cargo = "Analista Junior";
if (DocumentoValido(funcionarioUm))
Console.WriteLine($"Ola, {funcionarioUm.Nome} o CPF {funcionarioUm.Cpf} é valido");
else
Console.WriteLine($"O CPF {funcionarioUm.Cpf} não é valido");
#endregion
#region Funcionario2
var funcionarioDois = new Funcionario();
funcionarioDois.Nome = "Adalberto";
funcionarioDois.Cpf = "576.936.258-90";
funcionarioDois.Rg = "78.124.576-5";
funcionarioDois.Endereco = "Rua João Pessoa";
funcionarioDois.Email = "Gilberto@teste.com.br";
funcionarioDois.DataAdminissao = DateTime.Now;
funcionarioDois.Salario = 3000D;
funcionarioDois.Cargo = "Suporte Senior";
if (DocumentoValido(funcionarioDois))
Console.WriteLine($"Ola, {funcionarioDois.Nome} o CPF {funcionarioDois.Cpf} é valido");
else
Console.WriteLine($"Ola, {funcionarioDois.Nome} o CPF {funcionarioDois.Cpf} não é valido");
#endregion
#region Fornecedor1
var fornecedorUm = new Fornecedor();
var listaFornecedorUm = new List<string>() { "Produto 1", "Produto 2", "Produto 2" };
fornecedorUm.HistoricoDeCompra = listaFornecedorUm;
fornecedorUm.RazaoSocial = "Peça Geral LTDA";
fornecedorUm.Cnpj = "29.928.902/0001-74"; //CNPJ Valido
fornecedorUm.InscricaoEstadual = "123.123.132";
fornecedorUm.Endereco = "Rua São José, 1248, Jardim Primavera";
fornecedorUm.Email = "suporte@pecageral.com.br";
if (DocumentoValido(fornecedorUm))
Console.WriteLine($"Ola, {fornecedorUm.RazaoSocial} o CNPJ {fornecedorUm.Cnpj} é valido");
else
Console.WriteLine($"Ola, {fornecedorUm.RazaoSocial} o CNPJ {fornecedorUm.Cnpj} não é valido");
#endregion
#region Fornecedor2
var fornecedorDois = new Fornecedor();
var listaFornecedorDois = new List<string>() { "Produto 4", "Produto 5", "Produto 6" };
fornecedorDois.HistoricoDeCompra = listaFornecedorUm;
fornecedorDois.RazaoSocial = "Peça Geral LTDA";
fornecedorDois.Cnpj = "29.928.902/6521-74"; //Invalido
fornecedorDois.InscricaoEstadual = "123.123.132";
fornecedorDois.Endereco = "Rua São José, 1248, Jardim Primavera";
fornecedorDois.Email = "suporte@pecageral.com.br";
if (DocumentoValido(fornecedorDois))
Console.WriteLine($"Ola, {fornecedorDois.RazaoSocial} o CNPJ {fornecedorDois.Cnpj} é valido");
else
Console.WriteLine($"Ola, {fornecedorDois.RazaoSocial} o CNPJ {fornecedorDois.Cnpj} não é valido");
#endregion
}
private static bool DocumentoValido(Pessoa pessoa)
{
if (pessoa.ValidadorDocumento())
return true;
return false;
}
}
}
|
73d83a2acd0c2d14fe745bb04a0a8e0bb5e975b2
|
C#
|
LorandSol/Character-Customisation
|
/Assets/Scripts/Item.cs
| 3.109375
| 3
|
//in this script you will only need using UnityEngine as we just need the script to connect to unity
using UnityEngine;
//this public class doent inherit from MonoBehaviour
//this script is also referenced by other scripts but never attached to anything
public class Item
{
//basic variables for items that we need are
#region Private Variables
//Identification Number
private int _idNumber;
//Object Name
private string _name;
//Value of the Object
private int _value;
//Description of what the Object is
private string _description;
//Icon that displays when that Object is in an Inventory
private Texture2D _icon;
//Mesh of that object when it is equipt or in the world
private GameObject _mesh;
//Enum ItemType which is the Type of object so we can classify them
private ItemType _type;
private int _heal;
private int _damage;
private int _armour;
private int _amount;
#endregion
#region Constructors
//A constructor is a bit of code that allows you to create objects from a class. You call the constructor by using the keyword new
//followed by the name of the class, followed by any necessary parameters.
//the Item needs Identification Number, Object Name, Icon and Type
//here we connect the parameters with the item variables
public void ItemCon(int itemId, string itemName, Texture2D itemIcon, ItemType itemType)
{
_idNumber = itemId;
_name = itemName;
_icon = itemIcon;
_type = itemType;
}
#endregion
#region Public Variables
//here we are creating the public versions or our private variables that we can reference and connect to when interacting with items
//public Identification Number
public int ID
{
//get the private Identification Number
get { return _idNumber; }
//and set it to the value of our public Identification Number
set { _idNumber = value; }
}
//public Name
public string Name
{
//get the private Name
get { return _name; }
//and set it to the value of our public Name
set { _name = value; }
}
//public Value
public int Value
{
//get the private Value
get { return _value; }
//and set it to the value of our public Value
set { _value = value; }
}
//public Description
public string Description
{
//get the private Description
get { return _description; }
//and set it to the value of our public Description
set { _description = value; }
}
//public Icon
public Texture2D Icon
{
//get the private Icon
get { return _icon; }
//and set it to the value of our public Icon
set { _icon = value; }
}
//public Mesh
public GameObject Mesh
{
//get the private Mesh
get { return _mesh; }
//and set it to the value of our public Mesh
set { _mesh = value; }
}
//public Type
public ItemType Type
{
//get the private Type
get { return _type; }
//and set it to the value of our public Type
set { _type = value; }
}
public int Heal
{
get { return _heal; }
set { _heal = value; }
}
public int Damage
{
get { return _damage; }
set { _damage = value; }
}
public int Armour
{
get { return _armour; }
set { _armour = value; }
}
public int Amount
{
get { return _amount; }
set { _amount = value; }
}
#endregion
}
#region Enums
//The Global Enum ItemType that we have created categories in
public enum ItemType
{
Food,
Weapon,
Apparel,
Crafting,
Quest,
Money,
Ingredients,
Potions,
Scrolls,
}
#endregion
|
08768b131546bd30c7999711212dab7c4cfb7190
|
C#
|
aunomvo/Project_Euler
|
/Problem001/Program.cs
| 3.796875
| 4
|
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Problem001
{
/// <summary>
/// If we list all the natural numbers below 10 that are multiples of 3 or
/// 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
///
/// Find the sum of all the multiples of 3 or 5 below 1000.
/// </summary>
static class Program
{
static void Main()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = SolveProblem(1000);
stopwatch.Stop();
Console.WriteLine(string.Format("The result is {0}.", result));
Console.WriteLine(string.Format("The calculation took {0} ms.", stopwatch.ElapsedMilliseconds));
Console.WriteLine(string.Empty);
Console.WriteLine("Press any key to exit.");
Console.ReadKey(true);
}
internal static int SolveProblem(int max)
{
return Enumerable.Range(1, max - 1).Where(x => x%3 == 0 || x%5 == 0).Sum();
}
}
[TestClass]
public class TestProblem001
{
[TestMethod]
public void TestSolveProblemEasy()
{
Assert.AreEqual(23, Program.SolveProblem(10));
}
[TestMethod]
public void TestSolveProblemFull()
{
Assert.AreEqual(233168, Program.SolveProblem(1000));
}
}
}
|
c0f8b9a81118c54e1408175fdf8abb2c63ef61ca
|
C#
|
adriancheong/webserviceconsumer
|
/src/WebserviceConsumer/Controllers/HomeController.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using WebserviceConsumer.Model;
namespace WebserviceConsumer.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Calculator()
{
ViewData["Message"] = "Your Calculator page.";
return View();
}
public IActionResult Docker()
{
//ViewData["Message"] = "Your Docker 5.0 page.";
return View();
}
public IActionResult Christmas()
{
//ViewData["Message"] = "Your Docker 5.0 page.";
return View();
}
public IActionResult Results()
{
ViewData["Results"] = Math.Round(TwoThirdAverageGame.GetTwoThirdOfAverage(), 2);
ViewData["Winner"] = TwoThirdAverageGame.GetWinner();
ViewData["Count"] = TwoThirdAverageGame.GetNumberOfSubmissions();
return View();
}
public IActionResult Error()
{
return View();
}
public string Add(int param1, int param2)
{
return Controllers.Calculator.Add(param1, param2);
}
public string Subtract(int param1, int param2)
{
return Controllers.Calculator.Subtract(param1, param2);
}
}
class Calculator
{
private const string addUrl = "http://188.166.197.0:5010/api/add";
private const string subtractUrl = "http://188.166.197.0:5020/api/subtract";
public static string Add(int param1, int param2)
{
string urlParameters = "?param1=" + param1 + "¶m2=" + param2;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(addUrl);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
//var result = response.Content.ToString();
var result = response.Content.ReadAsStringAsync().Result;
//var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;
Console.WriteLine("Managed to successfull call Add Webservice with this result: {0}", result);
return result;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return "Error";
}
}
public static string Subtract(int param1, int param2)
{
string urlParameters = "?param1=" + param1 + "¶m2=" + param2;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(subtractUrl);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
//var result = response.Content.ToString();
var result = response.Content.ReadAsStringAsync().Result;
//var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;
Console.WriteLine("Managed to successfull call Subtract Webservice with this result: {0}", result);
return result;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
return "Error";
}
}
}
}
|
7a8ee1d79cc5c8b120a7fe8d32b3ac2ca0273cb9
|
C#
|
ntk148v/testing
|
/dotnet/VNStock.Bak/VNStockLib/TCBSClient.cs
| 2.546875
| 3
|
using Microsoft.Extensions.Logging;
namespace VNStockLib;
public class TCBSClient : IDisposable
{
private readonly HttpClient _client;
private readonly ILogger<TCBSClient> _logger = null!;
public TCBSClient(HttpClient client, ILogger<TCBSClient> logger)
{
(_client, _logger) = (client, logger);
}
public async Task<HttpResponseMessage> GetCompanyOverview(string symbol)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Get, $"tcanalysis/v1/ticker/{symbol}/overview");
var response = await _client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return response;
}
catch (Exception ex)
{
_logger.LogError($"Error getting company {symbol}overview", ex);
}
return new HttpResponseMessage();
}
public void Dispose() => _client?.Dispose();
}
|
939446372c63996acf37d2bdea6953fc173b6209
|
C#
|
brittkorycki/GoldBadgeChallenge
|
/KomodoGreenPlanTests/GreenPlanTests.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using KomodoGreenPlan;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace KomodoGreenPlanTests
{
[TestClass]
public class GreenPlanTests
{
CarRepository carRepo = new CarRepository();
[TestMethod]
public void TestMehodAddCar()
{
//Arrange
Car car1 = new Car();
string Make = "Kia";
string Model = "Sedona";
string Type = "gas";
int MilesPerGallon = 16;
//Act
car1.Make = Make;
car1.Model = Model;
car1.Type = Type;
car1.MilesPerGallon = MilesPerGallon;
carRepo.AddCarToList(car1);
Car car = carRepo.GetCarByModel(Model);
//Assert
Assert.AreSame(car.Model, "Sedona", "car model does not match");
}
[TestMethod]
public void TestUpdateCar()
{
//Arrange
Car newCar = new Car();
string Make = "Kia";
string Model = "Sedona";
int MilesPerGallon = 35;
//Act
newCar.Make = Make;
newCar.Model = Model;
newCar.MilesPerGallon = MilesPerGallon;
carRepo.UpdateCar(Make, Model, MilesPerGallon);
//Assert
Assert.AreNotEqual(Model, "Forte");
}
[TestMethod]
public void TestRemoveCar()
{
//Arrange
Car car = new Car();
string Model = "Forte";
//Act
carRepo.RemoveCarFromList(car);
//Assert
Assert.IsNotNull(carRepo.GetCarByModel(Model), "car not found.");
}
[TestMethod]
public void TestGetCarList()
{
//Arrange
List<Car> cars = new List<Car>();
//Act
cars = carRepo.GetCarList("gas");
//Assert
Assert.IsNotNull(cars, "No cars list found.");
}
}
}
|
fb61c31bca9a89a3ecf63063d7544fa6d527d952
|
C#
|
mjgomesvix/secure-privacy-task1
|
/Support/Extensions/EnumerableExtension.cs
| 3.1875
| 3
|
using System.Collections.Generic;
using System.Linq;
namespace Support.Extensions
{
public static class EnumerableExtension
{
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) => enumerable?.Any() != true;
public static IEnumerable<T> Pagination<T>(this IEnumerable<T> enumerable, int page, int pageSize)
{
var skip = (page - 1) * pageSize;
return enumerable.AsQueryable().Skip(skip).Take(pageSize);
}
}
}
|
c2e3894c607f3360a9ec7f2cad8ff8f7ffc5a12d
|
C#
|
aqib1831/LangaugeFeature
|
/CSharp6LangaugeFeature/Program.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp6LangaugeFeature
{
class Program
{
static void Main(string[] args)
{
//var p = new Point(3.14,2.71);
//(double X, double Y) = p;
//Console.WriteLine(X);
//
//Out_Variables.NewFunctionality("123");
//var (_, _, _, pop1, _, pop2) = Discards .QueryCityDataForYears("New York City", 1960, 2010);
// Console.WriteLine($"Population change, 1960 to 2010: {pop2 - pop1:N0}");
Person p = new Person("John", "Quincy", "Adams", "Boston", "MA");
// <Snippet1>
// Deconstruct the person object.
//var (fName, lName, city, _) = p;
//Console.WriteLine($"Hello {fName} {lName} of {city}!");
object[] objects = { CultureInfo.CurrentCulture,
CultureInfo.CurrentCulture.DateTimeFormat,
CultureInfo.CurrentCulture.NumberFormat,
new ArgumentException(), null };
foreach (var obj in objects)
Person.ProvidesFormatInfo(obj);
Console.ReadKey();
}
}
}
|
8b83e67905801d3a3e69d601cfa68c49bb6ca13e
|
C#
|
ClaytonMoutzouris/Gamble-v2.0
|
/Assets/Scripts/Entity/Player/InventorySlot.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InventorySlot
{
[HideInInspector]
public PlayerInventory inventory;
public Item item = null;
public int amount = 0;
private InventorySlotUI slotUI = null;
public InventorySlot(PlayerInventory inventory)
{
this.inventory = inventory;
}
public InventorySlotUI GetInventorySlot()
{
return slotUI;
}
public void SetInventorySlot(InventorySlotUI value)
{
slotUI = value;
value.slot = this;
}
public bool IsEmpty()
{
return item == null;
}
public Item GetOneItem()
{
Item returnItem = item;
amount--;
if(amount <= 0)
{
ClearSlot();
}
//update ui
slotUI.UpdateSlotUI();
return returnItem;
}
public bool AddItemToSlot(Item newItem, int numItems = 1)
{
if(item == null)
{
item = newItem;
amount = numItems;
slotUI.UpdateSlotUI();
return true;
} else
{
if(item.isStackable && item.itemName == newItem.itemName)
{
amount+= numItems;
slotUI.UpdateSlotUI();
return true;
} else
{
return false;
}
}
}
public void ClearSlot()
{
item = null;
amount = 0;
slotUI.UpdateSlotUI();
}
public void DropItem()
{
if (item == null)
return;
ItemObject temp = new ItemObject(item, Resources.Load("Prototypes/Entity/Objects/ItemObject") as EntityPrototype);
temp.Spawn(inventory.mPlayer.Position + new Vector2(0, MapManager.cTileSize / 2));
if (item is Equipment equip && equip.isEquipped)
{
UnequipItem();
}
GetOneItem();
//temp.Body.mPosition = mPlayer.Position + new Vector3(0, MapManager.cTileSize / 2);
}
public void EquipItem()
{
if (item is Equipment equippable)
{
if (equippable.isEquipped)
{
return;
}
inventory.mPlayer.Equipment.EquipItem(equippable);
}
}
public void UnequipItem()
{
if (item is Equipment equippable && equippable.isEquipped)
{
inventory.mPlayer.Equipment.Unequip(equippable);
slotUI.UpdateSlotUI();
}
}
public bool UseItem()
{
if (item is ConsumableItem consumable)
{
if(consumable.Use(inventory.mPlayer))
{
Debug.Log("Getting one item");
GetOneItem();
}
}
return false;
}
}
|
109ad772015a0d2836d85f28e8bf10b765c98cb2
|
C#
|
shendongnian/download4
|
/code10/1752971-51018705-176260366-4.cs
| 2.96875
| 3
|
<table>
<thead>
.... // add day name headings
</thead>
<tbody>
<tr>
@for (int i = 0; i < 42; i++)
{
DateTime date = startDate.AddDays(i);
if (i % 7 == 0 && i > 0)
{
@:</tr><tr> // start a new row every 7 days
}
<td>@date.Day</td>
}
</tr>
</tbody>
</table>
|
206a118bc51577ab15769a18427a28b1a3f8f278
|
C#
|
MatteoBertolino92/simple-client-server-file-storage
|
/server_v2/server_v2/Sanitizer.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Server_v2
{
class Sanitizer
{
public static string sanitize(string stringa)
{
stringa = stringa.Replace('\'', '|');
stringa = stringa.Replace('%', '*');
return stringa;
}
public static string desanitize(string stringa)
{
stringa = stringa.Replace('|', '\'');
stringa = stringa.Replace('*', '%');
return stringa;
}
}
}
|
d151a103ec0259f4e1c1ba7be8648addfd59798b
|
C#
|
AdrianoVerissimo/NightmareShooterOnline
|
/Assets/Scripts/Camera/CameraFollow.cs
| 2.671875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
public Transform target; //alvo que a câmera acompanhará
public float smooth = 5f; //velocidade em que a câmera se moverá para acompanhar o alvo
private Vector3 offset; //diferença inicial da posição da câmera com o alvo
void Start()
{
//pega a diferença entre a posição do alvo com a da câmera
offset = transform.position - target.position;
}
void FixedUpdate()
{
//define a posição da câmera como sendo a posição do alvo + a distância estabelecida pela diferença entre ambos
Vector3 targetCamPos = target.position + offset;
//move a câmera com a velocidade X para a posição do alvo
transform.position = Vector3.Lerp (transform.position, targetCamPos, smooth * Time.deltaTime);
}
}
|
66788644b5bf37372f9c2ad4361f7faa8122a832
|
C#
|
isscuss/learn.github.io
|
/ConsoleApplication3/通过Thread开启线程/Program.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 通过Thread开启线程
{
class Program
{
static void DonloadFile(object filename)//被线程调用的函数,传递的参数必须是object类型的
{
Console.WriteLine("开始下载"+Thread.CurrentThread.ManagedThreadId+"传递的是:"+filename);
Thread.Sleep(2000);
Console.WriteLine("下载完毕");
}
static void Main(string[] args)
{
//方法1
//Thread t = new Thread(DonloadFile);
//t.Start();
//Console.WriteLine("主体函数");
//Console.ReadKey();
//方法2 通过Lambda方法开启线程
//Thread t = new Thread(() =>
// {
// Console.WriteLine("开始下载:" + Thread.CurrentThread.ManagedThreadId);
// Thread.Sleep(2000);
// Console.WriteLine("下载完毕");
// }
// );
//t.Start();
//Console.ReadKey();
//方法3 通过线程传递参数
//Thread t = new Thread(DonloadFile);
//Console.WriteLine("Main");
//t.Start("什么乱七八糟的参数嘛");//通过start方法传递参数
//Console.ReadKey();
//方法4 通过新建一个线程类,定义需要传递的参数和传递的方法,进行参数的传递
Mythread my = new Mythread("路径什么的:", "需要种子吗");
Thread t = new Thread(my.DownFile);//通过构造出来的my,可以调用其中的函数,不一定是静态
t.Start();
Console.ReadKey();
}
}
}
|
288d1850e79e9ddfb986e6e68c68542fe4a3f30e
|
C#
|
6bee/Remote.Linq
|
/samples/00_SimpleRemoteQuery/Client/Program.cs
| 2.671875
| 3
|
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace Client
{
using static CommonHelper;
public static class Program
{
private static void Main()
{
Title("Simple Remote Query [Client]");
PrintDemoDescription();
WaitForEnterKey("Launch the server and then press <ENTER> to run the queries.");
new Demo().RunDemo();
PrintSetup("Done");
WaitForEnterKey("Press <ENTER> to terminate the client.");
}
public static void PrintDemoDescription()
{
PrintSetup("This sample client retrieves data from the backend by using:");
PrintSetup(" a) traditional data services (get by id/name)");
PrintSetup(" b) typed remote linq data services (dynamic filtering, sorting, and paging)");
PrintSetup(" c) a single generic remote linq data service (dynamic filtering, sorting, and paging)");
PrintSetup();
}
}
}
|
b78eb383661e63ebac71da9363314fa3d9bd9cff
|
C#
|
rebus-org/MongolianBarbecue
|
/MongolianBarbecue.Tests/Basic/Processing.cs
| 2.515625
| 3
|
using System.Collections.Generic;
using System.Threading.Tasks;
using MongolianBarbecue.Model;
using NUnit.Framework;
namespace MongolianBarbecue.Tests.Basic;
[TestFixture]
public class Processing : FixtureBase
{
const string QueueName = "nanomsg";
Producer _producer;
Consumer _consumer;
protected override void SetUp()
{
var database = GetCleanTestDatabase();
var config = new Config(database, "messages");
_producer = new Producer(config);
_consumer = new Consumer(config, QueueName);
}
[Test]
public async Task CanGetWhetherMessageExists()
{
var headers = new Dictionary<string, string> { { "id", "exists" } };
var message = new Message(headers, new byte[] {1, 2, 3});
await _producer.SendAsync(QueueName,message);
var doesNotExistsExists = await _consumer.Exists("does-not-exist");
var existsExists = await _consumer.Exists("exists");
Assert.That(doesNotExistsExists, Is.False);
Assert.That(existsExists, Is.True);
}
}
|
f3802f5fb9d82e714bdea02205138bb66236e4a2
|
C#
|
wangyangwang/urg-unity
|
/Assets/Scripts/Transport/SerialTransport.cs
| 2.75
| 3
|
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Threading;
using UnityEngine;
public class SerialTransport : MonoBehaviour, ITransport
{
public string portName = "/dev/tty.usbmodem1421";
public int baudRate = 115200;
private SerialPort serialPort;
public void Close()
{
serialPort.Close();
serialPort.Dispose();
}
public bool IsConnected()
{
return serialPort != null && serialPort.IsOpen;
}
public bool Open()
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
var portExists = File.Exists(portName);
if (!portExists)
{
Debug.LogWarning(string.Format("Port {0} does not exist.", portName));
return false;
}
#endif
bool openSuccess = false;
serialPort = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
for (int i = 0; i < 1; i++)
{
try
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
serialPort.ReadTimeout = 1000;
#else
serialPort.ReadTimeout = 10;
#endif
serialPort.WriteTimeout = 1000;
serialPort.ReadBufferSize = 4096;
serialPort.NewLine = "\n";
serialPort.Open();
openSuccess = true;
break;
}
catch (IOException ex)
{
Debug.LogWarning("error:" + ex.ToString());
}
Thread.Sleep(2000);
}
return openSuccess;
}
public string ReadLine()
{
return serialPort.ReadLine();
}
public void Write(byte[] bytes)
{
serialPort.Write(bytes, 0, bytes.Length);
}
}
|
c657bcd82c1eb0af32fa3d818ed000d6d1d09c36
|
C#
|
killvxk/footlocker
|
/bots/remote_40080485/Net-Weave R/Core/BaseChatPacket.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetLib.Misc;
namespace Net_Weave_R.Core
{
class BaseChatPacket
{
public ChatClient.Header Header;
public byte[] Data;
public byte[] GetBytes()
{
List<byte> bytes = new List<byte>();
bytes.AddRange(BitConverter.GetBytes((int)Header));
bytes.AddRange(Data);
byte[] packet = bytes.ToArray();
bytes.Clear();
bytes = null;
return Encryption.Encrypt(packet, true);
}
public BaseChatPacket(ChatClient.Header header, byte[] data)
{
Header = header;
Data = data;
}
}
}
|
c08e38d474ca6a49fe90b9da2f58bf30b34a60c9
|
C#
|
sergiocabral/App.Cabster
|
/Cabster/Business/Entities/GroupWorkHistorySet.cs
| 2.671875
| 3
|
using System;
namespace Cabster.Business.Entities
{
/// <summary>
/// Temporizador do trabalho em grupo MOB.
/// </summary>
public class GroupWorkHistorySet : EntityBase
{
/// <summary>
/// Momento do início.
/// </summary>
public DateTimeOffset Started { get; set; }
/// <summary>
/// Tempo esperado de execução.
/// </summary>
public TimeSpan TimeExpected { get; set; }
/// <summary>
/// Tempo decorrido de execução.
/// </summary>
public TimeSpan TimeElapsed { get; set; }
/// <summary>
/// Tempo foi concluído.
/// </summary>
public bool TimeConcluded { get; set; }
/// <summary>
/// Indica que é um intervalo
/// </summary>
public bool IsBreak { get; set; }
/// <summary>
/// Nome do Driver.
/// </summary>
public string? Driver { get; set; }
/// <summary>
/// Nome do Navegador.
/// </summary>
public string? Navigator { get; set; }
}
}
|
b23c7b8f1c54bc9b4b156263498a83f29a805099
|
C#
|
HowyoungZhou/dip
|
/DipLib/Utils.cs
| 3.375
| 3
|
using System;
namespace DipLib
{
public static class Utils
{
public static int Round(this double n) => (int) Math.Round(n);
public static float LimitTo(this float n, float min, float max) => n < min ? min : n > max ? max : n;
public static int LimitTo(this int n, int min, int max) => n < min ? min : n > max ? max : n;
public static double LimitTo(this double n, double min, double max) => n < min ? min : n > max ? max : n;
public static byte LimitTo(this byte n, byte min, byte max) => n < min ? min : n > max ? max : n;
public static double Squared(this double n) => n * n;
public static float Squared(this float n) => n * n;
public static double Squared(this int n) => n * n;
public static double Rearrange(this double n, double originMin, double originMax, double min, double max) =>
(max - originMax) / (min - originMin) * (n - originMin) + originMax;
}
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public static Point Zeros { get; } = new Point(0, 0);
public Point(int x = 0, int y = 0)
{
this.X = x;
this.Y = y;
}
public static Point operator +(Point p1, Point p2) => new Point(p1.X + p2.X, p1.Y + p2.Y);
public static Point operator -(Point p1, Point p2) => new Point(p1.X - p2.X, p1.Y - p2.Y);
public static Point operator -(Point p) => new Point(-p.X, -p.Y);
public int GetSquaredDistance(Point point)
{
return (X - point.X) * (X - point.X) + (Y - point.Y) * (Y - point.Y);
}
public Point RotateR(Point origin, double angle)
{
return new Point(
(int) Math.Round(origin.X + (X - origin.X) * Math.Cos(angle) - (Y - origin.Y) * Math.Sin(angle)),
(int) Math.Round(origin.Y + (X - origin.X) * Math.Sin(angle) + (Y - origin.Y) * Math.Cos(angle))
);
}
public Point RotateD(Point origin, double angle)
{
return RotateR(origin, angle / 180 * Math.PI);
}
}
public struct Line
{
public double A { get; set; }
public double B { get; set; }
public double C { get; set; }
public Line(double a, double b, double c)
{
A = a;
B = b;
C = c;
}
public Line(Point p1, Point p2) : this(p2.Y - p1.Y, p1.X - p2.X, p2.X * p1.Y - p1.X * p2.Y)
{
}
public Line(double h, Axis axis) : this(0, 0, -h)
{
switch (axis)
{
case Axis.X:
A = 1;
break;
case Axis.Y:
B = 1;
break;
default:
throw new ArgumentOutOfRangeException(nameof(axis), axis, null);
}
}
public enum Axis
{
X,
Y
}
public static Point? Intersection(Line l1, Line l2)
{
var m = l1.A * l2.B - l2.A * l1.B;
if (Math.Abs(m) <= double.Epsilon) return null;
var x = (l2.C * l1.B - l1.C * l2.B) / m;
var y = (l1.C * l2.A - l2.C * l1.A) / m;
return new Point(Convert.ToInt32(x), Convert.ToInt32(y));
}
}
}
|
02565f98e707df8555617e9a4ac17c6d72337dbb
|
C#
|
YAFNET/YAFNET
|
/yafsrc/ServiceStack/ServiceStack/Text/StringWriterCache.cs
| 2.765625
| 3
|
// ***********************************************************************
// <copyright file="StringWriterCache.cs" company="ServiceStack, Inc.">
// Copyright (c) ServiceStack, Inc. All Rights Reserved.
// </copyright>
// <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary>
// ***********************************************************************
using System;
using System.Globalization;
using System.IO;
namespace ServiceStack.Text;
/// <summary>
/// Reusable StringWriter ThreadStatic Cache
/// </summary>
public static class StringWriterCache
{
/// <summary>
/// The cache
/// </summary>
[ThreadStatic]
static StringWriter cache;
/// <summary>
/// Allocates this instance.
/// </summary>
/// <returns>StringWriter.</returns>
public static StringWriter Allocate()
{
var ret = cache;
if (ret == null)
return new StringWriter(CultureInfo.InvariantCulture);
var sb = ret.GetStringBuilder();
sb.Length = 0;
cache = null; //don't re-issue cached instance until it's freed
return ret;
}
/// <summary>
/// Frees the specified writer.
/// </summary>
/// <param name="writer">The writer.</param>
public static void Free(StringWriter writer)
{
cache = writer;
}
/// <summary>
/// Returns the and free.
/// </summary>
/// <param name="writer">The writer.</param>
/// <returns>System.String.</returns>
public static string ReturnAndFree(StringWriter writer)
{
var ret = writer.ToString();
cache = writer;
return ret;
}
}
/// <summary>
/// Alternative Reusable StringWriter ThreadStatic Cache
/// </summary>
public static class StringWriterCacheAlt
{
/// <summary>
/// The cache
/// </summary>
[ThreadStatic]
static StringWriter cache;
/// <summary>
/// Allocates this instance.
/// </summary>
/// <returns>StringWriter.</returns>
public static StringWriter Allocate()
{
var ret = cache;
if (ret == null)
return new StringWriter(CultureInfo.InvariantCulture);
var sb = ret.GetStringBuilder();
sb.Length = 0;
cache = null; //don't re-issue cached instance until it's freed
return ret;
}
/// <summary>
/// Frees the specified writer.
/// </summary>
/// <param name="writer">The writer.</param>
public static void Free(StringWriter writer)
{
cache = writer;
}
/// <summary>
/// Returns the and free.
/// </summary>
/// <param name="writer">The writer.</param>
/// <returns>System.String.</returns>
public static string ReturnAndFree(StringWriter writer)
{
var ret = writer.ToString();
cache = writer;
return ret;
}
}
//Use separate cache internally to avoid reallocations and cache misses
/// <summary>
/// Class StringWriterThreadStatic.
/// </summary>
internal static class StringWriterThreadStatic
{
/// <summary>
/// The cache
/// </summary>
[ThreadStatic]
static StringWriter cache;
/// <summary>
/// Allocates this instance.
/// </summary>
/// <returns>StringWriter.</returns>
public static StringWriter Allocate()
{
var ret = cache;
if (ret == null)
return new StringWriter(CultureInfo.InvariantCulture);
var sb = ret.GetStringBuilder();
sb.Length = 0;
cache = null; //don't re-issue cached instance until it's freed
return ret;
}
/// <summary>
/// Frees the specified writer.
/// </summary>
/// <param name="writer">The writer.</param>
public static void Free(StringWriter writer)
{
cache = writer;
}
/// <summary>
/// Returns the and free.
/// </summary>
/// <param name="writer">The writer.</param>
/// <returns>System.String.</returns>
public static string ReturnAndFree(StringWriter writer)
{
var ret = writer.ToString();
cache = writer;
return ret;
}
}
|
d8d24ed135c8b10ec3be79c2e01a8e5df4d4a547
|
C#
|
bt7s7k7/WordScript
|
/WordScriptCSTests/WorldScript.cs
| 2.703125
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace WordScript.Tests {
/// <summary>
/// Summary description for WorldScript
/// </summary>
[TestClass]
public class WorldScript {
public WorldScript() {
//
// TODO: Add constructor logic here
//
}
[AssemblyInitialize]
public static void Setup(TestContext context) {
TypeInfoProvider.GetGlobal().AddFunction("print", (a) => {
context.WriteLine((string)a[0]);
return null;
}, null, new Type[] { typeof(string) });
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext {
get {
return testContextInstance;
}
set {
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
TypeInfoProvider provider = TypeInfoProvider.GetGlobal();
[TestMethod]
public void GettingDefaultTypeName() {
Assert.AreEqual(provider.GetTypeName(typeof(string)), "string");
}
public class TestClass {
public int testValue;
[TypeName(typeof(TestClass))]
public static string GetTypeName() => "TestClass";
[TypeConversion]
public static int ToInt(TestClass inp) => inp.testValue;
[TypeConversion]
public static TestClass FromInt(int inp) => new TestClass { testValue = inp };
[TypeName(typeof(TestGenericClass<>))]
public static string TestGenericName() => "TestGenericClass";
[TypeConversion]
public static TestGenericClass<int> TestGenericFromInt(int i) => new TestGenericClass<int>();
}
[TestMethod]
public void GettingCustomTypeName() {
Assert.AreEqual(provider.GetTypeName(typeof(TestClass)), TestClass.GetTypeName());
}
[TestMethod]
public void CustomConversion() {
var overloads = provider.GetOverloads("TestClass");
Assert.AreEqual(overloads.Count, 1, "Function signature not found, error in GetOverloads or [TypeConversion]");
var function = provider.GetFunction(overloads[0]);
Assert.AreEqual(function.returnType, typeof(TestClass), "Function return value is not correct. Either a different overload is registered or error");
}
[TestMethod]
public void Tokenizing() {
var tokens = CodeTokenizer.Tokenize("print IN add \"Hello\" \"world\" . .\n mul 5 10 , string , add \" = 25\" , print .");
Assert.AreEqual(tokens.Count, 18);
}
[TestMethod]
public void Parsing() {
Enviroment enviroment = new Enviroment(TypeInfoProvider.GetGlobal());
var block = TokenParser.Parse("\"Comment\" .\nprint IN string 25 . .\nprint IN add \"Hello\" \"world\" . .\n mul 5 10 , string , add \" = 25\" , print .", enviroment, CodePosition.GetExternal());
var statements = block.GetSyntaxNodes();
Assert.AreEqual(statements.Count, 4);
}
[TestMethod]
public void VariableDefinition() {
Enviroment enviroment = new Enviroment(TypeInfoProvider.GetGlobal());
enviroment.StartBlock(CodePosition.GetExternal());
Assert.IsNull(enviroment.GetVariable("y"));
enviroment.DefineVariable("x", typeof(int), CodePosition.GetExternal());
Assert.IsNotNull(enviroment.GetVariable("x"));
enviroment.EndBlock();
}
[TestMethod]
[ExpectedException(typeof(VariableException))]
public void VariableRedefinitionFail() {
Enviroment enviroment = new Enviroment(TypeInfoProvider.GetGlobal());
enviroment.StartBlock(CodePosition.GetExternal());
enviroment.DefineVariable("x", typeof(int), CodePosition.GetExternal());
enviroment.DefineVariable("x", typeof(int), CodePosition.GetExternal());
enviroment.EndBlock();
}
[TestMethod]
public void VariablesInCode() {
Enviroment enviroment = new Enviroment(TypeInfoProvider.GetGlobal());
enviroment.StartBlock(CodePosition.GetExternal());
enviroment.DefineVariable("x", typeof(int), CodePosition.GetExternal());
TokenParser.Parse("DEFINE:y:int . &y . y= 0 . &x . x= &y .", enviroment, CodePosition.GetExternal(), true);
Assert.IsNotNull(enviroment.GetVariable("y"));
Assert.AreEqual(enviroment.GetVariable("y").Type, typeof(int));
enviroment.EndBlock();
}
[TestMethod]
[ExpectedException(typeof(FunctionNotFoundException))]
public void VariableTypeSafetyInCode() {
Enviroment enviroment = new Enviroment(TypeInfoProvider.GetGlobal());
enviroment.StartBlock(CodePosition.GetExternal());
enviroment.DefineVariable("x", typeof(string), CodePosition.GetExternal());
TokenParser.Parse("x= 0 .", enviroment, CodePosition.GetExternal());
enviroment.EndBlock();
}
[TestMethod]
public void VariableInheritance() {
Enviroment enviroment = new Enviroment(TypeInfoProvider.GetGlobal());
enviroment.StartBlock(CodePosition.GetExternal());
var xOut = enviroment.DefineVariable("x", typeof(string), CodePosition.GetExternal());
var yOut = enviroment.DefineVariable("y", typeof(int), CodePosition.GetExternal());
enviroment.StartBlock(CodePosition.GetExternal());
Assert.AreEqual(yOut, enviroment.GetVariable("y"));
Assert.AreEqual(xOut, enviroment.GetVariable("x"));
var yInner = enviroment.DefineVariable("y", typeof(string), CodePosition.GetExternal());
var zInner = enviroment.DefineVariable("z", typeof(string), CodePosition.GetExternal());
Assert.AreNotEqual(yOut, enviroment.GetVariable("y"));
enviroment.EndBlock();
Assert.AreEqual(yOut, enviroment.GetVariable("y"));
Assert.IsNull(enviroment.GetVariable("z"));
enviroment.EndBlock();
}
[TestMethod]
public void StandardInclusion() {
TypeInfoProvider provider = new TypeInfoProvider().LoadGlobals();
Assert.IsNotNull(provider.GetFunction("int float"));
}
[TestMethod]
[ExpectedException(typeof(FunctionNotFoundException))]
public void StandardInclusionFiltering() {
TypeInfoProvider provider = new TypeInfoProvider().LoadGlobals();
Assert.IsNotNull(provider.GetFunction("TestMethod int"));
}
[TestMethod()]
public void AddFunctionTest() {
TypeInfoProvider provider = new TypeInfoProvider();
provider.AddFunction("test", (v) => v, typeof(void), new Type[] { });
Assert.IsNotNull(provider.GetFunction("test"));
}
[TestMethod()]
public void GetFunctionSignatureTest() {
Assert.AreEqual(provider.GetFunctionSignature("test", new Type[] { }), "test");
Assert.AreEqual(provider.GetFunctionSignature("testa", new Type[] { }), "testa");
Assert.AreEqual(provider.GetFunctionSignature("testb", new Type[] { typeof(int) }), "testb int");
}
[TestMethod()]
public void StatementBlockPosition() {
Enviroment enviroment = new Enviroment(provider);
var block = TokenParser.Parse("int 0f .", enviroment, CodePosition.GetExternal());
Assert.AreEqual(block.position, CodePosition.GetExternal());
}
public class TestGenericClass<T> {
}
[TestMethod]
public void GenericTypeNames() {
Assert.AreEqual(provider.GetTypeName(typeof(TestGenericClass<int>)), "TestGenericClass!int");
}
[TestMethod]
public void GenericTypesFromName() {
Assert.AreEqual(provider.GetTypeByName("TestGenericClass!string"), typeof(TestGenericClass<string>));
}
[TestMethod]
public void ReturningFromBlock() {
Enviroment enviroment = new Enviroment(provider);
var block = TokenParser.Parse("return 10 .", enviroment, CodePosition.GetExternal());
block.Validate(enviroment);
Assert.AreEqual(block.ReturnType, typeof(int));
}
[TestMethod]
public void ReturningFromBlockMultiple() {
Enviroment enviroment = new Enviroment(provider);
var block = TokenParser.Parse("return 10 . return 15 .", enviroment, CodePosition.GetExternal());
block.Validate(enviroment);
Assert.AreEqual(block.ReturnType, typeof(int));
}
[TestMethod]
[ExpectedException(typeof(ReturnTypeException))]
public void ReturningFromBlockMismatchDetect() {
Enviroment enviroment = new Enviroment(provider);
var block = TokenParser.Parse("return 10 . return 1f .", enviroment, CodePosition.GetExternal());
block.Validate(enviroment);
Assert.AreEqual(block.ReturnType, typeof(int));
}
[TestMethod]
public void CodeExecution() {
Enviroment enviroment = new Enviroment(provider);
Assert.AreEqual(TokenParser.Parse("add 10 15 .", enviroment, CodePosition.GetExternal()).Evaluate(), 25);
}
[TestMethod]
public void CodeExecutionReturn() {
Enviroment enviroment = new Enviroment(provider);
Assert.AreEqual(TokenParser.Parse("add 10 15 , return .", enviroment, CodePosition.GetExternal()).Evaluate(), 25);
}
[TestMethod]
public void RunTheExampleFile() {
var text = System.IO.File.ReadAllText("../../../Examples/example.ws");
Enviroment enviroment = new Enviroment(TypeInfoProvider.GetGlobal());
var block = TokenParser.Parse(text, enviroment, CodePosition.GetExternal());
block.Validate(enviroment);
Assert.AreEqual(typeof(string), block.ReturnType);
Assert.AreEqual("aaaab", block.Evaluate());
}
[WordScriptType]
class TestMapClass {
public int i;
public TestMapClass() {
i = 5;
}
public TestMapClass(int i) {
this.i = i;
}
public int GetI() => i;
}
[TestMethod]
public void TypeAttribute() {
Enviroment enviroment = new Enviroment(provider);
Assert.IsNotNull(TokenParser.Parse("TestMapClass .", enviroment, CodePosition.GetExternal()).Evaluate() as TestMapClass);
Assert.AreEqual(5, TokenParser.Parse("TestMapClass , .i .", enviroment, CodePosition.GetExternal()).Evaluate());
Assert.AreEqual(20, TokenParser.Parse("TestMapClass 20 , .i .", enviroment, CodePosition.GetExternal()).Evaluate());
Assert.AreEqual(20, TokenParser.Parse("TestMapClass 20 , .GetI .", enviroment, CodePosition.GetExternal()).Evaluate());
}
}
}
|
116e95c884e5f833886cf01da13bb131174f91c6
|
C#
|
tiramisuzie/LoveThemBack
|
/LoveThemBackWebApp/LoveThemBackWebApp/Models/Services/FavoriteService.cs
| 3.0625
| 3
|
using LoveThemBackWebApp.Data;
using LoveThemBackWebApp.Models.Interfaces;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace LoveThemBackWebApp.Models.Services
{
public class FavoriteService : IFavorites
{
private LTBDBContext _context;
public FavoriteService(LTBDBContext context)
{
_context = context;
}
/// <summary>
/// creates a favorite and adds to database
/// </summary>
/// <param name="favorite"></param>
/// <returns></returns>
public async Task CreateFavorite(Favorite favorite)
{
_context.Favorites.Add(favorite);
await _context.SaveChangesAsync();
}
/// <summary>
/// deletes favorite object based on user and pet id
/// </summary>
/// <param name="userId"></param>
/// <param name="petId"></param>
/// <returns></returns>
public async Task DeleteFavorite(int userId, int petId)
{
Favorite favorite = await GetFavorite(userId, petId);
_context.Favorites.Remove(favorite);
await _context.SaveChangesAsync();
}
public async Task<Favorite> GetFavorite(int userId, int petId)
{
return await _context.Favorites.FirstOrDefaultAsync(x => x.UserID == userId && x.PetID == petId);
}
/// <summary>
/// get favorites list from user id
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public async Task<List<PetPost>> GetFavorites(int userId)
{
var pets = await GetJSON();
List<Favorite> favorites = _context.Favorites.Where(x => x.UserID == userId).ToList();
List<PetPost> myFavPets = new List<PetPost>();
foreach (var pet in favorites)
{
foreach (var item in pets)
{
if (item.PetID == pet.PetID)
{
myFavPets.Add(item);
}
}
}
foreach (var pet in myFavPets)
{
string[] photos = pet.Photos.Split(",");
pet.Photos = photos[2];
string[] breeds = pet.Breed.Split(",");
string newPetBreed = "";
foreach (var breed in breeds)
{
newPetBreed += breed + " ";
}
pet.Breed = newPetBreed;
}
return myFavPets;
}
/// <summary>
/// updates favorites object in database
/// </summary>
/// <param name="favorite"></param>
/// <returns></returns>
public async Task UpdateFavorite(Favorite favorite)
{
_context.Favorites.Update(favorite);
await _context.SaveChangesAsync();
}
/// <summary>
/// Custom API call to get pets in a list
/// </summary>
public async Task<List<PetPost>> GetJSON()
{
string url = "https://lovethembackapi2.azurewebsites.net/api/Pets";
using (var httpClient = new HttpClient())
{
var json = await httpClient.GetStringAsync(url);
var retrieveJSON = JsonConvert.DeserializeObject<List<PetPost>>(json);
// Now parse with JSON.Net
return retrieveJSON;
}
}
}
}
|
ed1b1e5319c302aae1c4da9e2269c398b18ff25f
|
C#
|
DavidZaidi/The-Flying-Kryptonian
|
/TheFlyingKryptonian Source Code/Assets/CameraFollow.cs
| 2.921875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
public GameObject objectToFollow; /* objectToFollow is an empty object of type GameObject, we have attached our Superman sprite to 'objectToFollow' object from Unity3D Inspector */
/* Camera Follow Properties */
float previousPosition;
float amountToMove;
// Use this for initialization
void Start () {
/*
1st Line: timeScale is a time property which pauses and unpauses the game, where 1.0f stands for Realtime (unpause) and 0 stands for freeze (pause)
2nd Line: Store objecToFollow positions to previousPosition so that we can use it in Update and move the camera */
Time.timeScale = 1.0f;
previousPosition = objectToFollow.transform.position.x;
}
// Update is called once per frame
void Update () {
/*
1st Line: Amount of camera to move and store it in variable, a simple formula which will calculate the amount to move
2nd Line: Set the current position to amountToMove on x axis and add it on every frame
3rd Line: Update the previous position so that we can move forward horizontally
This process will repeat on every frame so that our Camera can follow/move with the Superman sprite
*/
amountToMove = (objectToFollow.transform.position.x + 5f) - previousPosition;
transform.position += new Vector3(amountToMove, 0f, 0f);
previousPosition = transform.position.x;
}
}
|
8f96fdfa6ec99d8d8af567df28f8d8d0da66f35a
|
C#
|
axadn/leetcode-problems
|
/add two numbers/solution.cs
| 3.578125
| 4
|
/**You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
bool carry = false;
ListNode head = new ListNode(0);
ListNode currentNode = head;
while(true){
if(carry) currentNode.val += 1;
if(l1 != null) currentNode.val += l1.val;
if(l2 != null) currentNode.val += l2.val;
if(currentNode.val > 9){
carry = true;
currentNode.val = currentNode.val - 10;
}
else{
carry = false;
}
if(l1!=null) l1 = l1.next;
if(l2!=null) l2 = l2.next;
if(l1 == null && l2 ==null){
if(carry) currentNode.next = new ListNode(1);
break;
}
else{
currentNode.next = new ListNode(0);
currentNode = currentNode.next;
}
}
return head;
}
}
|
f26286d4cc12f94768761f452ca7807953ab149f
|
C#
|
tangledbootlace/gokesrentals
|
/gokesrentals/GokesRentals/Folly.Auth/Custom/FakeAuthenticationImplementation.cs
| 2.953125
| 3
|
using Folly.Auth;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Folly.Auth
{
//TODO: Implement your own Auth Engine, similar to this
public class FakeAuthenticationImplementation : IAuthenticationImplementation
{
///NOTE: This is a hack for this template. Don't actually do this, the credentials will be cleared
///everytime the website is restarted. You should be storing these in a database instead
public List<FakeUser> FakeDBCredStore = new List<FakeUser>();
public TimeSpan GetAuthTimeout()
{
return TimeSpan.FromDays(365);
}
/// <summary>
/// 32-character random key. GENERATE YOUR OWN.
/// You can run StringHelper.RandomString(32) on a one-off basis to generate one
/// </summary>
/// <returns></returns>
public string GetEncryptionKey()
{
//TODO: DEFINITELY change this.
return "*GENERATEYOUROWNKEYANDPUTITHERE*";
}
public async Task<PermissionResult> CheckPermission(LoginToken token, string roles = null)
{
if (roles == null)
return PermissionResult.Ok;
FakeUser user = null;
if (token.IDSource == "DBID")
user = FakeDBCredStore.SingleOrDefault(c => c.ID == token.ID);
if (user == null)
return PermissionResult.Invalid;
if (!roles.ToLower().Contains("[" + user.Role.ToLower() + "]"))
return PermissionResult.Denied;
return PermissionResult.Ok;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task<IAuthUser> Authenticate(string email, string password, bool isAdmin = false)
{
var user = FakeDBCredStore.SingleOrDefault(c => c.Email.ToLower() == email.ToLower());
if (user == null)
throw new UnauthorizedAccessException("There is no account with that email address."); ;
if (!PasswordHash.ValidatePassword(password, user.PasswordHash))
throw new UnauthorizedAccessException("Wrong password.");
return user;
}
/// <summary>
/// Assigns the user and ID and saves it to the "database"
/// </summary>
/// <param name="u"></param>
/// <returns></returns>
public async Task<IAuthUser> CreateAccount(IAuthUser u)
{
FakeUser user = (FakeUser)u;
if(FakeDBCredStore.Any(c => c.Email.ToLower() == user.Email.ToLower()))
{
throw new CreateAccountException("A user with this email address already exists!");
}
user.ID = StringHelper.RandomString(32);
FakeDBCredStore.Add(user);
return user;
}
}
}
|
68c34b904dbe86f573ac70f682f5ba408b11d05b
|
C#
|
kenperkerwicz/StudentExercises
|
/Program.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
namespace StudentExercises
{
class Program
{
static void Main(string[] args)
{
//create 4 or more exercises
Exercise firstEx = new Exercise()
{
language = "JavaScript"
};
Exercise secondEx = new Exercise()
{
language = "Python"
};
Exercise thirdEx = new Exercise()
{
language = "Ruby"
};
Exercise fourthEx = new Exercise()
{
language = "HTML"
};
//create cohorts//
Cohort Cohort30 = new Cohort("Cohort 30");
Cohort Cohort31 = new Cohort("Cohort 31");
Cohort Cohort32 = new Cohort("Cohort 32");
Cohort Cohort33 = new Cohort()
{
Cohortname = "Cohort 33"
};
//create 4 or more students//
Student Ken = new Student()
{
firstName = "Ken",
lastName = "Perkerwicz",
slackHandle = "kenPerkerwicz",
cohort = Cohort30,
};
Student Chad = new Student()
{
firstName = "Chad",
lastName = "Kroger",
slackHandle = "chadKroger",
cohort = Cohort31,
};
Student Bob = new Student()
{
firstName = "Bob",
lastName = "Ross",
slackHandle = "bobRoss",
cohort = Cohort32,
};
Student Jeff = new Student()
{
firstName = "Jeff",
lastName = "Goldblum",
slackHandle = "jeffGoldblum",
cohort = Cohort30
};
// create instructors//
Instructor Steven = new Instructor()
{
firstName = "Steven",
lastName = "Brownlee",
slackHandle = "steveB",
instructorCohort = Cohort30,
};
Instructor Meg = new Instructor()
{
firstName = "Meg",
lastName = "Ducharme",
slackHandle = "MegD",
instructorCohort = Cohort31
};
Instructor Biff = new Instructor()
{
firstName = "Biff",
lastName = "Trump",
slackHandle = "biffB",
instructorCohort = Cohort31
};
Biff.ExerciseAssignment(Bob, firstEx);
Biff.ExerciseAssignment(Bob, secondEx);
List<Student> students = new List<Student>();
students.Add(Ken);
students.Add(Bob);
Cohort30.studentList.Add(Ken);
Cohort30.studentList.Add(Jeff);
// produces cohort 30
Console.WriteLine(Jeff.cohort.Cohortname);
// produces cohort 31
Console.WriteLine(Biff.instructorCohort.Cohortname);
foreach (Student student in Cohort30.studentList)
{
Console.WriteLine($"the students first name is {student.firstName}, and their last name is {student.lastName}");
}
}
}
}
|
1cea3d9a33c52a7eda95d816c79638880f3a344c
|
C#
|
Vakuu/CSharp
|
/OOP/EnemyHomeWorks/1hw3/Persons/Person.cs
| 3.703125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Persons
{
public class Person
{
private string name;
private int age;
private string email;
private const string EmailPattern = @"(?<=\s|^)([A-Za-z0-9]*(?:[_.-][A-Za-z0-9]*)*@(?:[A-Za-z]*\-?[A-Za-z]*\.)*[A-Za-z]*\-?[A-Za-z]*)\b";
public Person(string name, int age)
: this(name, age, null)
{
}
public Person(string name, int age, string email)
{
this.Name = name;
this.Age = age;
this.Email = email;
}
public string Name
{
get { return this.name; }
set
{
if (String.IsNullOrWhiteSpace(value))
{
throw new ArgumentNullException("Name cannot be empty.");
}
this.name = value;
}
}
public int Age
{
get { return this.age; }
set
{
if (value <= 0 || value > 100)
{
throw new ArgumentOutOfRangeException("Age must be in the range [1 ... 100].");
}
this.age = value;
}
}
public string Email
{
get { return this.email; }
set
{
if (value != null && !Regex.IsMatch(value, EmailPattern))
{
throw new ArgumentException(@"Email should contain ""@""", "email");
}
this.email = value;
}
}
public override string ToString()
{
return "You are " + this.name + ". You are " + this.age + " years old. Your email is " + (string.IsNullOrEmpty(this.email) ? "not entered." : this.email);
}
static void Main()
{
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Enter your age:");
int age = int.Parse(Console.ReadLine());
Console.WriteLine("Enter your email:");
string email = Console.ReadLine();
Person one = new Person(name, age);
Console.WriteLine(one);
}
}
}
|