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
|
|---|---|---|---|---|---|---|
985b5bbd005774e60338082a33fb77a1b898051d
|
C#
|
WFR79/EngieEducation
|
/SuiteSecurity/Entities/EntityCollection.cs
| 2.578125
| 3
|
/*
* Created by SharpDevelop.
* User: HCE339
* Date: 22-05-2012
* Time: 15:35
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections;
namespace SynapseCore.Entities
{
/// <summary>
/// Description of EntityCollection.
/// </summary>
public class EntityCollection :CollectionBase
{
Hashtable Keys;
public EntityCollection()
{
Keys=new Hashtable();
}
public int Add(object item,string key)
{
if (!this.Contains(item))
{
int idx = List.Add(item);
Keys.Add(key,idx);
return idx;
}
else
return 0;
}
public void Remove(object item)
{
List.Remove(item);
}
public bool Contains(object item)
{
return List.Contains(item);
}
public int IndexOf(object item)
{
return List.IndexOf(item);
}
public void CopyTo(object[] array, int index)
{
List.CopyTo(array, index);
}
public object this[int index]
{
get { return (object)List[index]; }
set { List[index] = value; }
}
}
}
|
074513a70d5ab174927913438228f4944be9c5a0
|
C#
|
MiguePenaloza/TecWeb1-2020
|
/TiendaMusicalAPI/TiendaMusicalAPI/Models/InstrumentModel.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace InstrumentAPI.Models
{
public class InstrumentModel
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(1,100000)]
[Required]
public decimal? Price { get; set; }
[MaxLength(50, ErrorMessage ="To much letters")]
public string Description { get; set; }
public bool? Discount { get; set; }
}
}
|
1328811a47d2310cd98ed1f7f68f7ec75588c56e
|
C#
|
IvarsPL/C-Sharp-hw
|
/IfScooter/IfScooters.Test/RideHistoryTest.cs
| 2.71875
| 3
|
using NUnit.Framework;
using System;
namespace IfScooters.Test
{
class RideHistoryTest
{
[Test]
public void RideHistoryConstructor_CreateNewInstance_ReturnsNewInstance()
{
//Arrange
var expectedTurnover = 0;
var expectedId = "123";
//Act
var actual = new RideHistory("123");
//Assert
Assert.AreEqual(expectedId, actual.Id);
Assert.AreEqual(expectedTurnover, actual.Turnover);
}
[Test]
public void CalculateScooterRideTime_LessThanOneDay_ReturnsCorrectTime()
{
//Arrange
var minutesAdded = 10;
var daysAdded = 0;
var compare = new RideHistory("541");
var comparableMinute = DateTime.Now;
var inputMinute = comparableMinute + TimeSpan.FromMinutes(minutesAdded);
var comparableDay = DateTime.Now;
var inputDay = comparableDay + TimeSpan.FromDays(daysAdded);
var inputHour = DateTime.Now.Hour;
var inputMonth = DateTime.Now.Month;
var inputYear = DateTime.Now.Year;
//Act
compare.EndDateTime = new DateTime(inputYear, inputMonth, inputDay.Day, inputHour, inputMinute.Minute, 00);
compare.CalculateScooterRideTime();
//Assert
Assert.AreEqual(minutesAdded, compare.RideMinutes);
Assert.AreEqual(daysAdded, compare.RideDays);
}
[Test]
public void CalculateScooterRideTime_TwoDays_ReturnsCorrectTime()
{
//Arrange
var minutesAdded = 15;
var daysAdded = 2;
var compare = new RideHistory("123");
var comparableMinute = DateTime.Now;
var inputMinute = comparableMinute + TimeSpan.FromMinutes(minutesAdded);
var comparableDay = DateTime.Now;
var inputDay = comparableDay + TimeSpan.FromDays(daysAdded);
var inputHour = DateTime.Now.Hour;
var inputMonth = DateTime.Now.Month;
var inputYear = DateTime.Now.Year;
//Act
compare.EndDateTime = new DateTime(inputYear, inputMonth, inputDay.Day, inputHour, inputMinute.Minute, 00);
compare.CalculateScooterRideTime();
//Assert
Assert.AreEqual(minutesAdded, compare.RideMinutes);
Assert.AreEqual(daysAdded, compare.RideDays);
}
[Test]
public void CalculateScooterTurnover_TwoFullDaysAndSomeMinutes_ReturnsCorrectTurnover()
{
//Arrange
var minutesAdded = 15;
var daysAdded = 2;
var compare = new RideHistory("123");
var comparableMinute = DateTime.Now;
var inputMinute = comparableMinute + TimeSpan.FromMinutes(minutesAdded);
var comparableDay = DateTime.Now;
var inputDay = comparableDay + TimeSpan.FromDays(daysAdded);
var inputHour = DateTime.Now.Hour;
var inputMonth = DateTime.Now.Month;
var inputYear = DateTime.Now.Year;
var p = new ScooterService();
var s = new ScooterRent(p);
//Act
p.AddScooter("123", 1);
s.StartRent("123");
var q = p.GetScooterById("123");
compare.EndDateTime = new DateTime(inputYear, inputMonth, inputDay.Day, inputHour, inputMinute.Minute, 00);
compare.CalculateScooterRideTime();
compare.CalculateScooterTurnover(q);
//Assert
Assert.AreEqual(55, compare.Turnover);
}
[Test]
public void CalculateScooterTurnover_15MinutesAndSmallPrice_ReturnsCorrectTurnover()
{
//Arrange
var minutesAdded = 15;
var daysAdded = 0;
decimal pricePerMinute = 0.23m;
var expected = pricePerMinute * minutesAdded;
var compare = new RideHistory("123");
var comparableMinute = DateTime.Now;
var inputMinute = comparableMinute + TimeSpan.FromMinutes(minutesAdded);
var comparableDay = DateTime.Now;
var inputDay = comparableDay + TimeSpan.FromDays(daysAdded);
var inputHour = DateTime.Now.Hour;
var inputMonth = DateTime.Now.Month;
var inputYear = DateTime.Now.Year;
var p = new ScooterService();
var s = new ScooterRent(p);
//Act
p.AddScooter("123", pricePerMinute);
s.StartRent("123");
var q = p.GetScooterById("123");
compare.EndDateTime = new DateTime(inputYear, inputMonth, inputDay.Day, inputHour, inputMinute.Minute, 00);
compare.CalculateScooterRideTime();
compare.CalculateScooterTurnover(q);
//Assert
Assert.AreEqual(expected, compare.Turnover);
}
}
}
|
96a67b3ef8d90e70b51d2e8e01de6282b872bcdb
|
C#
|
fabracht/designPatterns
|
/singletonPattern1/Singleton.cs
| 3.96875
| 4
|
namespace singletonPattern1
{
public sealed class Singleton
{
// A readonly can only be assigned within the scope of the constructor
private static readonly Singleton _instance;
private static int TotalInstances;
/*
The private constructor is used to prevent the creation of instances with the 'new' keyword outside this class */
private Singleton()
{
System.Console.WriteLine("Private constructor called");
}
/* With a private constructor, creating an instance from outside is now impossible, so we need a static constructor as well */
static Singleton()
{
System.Console.WriteLine("This is the static constructor");
_instance = new Singleton();
TotalInstances++;
System.Console.WriteLine($"Total number of instances: {TotalInstances}");
}
public static Singleton Instance => _instance;
/* The following line shows one of the drawbacks of this approach to the singleton */
public static int Myint = 25;
}
}
|
dab6afa95818b82d766963dde6d5bfb6ec29dadc
|
C#
|
perpetualKid/DevTest
|
/HtmlParser/HtmlParserTest/HtmlNodeCollectionTest.cs
| 2.671875
| 3
|
using HtmlParser;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace HtmlParserTest
{
/// <summary>
///This is a test class for HtmlNodeCollectionTest and is intended
///to contain all HtmlNodeCollectionTest Unit Tests
///</summary>
[TestClass()]
public class HtmlNodeCollectionTest
{
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
/// <summary>
///A test for Item
///</summary>
[TestMethod()]
public void ItemByNameTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
target.Add(new HtmlElement("first"));
target.Add(new HtmlElement("second"));
target.Add(new HtmlElement("second"));
Assert.IsNotNull(target["second"]);
Assert.IsNull(target["anyname"]);
}
/// <summary>
///A test for Item
///</summary>
[TestMethod()]
[ExpectedException(typeof(System.ArgumentNullException))]
public void ItemByIndexTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
target.Add(new HtmlElement("first"));
target.Add(new HtmlElement("second"));
target.Add(new HtmlElement("third"));
Assert.AreEqual(target[1], target["second"]);
target[2] = new HtmlElement("another");
target[0] = null;
StringAssert.Contains(target[2].ToString(), "another");
}
/// <summary>
///A test for Insert
///</summary>
[TestMethod()]
[ExpectedException(typeof(System.ArgumentNullException))]
public void InsertTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
HtmlElement child = new HtmlElement("child");
target.Add(child);
child = new HtmlElement("second");
target.Insert(0, child);
Assert.AreEqual(root, child.Parent);
Assert.AreEqual(target.IndexOf(child), 0);
target.Insert(0, null);
}
/// <summary>
///A test for GetByName
///</summary>
[TestMethod()]
public void GetByNameTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
target.Add(new HtmlElement("first"));
target.Add(new HtmlElement("second"));
target.Add(new HtmlElement("second"));
Assert.AreEqual(target.GetByName("second").Count, 2);
((HtmlElement)target[0]).Nodes.Add(new HtmlElement("second"));
Assert.AreEqual(target.GetByName("second", false).Count, 2);
Assert.AreEqual(target.GetByName("second").Count, 3);
}
/// <summary>
///A test for FindByAttributeNameValue
///</summary>
[TestMethod()]
public void FindByAttributeNameValueTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
target.Add(new HtmlElement("first"));
target.Add(new HtmlElement("second"));
target.Add(new HtmlElement("third"));
((HtmlElement)target[1]).Nodes.Add(new HtmlElement("secondchild"));
((HtmlElement)target[1]).Attributes.Add(new HtmlAttribute("firstattribute", "firstvalue"));
((HtmlElement)target[1]).Attributes.Add(new HtmlAttribute("secondattribute", "firstvalue"));
((HtmlElement)target[2]).Attributes.Add(new HtmlAttribute("firstattribute", "secondvalue"));
((HtmlElement)((HtmlElement)target[1]).Nodes[0]).Attributes.Add(new HtmlAttribute("secondattribute", "secondvalue"));
((HtmlElement)((HtmlElement)target[1]).Nodes[0]).Attributes.Add(new HtmlAttribute("firstattribute", "anothervalue"));
Assert.AreEqual(target.FindByAttributeNameValue("firstattribute", "secondvalue", false).Count, 1);
Assert.AreEqual(target.FindByAttributeNameValue("firstattribute", "anothervalue").Count, 1);
}
/// <summary>
///A test for FindByAttributeName
///</summary>
[TestMethod()]
public void FindByAttributeNameTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
target.Add(new HtmlElement("first"));
target.Add(new HtmlElement("second"));
target.Add(new HtmlElement("third"));
((HtmlElement)target[0]).Nodes.Add(new HtmlElement("secondchild"));
((HtmlElement)target[1]).Attributes.Add(new HtmlAttribute("firstattribute"));
((HtmlElement)target[1]).Attributes.Add(new HtmlAttribute("secondattribute"));
((HtmlElement)target[2]).Attributes.Add(new HtmlAttribute("firstattribute"));
Assert.AreEqual(target.FindByAttributeName("firstattribute").Count, 2);
((HtmlElement)((HtmlElement)target[0]).Nodes[0]).Attributes.Add(new HtmlAttribute("firstattribute"));
Assert.AreEqual(target.FindByAttributeName("firstattribute", false).Count, 2);
Assert.AreEqual(target.FindByAttributeName("firstattribute", true).Count, 3);
}
/// <summary>
///A test for Add
///</summary>
[TestMethod()]
[ExpectedException(typeof(System.ArgumentNullException))]
public void AddTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
HtmlElement child = new HtmlElement("child");
int index = target.Add(child);
Assert.AreEqual(root, child.Parent);
Assert.AreEqual(index, 0);
target.Add(null);
}
/// <summary>
///A test for HtmlNodeCollection Constructor
///</summary>
[TestMethod()]
public void HtmlNodeCollectionConstructorTest()
{
HtmlElement root = new HtmlElement("root");
HtmlNodeCollection target = new HtmlNodeCollection(root);
HtmlElement child = new HtmlElement("child");
target.Add(child);
Assert.AreEqual(root, child.Parent);
}
}
}
|
66ff5c1bc698863fb857d76c75fefdb4a5bb3765
|
C#
|
GeorgiSpasov/CSharpAdvancedHW
|
/StringLibrary/StringLibrary.cs
| 3.734375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringLibrary
{
class StringLibrary
{
static void Main(string[] args)
{
string input = Console.ReadLine();
Console.WriteLine(StringToIntArray(input).Sum());
}
public static int[] StringToIntArray(string input)
{
int[] intArray = input.Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
return intArray;
}
public static string Decode(string encoded)
{
var result = "";
for (var i = 0; i < encoded.Length; i++)
{
var currentRepeat = "";
while (char.IsDigit(encoded[i]))
{
currentRepeat += encoded[i];
i++;
}
if (currentRepeat == "")
{
currentRepeat = "1";
}
var amount = int.Parse(currentRepeat);
result += new String(encoded[i], amount);
}
return result;
}
}
}
|
f23fe6304a3c483090011c77a22c384b9722c416
|
C#
|
akimlyubchenko/Training-Summer-Express-2018
|
/NET.S.2018.Lyubchenko.02/ArraySort.Tests/ArraySortTests.cs
| 2.9375
| 3
|
// <copyright file = "ArraySortTests.cs" company = "EPAM">
// Array Sort Tests
// </copyright>
namespace ArraySort.Tests
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for Array sort
/// </summary>
[TestClass]
public class ArraySortTests
{
#region Checker arrays
/// <summary>
/// Checker arrays
/// </summary>
[TestMethod]
public void FilterDigit_InputArray1217157_Return177()
{
// Arr
int[] arr = { 12, 17, 0, 7 };
int[] expected = { 17, 7 };
// Arc
int[] actual = ArraySort.FilterDigit(arr, 7);
// Assert
CollectionAssert.AreEqual(expected, actual);
}
#endregion
#region Checker arrays width value == 0
/// <summary>
/// Checker arrays width value == 0
/// </summary>
[TestMethod]
public void FilterDigit_InputValue0_NumbersWidth0()
{
// Arr
int[] arr = { 12, 0, 15, 105, 10456 };
int[] expected = { 0, 105, 10456 };
// Arc
int[] actual = ArraySort.FilterDigit(arr, 0);
// Assert
CollectionAssert.AreEqual(expected, actual);
}
#endregion
#region Checker negative numbers
/// <summary>
/// Checker negative numbers
/// </summary>
[TestMethod]
public void FilterDigit_Inputnegativenumbers_ReturnSuitableNumbers()
{
// Arr
int[] arr = { -12, -17, -20, 7 };
int[] expected = { -12, -20 };
// Arc
int[] actual = ArraySort.FilterDigit(arr, 2);
// Assert
CollectionAssert.AreEqual(expected, actual);
}
#endregion
#region Checker for null array
/// <summary>
/// Checker for null array
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void FilterDigit_NullInsteadArray_ThrowArgumentNullException()
=> ArraySort.FilterDigit(null, 0);
#endregion
[TestMethod]
public void NumberFinderByString_171017_177()
{
// Arr
int[] array = new int[] { 17, 10, 1, 7 };
int digit = 7;
int[] expected = new int[] { 17, 7 };
// Act
int[] actual = ArraySort.FilterDigit(array, digit, true);
// Assert
CollectionAssert.AreEqual(expected, actual);
}
[TestMethod]
public void NumberFinderByString_123456101636_61636()
{
// Arr
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 10, 16, 36 };
int digit = 6;
int[] expected = new int[] { 6, 16, 36 };
// Act
int[] actual = ArraySort.FilterDigit(array, digit, true);
// Assert
CollectionAssert.AreEqual(expected, actual);
}
[TestMethod]
public void NumberFinderByString_BigArray_ArrayContainOnlyNumbersWidthDigit()
{
Random rand = new Random();
// Arr
int[] array = new int[100000];
int digit = 6;
for (int i = 0; i < expected.Length - 1; i++)
{
array[i] = rand.Next(100);
}
// Act
ArraySort.FilterDigit(array, 0, digit, true);
// Assert
if (!IsTrueArray(array))
{
Assert.Fail();
}
}
[TestMethod]
public void FilterDigit_BigArray_ArrayContainOnlyNumbersWidthDigit()
{
Random rand = new Random();
// Arr
int[] array = new int[100000];
int digit = 6;
for (int i = 0; i < expected.Length - 1; i++)
{
array[i] = rand.Next(100);
}
// Act
ArraySort.FilterDigit(array, 0, digit, false);
// Assert
if (!IsTrueArray(array))
{
Assert.Fail();
}
}
private static bool IsTrueArray(int[] array, int digit)
{
int newArray = array;
int counter = 0;
for (int i = 0; i < array.Length; i++)
{
while (newArray[i] != 0)
{
if (newArray[i] % 10 == digit)
{
counter++;
break;
}
newArray /= 10;
}
}
if (array.Length - 1 == counter)
{
return true;
}
return false;
}
}
}
|
3d8da84e14d4066b9a4e00cec98cc0df7b646aec
|
C#
|
arrowflex/FreeAgent
|
/src/FreeAgent/ModelExtensions/BillExtensions.cs
| 2.578125
| 3
|
using FreeAgent.Helpers;
using FreeAgent.Model;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace FreeAgent
{
public static class BillExtensions
{
public static Task<IEnumerable<Bill>> GetBillsAsync(this FreeAgentClient client, BillFilter filterBy = BillFilter.All, BillOrder orderBy = BillOrder.DueDate, DateTime? fromDate = null, DateTime? toDate = null)
{
var view = filterBy.GetMemberValue();
var sort = orderBy.GetMemberValue();
return client.GetOrCreateAsync(c => c.BillList(client.Configuration.CurrentHeader, view, sort, fromDate, toDate), r => r.Bills);
}
public static Task<Bill> CreateBillAsync(this FreeAgentClient client, Bill bill)
{
return client.GetOrCreateAsync(c => c.CreateBill(client.Configuration.CurrentHeader, bill.Wrap()), r => r.Bill);
}
public static Task UpdateBillAsync(this FreeAgentClient client, Bill bill)
{
return client.UpdateOrDeleteAsync(bill, (c, id) => c.UpdateBill(client.Configuration.CurrentHeader, id, bill.Wrap()));
}
public static Task<Bill> GetBillAsync(this FreeAgentClient client, Bill bill)
{
var id = client.ExtractId(bill);
return client.GetBillAsync(id);
}
public static Task<Bill> GetBillAsync(this FreeAgentClient client, Uri url)
{
var id = client.ExtractId(url);
return client.GetBillAsync(id);
}
public static Task<Bill> GetBillAsync(this FreeAgentClient client, int billId)
{
return client.GetOrCreateAsync(c => c.GetBill(client.Configuration.CurrentHeader, billId), r => r.Bill);
}
public static Task DeleteBillAsync(this FreeAgentClient client, Bill bill)
{
return client.UpdateOrDeleteAsync(bill, (c,id) => c.DeleteBill(client.Configuration.CurrentHeader, id));
}
internal static BillWrapper Wrap(this Bill bill)
{
return new BillWrapper { Bill = bill };
}
}
public enum BillFilter
{
[EnumMember(Value = "all")] All,
[EnumMember(Value = "open")] Open,
[EnumMember(Value = "overdue")] Overdue,
[EnumMember(Value = "open_or_overdue")] OpenOrOverdue,
[EnumMember(Value = "paid")] Paid,
[EnumMember(Value = "recurring")] Recurring
}
public enum BillOrder
{
[EnumMember(Value = "dated_on")] DatedOn,
[EnumMember(Value = "-dated_on")] DatedOnDescending,
[EnumMember(Value = "due_date")] DueDate,
[EnumMember(Value = "-due_date")] DueDateDescending,
[EnumMember(Value = "total_value")] TotalValue,
[EnumMember(Value = "-total_value")] TotalValueDescending,
[EnumMember(Value = "reference")] Reference,
[EnumMember(Value = "-reference")] ReferenceDescending,
[EnumMember(Value = "contact_display_name")] ContactDisplayName,
[EnumMember(Value = "-contact_display_name")] ContactDisplayNameDescending
}
}
|
8ea6ae4d91c4a550e651df1eb2f71e8167dd3feb
|
C#
|
anychart-integrations/asp-net-core-mvc-mysql-template
|
/Models/FruitDBContext.cs
| 3.09375
| 3
|
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System.Collections.Generic;
namespace asp_net_core_mvc_mysql_template.Models
{
public class FruitDBContext
{
public string ConnectionString { get; set; }
public FruitDBContext(string connectionString)
{
this.ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
public List<Fruit> GetTopFruits()
{
List<Fruit> list = new List<Fruit>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM fruits ORDER BY value DESC LIMIT 5", conn);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Fruit(){
id = reader.GetInt32("id"),
name = reader.GetString("name"),
value = reader.GetInt32("value")
});
}
}
}
return list;
}
}
}
|
46909900d84347583d4c7ef834ca2759ec25c378
|
C#
|
thelarz/MvcRouteFlow
|
/MvcRouteFlow/Path.cs
| 2.9375
| 3
|
using System.Collections.Generic;
using System.Linq;
using MvcRouteFlow.Exceptions;
namespace MvcRouteFlow
{
public interface IPath
{
string Name { get; set; }
List<IStep> Steps { get; set; }
IPath AddStep(IStep step);
IPath Install();
void Remove();
}
public class Path<T> : IPath
{
public string Name { get; set; }
public List<IStep> Steps { get; set; }
private int _lastId = 1;
public Path()
{
Name = typeof (T).Name;
}
public IPath AddStep(IStep step)
{
if (Steps == null)
{
Steps = new List<IStep>();
}
step.Sequence = _lastId++;
Steps.Add(step);
return this;
}
public IPath Install()
{
if (Steps == null)
{
throw new RouteFlowException(string.Format("RouteFlow:No steps found on Path ({0})", this.Name));
}
PathManager.Install(this);
return this;
}
public void Remove()
{
PathManager.Remove(this);
}
}
}
|
c2152b3e82a4c53d8cfa388d2c94c56a10cec6ce
|
C#
|
IMHristov/SoftUni
|
/Tech Module 3.0/Programming Fundamentals/ExamPrep/Exam-Problem IV/ForceBook/Program.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace P_4ForceBook
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
Dictionary<string, List<string>> Sides = new Dictionary<string, List<string>>();
while (input != "Lumpawaroo")
{
var commands = input
.Split()
.ToArray();
if (commands[1] == "|")
{
string side = commands[0];
string jedi = commands[2];
if (!Sides.ContainsKey(side))
{
Sides.Add(side, new List<string>());
}
if (Sides[side].Contains(jedi) == false &&
Sides.Values.Any(x => x.Contains(jedi)) == false)
{
Sides[side].Add(jedi);
}
}
if (commands[1] == "->")
{
string side = commands[2];
string jedi = commands[0];
if (Sides.Values.Any(x => x.Contains(jedi)) == false)
{
if (Sides.ContainsKey(side) == false)
{
Sides.Add(side, new List<String>());
}
Sides[side].Add(jedi);
Console.WriteLine($"{jedi} joins the {side} side!");
}
else
{
foreach (var s in Sides)
{
if (s.Value.Contains(jedi))
{
s.Value.Remove(jedi);
}
}
if (Sides.ContainsKey(side) == false)
{
Sides.Add(side, new List<String>());
}
Sides[side].Add(jedi);
Console.WriteLine($"{jedi} joins the {side} side!");
}
}
input = Console.ReadLine();
}
var sorted = Sides.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key);
foreach (var side in sorted)
{
if (side.Value.Count != 0)
{
Console.WriteLine($"Side: {side.Key}, Members: {side.Value.Count}");
}
foreach (var user in side.Value.OrderBy(x => x))
{
Console.WriteLine($"! {user}");
}
}
}
}
}
|
61ca28fbbe70dc6bf52db7f895e1538c05587c15
|
C#
|
akexter/SlimeSlasher
|
/Slimy Slasher/Assets/3D Tilemap System/Scripts/TilePalette.cs
| 2.515625
| 3
|
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.TilemapSystem3D
{
[CreateAssetMenu(fileName = "New Tile Palette", menuName = "3D Tilemap System/ Tile Palette")]
public class TilePalette : ScriptableObject
{
/// <summary>
/// The tiles resolution.
/// </summary>
public int tileSize = 32;
/// <summary>
/// The atlas texture to convert to tiles.
/// </summary>
public Texture2D atlasTexture;
/// <summary>
/// The offset between each tile in the atlas texture.
/// </summary>
public int gridOffset = 0;
/// <summary>
/// The number of tiles in the atlas texture that you want to extract and convert to tiles.
/// </summary>
public int extractNumber = 255;
/// <summary>
/// The number of tiles inside this palette.
/// </summary>
public int tilesCount = 0;
// Editor only
#if UNITY_EDITOR
/// <summary>
/// Array that stores all the temporary tiles inside this palette.
/// </summary>
public Texture2D[] temporaryTileTextureArray = new Texture2D[256];
/// <summary>
/// Editor warning messages.
/// </summary>
private readonly string[] m_warning = new[]
{
"<b>3D Tilemap System:</b> There is no texture attached to the <b>Atlas Texture</b> field. Please add a texture and try again!",
"<b>3D Tilemap System:</b> The atlas texture is not readable. Please, check the <b>Read/Write Enabled</b> option in the texture import settings to be able to perform the conversion.",
"<b>3D Tilemap System:</b> Action aborted! The tile Pack is already full."
};
/// <summary>
/// Called by the custom reset button.
/// </summary>
public void ResetAsset()
{
DeleteTiles();
tileSize = 32;
gridOffset = 0;
tilesCount = 0;
atlasTexture = null;
}
/// <summary>
/// Delete all the temporary tile inside this palette.
/// </summary>
public void DeleteTiles()
{
for (int i = 0; i < 256; i++)
{
if (!temporaryTileTextureArray[i]) continue;
DestroyImmediate(temporaryTileTextureArray[i], true);
}
tilesCount = 0;
if (AssetDatabase.Contains(this))
{
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(this));
EditorGUIUtility.PingObject(this);
}
}
/// <summary>
/// Extracts all the tiles of the atlas texture and save inside this pallete as .asset file.
/// </summary>
public void ConvertAtlasToTiles()
{
if (!atlasTexture)
{
Debug.LogWarning(m_warning[0]);
return;
}
var texturePath = AssetDatabase.GetAssetPath(atlasTexture);
var textureImporter = (TextureImporter)AssetImporter.GetAtPath(texturePath);
if(!textureImporter.isReadable)
{
Debug.LogWarning(m_warning[1]);
return;
}
bool isFree = false;
for (int i = 0; i < 256; i++)
{
if (temporaryTileTextureArray[i]) continue;
isFree = true;
}
if (!isFree)
{
Debug.LogWarning(m_warning[2]);
return;
}
// Calculates the amount of tiles in the atlas texture
var horizontalColumns = atlasTexture.width / (tileSize + gridOffset);
var verticalColumns = atlasTexture.height / (tileSize + gridOffset);
// The tile index currently being scanned
var tileIndex = 0;
// Scans each tile of the atlas texture
for (var y = verticalColumns -1; y >= 0; y--)
{
for (var x = 0; x < horizontalColumns; x++)
{
if (tileIndex > 255 || tileIndex >= extractNumber) break;
while (temporaryTileTextureArray[tileIndex] && tileIndex < 255)
{
tileIndex++;
}
if (temporaryTileTextureArray[tileIndex]) continue;
// Get the color of the current tile from the atlas texture
var tileColor = atlasTexture.GetPixels(x * (tileSize + gridOffset) + gridOffset, y * (tileSize + gridOffset) + gridOffset, tileSize, tileSize);
// Create the tile texture
temporaryTileTextureArray[tileIndex] = new Texture2D(tileSize, tileSize, TextureFormat.ARGB32, false, true)
{
name = "Tile" + tileIndex,
filterMode = FilterMode.Point,
alphaIsTransparency = true,
wrapMode = TextureWrapMode.Repeat,
hideFlags = HideFlags.DontSaveInBuild
};
// Paste the tile color to new tile texture
temporaryTileTextureArray[tileIndex].SetPixels(tileColor);
temporaryTileTextureArray[tileIndex].Apply();
// Save the new tile texture into this palette as .asset file
AssetDatabase.AddObjectToAsset(temporaryTileTextureArray[tileIndex], this);
// Go to the next tile
tileIndex++;
tilesCount++;
}
}
// Refresh the project window
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(this));
EditorGUIUtility.PingObject(this);
}
#endif
}
}
|
c9cfe67c0e8ffd47d61280cb6827088d5e86376e
|
C#
|
supreethgangam/dragonage-lightmapper
|
/DALightmapper/Geometry/3D/Triangle.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace Geometry
{
public class Triangle
{
private Vector3[] _mVerts;
private Vector2[] _tVerts;
private Vector2[] _lVerts;
private Vector3 _normal;
private Vector2[] lightMapInverseMatrix;
private float determinant;
private bool degenerate;
public bool isDegenerate
{
get { return degenerate; }
}
public bool isLightmapped { get; private set; }
public Vector3 x
{
get { return _mVerts[0]; }
}
public Vector3 y
{
get { return _mVerts[1]; }
}
public Vector3 z
{
get { return _mVerts[2]; }
}
public Vector3 normal
{
get { return _normal; }
}
public Vector2 u
{
get { return _tVerts[0]; }
}
public Vector2 v
{
get { return _tVerts[1]; }
}
public Vector2 w
{
get { return _tVerts[2]; }
}
public Vector2 a
{
get { return _lVerts[0]; }
}
public Vector2 b
{
get { return _lVerts[1]; }
}
public Vector2 c
{
get { return _lVerts[2]; }
}
public Vector3 this[int i]
{
get { return _mVerts[i]; }
}
public Triangle(Triangle t, Vector3 offset, Quaternion rotation)
{
Matrix4 transform = new Matrix4(new Vector4(Vector3.Transform(Vector3.UnitX, rotation), 0),
new Vector4(Vector3.Transform(Vector3.UnitY, rotation), 0),
new Vector4(Vector3.Transform(Vector3.UnitZ, rotation), 0),
new Vector4(offset, 1));
_mVerts = new Vector3[3] { Vector3.Transform(t.x, transform), Vector3.Transform(t.y, transform), Vector3.Transform(t.z, transform) };
calculateNormal();
_tVerts = new Vector2[3] { t.u, t.v, t.w};
lightMapInverseMatrix = new Vector2[2];
if (t.isLightmapped)
{
isLightmapped = true;
_lVerts = new Vector2[3] { t.a, t.b, t.c };
calculateInverseMatrix();
degenerate = areColinear(c - a, b - a);
}
}
public Triangle(Vector3 x, Vector3 y, Vector3 z, Vector2 u, Vector2 v, Vector2 w)
{
_mVerts = new Vector3[3] { x, y, z };
_tVerts = new Vector2[3] { u, v, w };
lightMapInverseMatrix = new Vector2[2];
isLightmapped = false;
degenerate = false;
calculateNormal();
}
public Triangle(Vector3 x, Vector3 y, Vector3 z, Vector2 u, Vector2 v, Vector2 w, Vector2 a, Vector2 b, Vector2 c)
: this(x, y, z, u, v, w)
{
isLightmapped = true;
_lVerts = new Vector2[3] { a, b, c };
calculateInverseMatrix();
degenerate = areColinear(c - a, b - a);
}
public bool isOnUVPixel(Vector2 topLeft, Vector2 bottomRight)
{
//Separating axis theorem
return !((bottomRight.X < a.X && bottomRight.X < b.X && bottomRight.X < c.X) || //Right of uv
(bottomRight.Y > a.Y && bottomRight.Y > b.Y && bottomRight.Y > c.Y) || //Below uv
(topLeft.X > a.X && topLeft.X > b.X && topLeft.X > c.X) || //Left of uv
(topLeft.Y < a.Y && topLeft.Y < b.Y && topLeft.Y < c.Y) || //Above uv
allOnPositiveSide(b, a, topLeft, bottomRight) || //Triangle edges
allOnPositiveSide(c, b, topLeft, bottomRight) ||
allOnPositiveSide(a, c, topLeft, bottomRight));
}
public bool uvIsOnThisTriangle(Vector2 coord)
{
if (!isLightmapped)
{
return false;
}
Vector2 convertedCoord = convertToTextureBasis(coord);
//If the points are >= 0 and add up to <= 1 then its on the triangle.
// Remove the = to ignore the edges
//Floating point precision errors can cause problems so extremely close to 1 is good enough here
return ((convertedCoord.X >= 0f) && (convertedCoord.Y >= 0f) && (((float)(convertedCoord.X + convertedCoord.Y - 1)) <= 0.000001f));
}
//Find where the 2d input coordinates are on the 3d plane defined by this triangle
public Vector3 uvTo3d(Vector2 topLeft, Vector2 bottomRight)
{
//Find the center of the box in uv space
Vector2 center = convertToTextureBasis((topLeft + bottomRight) / 2);
//if the length is > 1 then we are outside the triangle
if (center.LengthSquared > 1)
{
center.Normalize();
}
return x + center.X * (y - x) + center.Y * (z - x);
}
public float intersection(Vector3 start, Vector3 direction, out Vector3 intersectionPoint)
{
Vector3 xTemp = x; //for some reason access to x in this function do not get optimized, this removes the function call overhead
Vector3 edge1 = y - xTemp;
Vector3 edge2 = z - xTemp;
float dot00 = Vector3.Dot(edge1, edge1);
float dot01 = Vector3.Dot(edge1, edge2);
float dot11 = Vector3.Dot(edge2, edge2);
float distanceDenominator = Vector3.Dot(normal, direction);
float baryDenominator = (dot00 * dot11) - (dot01 * dot01);
//If this is a degenerate triangle baryDenominator will be 0
//If the ray is parallel to the triangle, the distanceDenominator will be 0
if (baryDenominator != 0 && distanceDenominator != 0)
{
float t = Vector3.Dot(normal, xTemp - start) / distanceDenominator;
//If the triangle is in the opposite direction, this value will be negative
// I don't count the ray starting on the triangle as an intersection with that triangle
// so only consider positive values
if (t > 0)
{
intersectionPoint = start + t * direction;
Vector3 pointEdge = intersectionPoint - xTemp;
float dot02 = Vector3.Dot(edge1, pointEdge);
float dot12 = Vector3.Dot(edge2, pointEdge);
float u = (dot11 * dot02 - dot01 * dot12) / baryDenominator;
float v = (dot00 * dot12 - dot01 * dot02) / baryDenominator;
if ((u >= 0) && (v >= 0) && (u + v < 1))
{
return t;
}
}
}
intersectionPoint = Vector3.Zero;
return -1.0f;
}
private bool pointIsBetween(Vector2 a, Vector2 topLeft, Vector2 bottomRight)
{
if (!isLightmapped)
{
return false;
}
else
{
return a.X >= topLeft.X && a.X <= bottomRight.X && a.Y <= topLeft.Y && a.Y >= bottomRight.Y;
}
}
private Vector2 convertToTextureBasis(Vector2 coord)
{
//Find vector from origin to input point
Vector2 point = Vector2.Subtract(coord, a);
//Solve for the u and v values using the inverse matrix (matrix multiplication)
float u = Vector2.Dot(lightMapInverseMatrix[0], point);
float v = Vector2.Dot(lightMapInverseMatrix[1], point);
return new Vector2(u, v);
}
private void calculateInverseMatrix()
{
//Calculate the basis matrix, this matrix will only be singular if the triangle is degenerate
Vector2 firstCol = Vector2.Subtract(b, a);
Vector2 secondCol = Vector2.Subtract(c, a);
//Find the reciprocal determinant of the matrix
determinant = 1 / (firstCol.X * secondCol.Y - secondCol.X * firstCol.Y);
//calculate the inverse matrix
lightMapInverseMatrix[0] = Vector2.Multiply(new Vector2(secondCol.Y, -secondCol.X), determinant);
lightMapInverseMatrix[1] = Vector2.Multiply(new Vector2(-firstCol.Y, firstCol.X), determinant);
}
private bool allOnPositiveSide(Vector2 start, Vector2 end, Vector2 topLeft, Vector2 bottomRight)
{
Vector2 bottomLeft = new Vector2(topLeft.X, bottomRight.Y);
Vector2 topRight = new Vector2(bottomRight.X, topLeft.Y);
return onPositiveSide(start, end, topLeft) && onPositiveSide(start, end, bottomLeft) &&
onPositiveSide(start, end, topRight) && onPositiveSide(start, end, bottomRight);
}
private bool onPositiveSide(Vector2 start, Vector2 end, Vector2 p)
{
return (end.X - start.X) * (p.Y - start.Y) - (end.Y - start.Y) * (p.X - start.X) > 0;
/*
Vector2 aDirection = aEnd - aStart;
Vector2 bDirection = bEnd - bStart;
Vector2 aTobStart = bStart - aStart;
if (areColinear(aDirection, bDirection)) return false;
float detDenom = aDirection.X * bDirection.Y - aDirection.Y * bDirection.X;
if (detDenom == 0) return false;
//Need to explicitly cast these otherwise it will be optimized into the comparasin below at higher than float precision
// causing errors
float t = (float)(1 / detDenom * (bDirection.Y * aTobStart.X - bDirection.X * aTobStart.Y));
float u = (float)(-(1 / detDenom * (-aDirection.Y * aTobStart.X + aDirection.X * aTobStart.Y)));
//Do not count the end points
return t > 0f && t < 1f && u > 0f && u < 1f;
//*/
}
private bool areColinear(Vector2 a, Vector2 b)
{
//if either point at (0,0) then there is no line as direction vector has 0 length
if (b.X == 0 && b.Y == 0 ||
a.X == 0 && a.Y == 0)
return true;
//if one component is zero, its matching component must not be 0
if (a.X == 0 && b.X == 0 ||
a.Y == 0 && b.Y == 0 ||
b.X == 0 && a.X == 0 ||
b.Y == 0 && a.Y == 0)
return true;
//If the ratio of the components is the same then they are colinear
return (a.X / b.X == a.Y / b.Y);
}
private void calculateNormal()
{
Vector3 first = Vector3.Subtract(y, x);
Vector3 second = Vector3.Subtract(z, x);
_normal = Vector3.Cross(first, second);
if (_normal.Length == 0)
_normal = new Vector3(1, 0, 0);
else
_normal.Normalize();
}
}
}
|
c2eec7a70e98446cc6216fcf75774f85b7126dc2
|
C#
|
RyanTaite/JiraTimeLogSubmitter-BlazorServerSide
|
/JiraWorklogSubmitter/JiraWorklogSubmitter/Config/JiraSettings.cs
| 2.84375
| 3
|
namespace JiraWorklogSubmitter.Config
{
/// <summary>
/// Used to store the appsettings values
/// </summary>
public class JiraSettings
{
private string _baseUrl;
private string _email;
private string _token;
private string _apiUrl;
private string _firstName;
private string _lastName;
/// <summary>
/// The base url of the companies atlassian account.
/// Ex: https://COMPANY.atlassian.net
/// </summary>
public string BaseUrl
{
get => _baseUrl;
set => _baseUrl = value?.Trim();
}
/// <summary>
/// Meant to be used after <see cref="BaseUrl"/>
/// </summary>
public string ApiUrl
{
get => _apiUrl;
set => _apiUrl = value?.Trim();
}
/// <summary>
/// The email of the user to sign in as
/// </summary>
public string Email
{
get => _email;
set => _email = value?.Trim();
}
/// <summary>
/// Your first name.
/// Used for JQL queries.
/// </summary>
public string FirstName
{
get => _firstName;
set => _firstName = value?.Trim();
}
/// <summary>
/// Your last name.
/// Used for JQL queries.
/// </summary>
public string LastName
{
get => _lastName;
set => _lastName = value?.Trim();
}
/// <summary>
/// Combination of <see cref="FirstName"/> and <see cref="LastName"/>
/// </summary>
public string FullName => $"{_firstName} {_lastName}";
/// <summary>
/// The API token to use
/// </summary>
/// <remarks>
/// Learn how to setup a token here: https://confluence.atlassian.com/cloud/api-tokens-938839638.html
/// </remarks>
public string Token
{
get => _token;
set => _token = value?.Trim();
}
}
}
|
f1cfa52db12cf6222a5a4d03012206992b07af7f
|
C#
|
lorenzowind/csharp-projects
|
/ProjectWs02/src/DTOs/ProductDTO.cs
| 2.6875
| 3
|
using ProjectWs02.src.Models;
namespace ProjectWs02.src.DTOs
{
public class ProductDTO
{
public int Id { get; set; }
public string Name { get; set; }
public decimal UnitaryPrice { get; set; }
public static ProductDTO FromProduct(Product product)
{
return new ProductDTO
{
Id = product.Id,
Name = product.Name,
UnitaryPrice = product.Price
};
}
}
}
|
82007da6cbec254b6642d8d174d65a2e7a5d36b6
|
C#
|
imcody/restful-api-aspnetboilerplate
|
/src/ResponsibleSystem.Common/Domain/Operations/OperationResult`1.cs
| 2.5625
| 3
|
// Decompiled with JetBrains decompiler
// Type: ResponsibleSystem.Common.Domain.Operations.OperationResult`1
// Assembly: ns4D, Version=1.0.2.0, Culture=neutral, PublicKeyToken=null
// MVID: 9B44D8D9-B1BD-47D0-B47A-F7256B478C0B
// Assembly location: C:\Repos\sani_nudge_ui\ResponsibleSystem.Api\libs\ns4D.dll
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
namespace ResponsibleSystem.Common.Domain.Operations
{
/// <summary>
/// Describes the result of an operation that returns a value of type <typeparamref name="T" />.
/// </summary>
/// <typeparam name="T">Type of value returned from operation</typeparam>
[DataContract(Name = "{0}OperationResult")]
public class OperationResult<T> : BaseOperationResult
{
private T mValue;
private bool mHasValue;
/// <summary>
/// Creates a new, blank instance of <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" /> returning no value.
/// </summary>
[ExcludeFromCodeCoverage]
public OperationResult()
{
}
/// <summary>
/// Creates an instance of <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" /> returning the specified value.
/// </summary>
/// <param name="value">Value of <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" /></param>
public OperationResult(T value)
{
this.Value = value;
}
/// <summary>
/// Gets or sets the result of the operation. Always returns null/default value if operation failed.
/// </summary>
[DataMember]
public T Value
{
get
{
if (this.HasValue)
return this.mValue;
return default(T);
}
set
{
this.mValue = value;
this.mHasValue = true;
}
}
/// <summary>
/// Gets a value indicating whether the result of the operation contains any value.
/// Always returns false if operation failed.
/// </summary>
[DataMember]
public bool HasValue
{
get
{
if (this.mHasValue)
return this.Success;
return false;
}
protected set
{
}
}
/// <summary>
/// Implicitly converts an instance of <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" /> to <typeparamref name="T" />.
/// </summary>
/// <param name="result"><see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" /> to convert</param>
/// <exception cref="T:System.ArgumentNullException">If <paramref name="result" /> is <value>null</value></exception>
/// <returns>The value of <paramref name="result" /></returns>
/// <remarks>
/// This is the recommended method of retrieving the result of an operation, since this will
/// immediately fail if operation failed or returned no value (see <see cref="M:GetValueOrThrow" />),
/// thereby avoiding potential <see cref="T:System.NullReferenceException" />s elsewhere.
/// </remarks>
public static implicit operator T(OperationResult<T> result)
{
if (result == null)
throw new ArgumentNullException(nameof(result));
return result.GetValueOrThrow();
}
/// <summary>
/// Implicitly converts any value to an <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" /> containing the value
/// and indicating success.
/// </summary>
/// <param name="value">Value returned from an operation</param>
/// <returns>An <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" /> containing <paramref name="value" />
/// and indicating succes</returns>
public static implicit operator OperationResult<T>(T value)
{
return OperationResult.Returns<T>(value);
}
/// <summary>
/// Implicitly converts any <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult" /> to an <see cref="T:ResponsibleSystem.Common.Domain.Operations.OperationResult`1" />
/// that has no value.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public static implicit operator OperationResult<T>(OperationResult other)
{
OperationResult<T> operationResult = new OperationResult<T>();
operationResult.Messages.AddRange((IEnumerable<OperationMessage>)other.Messages);
return operationResult;
}
/// <summary>
/// Returns the value of the operation result. If operation failed or contains no value, an exception is thrown.
/// </summary>
/// <exception cref="T:ResponsibleSystem.Common.Domain.Operations.OperationFailedException">Thrown if the operation result indicates failure.</exception>
/// <exception cref="T:ResponsibleSystem.Common.Domain.Operations.OperationReturnedNoValueException">Thrown if the operation result contains no value.</exception>
/// <returns>The value of the current instance</returns>
private T GetValueOrThrow()
{
if (!this.Success)
throw new OperationFailedException((IEnumerable<OperationMessage>)this.Messages);
if (!this.HasValue)
throw new OperationReturnedNoValueException();
return this.Value;
}
}
}
|
81eed421e05cab1b9f0d59d202dc2efcfd0440db
|
C#
|
henanMayueyue/PicView
|
/PicView/Image Logic/SaveImages.cs
| 2.90625
| 3
|
using ImageMagick;
using System.Diagnostics;
namespace PicView
{
internal static class SaveImages
{
internal static void ResizeImageToFile(string file, int NewWidth, int NewHeight)
{
try
{
using (MagickImage magick = new MagickImage())
{
MagickGeometry size = new MagickGeometry(NewWidth, NewHeight)
{
IgnoreAspectRatio = true
};
magick.Resize(size);
magick.Quality = 100;
magick.Write(file);
}
}
#if DEBUG
catch (MagickException e)
{
Trace.WriteLine("ResizeImageToFile " + file + " null, \n" + e.Message);
return;
}
#else
catch (MagickException) { return; }
#endif
}
}
}
|
32e8e2ee10d705d937e5b2f1e41fe0e4777b1b1e
|
C#
|
gilles007-/ffxi-monitor
|
/DvsParse/FFACETools/ParseResources.cs
| 2.5625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using System.IO;
namespace FFACETools
{
public partial class FFACE
{
/// <summary>
/// This class will parse the resources.xml file to
/// translate ID <-> Names of spells/abilities/items
/// </summary>
public class ParseResources
{
#region Constants
/// <summary>
/// Name of the resources.xml file
/// </summary>
private const string RESOURCES_FILE_NAME = "resources.xml";
private const string RESOURCES_ITEMS_GENERAL_FILE_NAME = "items_general.xml";
private const string RESOURCES_ITEM_ARMOR_FILE_NAME = "items_armor.xml";
private const string RESOURCES_ITEM_WEAPONS_FILE_NAME = "items_weapons.xml";
private const string RESOURCES_AREAS_FILE_NAME = "areas.xml";
private const string RESOURCES_STATUS_FILE_NAME = "status.xml";
private const string RESOURCES_SPELLS_FILE_NAME = "spells.xml";
private const string RESOURCES_ABILS_FILE_NAME = "abils.xml";
private const string FILENOTFOUND_MSG = "Ensure WindowerPath is set to an absolute path to Windower plugins folder and that the file stated is present.";
private const string WINDOWERPATH_MSG = "WindowerPath has not been set!";
//private KeyValuePair<int, String> ResourcesCache = new KeyValuePair<int, string>();
private static Dictionary<UInt32, String> ResourcesCache = new Dictionary<UInt32, String>(50);
[Flags]
private enum ResourceBit : uint {
None = 0,
Area = 0x010000U,
Item = 0x020000U,
Status = 0x040000U,
Spell = 0x080000U,
Abils = 0x100000U
};
#endregion
/// <summary>
/// Will get the name of the passed status effect
/// </summary>
/// <param name="statusEffect">StatusEffect that you want the in-game name for.</param>
/// <returns>An empty string if status not found.</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static String GetStatusEffectName(StatusEffect statusEffect)
{
UInt32 cacheHash = ((UInt16)statusEffect | (UInt32)ResourceBit.Status);
//cacheHash |= (UInt32)ResourceBit.Status;
String sResult = String.Empty;
if ((ResourcesCache.Count > 0) && ResourcesCache.TryGetValue(cacheHash, out sResult))
{
return sResult;
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
String fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_STATUS_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//status/b[@id='" + statusEffect + "']");
if (null != node && !String.IsNullOrEmpty(node.Value))
{
sResult = node.Value;
}
else
{
sResult = String.Empty;
}
if (sResult != String.Empty)
{
ResourcesCache.Add(cacheHash, sResult);
}
return sResult;
} // @ public static string GetStatusEffectName(StatusEffect statusEffect)
/// <summary>
/// Will get the name of the passed area ID
/// </summary>
/// <param name="id">ID of the area to get the name for</param>
/// <returns>An empty string if no matching area was found.</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static String GetAreaName(int id)
{
if (id < 0)
return String.Empty;
UInt32 cacheHash = (UInt32)id | (UInt32)ResourceBit.Area;
String sResult = String.Empty;
if ((ResourcesCache.Count > 0) && ResourcesCache.TryGetValue(cacheHash, out sResult))
{
return sResult;
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
String fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_AREAS_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//areas/a[@id='" + id + "']");
if (null != node && !String.IsNullOrEmpty(node.Value))
{
sResult = node.Value;
}
else
{
sResult = String.Empty;
}
if (sResult != String.Empty)
{
ResourcesCache.Add(cacheHash, sResult);
}
return sResult;
} // @ public static string GetAreaName(int id)
/// <summary>
/// Will get the name of the passed item ID
/// </summary>
/// <param name="id">ID of the item to get the name for</param>
/// <returns>An empty string if no matching item was found in the items_general.xml file.</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static String GetItemNameGeneral(int id)
{
if (id < 0)
return String.Empty;
UInt32 cacheHash = (UInt32)id | (UInt32)ResourceBit.Item;
String sResult = String.Empty;
if ((ResourcesCache.Count > 0) && ResourcesCache.TryGetValue(cacheHash, out sResult))
{
return sResult;
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
String fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_ITEMS_GENERAL_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//items/i[@id='" + id + "']"); // Items Armor items_armor.xml
if (null != node && !String.IsNullOrEmpty(node.Value))
{
sResult = node.Value;
}
else
{
sResult = String.Empty;
}
if (sResult != String.Empty)
{
ResourcesCache.Add(cacheHash, sResult);
}
return sResult;
}
/// <summary>
/// Will get the name of the passed item ID
/// </summary>
/// <param name="id">ID of the item to get the name for</param>
/// <returns>An empty string if no matching item was found in the items_armor.xml file.</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static String GetItemNameArmor(int id)
{
if (id < 0)
return String.Empty;
UInt32 cacheHash = (UInt32)id | (UInt32)ResourceBit.Item;
String sResult = String.Empty;
if ((ResourcesCache.Count > 0) && ResourcesCache.TryGetValue(cacheHash, out sResult))
{
return sResult;
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
String fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_ITEM_ARMOR_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//items/i[@id='" + id + "']"); // Items Weapons item_weapons.xml
if (null != node && !String.IsNullOrEmpty(node.Value))
{
sResult = node.Value;
}
else
{
sResult = String.Empty;
}
if (sResult != String.Empty)
{
ResourcesCache.Add(cacheHash, sResult);
}
return sResult;
}
/// <summary>
/// Will get the name of the passed item ID
/// </summary>
/// <param name="id">ID of the item to get the name for</param>
/// <returns>An empty string if no matching item was found in the items_weapons.xml file.</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static String GetItemNameWeapons(int id)
{
if (id < 0)
return String.Empty;
UInt32 cacheHash = (UInt32)id | (UInt32)ResourceBit.Item;
String sResult = String.Empty;
if ((ResourcesCache.Count > 0) && ResourcesCache.TryGetValue(cacheHash, out sResult))
{
return sResult;
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
String fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_ITEM_WEAPONS_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//items/i[@id='" + id + "']"); // Items General items_general.xml
if (null != node && !String.IsNullOrEmpty(node.Value))
{
sResult = node.Value;
}
else
{
sResult = String.Empty;
}
if (sResult != String.Empty)
{
ResourcesCache.Add(cacheHash, sResult);
}
return sResult;
}
/// <summary>
/// Will get the name of the passed item ID
/// </summary>
/// <param name="id">ID of the item to get the name for</param>
/// <returns>An empty string if no matching item was found.</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static String GetItemName(int id)
{
if (id < 0)
return String.Empty;
UInt32 cacheHash = (UInt32)id | (UInt32)ResourceBit.Item;
String sResult = String.Empty;
if ((ResourcesCache.Count > 0) && ResourcesCache.TryGetValue(cacheHash, out sResult))
{
return sResult;
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
sResult = GetItemNameGeneral(id);
if (String.IsNullOrEmpty(sResult))
{
sResult = GetItemNameArmor(id);
}
if (String.IsNullOrEmpty(sResult))
{
sResult = GetItemNameWeapons(id);
}
if (sResult != String.Empty)
{
ResourcesCache.Add(cacheHash, sResult);
}
return sResult;
} // @ public static string GetItemName(int id)
/// <summary>
/// Internal and private FindKey function for finding a key by value in a Dictionary
/// </summary>
/// <param name="lookup">Dictionary to look through.</param>
/// <param name="value">Value to locate.</param>
/// <returns>Key if value is found in Dictionary, null otherwise.</returns>
private static UInt32? FindKey(IDictionary<UInt32, String> lookup, String value)
{
foreach (KeyValuePair<UInt32, String> pair in lookup)
{
if (pair.Value == value)
return pair.Key;
}
return null;
}
/// <summary>
/// Will get the ID of of the passed item name (case insenstitive)
/// </summary>
/// <param name="name">Name of the item</param>
/// <returns>-1 if no ID was found for passed name</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static int GetItemIDGeneral(string name)
{
if (ResourcesCache.Count > 0)
{
//Dictionary<UInt32, String> lookup = new Dictionary<UInt32, String>(); // etc
UInt32? value = FindKey(ResourcesCache, name);
if (value.HasValue)
{
return (int)(value & ~(UInt32)ResourceBit.Item);
}
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
int iResult = -1;
String fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_ITEMS_GENERAL_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//items/i[translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')=\"" + name.ToLower() + "\"]");
if (null != node && !String.IsNullOrEmpty(node.Value))
{
try
{
iResult = Convert.ToInt32(node.GetAttribute("id", String.Empty));
}
catch (Exception)
{
iResult = -1;
}
}
if (iResult >= 0)
{
ResourcesCache.Add(((UInt32)iResult | (UInt32)ResourceBit.Item), name);
}
return iResult;
}
/// <summary>
/// Will get the ID of of the passed item name (case insenstitive)
/// </summary>
/// <param name="name">Name of the item</param>
/// <returns>-1 if no ID was found for passed name</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static int GetItemIDWeapons(string name)
{
if (ResourcesCache.Count > 0)
{
//Dictionary<UInt32, String> lookup = new Dictionary<UInt32, String>(); // etc
UInt32? value = FindKey(ResourcesCache, name);
if (value.HasValue)
{
return (int)(value & ~(UInt32)ResourceBit.Item);
}
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
int iResult = -1;
string fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_ITEM_WEAPONS_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//items/i[translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')=\"" + name.ToLower() + "\"]");
if (null != node && !String.IsNullOrEmpty(node.Value))
{
try
{
iResult = Convert.ToInt32(node.GetAttribute("id", String.Empty));
}
catch (Exception)
{
iResult = -1;
}
}
if (iResult >= 0)
{
ResourcesCache.Add(((UInt32)iResult | (UInt32)ResourceBit.Item), name);
}
return iResult;
}
/// <summary>
/// Will get the ID of of the passed item name (case insenstitive)
/// </summary>
/// <param name="name">Name of the item</param>
/// <returns>-1 if no ID was found for passed name</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static int GetItemIDArmor(string name)
{
if (ResourcesCache.Count > 0)
{
//Dictionary<UInt32, String> lookup = new Dictionary<UInt32, String>(); // etc
UInt32? value = FindKey(ResourcesCache, name);
if (value.HasValue)
{
return (int)(value & ~(UInt32)ResourceBit.Item);
}
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
int iResult = -1;
string fileName = FFACE.WindowerPath.Trim(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar + RESOURCES_ITEM_ARMOR_FILE_NAME;
if (!File.Exists(fileName))
{
throw new FileNotFoundException(FILENOTFOUND_MSG, fileName);
}
XPathDocument document = new XPathDocument(fileName);
XPathNavigator node = document.CreateNavigator().SelectSingleNode("//items/i[translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')=\"" + name.ToLower() + "\"]");
if (null != node && !String.IsNullOrEmpty(node.Value))
{
try
{
iResult = Convert.ToInt32(node.GetAttribute("id", String.Empty));
}
catch (Exception)
{
iResult = -1;
}
}
if (iResult >= 0)
{
ResourcesCache.Add(((UInt32)iResult | (UInt32)ResourceBit.Item), name);
}
return iResult;
}
/// <summary>
/// Will get the ID of of the passed item name (case insenstitive)
/// </summary>
/// <param name="name">Name of the item</param>
/// <returns>-1 if no ID was found for passed name</returns>
/// <exception cref="System.IO.FileNotFoundException">Thrown if the resources file in question is not found (Check WindowerPath).</exception>
public static int GetItemID(string name)
{
if (ResourcesCache.Count > 0)
{
//Dictionary<UInt32, String> lookup = new Dictionary<UInt32, String>(); // etc
UInt32? value = FindKey(ResourcesCache, name);
if (value.HasValue)
{
return (int)(value & ~(UInt32)ResourceBit.Item);
}
}
if (String.IsNullOrEmpty(FFACE.WindowerPath))
{
throw new FileNotFoundException(WINDOWERPATH_MSG);
}
int iResult = GetItemIDGeneral(name);
if (iResult < 0)
iResult = GetItemIDArmor(name);
if (iResult < 0)
iResult = GetItemIDWeapons(name);
// DO NOT ADD TO DICTIONARY AT THE END
// It's already handled by the previous 3 functions as they're called.
return iResult;
} // @ public static string GetItemID(string name)
/// <summary>
/// Current array of exact file numbers that contain the information for each file type.
/// </summary>
private static int[] _fileNumberArray = { -1, // Nil, ignore
// To access, do (NUM_LANG_MAX * file_type) + Pref.Language
// Items = 0
4, 73, 55815, 56235,
// Objs = 1
5, 74, 55816, 56236,
// Weapons = 2
6, 75, 55817, 56237,
// Armor = 3
7, 76, 55818, 56238,
// Puppet = 4
8, 77, 55819, 56239,
// Gil = 5
9, 91, 55820, 56240
};
public static string[] _FileNumberArrayList = null;
public static void GetItemList(int processID)
{
string datpath = String.Empty;
System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById(processID);
foreach (System.Diagnostics.ProcessModule module in proc.Modules)
{
if (module.ModuleName.ToLower().Equals("ffxi.dll"))
datpath = module.FileName.Substring(0, module.FileName.Length - 8);
}
String filenameToCheck = String.Empty;
BinaryReader vtable = new BinaryReader(File.Open(datpath + "VTABLE.DAT", FileMode.Open));
BinaryReader ftable = new BinaryReader(File.Open(datpath + "FTABLE.DAT", FileMode.Open));
foreach (int num in _fileNumberArray)
{
if (null == _FileNumberArrayList)
_FileNumberArrayList = new string[1];
else
Array.Resize(ref _FileNumberArrayList, _FileNumberArrayList.Length + 1);
if (num > 0)
{
vtable.BaseStream.Position = num;
if (vtable.ReadByte() == 0x00)
{
_FileNumberArrayList[_FileNumberArrayList.Length - 1] = "INVALID FILE - num less than 0";
continue;
}
ftable.BaseStream.Position = num * 2;
filenameToCheck = datpath + InterpretPath(ftable.ReadUInt16());
if (!File.Exists(filenameToCheck))
throw new FileNotFoundException("File does not exist!", filenameToCheck);
_FileNumberArrayList[_FileNumberArrayList.Length - 1] = filenameToCheck;
}
else
_FileNumberArrayList[_FileNumberArrayList.Length - 1] = "INVALID_FILE - num less than 0";
}
vtable.Close();
ftable.Close();
}
/// <summary>
/// Returns a string in the format ROM\dir\file.DAT given a UInt16 fileID.
/// </summary>
/// <param name="fileID">The file ID found in FTABLE.DAT and VTABLE.DAT</param>
/// <returns>String location of the file that fileID references.</returns>
private static string InterpretPath(UInt16 fileID)
{
// all files for the FINAL FANTASY XI\FTABLE & VTABLE.DAT files are in ROM\
// further files in the ROM2, ROM3, ROM4 folders have a separate FTABLE/VTABLE file
// in their subdirectory.
return String.Format("ROM\\{0}\\{1}.DAT", fileID >> 7, fileID & 0x007F);
}
private static class ffxiFileTypes
{
public static readonly int ITEMS = 0;
public static readonly int OBJS = 1;
public static readonly int WPNS = 2;
public static readonly int ARMR = 3;
public static readonly int PUPP = 4;
public static readonly int GIL = 5;
}
private int GetFileNumber(int filetype)
{
if ((filetype < 0) || (filetype >= _FileNumberArrayList.Length))
return 0;
return (int)((filetype * 4) + 2);
}
/*
/// <summary>
/// Generic loader for loading Item names into a permanent array for use by GetPhrases().
/// </summary>
/// <param name="file_num">File number to load (OBJ, ITEMS, PUPP, ARMR, WEPN, GIL)</param>
private void LoadItemFile(int file_num)
{
if (_FileNumberArrayList == null)
return;
else if ((file_num < 0) || (file_num >= _FileNumberArrayList.Length))
return;
FileInfo fi = new FileInfo(_FileNumberArrayList[file_num]);
Boolean file_error = false;
if (!fi.Exists) return;
if ((fi.Length % 0xC00) != 0) return;
int items_in_file = (int)(fi.Length / 0xC00);
BinaryReader iteminfo = null;
try
{
iteminfo = new BinaryReader(File.Open(_FileNumberArrayList[file_num], FileMode.Open));
}
catch (IOException e)
{
//System.Windows.Forms.MessageBox.Show(e.Message + "\r\nSome Auto-Translate phrases may not be available.");
file_error = true;
}
if (file_error == true)
return; // Attempt a Sanity Check
for (int item_counter = 0; item_counter < items_in_file; item_counter++)
{
iteminfo.BaseStream.Position = 0xC00 * item_counter;
byte[] readbytes = DecodeBlock(iteminfo.ReadBytes(0x200), 5);
BinaryReader data = new BinaryReader(new MemoryStream(readbytes, false));
itemFormat itemObjects = new itemFormat(data, FFXIConvert);
// INSERT ITEM CHECK DATA HERE
data.Close();
//if ((itemObjects.itemHeader.ID < 0xFFFF) && (itemObjects.itemHeader.ID > 0x6FFF))
// continue;
//else if (itemObjects.text == String.Empty)
// continue;
//else
if ((itemObjects.itemHeader.Flags & (ushort)ItemFlags.Nothing) == (ushort)ItemFlags.Nothing)
continue;
else if (itemObjects.itemHeader.ID == 0x00)
continue;
// 0x0100 0x0040 0x1000
/* UINT32 ID
* UINT16 Flags
* UINT16 Stack Size
* UINT16 Type
* UINT16 ResourceID
* UINT16 ValidTargets
* 14 Bytes - Common Header Size
*
int atp = 0;
if (_ATKeys_Items == null)
_ATKeys_Items = new FFXIATPhrase[1];
else Array.Resize(ref _ATKeys_Items, (int)(_ATKeys_Items.Length + 1));
atp = _ATKeys_Items.Length - 1;
_ATKeys_Items[atp] = new FFXIATPhrase();
_ATKeys_Items[atp].StringResource = 0x07;
_ATKeys_Items[atp].Language = (byte)2;
_ATKeys_Items[atp].GroupID = (byte)((itemObjects.itemHeader.ID & 0xFF00) >> 8);
_ATKeys_Items[atp].MessageID = (byte)(itemObjects.itemHeader.ID & 0x00FF);
_ATKeys_Items[atp].Flags = itemObjects.itemHeader.Flags;
if (itemObjects.itemHeader.Type != 0) // if it's nothing, categorize at as something else
_ATKeys_Items[atp].Type = itemObjects.itemHeader.Type;
else
{
if ((itemObjects.itemHeader.ID <= 0x2FFF) && (itemObjects.itemHeader.ID >= 0x2000))
_ATKeys_Items[atp].Type = 13; // Puppet Items
else if ((itemObjects.itemHeader.ID <= 0x3FFF) && (itemObjects.itemHeader.ID >= 0x3000))
_ATKeys_Items[atp].Type = 5; // Armor Items
else if ((itemObjects.itemHeader.ID <= 0x6FFF) && (itemObjects.itemHeader.ID >= 0x4000))
_ATKeys_Items[atp].Type = 4; // Weapon Items
}
_ATKeys_Items[atp].value = itemObjects.text;
_ATKeys_Items[atp].shortvalue = itemObjects.logtext; // misleading i know
}
iteminfo.Close();
}
/// <summary>
/// Decodes a data/text block by reversing the set bit rotation.
/// </summary>
/// <param name="bytes">Array of bytes to decode.</param>
/// <param name="shiftcount">The number of bits to shift right by.</param>
/// <returns>The modified bytes array.</returns>
private static byte[] DecodeBlock(byte[] bytes, int shiftcount)
{
for (int i = 0; i < bytes.Length; i++)
bytes[i] = RotateRight(bytes[i], shiftcount);
return bytes;
}
/// <summary>Rotates the bits to the right by a set number of places.</summary>
/// <param name="b">The byte whose bits we want to shift with rotation (preserving all set bits).</param>
/// <param name="count">The number of places we want to shift the byte by.</param>
/// <returns>The newly rotated byte.</returns>
private static byte RotateRight(byte b, int count)
{
for (; count > 0; count--)
{
if ((b & 0x01) == 0x01)
{
b >>= 1; // if the last bit is 1 (ex. 00000001, it needs to be dropped
b |= 0x80; // and then set as the first bit (ex. 10000000)
}
else b >>= 1; // if the last bit is not 1 (set), just rotate as normal.
}
return b;
}
private class itemHeaderFormat : Object
{
#region itemHeaderFormat Variables
public UInt32 ID;
public UInt16 Flags;
public UInt16 StackSize;
public UInt16 Type;
public UInt16 ResourceID;
public UInt16 ValidTargets;
public UInt16 HeaderSize;
#endregion
#region itemHeaderFormat Constructor
public itemHeaderFormat(BinaryReader br)
{
ID = br.ReadUInt32();
Flags = br.ReadUInt16();
StackSize = br.ReadUInt16();
Type = br.ReadUInt16();
ResourceID = br.ReadUInt16();
ValidTargets = br.ReadUInt16();
HeaderSize = 0x0E; // 14 bytes, Common
}
#endregion
}
private class itemFormat : Object
{
#region itemFormat Variables
public itemHeaderFormat itemHeader;
public String text;
public String logtext;
#endregion
#region itemFormat Constructor
public itemFormat(BinaryReader br, FFXIEncoding FFXIConvert)
{
String[] ItemTexts = new String[9];
itemHeader = new itemHeaderFormat(br);
long data_pos = 0;
UInt32 num_strings = 0, offset = 0, flags = 0;
// Objects (General Items) skip 6 bytes
if ((itemHeader.ID <= 0x0FFF) && (itemHeader.ID >= 0x0000))
br.BaseStream.Position = itemHeader.HeaderSize + 6;
// Usable items skip 2 bytes
// Usable Items skip 6 bytes as of March 10, 2008 Update (new UINT32)
else if ((itemHeader.ID <= 0x1FFF) && (itemHeader.ID >= 0x1000))
br.BaseStream.Position = itemHeader.HeaderSize + 6;
// Gil skip just 2 bytes
else if (itemHeader.ID == 0xFFFF)
br.BaseStream.Position = itemHeader.HeaderSize + 2;
// Puppet Items, skip 8 bytes
else if ((itemHeader.ID <= 0x2FFF) && (itemHeader.ID >= 0x2000))
br.BaseStream.Position = itemHeader.HeaderSize + 10; // Unknown is 0x04 bytes not 0x02
// Armor Specific Info, 22 bytes to skip to get to text
// 26 in March 10, 2008 Update (new UINT32)
else if ((itemHeader.ID <= 0x3FFF) && (itemHeader.ID >= 0x3000))
br.BaseStream.Position = itemHeader.HeaderSize + 26;
// Weapon Specific Info, 30 bytes to skip
// 34 bytes in March 10, 2008 Update (new UINT32)
else if ((itemHeader.ID <= 0x6FFF) && (itemHeader.ID >= 0x4000))
br.BaseStream.Position = itemHeader.HeaderSize + 34;
// Unknown, should not have anything in the way...
else br.BaseStream.Position = itemHeader.HeaderSize + 2;
data_pos = br.BaseStream.Position;
num_strings = br.ReadUInt32();
long fallback_pos = 0;
for (int i = 0; i < num_strings; i++)
{
// if (num_strings >= 5)
//{ int x = i; }
offset = br.ReadUInt32();
flags = br.ReadUInt32();
fallback_pos = br.BaseStream.Position;
// Indicator (UInt32) + UInt32 x 6 Padding before text
br.BaseStream.Position = data_pos + offset + 28;
byte[] b = new byte[4];
int counter = 0;
do
{
if (br.BaseStream.Position >= br.BaseStream.Length) break;
if (b == null)
b = new byte[4];
else if ((counter + 4) > b.Length)
Array.Resize(ref b, (int)(counter + 4));
b[counter++] = br.ReadByte();
b[counter++] = br.ReadByte();
b[counter++] = br.ReadByte();
b[counter++] = br.ReadByte();
if (b[counter - 1] == 0x00)
break;
} while (true);
ItemTexts[i] = FFXIConvert.GetString(b).Trim().Trim("\0\u0001.".ToCharArray());
br.BaseStream.Position = fallback_pos;
}
text = ItemTexts[0];
if (num_strings <= 4) // Japanese (no log name, same as shortname)
logtext = text;
else if (num_strings <= 5) // English (shortname, logname is position 3)
logtext = ItemTexts[2];
else if (num_strings <= 6) // French (shortname, logname is position 4)
logtext = ItemTexts[3];
else if (num_strings <= 9)
logtext = ItemTexts[4];
else logtext = text;
}
#endregion
}
*/
} // @ public class ParseResources
} // @ public partial class FFACE
}
|
63e440bba7102b1ae6b84a75e5518998f36d73d7
|
C#
|
salvamr/zurrxpa
|
/ZurrapaLoader/DataBaseManagement/DataBase.cs
| 2.75
| 3
|
using FireSharp;
using FireSharp.Config;
using System;
using System.Net;
using ZurrapaGlobals;
using SecuritySpace;
namespace ZurrapaDataBase
{
public class DataBase
{
private FirebaseConfig Config { get; set; }
private FirebaseClient Client { get; set; }
private DateTime ExpireDate { get; set; }
#region Singleton
private static DataBase _instance;
public static DataBase Instance
{
get
{
if (_instance == null)
{
_instance = new DataBase();
}
return _instance;
}
}
private DataBase()
{
this.Config = new FirebaseConfig
{
AuthSecret = Global.AUTH_SECRET,
BasePath = Global.BASEPATH
};
this.Client = new FirebaseClient(Config);
if (DateTime.TryParse(Get().ExpirationDate, out DateTime temp))
this.ExpireDate = temp;
}
#endregion
public bool Set(DataBaseStructure dbStructure)
{
return this.Client.Set<DataBaseStructure>(Security.serial, dbStructure).StatusCode.Equals(HttpStatusCode.OK) ? true : false;
}
public DataBaseStructure Get()
{
return this.Client.Get(Security.serial).ResultAs<DataBaseStructure>();
}
}
}
|
7e84a36950d4ab02039fffd93e393973f3a80278
|
C#
|
karabeliov/Telerik-Academy
|
/Courses/C#1/05.ConditionalStatements/01.ExchangeIfGreater/ExchangeIfGreater.cs
| 4.6875
| 5
|
using System;
/// <summary>
///
/// Write an if-statement that takes two integer variables a and b and exchanges their values if the first one is greater than the second one.
/// As a result print the values a and b, separated by a space.
///
/// </summary>
class ExchangeIfGreater
{
static void Main()
{
Console.Write("a = ");
double a = double.Parse(Console.ReadLine());
Console.Write("b = ");
double b = double.Parse(Console.ReadLine());
Console.Write("Result = ");
if (a > b)
{
Console.Write(b + " ");
Console.WriteLine(a);
}
else
{
Console.Write(a + " ");
Console.WriteLine(b);
}
}
}
|
50c2c3458456e2ec1d4fbc062a2d3e14978afdce
|
C#
|
NunoGhost/Enterprise
|
/Common/Client.cs
| 3.015625
| 3
|
using System;
using System.Runtime.Serialization;
namespace Common
{
[DataContract]
public class Client : IComparable<Client>
{
[DataMember(Name = "id")]
public string Id;
[DataMember(Name = "Email")]
public string Email { get; set; }
[DataMember(Name = "Username")]
public string Username { get; set; }
[DataMember(Name = "Address")]
public string Address { get; set; }
[DataMember(Name = "Password")]
public string Password { get; set; }
public Client(string username, string password, string address, string email)
{
var random = new Random();
var timestamp = DateTime.UtcNow;
var machine = random.Next(0, 16777215);
var pid = (short)random.Next(0, 32768);
var increment = random.Next(0, 16777215);
//Id = new ObjectId(timestamp, machine, pid, increment).ToString();
Username = username;
Password = password;
Address = address;
Email = email;
}
public Field IsComplete()
{
if (Username.Equals(""))
return Field.Username;
if (Password.Equals(""))
return Field.Password;
if (Address.Equals(""))
return Field.Address;
if (Email.Equals(""))
return Field.Email;
return Field.OK;
}
public override string ToString()
{
return String.Format("Username: {0}, Password:{1}, Email:{2}, Address:{3}", Username, Password, Email, Address);
}
public int CompareTo(Client other)
{
return String.Compare(Username, other.Username, StringComparison.Ordinal);
}
public override int GetHashCode()
{
if (Username == null) return 0;
return Username.GetHashCode();
}
public override bool Equals(object obj)
{
Client other = (Client)obj;
Console.WriteLine("Equals: " + ToString() + " " + other);
return other.Username == Username;
}
}
public enum Field
{
Username, Password, Email, Address, OK
}
}
|
20acbb5f715816c83b6d48704ceda2a2f2b6e528
|
C#
|
MakoLab/RomanticWeb
|
/RomanticWeb/Mapping/Conventions/EntityIdPropertiesConvention.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using RomanticWeb.Converters;
using RomanticWeb.Entities;
using RomanticWeb.Mapping.Providers;
namespace RomanticWeb.Mapping.Conventions
{
/// <summary>Sets the converter of EntityId properties to an appropriate.<see cref="EntityIdConverter{TEntityId}"/>
/// </summary>
public class EntityIdPropertiesConvention : IPropertyConvention
{
private static readonly IEnumerable<Type> Predecesors = new Type[0];
/// <inheritdoc/>
public IEnumerable<Type> Requires { get { return Predecesors; } }
/// <inheritdoc/>
public bool ShouldApply(IPropertyMappingProvider target)
{
return target.ConverterType == null && typeof(EntityId).IsAssignableFrom(target.PropertyInfo.PropertyType.FindItemType());
}
/// <inheritdoc/>
public void Apply(IPropertyMappingProvider target)
{
target.ConverterType = typeof(EntityIdConverter<>).MakeGenericType(target.PropertyInfo.PropertyType.FindItemType());
}
}
}
|
5506782180b43675eb41d7097a69d1ee54bbfcba
|
C#
|
SvenLauterbach/Thinktecture.Abstractions
|
/src/Thinktecture.Net.Sockets.Abstractions/Net/Sockets/Adapters/UnixDomainSocketEndPointAdapter.cs
| 2.828125
| 3
|
using System.Net.Sockets;
using Thinktecture.Net.Adapters;
namespace Thinktecture.Net.Sockets.Adapters
{
/// <summary>
/// Unix domain socket endpoint.
/// </summary>
public class UnixDomainSocketEndPointAdapter : EndPointAdapter, IUnixDomainSocketEndPoint
{
/// <summary>
/// Implementation used by the adapter.
/// </summary>
protected new UnixDomainSocketEndPoint Implementation { get; }
/// <inheritdoc />
UnixDomainSocketEndPoint IAbstraction<UnixDomainSocketEndPoint>.UnsafeConvert()
{
return Implementation;
}
/// <summary>
/// Initializes new instance of <see cref="UnixDomainSocketEndPointAdapter"/>.
/// </summary>
/// <param name="path">Path.</param>
public UnixDomainSocketEndPointAdapter(string path)
:this(new UnixDomainSocketEndPoint(path))
{
}
/// <summary>
/// Initializes new instance of <see cref="UnixDomainSocketEndPointAdapter"/>.
/// </summary>
public UnixDomainSocketEndPointAdapter(UnixDomainSocketEndPoint implementation)
: base(implementation)
{
Implementation = implementation;
}
}
}
|
f0a5b27fc55c327b204f832522d0293e8af41544
|
C#
|
arthurrump/Zermelo.App.UWP
|
/Zermelo.App.UWP/Helpers/ExceptionHelper.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Azure.Mobile.Analytics;
using Zermelo.API.Exceptions;
namespace Zermelo.App.UWP.Helpers
{
class ExceptionHelper
{
public static void HandleException(Exception ex, string location, Action<string> ShowError,
string zermelo400Text = "De opgevraagde gegevens zijn niet gevonden in Zermelo.",
string zermelo404Text = "De opgevraagde gegevens zijn niet gevonden in Zermelo.",
string zermelo403Text = "Je hebt niet voldoende rechten om deze informatie te bekijken.",
string zermeloDefaultText = "Er is iets fout gegaan. Zermelo geeft de volgende foutmelding: {0} {1}",
string defaultText = "Er is iets fout gegaan. De ontwikkelaar wordt op de hoogte gesteld.")
{
if (Debugger.IsAttached)
Debugger.Break();
switch (ex)
{
case ZermeloHttpException zex:
if (zex.StatusCode == 400)
ShowError(zermelo400Text);
else if (zex.StatusCode == 404)
ShowError(zermelo404Text);
else if (zex.StatusCode == 403)
ShowError(zermelo403Text);
else
ShowError(string.Format(zermeloDefaultText, zex.StatusCode, zex.Status));
Analytics.TrackEvent("ZermeloHttpException", new Dictionary<string, string>
{
{ "Location", location },
{ "Message", zex.Message.MaxLength(64) },
{ "StatusCode", zex.StatusCode.ToString() },
{ "ResponseContent", zex.ResponseContent.MaxLength(64) }
});
break;
case System.Net.Http.HttpRequestException hre:
Analytics.TrackEvent("HttpRequestException", new Dictionary<string, string>
{
{ "Location", location },
{ "Message", hre.Message.MaxLength(64) },
{ "Source", hre.Source },
{ "StackTrace", ex.StackTrace.MaxLength(64) }
});
break;
default:
ShowError(defaultText);
Analytics.TrackEvent("UnknownException", new Dictionary<string, string>
{
{ "Location", location },
{ "Message", ex.Message.MaxLength(64) },
{ "Source", ex.Source },
{ "StackTrace", ex.StackTrace.MaxLength(64) }
});
break;
}
}
}
}
|
d6fb3d40608c6935ac62edc0539a22304056d10c
|
C#
|
eledalsav/Week4_EsFinale_Dal_Savio
|
/Week4_EsFinale_Dal_Savio.Core/Week4_EsFinale_Dal_Savio.Core/BusinessLayer/MainBL.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Week4_EsFinale_Dal_Savio.Core
{
public class MainBL : IMainBL
{
private readonly IOrderRepository orderRepo;
private readonly ICustomerRepository customerRepo;
public MainBL(IOrderRepository orderRepo, ICustomerRepository customerRepo
)
{
this.orderRepo = orderRepo;
this.customerRepo = customerRepo;
}
#region Customers
//Metodi per i clienti
public List<Customer> FetchCustomers()
{
throw new NotImplementedException();
}
public bool CreateCustomer(Customer newCustomer)
{
throw new NotImplementedException();
}
public bool EditCustomer(Customer editedCustomer)
{
throw new NotImplementedException();
}
public bool DeleteCustomer(Customer customerToBeDeleted)
{
throw new NotImplementedException();
}
public Customer GetCustomerById(int id)
{
throw new NotImplementedException();
}
#endregion
#region Orders
//Metodi per gli ordini
public bool CreateOrder(Order newOrder)
{
throw new NotImplementedException();
}
public bool DeleteOrder(Order orderToBeDeleted)
{
throw new NotImplementedException();
}
public bool EditOrder(Order editedOrder)
{
throw new NotImplementedException();
}
public List<Order> FetchOrders()
{
throw new NotImplementedException();
}
public Order GetOrderById(int id)
{
throw new NotImplementedException();
}
#endregion
}
}
|
8f2946da37a34ac04d04846183f77c72ba8b2fee
|
C#
|
ihristova11/TelerikSchoolAcademy
|
/C# Part1/02. Primitive-Data-Types-and-Variables/2. Primitive-Data-Types-and-Variables/12. PrintASCIITable/PrintASCIITable.cs
| 3.46875
| 3
|
using System;
using System.Text;
class PrintASCIITable
{
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("\t \t \t \t ASCII Table\n");
byte counter = 0;
char symbol = Convert.ToChar(counter);
for (counter = 0; counter <= 127; counter++)
{
Console.Write("{0} - {1}\t", counter, (char)counter);
}
Console.WriteLine();
}
}
|
d525e16e5440c3a43f901172ecd017595272d53d
|
C#
|
istolboff/ExampleMapping
|
/ExampleMapping.Specs/SpecFlow/MismatchedRow.cs
| 2.703125
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ExampleMapping.Specs.SpecFlow
{
internal sealed class MismatchedRow : RowMatchingResult, IEquatable<MismatchedRow>
{
public MismatchedRow(string rowKey, int rowIndex, IReadOnlyCollection<MismatchedColumn> mismatchedColumns)
: base(rowKey, rowIndex)
{
Contract.Requires(mismatchedColumns.Any());
_mismatchedColumns = mismatchedColumns;
}
public bool Equals(MismatchedRow other)
{
return
!ReferenceEquals(other, null) &&
RowKey == other.RowKey &&
_mismatchedColumns.SequenceEqual(other._mismatchedColumns);
}
public override bool Equals(object obj)
{
return Equals(obj as MismatchedRow);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return DescribeRow(string.Join(", ", _mismatchedColumns));
}
private readonly IReadOnlyCollection<MismatchedColumn> _mismatchedColumns;
}
}
|
28b665effdc8f6fffc8338a97c2396f7630c09bb
|
C#
|
redcake36/file_converter
|
/file_converter/json.cs
| 3.171875
| 3
|
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace file_converter
{
public class FileJson : IFileWrapper
{
public string FilePath { get; }
public FileJson() { FilePath = ""; }
public FileJson(string s) { FilePath = s; }
static string jsonTakeWords(string[] lines, int i, ref int j)
{
string s = "";
bool flag = true;
while (flag)
{
if (lines[i][j] == '"')
{
j++;
while (lines[i][j] != '"')
{
s += lines[i][j];
j++;
}
j++;
flag = false;
}
else
j++;
}
return s;
}
public Data Parse()
{
string[] lines = System.IO.File.ReadAllLines(FilePath);
List<string> f = new List<string>();
List<List<string>> v = new List<List<string>>();
for (int i = 0; i < lines.Length; i++)
{
List<string> a = new List<string>();
if (lines[i].Contains('{'))
{
i++;
while (!lines[i].Contains('}'))
{
int j = 0;
f.Add(jsonTakeWords(lines, i, ref j));
a.Add(jsonTakeWords(lines, i, ref j));
i++;
}
v.Add(a);
}
}
return (new Data(f.Distinct().ToList(), v));
}
public void Export(Data input)
{
if (input.FieldNames.Count == 0)
return;
using (StreamWriter sw = new StreamWriter(this.FilePath))
{
sw.WriteLine("[");
for (int i = 0; i < input.Content.Count; i++)
{
sw.WriteLine("\t{");
for (int j = 0; j < input.FieldNames.Count; j++)
{
sw.Write("\t\t\"{0}\": \"{1}\"", input.FieldNames[j], input.Content[i][j]);
if (j != input.FieldNames.Count - 1)
sw.Write(",");
sw.Write("\n");
}
if (i == input.Content.Count - 1)
sw.WriteLine("\t}");
else
sw.WriteLine("\t},");
}
sw.Write("]");
}
}
}
}
|
2f16faa59b9a3764d9f16cf97049bfd1b7e95e8e
|
C#
|
ElinamLLC/SharpVectors
|
/Source/SharpVectorRenderingWpf/Texts/WpfTextPosition.cs
| 2.8125
| 3
|
using System;
using System.Windows;
namespace SharpVectors.Renderers.Texts
{
public struct WpfTextPosition
{
private Point _location;
private double _rotation;
public WpfTextPosition(Point location, double rotation)
{
if (Double.IsNaN(rotation) || Double.IsInfinity(rotation))
{
rotation = 0;
}
_location = location;
_rotation = rotation;
}
public Point Location
{
get
{
return _location;
}
set
{
_location = value;
}
}
public double Rotation
{
get
{
return _rotation;
}
set
{
if (Double.IsNaN(value) || Double.IsInfinity(value))
{
_rotation = 0;
}
else
{
_rotation = value;
}
}
}
}
}
|
8681fa1eb3dffe7ac2c6dd0f347d309fdb3a9c00
|
C#
|
gcvalderrama/Jarvis
|
/Lincoln/07Summarization/JarvisSummarization/JarvisSummarization/PageRank/KnowledgeGraph.cs
| 2.921875
| 3
|
using edu.stanford.nlp.ling;
using edu.stanford.nlp.trees;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JarvisSummarization.PageRank
{
public class PRKnowledgeGraph
{
public int Size { get; set; }
private IEnumerable<CG.CGNode> vertexs;
public double[][] matrix;
public double GetRSTWeight(int pos)
{
var result = this.vertexs.Where(c => c.id == pos).SingleOrDefault();
if (result != null)
return result.rstweight;
else
return 0;
}
/**
* This method builds the knowledge graph
* @param words
* @param dependencies
*/
public void create(CG.CGGraph cggraph)
{
this.Size = cggraph.Nodes.Max(c => c.id) + 1; //start in 0
this.vertexs = cggraph.Nodes;
initMatrix();
FillMatrix(cggraph.Relations);
}
public void FillMatrix(IEnumerable<CG.CGRelation> Relations )
{
foreach (var item in Relations)
{
this.matrix[item.Head][item.Tail]= 1;
this.matrix[item.Tail][item.Head] = 1;
}
}
/**
* This method initializes the graph's matrix
*/
private void initMatrix()
{
matrix = new double[this.Size][];
for (int i = 0; i < this.Size; i++)
{
matrix[i] = new double[this.Size];
for (int j = 0; j < this.Size; j++)
matrix[i][j] = 0;
}
}
/**
* This method returns the list of vertexs
* @return
*/
public IEnumerable<CG.CGNode> getVertexs()
{
return vertexs;
}
}
}
|
ffce624f915664d55ffce03c3fec40976e95d807
|
C#
|
indigoYoshimaru/OOP_game_project
|
/Objects/Zombies/LaneJumpingZombie.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace PlantvsZombie
{
public class LaneJumpingZombie:Zombie
{
private Vector2 _Position;
private float _DamageFactor = 4;
private Tile _ZombieTile;
private float _YDes;
private float _XMinus = 0f;
private Plant MeetPlant()
{
if (_ZombieTile != null && _ZombieTile.HasPlant())
return _ZombieTile.Plant;
return null;
}
public override void Update()
{
_ZombieTile = PVZGame.Game.LogicManager.GameMap.GetTileAt(_Position);
ObjectTile = _ZombieTile;
base.Update();
var p = MeetPlant();
if (p != null) Attack(p);
else Move();
}
public override void Attack(Plant p)
{
p.Damaged(_DamageFactor);
}
public override void Damaged(float dam)
{
Health -= dam;
}
public override void Move()
{
_Position.X -= Speed;
_XMinus += Speed;
Tile tileCheck;
Random rand = new Random();
if (Math.Abs(_Position.Y - _YDes) < 1 && _XMinus >= 2*PVZGame.Game.LogicManager.GameMap.TileSize.X)
{
int r = rand.Next(-1,2);
tileCheck = _ZombieTile.GetRelativeTile(0, r);
if (tileCheck != null)
{
System.Diagnostics.Debug.WriteLine(tileCheck.Y);
_YDes = tileCheck.GetCenter().Y;
}
_XMinus = 0;
}
_Position.Y = Lerp(_Position.Y, _YDes, 0.02f);
this.Position = _Position;
}
private float Lerp(float firstFloat, float secondFloat, float by)
{
return firstFloat * (1 - by) + secondFloat * by;
}
public LaneJumpingZombie() : base()
{
_Position = Position;
_ZombieTile = PVZGame.Game.LogicManager.GameMap.GetTileAt(_Position);
ObjectTile = _ZombieTile;
_YDes = Position.Y;
Speed = 0.7f;
Score = 15;
}
}
}
|
f076c23d49f2ab991ebde6a5e9bb589b5b85cdda
|
C#
|
s-afterimage/FakeSimCity
|
/Assets/Scripts/common/constants/GameModel.cs
| 2.546875
| 3
|
using System.Collections.Generic;
using UnityEngine;
namespace Cariacity.game
{
public static class GameModel
{
private static IList<GameObject> hashList = new List<GameObject>();
public static void Add(GameObject model)
{
hashList.Add(model);
}
public static GameObject Get(int id)
{
return hashList[id];
}
public static int Get(GameObject model)
{
return hashList.IndexOf(model);
}
}
}
|
68c0b2d3f2b299bd6add7a1f3202a73d074d544e
|
C#
|
gogetenk/asp-core-crud-example
|
/SecurePrivacy.Sample/src/SecurePrivacy.Sample.WebApi/Controllers/StuffController.cs
| 2.5625
| 3
|
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SecurePrivacy.Sample.Bll.Services;
using SecurePrivacy.Sample.Dto;
using SecurePrivacy.Sample.Model;
namespace SecurePrivacy.Sample.WebApi.Controllers
{
[ApiController]
[Route("api/stuff")]
public class StuffController : ControllerBase
{
private readonly ILogger<StuffController> _logger;
private readonly IMapper _mapper;
private readonly IStuffService _stuffService;
public StuffController(ILogger<StuffController> logger, IMapper mapper, IStuffService stuffService)
{
_logger = logger;
_mapper = mapper;
_stuffService = stuffService;
}
[HttpGet]
[ProducesResponseType(200, Type = typeof(StuffDto))]
public async Task<IActionResult> Get(string id)
{
_logger.LogInformation("GET operation started.");
var result = await _stuffService.GetAsync(id);
return Ok(_mapper.Map<StuffDto>(result));
}
[HttpPost]
[ProducesResponseType(201, Type = typeof(StuffDto))]
public async Task<IActionResult> Post(StuffDto stuff)
{
_logger.LogInformation("POST operation started.");
var result = await _stuffService.CreateAsync(_mapper.Map<Stuff>(stuff));
return Created("", _mapper.Map<StuffDto>(result));
}
[HttpPut]
[ProducesResponseType(204)]
public async Task<IActionResult> Put(string id, StuffDto stuff)
{
_logger.LogInformation("PUT operation started.");
if (await _stuffService.UpdateAsync(id, _mapper.Map<Stuff>(stuff)))
return NoContent();
else
return BadRequest("The entity doesn't exist.");
}
[HttpDelete]
[ProducesResponseType(204)]
public async Task<IActionResult> Delete(string id)
{
_logger.LogInformation("DELETE operation started.");
await _stuffService.DeleteAsync(id);
return NoContent();
}
}
}
|
47a3d82364d75a19ad708c8cd82d8469e7f73cdb
|
C#
|
Anil1111/LearningCSharp-1
|
/ExceptionExtensions.cs
| 3.265625
| 3
|
using System;
using System.Reflection;
namespace LearningCSharp
{
public static class ExceptionExtensions
{
public static void ShowException(this Exception e)
{
if (e is TargetInvocationException invocationException)
{
invocationException.InnerException.ShowException();
}
else if (e is AggregateException aggregateException)
{
foreach (var innerException in aggregateException.InnerExceptions)
{
innerException.ShowException();
}
}
else
{
Console.WriteLine($"Exception of type {e.GetType().Name} has been thrown with the following message: {e.Message}");
}
}
}
}
|
f1151c74c4851b1e631a940566ee000cc4f5da00
|
C#
|
tbergstrom/person_of_interest
|
/Classes/ConnectionMapper.cs
| 2.78125
| 3
|
using System.Collections.Generic;
using System.Linq;
namespace AspNetCoreSignalr.SignalRHubs {
public class ConnectionMapping<T> {
private readonly Dictionary<T, HashSet<string>> _connections =
new Dictionary<T, HashSet<string>> ();
public int Count {
get { return _connections.Count; }
}
public void Add (T key, string connectionId) {
lock (_connections) {
HashSet<string> connections;
if (!_connections.TryGetValue (key, out connections)) {
connections = new HashSet<string> ();
_connections.Add (key, connections);
}
lock (connections) {
connections.Add (connectionId);
}
}
}
public IEnumerable<string> GetConnections (T key) {
HashSet<string> connections;
if (_connections.TryGetValue (key, out connections)) {
return connections;
}
return Enumerable.Empty<string> ();
}
public void Remove (T key, string connectionId) {
lock (_connections) {
HashSet<string> connections;
if (!_connections.TryGetValue (key, out connections)) {
return;
}
lock (connections) {
connections.Remove (connectionId);
if (connections.Count == 0) {
_connections.Remove (key);
}
}
}
}
}
}
|
514f5ba51529ec149dd2170dbfb23525fc2bf75f
|
C#
|
littletelx360/Graphql-Controller
|
/GraphqlController/GraphqlController/Services/GraphqlControllerServiceBuilder.cs
| 2.703125
| 3
|
using GraphQL.Types;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace GraphqlController.Services
{
public class GraphqlControllerServiceBuilder
{
public IServiceCollection Services { get; }
AssemblyResolver _assemblyResolver;
internal GraphqlControllerServiceBuilder(IServiceCollection services)
{
Services = services;
_assemblyResolver = new AssemblyResolver();
services.AddSingleton<IAssemblyResolver>(_assemblyResolver);
}
/// <summary>
/// Add the assembly where the curreent code is running to find graph types
/// </summary>
public void AddCurrentAssembly()
{
AddAssembly(Assembly.GetCallingAssembly());
}
/// <summary>
/// Add assembly to find for graph types
/// </summary>
/// <param name="assembly">The assembly</param>
public void AddAssembly(Assembly assembly)
{
// Add the assembly to the resolver
_assemblyResolver.AddAssembly(assembly);
// Add all type nodes to the container as transient
var nodeTypes = assembly.GetTypes().Where(x => typeof(IGraphNodeType).IsAssignableFrom(x));
foreach (var type in nodeTypes)
{
Services.AddTransient(type);
}
}
}
}
|
de7079c734ab4cdb96366b69191be22e3333db6a
|
C#
|
spooky-doodle/Trestlebridge-Farms
|
/src/Actions/Facilities/ChooseGrazingField.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Trestlebridge.Interfaces;
using Trestlebridge.Models;
using Trestlebridge.Models.Animals;
using Trestlebridge.Models.Facilities;
namespace Trestlebridge.Actions
{
public class ChooseGrazingField
{
public static void CollectInput(List<GrazingField> field, IGrazing animal)
{
Console.Clear();
for (int i = 0; i < field.Count; i++)
{
Console.WriteLine($"{i + 1}. Grazing Field: {field[i].Name} ({field[i].NumAnimals} animals)");
}
Console.WriteLine();
// How can I output the type of animal chosen here?
Console.WriteLine($"Place the animal where?");
Console.Write("> ");
try
{
int choice = Int32.Parse(Console.ReadLine());
field[choice - 1].AddResource(animal);
}
catch (Exception)
{
Program.ShowMessage("Invalid Input");
}
}
}
}
|
7fea29381dfbdf3701f12097a843326dff94e0c3
|
C#
|
mertbogus/OOP_Stok
|
/DataAcessLayer/DALPersonel.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityLayer;
using System.Data;
using System.Data.SqlClient;
namespace DataAcessLayer
{
public class DALPersonel
{
public static List<EntityPersonel> PersonelListele()
{
List<EntityPersonel> personel = new List<EntityPersonel>();
SqlCommand kmt = new SqlCommand("DEPARTMANLİST", baglanti.bgl);
kmt.CommandType = CommandType.StoredProcedure;
if (kmt.Connection.State!=ConnectionState.Open)
{
kmt.Connection.Open();
}
SqlDataReader dr = kmt.ExecuteReader();
while (dr.Read())
{
EntityPersonel prs = new EntityPersonel();
prs.Personelid = Convert.ToInt32(dr["PERSONELID"].ToString());
prs.Personelad = dr["PERSONELAD"].ToString();
prs.Personelsoyad = dr["PERSONELSOYAD"].ToString();
prs.Personeldepartman= Convert.ToByte(dr["PERSONELDEPARTMAN"].ToString());
prs.Personelmaas = Convert.ToDecimal(dr["PERSONELMAAS"].ToString());
prs.Fotograf= dr["PERSONELFOTOGRAF"].ToString();
personel.Add(prs);
}
dr.Close();
return personel;
}
public static int PersonelEkle(EntityPersonel personel)
{
SqlCommand komut = new SqlCommand("insert into TBLPERSONEL (PERSONELAD,PERSONELSOYAD,PERSONELDEPARTMAN,PERSONELMAAS) values (@p1,@p2,@p3,@p4)", baglanti.bgl);
if (komut.Connection.State != ConnectionState.Open)
{
komut.Connection.Open();
}
komut.Parameters.AddWithValue("@p1", personel.Personelad);
komut.Parameters.AddWithValue("@p2", personel.Personelsoyad);
komut.Parameters.AddWithValue("@p3", personel.Personeldepartman);
komut.Parameters.AddWithValue("@p4", personel.Personelmaas);
return komut.ExecuteNonQuery();
}
}
}
|
8c215972f55ae624e9fd1c17eef7900a453ab8e5
|
C#
|
rpaschoal/DynamicRepository
|
/DynamicRepository/DataPagerAdapter.cs
| 2.71875
| 3
|
using DynamicRepository.Filter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using DynamicRepository.Annotation;
namespace DynamicRepository
{
/// <summary>
/// Translates annotation filter settings from annotations to be given as input for the <see cref="DataPager{Key, Entity}"/> class.
/// </summary>
/// <remarks>
/// The <see cref="DataPager{Key, Entity}"/> class is case sensitive, so make sure you set the correct mappings FROM => TO.
/// </remarks>
public static class DataPagerAdapter
{
/// <summary>
/// This method translates a <see cref="PagedDataSettings"/> payload to another configured instance based on
/// any <see cref="PagedDataFilterAttribute"/> or <see cref="PagedDataDefaultSortingAttribute"/>
/// that may have been applied to a controller method.
/// </summary>
/// <param name="settings">
/// Payload received by the controller serialized by the ASP.NET default serializer or anyother type
/// of configuration you may use.
/// </param>
/// <param name="callingMethodInfo">
/// The method base information that contains all the attributes in order to perform the adapter operation.
/// </param>
/// <remarks>
/// This method needs to be called directly in the Controller method.
/// It won't work if called inside another method called by the controller.
/// It needs to be right after the controller method's execution call stack.
/// </remarks>
/// <returns>Updated/Adapted settings that are ready to be supplied to the <see cref="DataPager{Key, Entity}"/> class.</returns>
public static PagedDataSettings TransformSettings(PagedDataSettings settings, MethodBase callingMethodInfo)
{
// TODO: Not yet supported on .NET Core, refer to this: https://github.com/dotnet/corefx/issues/1797
// Gets previous calling method information to get whatever attribute that may have been applied.
//StackTrace stackTrace = new StackTrace();
//MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
var props = callingMethodInfo.GetCustomAttributes<PagedDataFilterAttribute>();
var sorting = callingMethodInfo.GetCustomAttribute<PagedDataDefaultSortingAttribute>();
// Checks if the consumer of the search wants to filter in ALL fields.
if (settings.Filter.Where(x => x.Property.ToUpper() == PagedDataSettings.FILTERALLIDENTIFIER).Any())
{
// Overriding all possible conjunctions set as OR since this is a "ALL" search.
foreach (var filter in settings.Filter)
{
filter.Conjunction = LogicalConjunctionEnum.AND;
}
TranslateALLSearchFilters(props.Where(x => x.IgnoreOnSearch == false), settings);
}
TranslateDefaultFilters(props.Where(x => x.IgnoreOnSearch == false), settings);
foreach (var property in props)
{
if (settings.Sorting != null)
{
// Searchs replacements for sort queries.
var item = settings.Sorting.Where(x => x.Property == property.MapsFrom).FirstOrDefault();
if (item != null)
{
item.Property = property.MapsTo;
// Only gets the first item if it is piped for sorting.
// TODO: Implement piped sorting for future releases.
item.PostQuerySortingPath = property.PostQueryFilterPath.Split('|').First();
}
}
}
TranslateDefaultSorting(sorting, settings);
return settings;
}
private static void TranslateDefaultFilters(IEnumerable<PagedDataFilterAttribute> props, PagedDataSettings settings)
{
// If it can find, then do the job. Otherwise we will fallback to whatever the UI sends directly to IQueryable. (No security issue since this is just for filter/ordering.
foreach (var property in props)
{
// Translates a prom from => to relationship.
var filterProp = settings.Filter.Where(x => x.Property.Equals(property.MapsFrom)).FirstOrDefault();
if (filterProp != null)
{
filterProp.Property = property.MapsTo;
filterProp.PostQueryFilterPath = String.IsNullOrEmpty(property.PostQueryFilterPathExplict) ? property.PostQueryFilterPath : property.PostQueryFilterPathExplict;
}
}
}
private static void TranslateALLSearchFilters(IEnumerable<PagedDataFilterAttribute> props, PagedDataSettings settings)
{
bool firstExecution = true;
settings.SearchInALL = true;
// Saves all previous filters (Some cases we need it, as in TabView case).
var otherFilters = settings.Filter.Where(x => x.Property.ToUpper() != PagedDataSettings.FILTERALLIDENTIFIER).ToList();
// Gets "All" supplied value
var filterValue = settings.Filter.Where(x => x.Property.ToUpper() == PagedDataSettings.FILTERALLIDENTIFIER).FirstOrDefault().Value;
// Resets all prior filter
settings.Filter.Clear();
foreach (var property in props)
{
var attrValue = property.MapsTo;
settings.Filter.Add(new FilterSettings()
{
PostQueryFilterPath = String.IsNullOrEmpty(property.PostQueryFilterPathExplict) ? property.PostQueryFilterPath : property.PostQueryFilterPathExplict,
Property = property.MapsTo,
IsExactMatch = false,
Value = filterValue ?? string.Empty,
Conjunction = firstExecution ? LogicalConjunctionEnum.AND : LogicalConjunctionEnum.OR
});
firstExecution = false;
}
// Removes all duplicates from pre existing filters.
otherFilters.RemoveAll(x => settings.Filter.Where(y => y.Property == x.Property).Any());
// Adds any other existing filters.
settings.Filter = settings.Filter.Concat(otherFilters).ToList();
}
private static void TranslateDefaultSorting(PagedDataDefaultSortingAttribute sortingAttribute, PagedDataSettings settings)
{
if (settings.Sorting == null || settings.Sorting.Count == 0)
{
if (settings.Sorting == null)
settings.Sorting = new List<SortingSettings>();
if (sortingAttribute != null)
{
settings.Sorting.Add(new SortingSettings()
{
Property = sortingAttribute.Property,
Order = sortingAttribute.IsAscending ? SortOrderEnum.ASC : SortOrderEnum.DESC
});
}
}
}
}
}
|
ff97dd2ea692787f1664e03df1016cc608adcde5
|
C#
|
bakanaouji/CRFMNES_CS
|
/CRFMNES/Tests/OptimizerTests/EllipsoidTest.cs
| 2.921875
| 3
|
using NUnit.Framework;
using System;
using CRFMNES.Utils;
namespace CRFMNES.Tests.OptimizerTests
{
[TestFixture()]
public class EllipsoidTest
{
static double Ellipsoid(Vector x)
{
double f = 0.0;
for (int i = 0; i < x.GetDim(); ++i)
{
double tmp = Math.Pow(1000.0, i / (x.GetDim() - 1.0)) * x[i];
f += tmp * tmp;
}
return f;
}
[Test()]
public void TestEllipsoid40()
{
int dim = 40;
Vector mean = Vector.Fill(dim, 3.0);
double sigma = 2.0;
int lamb = 16;
Optimizer optimizer = new Optimizer(dim, Ellipsoid, mean, sigma, lamb);
int evalCnt = 0;
while (optimizer.FBest >= 1e-12)
{
optimizer.OneIteration();
evalCnt += lamb;
}
Console.WriteLine("Ellipsoid40 evalCnt: {0}", evalCnt);
}
[Test()]
public void TestEllipsoid80()
{
int dim = 80;
Vector mean = Vector.Fill(dim, 3.0);
double sigma = 2.0;
int lamb = 16;
Optimizer optimizer = new Optimizer(dim, Ellipsoid, mean, sigma, lamb);
int evalCnt = 0;
while (optimizer.FBest >= 1e-12)
{
optimizer.OneIteration();
evalCnt += lamb;
}
Console.WriteLine("Ellipsoid80 evalCnt: {0}", evalCnt);
}
}
}
|
b45d80d99843363725c70c4c5f1eb1b1558cc913
|
C#
|
giokeyboard/HeadFirst-CSharp
|
/Chapt6/DinnerPartyPlanner-v3.0/DinnerPartyPlanner-v3.0/Party.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinnerPartyPlanner_v3._0
{
class Party
{
public const int costOfFoodPerPerson = 25;
public int NumberOfPeople { get; set; }
public bool FancyDecorations { get; set; }
virtual public decimal Cost
{
get
{
decimal totalCost = CalculateCostOfDecorations() + (costOfFoodPerPerson * NumberOfPeople);
return (NumberOfPeople > 12) ? totalCost + 100 : totalCost;
}
}
private decimal CalculateCostOfDecorations()
{
return (FancyDecorations) ? (NumberOfPeople * 15.00M) + 50M : (NumberOfPeople * 7.50M) + 30M;
}
}
}
|
08d54856d9dac1c3a93db06bfe43f09509ea005f
|
C#
|
whyknotnow/blogproject
|
/NBlog-master/NBlog.Web/Application/Storage/Azure/AzureExtensions.cs
| 2.59375
| 3
|
namespace NBlog.Web.Application.Storage.Azure
{
using Microsoft.WindowsAzure.Storage.Blob;
using System.IO;
public static class AzureExtensions
{
public static void UploadText(this ICloudBlob blob, string text)
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(text);
blob.UploadFromByteArray(buffer, 0, buffer.Length);
}
public static string DownloadText(this ICloudBlob blob)
{
string text;
using (var memoryStream = new MemoryStream())
{
blob.DownloadToStream(memoryStream);
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
return text;
}
//public static bool Exists(this ICloudBlob blob)
//{
// try
// {
// blob.FetchAttributes();
// return true;
// }
// catch (StorageException e)
// {
// if (e.RequestInformation.ExtendedErrorInformation != null &&
// e.RequestInformation.ExtendedErrorInformation.ErrorCode == StorageErrorCodeStrings.ResourceNotFound)
// {
// return false;
// }
// else
// {
// throw;
// }
// }
//}
//public static bool Exists(this CloudBlobContainer container)
//{
// try
// {
// container.FetchAttributes();
// return true;
// }
// catch (StorageException e)
// {
// if (e.RequestInformation.ExtendedErrorInformation != null &&
// e.RequestInformation.ExtendedErrorInformation.ErrorCode == StorageErrorCodeStrings.ResourceNotFound)
// {
// return false;
// }
// else
// {
// throw;
// }
// }
//}
}
}
|
4783765606c0d88b430936e88a7fd3a22c3aaf95
|
C#
|
flu55y/AutoServiceApp
|
/AutoServiceApp/Model/Repositories/CarRepository.cs
| 2.75
| 3
|
using AutoServiceApp.Model.EF;
using AutoServiceApp.Model.Entities;
using System.Linq;
namespace AutoServiceApp.Model.Repositories
{
class CarRepository
{
public string AddCar(Car car)
{
using (EfDbContext context = new EfDbContext())
{
var carItem = context.Cars.FirstOrDefault(x => x.CarNumber == car.CarNumber);
if (carItem != null)
{
carItem.Mark = car.Mark;
}
else
{
context.Cars.Add(car);
}
context.SaveChanges();
}
return car.CarNumber;
}
}
}
|
9df4e55d3a07b84cbe660144a6f9bc741122d858
|
C#
|
ParvathiRPai/AlgorithmsDataStructure
|
/DynamicProgramming/Recursion/RecursionofStrings/RecursionofStrings/SumofSubsets.cs
| 3.4375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RecursionofStrings
{
class SumofSubsets
{
public void Sum(int []set, int l, int r, int sum=0)
{
if(l > r)
{
Console.WriteLine(sum);
return;
}
Sum(set, l + 1, r, sum + set[l]);
Sum(set, l + 1, r, sum);
}
}
}
|
db7fb8b5d9e126f9ab059b45219382ffbd1b8fb0
|
C#
|
Maxai2/Bank
|
/Bank/Bank/TransferTransaction.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//--------------------------------------------------------------
namespace BankName
{
class TransferTransaction : ITransaction
{
BaseClient to;
BaseClient from;
public double Amount { get; set; }
public DateTime DT { get; set; }
public TransferTransaction(double Amount, DateTime DT, BaseClient to, BaseClient from)
{
this.Amount = Amount;
this.DT = DT;
this.to = to;
this.from = from;
}
}
}
//--------------------------------------------------------------
|
fc0c6fecf4d3350ed0a7f2704432d8931cec8713
|
C#
|
TymurLysenkoIU/il-compiler
|
/ILangCompiler/Scanner/Tokens/IdentifierToken.cs
| 2.84375
| 3
|
using System.Text.RegularExpressions;
using LanguageExt;
namespace ILangCompiler.Scanner.Tokens
{
public class IdentifierToken : IToken
{
public string Lexeme { get; }
public uint AbsolutePosition { get; }
public uint LineNumber { get; }
public uint PositionInLine { get; }
private IdentifierToken(string lexeme, uint absolutePosition, uint lineNumber, uint positionInLine)
{
Lexeme = lexeme;
AbsolutePosition = absolutePosition;
LineNumber = lineNumber;
PositionInLine = positionInLine;
}
public static readonly Regex IdentifierPatten =
new Regex(@"^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled);
public static Option<IToken> FromString(
string s,
uint absolutePosition,
uint lineNumber,
uint positionInLine
) =>
IdentifierPatten.IsMatch(s)
? new IdentifierToken(
s,
absolutePosition,
lineNumber,
positionInLine
)
: Option<IToken>.None;
}
}
|
a686a40d1844e3345993d90bb5147922af526963
|
C#
|
kivanov22/SoftUni-CSharp-Advanced
|
/CSharp-Advanced/06_DefiningClasses/Exercise/P08.CarSalesman/Car.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace P08.CarSalesman
{
public class Car
{
public Car(string model, int engine)
{
Model = model;
Engine = engine;
}
public string Model { get; set; }
public int Engine { get; set; }
public int Weight { get; set; }
public string Color { get; set; }
}
}
|
c31b45fbf7700b24281c8a02a9d215cbfbc5dec8
|
C#
|
JeffGillispie/LoadFileAdapter
|
/LoadFileAdapter/Transformers/MetaDataTransformation.cs
| 2.78125
| 3
|
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace LoadFileAdapter.Transformers
{
/// <summary>
/// Contains the settings to perform a transformation on the metadata
/// of a <see cref="Document"/>.
/// </summary>
public class MetaDataTransformation : Transformation
{
private string fieldName = String.Empty;
private string alternateDestinationField = String.Empty;
private string prependField = String.Empty;
private string appendField = String.Empty;
private string joinDelimiter = String.Empty;
private DirectoryInfo prependDirectory = null;
private MetaDataTransformation(Regex findText, string replaceText, string filterField, Regex filterText)
: base(findText, replaceText, filterField, filterText)
{
// do nothing here
}
/// <summary>
/// The target field name.
/// </summary>
public string FieldName { get { return fieldName; } }
/// <summary>
/// The field name of an optional alternate destination for the
/// modified value.
/// </summary>
public string AlternateDestinationField { get { return alternateDestinationField; } }
/// <summary>
/// The field name of a field that should be prepended to the
/// target field value.
/// </summary>
public string PrependField { get { return prependField; } }
/// <summary>
/// The field name of a field that should be appended to the
/// target field value.
/// </summary>
public string AppendField { get { return appendField; } }
/// <summary>
/// The delimiter used to join a preprend or append value to the
/// target field.
/// </summary>
public string JoinDelimiter { get { return joinDelimiter; } }
/// <summary>
/// A root path that is prepended to a relational path in order to
/// convert it to an absolute path.
/// </summary>
public DirectoryInfo PrependDirectory { get { return prependDirectory; } }
/// <summary>
/// Modifies the supplied <see cref="Document"/>. If the doc does not
/// contains the target field name that field is added to the doc's
/// metadata. The find/replace is performed, followed by append,
/// preprend, preprend directory, The the destination is set with the
/// new value.
/// </summary>
/// <param name="doc">the document to be modified.</param>
public override void Transform(Document doc)
{
if (!doc.Metadata.ContainsKey(this.fieldName))
{
doc.Metadata.Add(this.fieldName, String.Empty);
}
if (!String.IsNullOrWhiteSpace(this.alternateDestinationField) &&
!doc.Metadata.ContainsKey(this.alternateDestinationField))
{
doc.Metadata.Add(this.alternateDestinationField, String.Empty);
}
if (base.hasEdit(doc))
{
// get orig value
string value = doc.Metadata[FieldName];
// perform find / replace
value = base.Replace(value);
// append if set
if (!String.IsNullOrWhiteSpace(AppendField))
{
value = value + JoinDelimiter + doc.Metadata[AppendField];
}
// prepend if set
if (!String.IsNullOrWhiteSpace(PrependField))
{
value = doc.Metadata[PrependField] + JoinDelimiter + value;
}
// preprend with file path if set
if (PrependDirectory != null)
{
value = Path.Combine(PrependDirectory.FullName, value.TrimStart('\\'));
}
// update destination
if (!String.IsNullOrWhiteSpace(AlternateDestinationField))
{
doc.Metadata[AlternateDestinationField] = value;
}
else
{
doc.Metadata[fieldName] = value;
}
}
}
public class Builder
{
private MetaDataTransformation instance;
private Builder(Regex findText, string replaceText, string filterField, Regex filterText)
{
instance = new MetaDataTransformation(findText, replaceText, filterField, filterText);
}
public static Builder Start(string fieldName, Regex findText, string replaceText,
string filterField, Regex filterText)
{
Builder builder = new Builder(findText, replaceText, filterField, filterText);
builder.instance.fieldName = fieldName;
return builder;
}
public static Builder Start(string fieldName, Regex findText, string replaceText)
{
Builder builder = new Builder(findText, replaceText, null, null);
builder.instance.fieldName = fieldName;
return builder;
}
public Builder SetFilterField(string value)
{
var instance = new MetaDataTransformation(
this.instance.FindText,
this.instance.ReplaceText,
value,
this.instance.FilterText);
instance.alternateDestinationField = this.instance.alternateDestinationField;
instance.appendField = this.instance.appendField;
instance.fieldName = this.instance.fieldName;
instance.joinDelimiter = this.instance.joinDelimiter;
instance.prependDirectory = this.instance.prependDirectory;
instance.prependField = this.instance.prependField;
this.instance = instance;
return this;
}
public Builder SetFilterText(Regex value)
{
var instance = new MetaDataTransformation(
this.instance.FindText,
this.instance.ReplaceText,
this.instance.FilterField,
value);
instance.alternateDestinationField = this.instance.alternateDestinationField;
instance.appendField = this.instance.appendField;
instance.fieldName = this.instance.fieldName;
instance.joinDelimiter = this.instance.joinDelimiter;
instance.prependDirectory = this.instance.prependDirectory;
instance.prependField = this.instance.prependField;
this.instance = instance;
return this;
}
public Builder SetAltDestinationField(string value)
{
instance.alternateDestinationField = value;
return this;
}
public Builder SetPrependField(string value)
{
instance.prependField = value;
return this;
}
public Builder SetAppendField(string value)
{
instance.appendField = value;
return this;
}
public Builder SetJoinDelimiter(string value)
{
instance.joinDelimiter = value;
return this;
}
public Builder SetPrependDir(DirectoryInfo value)
{
instance.prependDirectory = value;
return this;
}
public MetaDataTransformation Build()
{
MetaDataTransformation instance = this.instance;
this.instance = null;
return instance;
}
}
}
}
|
e4f273dd19ba8c0669395676b272f2d6374f53f0
|
C#
|
muguangyi/pioneer
|
/src/pioneer/PureLogic.cs
| 2.671875
| 3
|
/*
* This file is part of the Pioneer package.
*
* (c) MuGuangYi <muguangyi@hotmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pioneer
{
/// <summary>
/// Logic base class.
/// </summary>
public abstract class PureLogic
{
public PureLogic()
{
var attrs = GetType().GetCustomAttributes(typeof(PClassAttribute), false);
this.Domain = (attrs.Length > 0 ? ((PClassAttribute)attrs[0]).Domain : ApplyDomain.NetMultiple);
}
private ApplyDomain Domain { get; set; }
internal bool IsApplied(WorldMode worldMode)
{
return (WorldMode.Standalone == worldMode) ||
(ApplyDomain.NetMultiple == this.Domain) ||
(ApplyDomain.Client == this.Domain && WorldMode.Client == worldMode) ||
(ApplyDomain.Server == this.Domain && WorldMode.Server == worldMode);
}
}
}
|
d320fc1013f028f5b2a8e824fade32f46debc6eb
|
C#
|
tijujohn83/CSharpLearn
|
/StringTrials/StringTrials/Program.cs
| 4.0625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringTrials
{
class Program
{
static void Main(string[] args)
{
string s = "Technology";
Console.WriteLine("IS string null or empty: {0}", String.IsNullOrEmpty(s));
bool contains = s.Contains("Tech");
Console.WriteLine("String contains tech? {0}", contains );
int? t;
int? a = 1;
//a = null;
Console.WriteLine("Value of a is {0}", a);
int b = a ?? -1; // if a = null then b= -1, else b will have same value as of a
Console.WriteLine("Value of b is {0}", b);
int? e = 11;
int? f = 19;
e = null;
//f = null;
// g = e or f, unless e and f are both null, in which case g = -1.
int g = e ?? f ?? -1; // if e n f both are null g= -1, else g will have value of e or f, who so ever is not null, if both are not null, g=e will get its precedence.
Console.WriteLine("e = {0}, f= {1}, g={2} ", e, f, g);
}
}
}
|
102335dd3792789dcd04cd775624a907ff328d1a
|
C#
|
Tokiarivelo/pro
|
/doc/PdfTemplateGrid/PdfTemplateApp/Utils/AdornerClass.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace PdfTemplateApp.Utils
{
class AdornerClass : Adorner
{
public AdornerClass(UIElement adornedElement) : base(adornedElement)
{
}
// A common way to implement an adorner's rendering behavior is to override the OnRender
// method, which is called by the layout system as part of a rendering pass.
protected override void OnRender(DrawingContext drawingContext)
{
Rect adornedElementRect = new Rect(this.AdornedElement.DesiredSize);
// Some arbitrary drawing implements.
SolidColorBrush renderBrush = new SolidColorBrush(Colors.Green);
renderBrush.Opacity = 0.5;
Pen renderPen = new Pen(new SolidColorBrush(Colors.Navy), 1.5);
double renderRadius = 3.0;
// Draw a circle at each corner.
drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.TopLeft, renderRadius, renderRadius);
drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.TopRight, renderRadius, renderRadius);
drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.BottomLeft, renderRadius, renderRadius);
drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.BottomRight, renderRadius, renderRadius);
}
}
}
|
97fb20aa35e9dcb2c4a5d0d865e348a5c8cbb8a4
|
C#
|
matheuscardoso96/ApiCatalogoDeJogos
|
/ApiCatalogoDeJogos/Controllers/V1/GamesController.cs
| 2.6875
| 3
|
using ApiCatalogoDeJogos.Exceptions;
using ApiCatalogoDeJogos.Models.InputModels;
using ApiCatalogoDeJogos.Models.ViewModels;
using ApiCatalogoDeJogos.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
namespace ApiCatalogoDeJogos.Controllers.V1
{
[Route("api/V1/[controller]")]
[ApiController]
public class GamesController : ControllerBase
{
private readonly IGameService _gameService;
public GamesController(IGameService gameService)
{
_gameService = gameService;
}
[HttpGet]
public async Task<ActionResult<List<GameViewModel>>> Get([FromQuery, Range(1, int.MaxValue)] int page = 1, [FromQuery, Range(1, 50)] int count = 1)
{
var result = await _gameService.Get(page, count);
if (result.Count == 0)
{
return NoContent();
}
return Ok(result);
}
[HttpGet("{gameId:guid}")]
public async Task<ActionResult<GameViewModel>> Get([FromRoute]Guid gameId)
{
var game = await _gameService.Get(gameId);
if (game == null)
{
return NoContent();
}
return Ok(game);
}
[HttpPost]
public async Task<ActionResult<GameInputModel>> Insert([FromBody]GameInputModel gameInputModel)
{
try
{
await _gameService.Insert(gameInputModel);
return Ok(gameInputModel);
}
catch (GameAlreadyInDataBaseException ex)
{
return UnprocessableEntity("This game already exist.");
}
}
[HttpPut("{gameId:guid}")]
public async Task<ActionResult> UpdateGame([FromRoute]Guid gameId, [FromBody]GameInputModel game)
{
try
{
await _gameService.Update(gameId, game);
return Ok();
}
catch (GameNotRegisteredException ex)
{
return UnprocessableEntity("This game is not registered in database.");
}
}
[HttpPatch("{gameId:guid}/price/{price:double}")]
public async Task<ActionResult> UpdateGamePrice([FromRoute] Guid gameId, [FromRoute] double price)
{
try
{
await _gameService.Update(gameId, price);
return Ok();
}
catch (GameNotRegisteredException ex)
{
return UnprocessableEntity("This game is not registered in database.");
}
}
[HttpDelete("{gameId:guid}")]
public async Task<ActionResult> Delete([FromRoute] Guid gameId)
{
try
{
await _gameService.Delete(gameId);
return Ok();
}
catch (GameNotRegisteredException ex)
{
return UnprocessableEntity("This game is not registered in database.");
}
}
}
}
|
e3d4858494cceebea164f62105a062200916f698
|
C#
|
fabtosz/akademia_c_sharp_wieza_czarodzieja
|
/Form1.cs
| 2.578125
| 3
|
// Bartosz Fabiański
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 WindowsFormsApplication6
{
public partial class Form1 : Form
{
Location currentLocation;
RoomWithDoor magicRoom;
Room library;
RoomWithDoor tortureRoom;
OutsideWithDoor frontYard;
OutsideWithDoor backYard;
Outside outland;
public Form1()
{
InitializeComponent();
CreateObjects();
MoveToANewLocation(magicRoom);
}
private void CreateObjects()
{
magicRoom = new RoomWithDoor("Sala magii", "starożytny gobelin i obsydianowe gargulce",
"kamienny portal w szkarłatnych płomieniach");
library = new Room("Biblioteka", "wysokie przepastne regały pełne starożytnych manuskryptów");
tortureRoom = new RoomWithDoor("Sala tortur", "ponury lock pełen szkieletów, klatek i brunatnych śladów krwi", "jedwabna kotara");
frontYard = new OutsideWithDoor("Podwórze", false, "wielki kamienny portal w jaskrawo-zielonych płomieniach");
backYard = new OutsideWithDoor("Ogród Posągów", true, "dębowe drzwi");
outland = new Outside("Pustkowie", false);
library.Exits = new Location[] { magicRoom, tortureRoom };
magicRoom.Exits = new Location[] { library };
tortureRoom.Exits = new Location[] { library };
frontYard.Exits = new Location[] { backYard, outland };
backYard.Exits = new Location[] { frontYard, outland };
outland.Exits = new Location[] { backYard, frontYard };
magicRoom.DoorLocation = frontYard;
frontYard.DoorLocation = magicRoom;
tortureRoom.DoorLocation = backYard;
backYard.DoorLocation = tortureRoom;
}
private void MoveToANewLocation(Location newLocation)
{
currentLocation = newLocation;
exits.Items.Clear();
for (int i = 0; i < currentLocation.Exits.Length; i++)
exits.Items.Add(currentLocation.Exits[i].Name);
exits.SelectedIndex = 0;
description.Text = currentLocation.Description;
if (currentLocation is IHasExteriorDoor)
goThroughTheDoor.Visible = true;
else
goThroughTheDoor.Visible = false;
}
private void goHere_Click(object sender, EventArgs e)
{
MoveToANewLocation(currentLocation.Exits[exits.SelectedIndex]);
}
private void goThroughTheDoor_Click(object sender, EventArgs e)
{
IHasExteriorDoor hasDoor = currentLocation as IHasExteriorDoor;
MoveToANewLocation(hasDoor.DoorLocation);
}
}
}
|
a7a503b7acca5837fcb478e7e7baa5b33e6e784d
|
C#
|
lvkat/Lab_5
|
/Lab_5/UtilsCreators.cs
| 2.875
| 3
|
using IMainInterface;
using Lab_5.Utensils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IMainInterface;
namespace Lab_5
{
class CupCreator : BaseUtensilCreator
{
public override void SetProperties(Utensil utensil, List<string> values)
{
base.SetProperties(utensil as Cup, values);
(utensil as Cup).HaftCount = int.Parse(values[3]);
utensil.Name = "Кружка";
}
public override List<string> GetProperties(Utensil utensil)
{
var values = base.GetProperties(utensil);
values.Add((utensil as Cup).HaftCount.ToString());
return values;
}
public override Utensil CreateUtensil(List<string> values)
{
Cup cup = new Cup();
SetProperties(cup, values);
return cup;
}
public override List<string> GetPropertyNames()
{
var propertyName = base.GetPropertyNames();
propertyName.Add("Количество ручек");
return propertyName;
}
}
class PanCreator : BaseUtensilCreator
{
public override void SetProperties(Utensil utensil, List<string> values)
{
base.SetProperties(utensil as Pan, values);
(utensil as Pan).Diameter = Int32.Parse(values[3]);
(utensil as Pan).CoverType = values[4];
utensil.Name = "Сковорода";
}
public override List<string> GetProperties(Utensil utensil)
{
var values = base.GetProperties(utensil);
values.Add((utensil as Pan).Diameter.ToString());
values.Add((utensil as Pan).CoverType);
return values;
}
public override Utensil CreateUtensil(List<string> values)
{
Pan pan = new Pan();
SetProperties(pan, values);
return pan;
}
public override List<string> GetPropertyNames()
{
var propertyName = base.GetPropertyNames();
propertyName.Add("Диаметр");
propertyName.Add("Тип покрытия");
return propertyName;
}
}
class SteamerCreator : PanCreator
{
public override void SetProperties(Utensil utensil, List<string> values)
{
base.SetProperties(utensil as Steamer, values);
(utensil as Steamer).Capasity = int.Parse( values[5]);
(utensil as Steamer).ContainersCout = int.Parse(values[6]);
utensil.Name = "Пароварка";
}
public override List<string> GetProperties(Utensil utensil)
{
var values = base.GetProperties(utensil);
values.Add((utensil as Steamer).Capasity.ToString());
values.Add((utensil as Steamer).ContainersCout.ToString());
return values;
}
public override Utensil CreateUtensil(List<string> values)
{
Steamer steamer = new Steamer();
SetProperties(steamer, values);
return steamer;
}
public override List<string> GetPropertyNames()
{
var propertyName = base.GetPropertyNames();
propertyName.Add("Мощность");
propertyName.Add("Емкость для готовки");
return propertyName;
}
}
class TureenCreator : BaseUtensilCreator
{
public override void SetProperties(Utensil utensil, List<string> values)
{
base.SetProperties(utensil as Tureen, values);
(utensil as Tureen).HaftCount = int.Parse(values[3]);
(utensil as Tureen).Shape = values[4];
utensil.Name = "Супница";
}
public override List<string> GetProperties(Utensil utensil)
{
var values = base.GetProperties(utensil);
values.Add((utensil as Tureen).HaftCount.ToString());
values.Add((utensil as Tureen).Shape);
return values;
}
public override Utensil CreateUtensil(List<string> values)
{
Tureen tureen = new Tureen();
SetProperties(tureen, values);
return tureen;
}
public override List<string> GetPropertyNames()
{
var propertyName = base.GetPropertyNames();
propertyName.Add("Количество ручек");
propertyName.Add("Форма");
return propertyName;
}
}
}
|
94b10da9c431e825b3fb8e95261103d1cd8daa27
|
C#
|
hitinder/PropertyManagement
|
/PropertyManagement.BusinessObjectLayer/Services/StatusService.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using PropertyManagement.BusinessObjectLayer.ViewModels;
using PropertyManagement.DataObjectLayer;
using PropertyManagement.DataObjectLayer.Models;
using System.Threading.Tasks;
namespace PropertyManagement.BusinessObjectLayer
{
public class StatusService: IStatusService
{
private readonly IStatusRepository _statusRepository;
public StatusService(IStatusRepository statusRepository)
{
_statusRepository = statusRepository;
}
public async Task<List<StatusViewModel>> StatusList()
{
List<Status> status = await _statusRepository.StatusList();
List<StatusViewModel> statusVM = new List<StatusViewModel>();
foreach(Status s in status)
{
StatusViewModel sVM = new StatusViewModel();
sVM.StatusId = s.StatusId;
sVM.StatusName = s.StatusName;
sVM.StatusType = s.StatusType;
statusVM.Add(sVM);
}
return statusVM;
}
public List<StatusViewModel> StatusList(int StatusTypeId)
{
List<Status> status = _statusRepository.StatusList(StatusTypeId);
List<StatusViewModel> statusVM = new List<StatusViewModel>();
foreach (Status s in status)
{
StatusViewModel sVM = new StatusViewModel();
sVM.StatusId = s.StatusId;
sVM.StatusName = s.StatusName;
sVM.StatusType = s.StatusType;
statusVM.Add(sVM);
}
return statusVM;
}
public async Task<StatusViewModel> StatusById(int StatusId)
{
var s = await _statusRepository.StatusById(StatusId);
StatusViewModel sVM = new StatusViewModel();
sVM.StatusId = s.StatusId;
sVM.StatusName = s.StatusName;
sVM.StatusType = s.StatusType;
return sVM;
}
public async Task SaveStatusData(string StatusName, int StatusId, int StatusType)
{
await _statusRepository.SaveStatusData(StatusName, StatusId, StatusType);
}
}
}
|
d9ff729fea5ef66438273a78eb012593d0866ad3
|
C#
|
esauri/ProjectQuest
|
/Project3/ErickSauri_Project2/Monster.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sauri_Project3
{
public class Monster
{
int life;
string type;
string name;
int damage;
Dictionary<string, int> enemyAttack = new Dictionary<string, int>();
string[] champnames = new string[5];
string[] bossnames = new string[3];
Random rand = new Random();
int attackchoose;
string attack;
public Monster(string t)
{
type = t;
pickmove();
//Minion moves:
enemyAttack.Add("Headbutt", 5);
enemyAttack.Add("Kick", 10);
enemyAttack.Add("Quick Strike", 15);
enemyAttack.Add("Slash", 25);
//Squad moves + slash:
enemyAttack.Add("Piercing Shot", 20);
enemyAttack.Add("Scorch", 30);
enemyAttack.Add("Flank", 40);
//Champion moves:
enemyAttack.Add("Charge", 35);
enemyAttack.Add("Fatal Strike", 40);
enemyAttack.Add("Impale", 50);
enemyAttack.Add("Execute", 55);
//Boss moves
enemyAttack.Add("Desecrate", 65);
enemyAttack.Add("Obliterate", 65);
enemyAttack.Add("Conflagrate", 75);
enemyAttack.Add("Decapitate", 80);
if (t == "Boss") { Boss(); }
else if (t == "Champion") { Champion(); }
else if (t == "Squad") { Squad(); }
else { Minion(); }
}
public int Life
{
get { return life; }
set { life = value; }
}
public int Damage
{
get { return damage; }
}
public string Attack
{
get { return attack; }
}
public string Type
{
get { return type; }
}
public void takeDamage(int h)
{
life -= h;
}
public string Name
{
get { return name; }
}
public void pickmove() //picks which attack the monster uses
{
attackchoose = rand.Next(1, 101);
}
public void Minion() //Minion type
{
life = 30;
name = "Goblin Patroller";
//Attacking
if (attackchoose > 40)
{
damage = enemyAttack["Headbutt"];
attack = "Headbutt";
}
else if (attackchoose > 25)
{
damage = enemyAttack["Kick"];
attack = "Kick";
}
else if (attackchoose > 10)
{
damage = enemyAttack["Quick Strike"];
attack = "Quick Strike";
}
else
{
damage = enemyAttack["Slash"];
attack = "Slash";
}
}
public void Squad() //Squad Type
{
life = 90;
name = "Orc Raiders";
//Attacking
if (attackchoose > 40)
{
damage = enemyAttack["Piercing Shot"];
attack = "Piercing Shot";
}
else if (attackchoose > 25)
{
damage = enemyAttack["Slash"];
attack = "Slash";
}
else if (attackchoose > 10)
{
damage = enemyAttack["Scorch"];
attack = "Scorch";
}
else
{
damage = enemyAttack["Flank"];
attack = "Flank";
}
}
public void Champion() //Champion type
{
life = 120;
//Champion names:
champnames[0] = "Rhozaq the Skullsplitter";
champnames[1] = "Warlord Gurkosh";
champnames[2] = "Rekkul, Champion of the Blood Guard";
champnames[3] = "Omokk, The Gluttony";
champnames[4] = "Harromm the Earthshatterer";
int namepicker = rand.Next(0, champnames.Length);
name = champnames[namepicker];
//Attacking
if (attackchoose > 40)
{
damage = enemyAttack["Charge"];
attack = "Charge";
}
else if (attackchoose > 25)
{
damage = enemyAttack["Fatal Strike"];
attack = "Fatal Strike";
}
else if (attackchoose > 10)
{
damage = enemyAttack["Implae"];
attack = "Impale";
}
else
{
damage = enemyAttack["Execute"];
attack = "Execute";
}
}
public void Boss() //Boss type
{
life = 150;
//boss names:
bossnames[0] = "Alexei, Sword of the Nightfall";
bossnames[1] = "The Dark Knight";
bossnames[2] = "Lancaster, Bane of Aran";
int namepicker = rand.Next(0, bossnames.Length);
name = bossnames[namepicker];
//Attacking
if (attackchoose > 40)
{
damage = enemyAttack["Desecrate"];
attack = "Desecrate";
}
else if (attackchoose > 25)
{
damage = enemyAttack["Obliterate"];
attack = "Obliterate";
}
else if (attackchoose > 10)
{
damage = enemyAttack["Conflagrate"];
attack = "Conflagrate";
}
else
{
damage = enemyAttack["Decapitate"];
attack = "Decapitate";
}
}
}
}
|
f756f33e4214a358904221fad49687bd1332aa7f
|
C#
|
shendongnian/download4
|
/latest_version_download2/84655-15962447-38986691-4.cs
| 2.890625
| 3
|
private void CreateColumns()
{
var startDate = new DateTime(2013, 05, 07);
var endDate = new DateTime(2013, 05, 17);
//// Ensure that startDate < endDate, no validation in this example.
var tmp = startDate;
while (tmp <= endDate)
{
GridViewColumn gc = new GridViewColumn();
gc.Header = tmp.ToShortDateString();
gc.Width = 100;
this.myView.Columns.Add(gc);
tmp = tmp.AddDays(1);
}
}
|
498aeeca092553905c7d362a59f2ccefce7048f4
|
C#
|
shendongnian/download4
|
/first_version_download2/427299-37603272-119564103-2.cs
| 2.5625
| 3
|
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2\\Security\\MicrosoftVolumeEncryption",
"SELECT * FROM Win32_EncryptableVolume");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_EncryptableVolume instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("ProtectionStatus: {0}", queryObj["ProtectionStatus"]);
bitLockerCheckInvis.Text += string.Format("ProtectionStatus: {0}", queryObj["ProtectionStatus"]);
//bitLockerCheck.Text = queryObj["ProtectionStatus"] == "1" ? "Bitlocker Disabled" : "Bitlocker Enabled";
// if ((string)queryObj["ProtectionStatus"] == "0") { bitLockerCheck.Text = "Bitlocker Disabled"; }
//else if ((string)queryObj["ProtectionStatus"] == "1") { bitLockerCheck.Text = "Bitlocker Enabled"; }
// else { bitLockerCheck.Text = ""; }
}
}
catch (ManagementException)
{
MessageBox.Show("Please Restart the program to check Administrative Settings");
}
{
if (bitLockerCheckInvis.Text == "ProtectionStatus: 1") { bitLockerCheck.Text += "Bitlocker Enabled"; }
if (bitLockerCheckInvis.Text == "ProtectionStatus: 0") { bitLockerCheck.Text += "Bitlocker Disabled"; }
if (bitLockerCheckInvis.Text == "ProtectionStatus: ") { bitLockerCheck.Text += "Bitlocker Not Available"; }
|
4c4548f66587927eb45cef348d33cddc8bcd9532
|
C#
|
someExampleName/exampleOfRepository
|
/1.School/Class.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace School
{
class Class
{
// due to the fact that classes contain students we need to have a field made of list of students
private List<Student> students;
// each class has a set of teachers => we need a list of teachers
private List<Teacher> teachers = new List<Teacher>();
private string identifier;
private List<string> comments;
// properties of the field
public List<Student> Students
{
get
{
return this.students;
}
set
{
this.students = new List<Student>(value); // in this way we copy the value, not only the reference
}
}
public string Identifier
{
get
{
return this.identifier;
}
set
{
this.identifier = value;
}
}
public List<Teacher> Teachers
{
get
{
return this.teachers;
}
set
{
this.teachers = new List<Teacher>(value);
}
}
public List<string> Comments
{
get
{
return this.comments;
}
set
{
this.comments = new List<string>(value);
}
}
// constructor
public Class()
{
this.students = new List<Student>();
this.comments = new List<string>();
}
public void AddComment(string comment)
{
this.comments.Add(comment);
}
}
}
|
40225470ab84edd0d40255fe67287c26aeaea4bd
|
C#
|
philong192001/EzTrade
|
/DAL/CodeDAL.cs
| 2.546875
| 3
|
using DAL.Models;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace DAL
{
public class CodeDAL
{
private readonly IConfiguration _configuration;
private readonly string _strConn;
private const string __DEFAULT_CONN = "EzTrade_Demo";
private readonly SqlConnection _sqlConnection;
public CodeDAL(IConfiguration config)
{
this._configuration = config;
_strConn = _configuration.GetConnectionString(__DEFAULT_CONN);
_sqlConnection = new SqlConnection(_strConn);
}
public DataTable GetCode()
{
DataTable dt = new DataTable();
try
{
if (ConnectionState.Closed == _sqlConnection.State)
{
_sqlConnection.Open();
}
SqlCommand cmd = new SqlCommand("SP_GetPiceList", _sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
}
catch (Exception e)
{
throw;
}
finally
{
_sqlConnection.Close();
}
return dt;
}
public DataTable GetCodeById(int? id)
{
DataTable dt = new DataTable();
try
{
if(ConnectionState.Closed == _sqlConnection.State)
{
_sqlConnection.Open();
}
SqlCommand cmd = new SqlCommand("SP_getCodeById", _sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", id);
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
}
catch (Exception)
{
throw;
}
finally
{
_sqlConnection.Close();
}
return dt;
}
public DataSet AllCodeDetails()
{
DataSet ds = new DataSet();
try
{
if (ConnectionState.Closed == _sqlConnection.State)
{
_sqlConnection.Open();
}
SqlCommand cmd = new SqlCommand("SP_GetAllCodeDetails", _sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
catch
{
throw;
}
finally
{
_sqlConnection.Close();
}
return ds;
}
public DataTable GetAllCode()
{
DataTable dt = new DataTable();
try
{
if (ConnectionState.Closed == _sqlConnection.State)
{
_sqlConnection.Open();
}
SqlCommand cmd = new SqlCommand("SP_GetAllCode", _sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch
{
throw;
}
finally
{
_sqlConnection.Close();
}
return dt;
}
public void InsertCode(Code code)
{
try
{
if (ConnectionState.Closed == _sqlConnection.State)
{
_sqlConnection.Open();
}
SqlCommand cmd = new SqlCommand("SP_InsertCode",_sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@NAME_CODE", code.NameCode);
cmd.Parameters.AddWithValue("@ID_DETAILS", code.Id_details);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
_sqlConnection.Close();
}
}
public void UpdateCode(Code code)
{
try
{
if (ConnectionState.Closed == _sqlConnection.State)
{
_sqlConnection.Open();
}
SqlCommand cmd = new SqlCommand("Sp_UpdateCode", _sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", code.Id);
cmd.Parameters.AddWithValue("@NAME_CODE", code.NameCode);
cmd.Parameters.AddWithValue("@ID_DETAILS", code.Id_details);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
_sqlConnection.Close();
}
}
public void Delete(int? id)
{
SqlCommand cmd = new SqlCommand("Sp_DeleteCode", _sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", id);
_sqlConnection.Open();
cmd.ExecuteReader();
_sqlConnection.Close();
}
}
}
|
83dc323e53e01969461e331f43ac3999323ffeea
|
C#
|
CodyHoll/GenericRPG_TeamMagenta
|
/Implementation/GenericRPG/FrmMap.cs
| 3.046875
| 3
|
using GameLibrary;
using GenericRPG.Properties;
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
namespace GenericRPG {
public partial class FrmMap : Form {
private Character character;
private Map map;
private Game game;
public FrmMap() {
InitializeComponent();
}
private void FrmMap_Load(object sender, EventArgs e) {
game = Game.GetGame();
map = new Map();
Random rnd = new Random();
string output = "";
List<string> mapLines = new List<string>();
int row = rnd.Next(15,21);
int col = rnd.Next(15,21);
char[,] arr = new char[row,col];
//create box and border
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if (i == 0 | i == row-1 | j == 0 | j == col-1)
{
arr[i, j]= '1';
}
else
{
arr[i, j]= '0';
}
}
}
//randomly assign values
for(int i=1;i<row-1;i++)
{
for(int j=1;j<col-1;j++)
{
int x = rnd.Next(100);
if (x%3 == 1)
{
arr[i, j]= '1';
}
}
}
//makes floor out of random values
for(int i=1 ;i<row-1 ;i++)
{
for(int j=1;j<col-1;j++)
{
int count = 0;
int randint = rnd.Next();
if (arr[i,j-1] == '0')
{
count +=1;
}
if (arr[i-1,j] == '0')
{
count +=1;
}
if (arr[i+1,j] == '0')
{
count +=1;
}
if (arr[i,j+1] == '0')
{
count +=1;
}
if (count >= 3 & randint % 4 == 1)
{
arr[i,j] = '1';
}
}
}
//filling in 1x1 openings
for(int i=1 ;i<row-1 ;i++)
{
for(int j=1;j<col-1;j++)
{
int count = 0;
int randint = rnd.Next();
if (arr[i,j-1] == '0')
{
count +=1;
}
if (arr[i-1,j] == '0')
{
count +=1;
}
if (arr[i+1,j] == '0')
{
count +=1;
}
if (arr[i,j+1] == '0')
{
count +=1;
}
if (count == 0)
{
arr[i,j] = '1';
}
}
}
//opening up closed off areas
for(int i=1 ;i<row-1 ;i++)
{
for(int j=1;j<col-1;j++)
{
if ((arr[i-1,j] == '0' & arr[i+1,j] == '0') | (arr[i,j-1] == '0' & arr[i,j+1] == '0'))
{
arr[i,j] = '0';
}
}
}
int rndrow = rnd.Next(1,row);
int rndcol = rnd.Next(1,col);
while (arr[rndrow,rndcol] != '0')
{
rndrow = rnd.Next(1,row);
rndcol = rnd.Next(1,col);
}
arr[rndrow,rndcol] = '2';
int rndrow2 = rnd.Next(1,row);
int rndcol2 = rnd.Next(1,col);
while ( (arr[rndrow2,rndcol2] != '0') | (Math.Abs(rndrow2-rndrow) <= 5) | (Math.Abs(rndcol2-rndcol) <= 5))
{
rndrow2 = rnd.Next(1,row);
rndcol2 = rnd.Next(1,col);
}
arr[rndrow2,rndcol2] = '3';
int rndrow3 = rnd.Next(1,row);
int rndcol3 = rnd.Next(1,col);
while (arr[rndrow3,rndcol3] != '0')
{
rndrow3 = rnd.Next(1,row);
rndcol3 = rnd.Next(1,col);
}
int rnditem = rnd.Next(6,9);
if (rnditem == 6)
{
arr[rndrow3,rndcol3] = '6';
}
if (rnditem == 7)
{
arr[rndrow3,rndcol3] = '7';
}
if (rnditem == 8)
{
arr[rndrow3,rndcol3] = '8';
}
//combine to 1 string
for(int i=0;i<row;i++)
{
output = "";
for(int j=0;j<col;j++)
{
output += arr[i,j];
}
mapLines.Add(output);
}
character = map.LoadMap(mapLines, grpMap,
str => Resources.ResourceManager.GetObject(str) as Bitmap
);
Width = grpMap.Width + 25;
Height = grpMap.Height + 50;
game.SetCharacter(character);
}
private void FrmMap_KeyDown(object sender, KeyEventArgs e) {
MoveDir dir = MoveDir.NO_MOVE;
switch (e.KeyCode) {
case Keys.Left:
dir = MoveDir.LEFT;
break;
case Keys.Right:
dir = MoveDir.RIGHT;
break;
case Keys.Up:
dir = MoveDir.UP;
break;
case Keys.Down:
dir = MoveDir.DOWN;
break;
}
if (dir != MoveDir.NO_MOVE) {
character.Move(dir);
if (game.State == GameState.FIGHTING) {
FrmArena frmArena = new FrmArena();
frmArena.Show();
}
}
}
public void RemoveItem(int num)
{
switch (num)
{
case 6:
foreach (var control in grpMap.Controls)
{
var ctrl = control as Control;
if ((ctrl.Tag as string) == "sword")
{
this.Controls.Remove(ctrl);
}
}
break;
}
//return 0;
}
}
}
|
d472a700ebb6861771f453047219d0bae9181246
|
C#
|
voinekku/tali-ihantala
|
/Assets/Scripts/Weapons/Weapon.cs
| 2.78125
| 3
|
using UnityEngine;
using System.Collections;
public abstract class Weapon : MonoBehaviour {
public float timeBetweenShots = 0.5f;
private bool firing = false;
private float fireTimer = 1f;
// Update is called once per frame
void Update () {
fireTimer += Time.deltaTime;
if(firing) {
if(fireTimer >= timeBetweenShots) {
fireTimer = 0f;
Fire();
}
}
}
public void TriggerPulled() {
firing = true;
}
public void TriggerReleased() {
firing = false;
}
protected abstract void Fire();
}
|
8538de3fec03ffd1b62b0e804151df42364c1883
|
C#
|
sunny-lan/GenshinbotCsharp
|
/GenshinBotCore/reactive/Poller.cs
| 3.03125
| 3
|
using genshinbot.reactive.wire;
using genshinbot.util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace genshinbot.reactive
{
public class Poller
{
public Wire<NoneT> wire { get; }
public Poller(Func<Task> a, int? delay = null)
{
var lck = new SemaphoreSlim(1);
wire= new Wire<NoneT>(_ => Poller.InfiniteLoop(async()=> {
await lck.WaitAsync().ConfigureAwait(false);
try
{
await a();
}
finally
{
lck.Release();
}
}, delay));
}
public Poller(Action a, int? delay = null)
{
wire = new Wire<NoneT>((_,eH) => Poller.InfiniteLoop(a, delay,eH));
}
public static IDisposable InfiniteLoop(Action a, int? delay = null,Action<Exception> ?eH=null)
{
return InfiniteLoop(async () => a(), delay,eH);
}
public static IDisposable InfiniteLoop(Func<Task> a, int? delay=null, Action<Exception>? eH = null)
{
var ts = new CancellationTokenSource();
Task.Run(async() => {
// Console.WriteLine("begin loop");
while (!ts.Token.IsCancellationRequested)
{
// Console.WriteLine(" begin poll");
try
{
await a().ConfigureAwait(false);
}catch(Exception e)
{
eH?.Invoke(e);
}
if (delay is int dd)
await Task.Delay(dd, ts.Token).ConfigureAwait(false);
}
// Console.WriteLine("end loop");
}, ts.Token);
return DisposableUtil.From(() => {
Console.WriteLine("request cancellation");
ts.Cancel();
});
}
#region tests
/// <summary>
/// No interval, task takes 1000ms
/// </summary>
public static void Test1()
{
int i = 0;
var stream = new Poller<int>(() =>
{
Thread.Sleep(1000);
return i++;
});
using (stream.Wire.Subscribe(x => Console.WriteLine(x)))
{
Thread.Sleep(10000);
}
}
/// <summary>
/// Task takes 0ms, interval is 500ms
/// </summary>
public static void Test2()
{
int i = 0;
var stream = new Poller<int>(() =>
{
return i++;
});
stream.Interval = 500;
using (stream.Wire.Subscribe(x => Console.WriteLine(x)))
{
Thread.Sleep(5000);
}
}
/// <summary>
/// Task takes 1000ms, no interval, max in flight=2
/// </summary>
public static void Test3()
{
int i = 0;
var stream = new Poller<int>(() =>
{
Thread.Sleep(1000);
return i++;
});
stream.MaxInFlight = 2;
using (stream.Wire.Subscribe(x => Console.WriteLine(x)))
{
Thread.Sleep(5000);
}
}
/// <summary>
/// multiple tasks in flight where task takes longer than interval
/// </summary>
public static void Test4()
{
int i = 0;
var stream = new Poller<int>(() =>
{
Thread.Sleep(1000);
return i++;
});
stream.Interval = 100;
stream.MaxInFlight = 3;
using (stream.Wire.Subscribe(x => Console.WriteLine(x)))
{
Thread.Sleep(5000);
}
}
/// <summary>
/// check if poll starts and stops properly
/// </summary>
public static void Test5()
{
int i = 0;
var stream = new Poller<int>(() =>
{
Console.WriteLine("poll");
return i++;
});
stream.Interval = 100;
stream.MaxInFlight = 3;
Console.WriteLine("poll should begin after");
using (stream.Wire.Subscribe(x => Console.WriteLine(x)))
{
Thread.Sleep(5000);
}
Console.WriteLine("no poll should be");
Thread.Sleep(2000);
Console.WriteLine("poll should begin after");
using (stream.Wire.Subscribe(x => Console.WriteLine(x)))
{
Thread.Sleep(5000);
}
Console.WriteLine("no poll should be");
Thread.Sleep(5000);
}
public static void Test()
{
Test5();
}
#endregion
}
/// <summary>
/// Polls the value of a function and outputs it into a stream
/// </summary>
/// <typeparam name="T"></typeparam>
public class Poller<T>
{
public ILiveWire<T> Wire => obsSubj;
private LiveWire<T> obsSubj;
Func<T> poll;
public Poller(Func<T> poll)
{
this.poll = poll;
// obsSubj = new LiveWire<T>(poll, Poller.InfiniteLoop);
throw new NotImplementedException();
}
/// <summary>
/// Polling interval, in milliseconds.
/// If 0, the maximum speed possible is used
/// </summary>
public int Interval
{
get => 0; set => throw new NotImplementedException();
}
public int MaxInFlight
{
get => 1; set
{
if (value != 1) throw new NotImplementedException();
}
}
}
}
|
52aac676a57e685385151e26546b9ac094e0cca0
|
C#
|
mpalics/MemCatch
|
/Program.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace MemCatcher
{
class Program
{
// REQUIRED CONSTS
const int PROCESS_QUERY_INFORMATION = 0x0400;
const int MEM_COMMIT = 0x00001000;
const int PAGE_READWRITE = 0x04;
const int PROCESS_WM_READ = 0x0010;
// REQUIRED METHODS
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(int hProcess, long lpBaseAddress, byte[] lpBuffer, long dwSize, ref int lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
// REQUIRED STRUCTS
public enum AllocationProtect : uint
{
PAGE_EXECUTE = 0x00000010,
PAGE_EXECUTE_READ = 0x00000020,
PAGE_EXECUTE_READWRITE = 0x00000040,
PAGE_EXECUTE_WRITECOPY = 0x00000080,
PAGE_NOACCESS = 0x00000001,
PAGE_READONLY = 0x00000002,
PAGE_READWRITE = 0x00000004,
PAGE_WRITECOPY = 0x00000008,
PAGE_GUARD = 0x00000100,
PAGE_NOCACHE = 0x00000200,
PAGE_WRITECOMBINE = 0x00000400
}
public struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
}
public struct MEMORY_BASIC_INFORMATION64
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public int AllocationProtect;
public int __alignment1;
public IntPtr RegionSize;
public int State;
public int Protect;
public int Type;
public int __alignment2;
}
public struct SYSTEM_INFO
{
public ushort processorArchitecture;
ushort reserved;
public uint pageSize;
public IntPtr minimumApplicationAddress;
public IntPtr maximumApplicationAddress;
public IntPtr activeProcessorMask;
public uint numberOfProcessors;
public uint processorType;
public uint allocationGranularity;
public ushort processorLevel;
public ushort processorRevision;
}
// finally...
public static void Main()
{
// getting minimum & maximum address
SYSTEM_INFO sys_info = new SYSTEM_INFO();
GetSystemInfo(out sys_info);
IntPtr proc_min_address = sys_info.minimumApplicationAddress;
IntPtr proc_max_address = sys_info.maximumApplicationAddress;
// saving the values as long ints so I won't have to do a lot of casts later
long proc_min_address_l = (long)proc_min_address;
long proc_max_address_l = (long)proc_max_address;
// notepad better be runnin'
Process process = Process.GetProcessesByName("notepad")[0];
Console.Write("String: ");
string searchstr = Console.ReadLine();
// opening the process with desired access level
IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);
List<Tuple<string, char>> searchbuffer = new List<Tuple<string, char>>();
StreamWriter sw = new StreamWriter("mem_dump.txt");
StreamWriter sw2 = new StreamWriter("found.txt");
// this will store any information we get from VirtualQueryEx()
MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();
uint mbi_size;
unsafe
{
mbi_size = (uint)sizeof(MEMORY_BASIC_INFORMATION);
}
int bytesRead = 0; // number of bytes read with ReadProcessMemory
while (proc_min_address_l < proc_max_address_l)
{
// 28 = sizeof(MEMORY_BASIC_INFORMATION)
VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, mbi_size);
Console.Write(proc_min_address_l + " / " + proc_max_address_l);
Console.SetCursorPosition(0, 0);
// if this memory chunk is accessible
if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
{
byte[] buffer = new byte[(ulong)mem_basic_info.RegionSize];
// read everything in the buffer above
ReadProcessMemory((int)processHandle, (long)mem_basic_info.BaseAddress, buffer, (long)mem_basic_info.RegionSize, ref bytesRead);
// then output this in the file
for (int i = 0; i < (long)mem_basic_info.RegionSize; i++)
{
if ((char)buffer[i] != '\0')
{
sw.WriteLine("0x{0} : {1}", (mem_basic_info.BaseAddress + i).ToString("X"), (char)buffer[i]);
searchbuffer.Add(new Tuple<string, char>(
String.Format("0x{0}", (mem_basic_info.BaseAddress + i).ToString("X")),
(char)buffer[i]));
}
//
if (new String(searchbuffer.Select(s => s.Item2).ToArray()).Equals(searchstr))
{
foreach (var chunk in searchbuffer)
{
sw2.WriteLine("0x{0} : {1}", chunk.Item1, chunk.Item2);
}
}
if (searchbuffer.Count >= searchstr.Length)
{
searchbuffer.Clear();
}
}
}
// move to the next memory chunk
proc_min_address_l += (long)mem_basic_info.RegionSize;
proc_min_address = new IntPtr(proc_min_address_l);
}
sw.Close();
sw2.Close();
}
}
}
|
b96d84fde0eab8eaf485d3f60ce097daa0152de0
|
C#
|
torkkeli/ChessLearningTool
|
/branches/master/src/ChessLearningTool/ChessLearningTool.Logic/ChessLogic/Pieces/ChessPiece.cs
| 3.015625
| 3
|
using ChessLearningTool.Data.Enums;
using ChessLearningTool.Logic.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace ChessLearningTool.Logic.ChessLogic.Pieces
{
public abstract class ChessPiece : IChessPiece
{
protected ChessPiece(ChessColor color, BoardCoordinates coordinates)
{
Color = color;
Coordinates = coordinates;
}
public event Action<ChessMove> MoveMade;
public abstract Bitmap Image { get; }
public BoardCoordinates Coordinates { get; set; }
public ChessColor Color { get; }
public abstract decimal Value { get; }
public bool TryMakeMove(BoardCoordinates to, ChessPosition position)
{
if (CanMakeMove(to, position))
{
MakeMove(to, position);
return true;
}
return false;
}
protected abstract bool IsMoveLegal(BoardCoordinates square, ChessPosition position);
protected bool IsPieceBlocking(BoardCoordinates square, ChessPosition position)
{
var rowDiff = Coordinates.Row - square.Row;
var columnDiff = Coordinates.Column - square.Column;
var squaresMoved = Math.Max(Math.Abs(rowDiff), Math.Abs(columnDiff));
for (int i = 1; i < squaresMoved; i++)
{
var row = rowDiff == 0 ? Coordinates.Row : rowDiff < 0 ? Coordinates.Row + i : Coordinates.Row - i;
var column = columnDiff == 0 ? Coordinates.Column : columnDiff < 0 ? Coordinates.Column + i : Coordinates.Column - i;
if (column > 7)
column = 7;
if (column < -7)
column = -7;
if (row > 7)
row = 7;
if (row < -7)
row = -7;
if (position[row, column] != null)
return true;
}
return position[square] != null && position[square].Color == Color;
}
protected bool IsCapture(BoardCoordinates square, ChessPosition position)
{
return position[square] != null && position[square].Color != Color;
}
public IEnumerable<BoardCoordinates> LegalMoves(ChessPosition position)
{
for (int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
var square = new BoardCoordinates(r, c);
if (CanMakeMove(square, position))
{
yield return square;
}
}
}
}
public abstract IChessPiece Copy();
private bool CanMakeMove(BoardCoordinates to, ChessPosition position)
{
return !Coordinates.Equals(to) && IsMoveLegal(to, position);
}
private void MakeMove(BoardCoordinates to, ChessPosition position)
{
ChessMove move = new ChessMove(Coordinates, to, this);
OnMoveMade(move, position);
Coordinates = to;
}
protected virtual void OnMoveMade(ChessMove move, ChessPosition position)
{
MoveMade?.Invoke(move);
}
}
}
|
525570d2eb291190b17b4a2a7da4f5542ce9058f
|
C#
|
hetzermj/AutomationBaseFramework
|
/APITestBase/DummyEmployeeAPIBase.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using APITestBase.DataObjects;
using Newtonsoft.Json;
using RestSharp;
namespace APITestBase
{
public class DummyEmployeeAPIBase
{
const string BaseUrl = "http://dummy.restapiexample.com/";
readonly IRestClient _client;
//string _accountSid;
public DummyEmployeeAPIBase()
{
_client = new RestClient(BaseUrl);
}
public T Execute<T>(RestRequest request) where T : new()
{
IRestResponse<T> response = _client.Execute<T>(request);
var objectToReturn = JsonConvert.DeserializeObject<T>(response.Content);
return objectToReturn;
}
public Employee GetEmployee(string employeeID)
{
var request = new RestRequest("http://dummy.restapiexample.com/api/v1/employee/{EmployeeID}");
request.AddParameter("EmployeeID", employeeID, ParameterType.UrlSegment);
return Execute<Employee>(request);
}
}
}
|
9a40ee98856ccdada85f72cbc975578212d2c4be
|
C#
|
Meir-Shtarkman/BackEndSadna
|
/Classes/MultiplayerMatch.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UsefullMethods;
namespace Classes
{
public class MultiplayerMatch
{
private string MultiplayerMatchID { get; set; }
private List<User> PlayersList { get; set; }
private List<Round> RoundsList { get; set; }
private List<int> ScoreList { get; set; }
public MultiplayerMatch(string i_MultiplayerMatchId, List<User> i_PlayersList, List<Round> i_RoundsList, List<int> i_ScoreList)
{
MultiplayerMatchID = i_MultiplayerMatchId;
PlayersList = i_PlayersList;
RoundsList = i_RoundsList;
ScoreList = i_ScoreList;
}
public MultiplayerMatch(List<User> i_PlayersList, List<Round> i_RoundsList, List<int> i_ScoreList)
{
MultiplayerMatchID = "multiplayerMatch_" + SystemTools.RandomString();
PlayersList = i_PlayersList;
RoundsList = i_RoundsList;
ScoreList = i_ScoreList;
}
}
}
|
b0b2d81e51eba463e21198ccd1bde79f256a3d1f
|
C#
|
Vietcuong0508/Lab_Rider
|
/Ex5/Program.cs
| 3.6875
| 4
|
using System;
namespace Ex5
{
internal class Program
{
public static void Main(string[] args)
{
{
for (int num = 1; num < 21; num++)
{
Console.WriteLine("Factorial of "
+ num + " is " + factorial(num));
}
}
}
static long factorial(long n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
}
}
|
da7fba75762f3701331ca6171c3e93ec9664f5f4
|
C#
|
danwatland/FiascoRL
|
/FiascoRL/Display/SpriteGraphic.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using FiascoRL.Entities;
namespace FiascoRL.Display
{
/// <summary>
/// Collection of utility methods and variables used for processing graphics drawn to the screen.
/// </summary>
public static class SpriteGraphic
{
public static Texture2D Icons { get; private set; }
public static Texture2D Effects24 { get; private set; }
public static Texture2D Effects32 { get; private set; }
public static Texture2D Items { get; private set; }
public static Texture2D World { get; private set; }
public static Texture2D Creatures { get; private set; }
/// <summary>
/// Load all textures used by the game into memory.
/// </summary>
/// <param name="game">Game to load textures for.</param>
public static void Initialize(Game game)
{
Icons = game.Content.Load<Texture2D>("oryx_16bit_fantasy_classes_trans");
Effects24 = game.Content.Load<Texture2D>("oryx_16bit_fantasy_fx_trans");
Effects32 = game.Content.Load<Texture2D>("oryx_16bit_fantasy_fx_trans");
Items = game.Content.Load<Texture2D>("oryx_16bit_fantasy_items_trans");
World = game.Content.Load<Texture2D>("oryx_16bit_fantasy_world_trans");
Creatures = game.Content.Load<Texture2D>("oryx_16bit_fantasy_creatures_trans");
}
public static Rectangle GetSprite(Texture2D texture, int index)
{
if (texture == World || texture == Creatures || texture == Effects24)
{
return Get24By24(texture, index);
}
else if (texture == Items)
{
return Get16By16(texture, index);
}
else if (texture == Effects32)
{
return Get32By32Effect(texture, index);
}
else
{
throw new InvalidOperationException("Texture not recognized.");
}
}
/// <summary>
/// Draws healthbars for each creature.
/// </summary>
/// <param name="spriteBatch"></param>
/// <param name="c"></param>
public static void DrawHealthBar(SpriteBatch spriteBatch, FiascoGame game, Creature c)
{
var texture = new Texture2D(game.GraphicsDevice, 1, 1);
texture.SetData(new Color[] { Color.White });
if (c.HP.Current < c.HP.Max)
{
int length = (int)(((double)c.HP.Current / c.HP.Max) * 24);
spriteBatch.Draw(texture, new Rectangle(c.Coords.X * 24, c.Coords.Y * 24 + 22, 24, 2), Color.Red);
spriteBatch.Draw(texture, new Rectangle(c.Coords.X * 24, c.Coords.Y * 24 + 22, length, 2), Color.Lime);
}
}
/// <summary>
/// Return a rectangle representing the specified sprite from a 24x24 spritesheet.
/// </summary>
/// <param name="texture">Spritesheet to be used.</param>
/// <param name="index">Index of sprite.</param>
/// <returns></returns>
private static Rectangle Get24By24(Texture2D texture, int index)
{
int numColumns = texture.Width / 24 - 2;
// World spritesheet does not line up exactly.
if (texture == World)
{
numColumns++;
}
else if (texture == Effects24)
{
numColumns = 10;
}
int row = 1 + index / numColumns;
int col = 1 + index % numColumns;
return new Rectangle(col * 24, row * 24, 24, 24);
}
/// <summary>
/// Return a rectangle representing the specified sprite from a 16x16 spritesheet.
/// </summary>
/// <param name="texture">Spritesheet to be used.</param>
/// <param name="index">Index of sprite.</param>
/// <returns></returns>
private static Rectangle Get16By16(Texture2D texture, int index)
{
int numColumns = texture.Width / 16 - 2;
int row = 1 + index / numColumns;
int col = 1 + index % numColumns;
return new Rectangle(col * 16, row * 16, 16, 16);
}
private static Rectangle Get32By32Effect(Texture2D texture, int index)
{
int row = index / 8;
int col = index % 8;
return new Rectangle(col * 32 + 287, row * 32 + 32, 32, 32);
}
}
}
|
da42288cba1b21ccd22c7bf9d96e3f65aedc2b95
|
C#
|
NewLifeWorks/Software_-Bulgaria
|
/Software_University_Bulgaria/Open_Courses/Data_Structures/Other_Source_partII/07.Lesson.SimpleArray/Program.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _07.Lesson.SimpleStack
{
class Program
{
static void Main(string[] args)
{
// Stack One <> ID values
Stack<int> values = new Stack<int>();
values.Push(10);
values.Push(20);
int twenty = values.Pop();
int ten = values.Pop();
// Stack One <> ID secondValues
Stack<int> secondValues = new Stack<int>();
secondValues.Push(30);
secondValues.Push(40);
int thirthy = secondValues.Pop();
int fourty = secondValues.Pop();
foreach (var TheValue in values)
{
Console.WriteLine(TheValue);
if (TheValue == 0)
{
Console.WriteLine("Stack can not be empty");
}
else
{
Console.WriteLine("{0}",secondValues);
}
}
}
}
}
|
08763cbc0f4be5bde4331a58a9597db2f066db00
|
C#
|
nickworonekin/PPFVoicePatternEditor
|
/PPFVoicePatternEditor/PPFVoicePatternEditor.cs
| 2.75
| 3
|
/*
* PPF Voice Pattern Editor v3.0
* Written by Nick Woronekin
* <http://puyonexus.net>
*
* This program allows you to change the voice patterns in
* Puyo Puyo Fever PC and Puyo Puyo Fever 2 PS2.
*
* This program is being released as open source with no
* specific license. Feel free to do whatever you want to do
* with it, as long as you do not claim that it is your program.
* If you're distrubuting this program, or any modifications of it,
* I would like it if you would mention my name, but I do not
* require it. Anyway, enjoy this program!
*
*/
using System;
using System.Windows.Forms;
namespace PPFVoicePatternEditor
{
public class PPFVoicePatternEditor
{
public const string ProgramName = "PPF Voice Pattern Editor";
public const string ProgramVersion = "3.0";
public const string ProgramCopyright = "© 2008-2012 Nick Woronekin";
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainWindow());
}
}
}
|
e4ce970ad660b415105d0b00f58cca60a5c19b3e
|
C#
|
wi16b046/CodingDojo4
|
/Client/Communication/ClientObj.cs
| 3.203125
| 3
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client.ViewModel
{
class ClientObj
{
Socket clientSocket;
byte[] buffer = new byte[1024];
//Delegate for informing about receiving messages
Action<string> MessageInformer;
//Delegate for informing about aborting the connection
Action AbortInformer;
public ClientObj(string ip, int port, Action<string> messageInformer, Action abortInformer)
{
MessageInformer = messageInformer;
AbortInformer = abortInformer;
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(ip), port);
clientSocket = client.Client;
StartReceiving();
}
public void Send(string message)
{
if (clientSocket != null)
clientSocket.Send(Encoding.UTF8.GetBytes(message));
}
private void StartReceiving()
{
Task.Factory.StartNew(Receive);
}
private void Receive()
{
string message;
do
{
int length = clientSocket.Receive(buffer);
message = Encoding.UTF8.GetString(buffer, 0, length);
MessageInformer(message);
} while (message != "@quit");
Close();
}
private void Close()
{
clientSocket.Close();
AbortInformer();
}
}
}
|
d05495d1b8caf4f8ab80c1c804fdc38aa28cbcad
|
C#
|
shendongnian/download4
|
/latest_version_download2/123788-24544927-68628704-2.cs
| 2.703125
| 3
|
public class Trade
{
}
public class PositionNTS
{
public virtual void Adjust(Trade newfill)
{
}
}
public class Position : PositionNTS
{
private readonly object locker = new object();
public override void Adjust(Trade newfill)
{
lock (locker)
{
base.Adjust(newfill);
}
}
}
|
112503c2608053ed74374f496c320d7b223e204c
|
C#
|
shendongnian/download4
|
/code5/902192-22494784-60723102-2.cs
| 3.15625
| 3
|
private void btn_proceed_Click(object sender, EventArgs e)
{
// This dictionary contains indices of rows we need to replace.
Dictionary<int, int> replaceable = new Dictionary<int, int>();
replaceable.Add(4, 1);
replaceable.Add(7, 5);
replaceable.Add(13, 11);
string input = String.Empty;
OpenFileDialog pfdg = new OpenFileDialog();
if (pfdg.ShowDialog() == DialogResult.OK)
{
input = pfdg.FileName;
}
// I placed the result into the another file called result.txt. You can use output path as same as input to overwrite the file.
ReplaceLines(replaceable, input, @"C:\Users\Wallstrider\Documents\Visual Studio 2010\Projects\result.txt");
}
/// <summary>
/// Replaces lines of the file depends on 9th item is exist.
/// </summary>
/// <param name="replaceable">Rows incides to replace.</param>
/// <param name="input_path">Path to the input file.</param>
/// <param name="output_path">Path to the output file.</param>
private void ReplaceLines(Dictionary<int, int> replaceable, string input_path, string output_path)
{
if (File.Exists(input_path))
{
string file;
file = new StreamReader(input_path).ReadToEnd();
string[] lines = file.Split(new char[] { '\n' });
List<string[]> split_data = new List<string[]>();
for (int i = 0; i < lines.Length; i++)
split_data.Add(lines[i].Split(','));
List<int> allowed_for_replace_indices = new List<int>();
List<int> not_allowed_for_replace_indices = new List<int>();
// Check if the row has the value of 9th item then we are allowed to replace rows.
for (int i = 1; i < split_data.Count; i++)
{
if (split_data[i][9] != String.Empty)
allowed_for_replace_indices.Add(i);
else
not_allowed_for_replace_indices.Add(i);
}
List<int> rows_replaced = new List<int>();
List<int> rows_not_replaced = new List<int>();
// Loop through our replaceable indices dictionary.
for (int i = 0; i < replaceable.Count; i++)
{
int key = replaceable.ElementAt(i).Key;
int value = replaceable.ElementAt(i).Value;
// if both rows have 9th item then we can start replacement.
if (allowed_for_replace_indices.Contains(key) && allowed_for_replace_indices.Contains(value))
{
string temp = lines[value];
lines[value] = lines[key];
lines[key] = temp;
rows_replaced.Add(key);
rows_replaced.Add(value);
}
else
{
rows_not_replaced.Add(key);
rows_not_replaced.Add(value);
}
}
using (StreamWriter sw = new StreamWriter(output_path))
{
for (int i = 0; i < lines.Length; i++)
sw.WriteLine(lines[i]);
sw.Flush();
sw.Close();
}
MessageBox.Show("Rows replaced: " + String.Join("; ", rows_replaced.ToArray()) + " .\nRows not replaced: " + String.Join("; ", rows_not_replaced.ToArray()) + ".\nComplete.");
}
}
|
13af66cca61d808f4199a0216902449e8de1ad38
|
C#
|
angew74/GestionePEC
|
/FaxPec.Model/ManagedModules/ModuleParts/DatiComuniRichiesta.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Com.Unisys.Pdf.ManagedModules.ModuleParts
{
/// <summary>
/// Classe che espone i dati "più comuni" relativi alla richiesta.
/// Dipendentemente dal tipo specifico di richiesta i dati possono
/// essere presenti o meno.
/// </summary>
public class DatiComuniRichiesta
{
/// <summary>
///
/// </summary>
public virtual string Cognome { get; set; }
/// <summary>
///
/// </summary>
public virtual string Nome { get; set; }
/// <summary>
///
/// </summary>
public virtual string CodiceFiscale { get; set; }
/// <summary>
///
/// </summary>
public virtual string GiornoNascita { get; set; }
/// <summary>
///
/// </summary>
public virtual string MeseNascita { get; set; }
/// <summary>
///
/// </summary>
public virtual string AnnoNascita { get; set; }
/// <summary>
///
/// </summary>
public string DataDiNascita
{
get
{
string ddn = String.Format("{0}/{1}/{2}",
!string.IsNullOrEmpty(GiornoNascita) ? GiornoNascita : "00",
!string.IsNullOrEmpty(MeseNascita) ? MeseNascita : "00",
AnnoNascita);
// salta solo se anno non presente
return (ddn.Length != 10) ? string.Empty : ddn;
}
}
/// <summary>
///
/// </summary>
public virtual string Sesso { get; set; }
/// <summary>
///
/// </summary>
public virtual string TestoLibero { get; set; }
/// <summary>
/// Proprietà in sola lettura che riepiloga i dati.
/// </summary>
public string FullText
{
get
{
string t = "";
t += (!string.IsNullOrEmpty(Cognome)) ? Cognome + " " : "";
t += (!string.IsNullOrEmpty(Nome)) ? Nome + " " : "";
t += (!string.IsNullOrEmpty(CodiceFiscale)) ? CodiceFiscale + " " : "";
t += (!string.IsNullOrEmpty(DataDiNascita)) ? DataDiNascita + " " : "";
t += (!string.IsNullOrEmpty(TestoLibero)) ? TestoLibero : "";
return t.Trim();
}
}
/// <summary>
/// Proprietà in sola lettura che indica se i dati sono empty.
/// </summary>
public bool IsEmpty
{
get
{
return (string.IsNullOrEmpty(Cognome)
&& string.IsNullOrEmpty(Nome)
&& string.IsNullOrEmpty(CodiceFiscale)
&& string.IsNullOrEmpty(DataDiNascita));
}
}
}
}
|
fbbdf9c8dcfc273f05682ca8d2075c13e36ce337
|
C#
|
briansalato/InnerTrack
|
/InnerTrack.Common/Interfaces/Logic/IProjectLogic.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InnerTrack.Common.Objs;
namespace InnerTrack.Common.Interfaces.Logic
{
public interface IProjectLogic
{
/// <summary>
/// Returns a single project
/// </summary>
/// <param name="id">The id of the project to find</param>
/// <returns>A project or null if no project has that Id</returns>
ProjectObj Get(int id);
/// <summary>
/// Returns all projects owned by a user
/// </summary>
/// <param name="owner">The username to find projects for</param>
/// <returns>This will return a blank list if no projects are found, or the list of projects if there are some</returns>
IList<ProjectObj> GetByOwner(string username);
/// <summary>
/// Adds a new entry to the project table
/// </summary>
/// <param name="proj">The item to add</param>
/// <param name="username">The username of who is taking this action</param>
/// <returns>
/// The Id of the created item or -1 if no item was created
/// </returns>
int Create(ProjectObj proj, string username);
/// <summary>
/// Updates an entry in the project table
/// </summary>
/// <param name="proj">The item to update. It will be updated based on it's Id</param>
/// <param name="username">The username of who is taking this action</param>
/// <returns>True if the Id was found and the entry updated, or false if the Id was not found or the entry not able to be updated</returns>
bool Update(ProjectObj proj, string username);
/// <summary>
/// Get all projects in the repository
/// </summary>
/// <returns>This will return a blank list if no projects are found, or the list of projects if there are some</returns>
IList<ProjectObj> GetAll();
/// <summary>
/// Returns the search data for the query
/// </summary>
/// <param name="query">The query.</param>
/// <param name="curPage">The cur page.</param>
/// <param name="pageSize">Size of the page.</param>
/// <returns></returns>
SearchResult<ProjectObj> Search(string query, int curPage, int pageSize);
}
}
|
73de4dc2b2ace03f3365f19a5817204a9a9e8eb1
|
C#
|
bmdevx/Ternary
|
/Core/_OLD/Chips/IChip.cs
| 2.65625
| 3
|
using System;
using System.Diagnostics;
using System.Linq;
using Ternary.Tools;
namespace Ternary.Old
{
[DebuggerDisplay("{DebuggerInfo}")]
public abstract class IChip : IMultiIOComponent
{
public abstract int NUMBER_OF_PINS { get; }
public ComponentTriggeredEvent[] Outputs { get; }
public ComponentTriggeredEvent[] Inputs { get; }
protected Trit[] PinStates { get; }
protected string PinOutOfRange => $"Pin must be in range of 0 to {NUMBER_OF_PINS - 1}";
internal string DebuggerInfo => ToString();
public string ComponentName { get; internal set; }
public IChip()
{
Outputs = new ComponentTriggeredEvent[NUMBER_OF_PINS];
Inputs = new ComponentTriggeredEvent[NUMBER_OF_PINS];
PinStates = new Trit[NUMBER_OF_PINS];
}
public Trit PinState(int pin)
{
if (pin >= NUMBER_OF_PINS || pin < 0)
throw new IndexOutOfRangeException(PinOutOfRange);
return PinStates[pin];
}
public void Input(int pin, Trit trit, object sender = null)
{
if (pin >= NUMBER_OF_PINS || pin < 0)
throw new IndexOutOfRangeException(PinOutOfRange);
Inputs[pin]?.Invoke(sender ?? this, trit);
}
protected void Output(int pin, Trit trit, object sender = null)
{
if (pin >= NUMBER_OF_PINS || pin < 0)
throw new IndexOutOfRangeException(PinOutOfRange);
Outputs[pin]?.Invoke(sender ?? this, trit);
}
public ComponentTriggeredEvent this[int pin]
{
get {
return (NUMBER_OF_PINS > pin && pin > -1) ? Inputs[pin] :
throw new IndexOutOfRangeException(PinOutOfRange);
}
set {
if (NUMBER_OF_PINS > pin && pin > -1) Outputs[pin] += value;
else throw new IndexOutOfRangeException(PinOutOfRange);
}
}
public override string ToString()
{
return String.Join(" | ", Create.NewTryteSizedArray(i => $"{i}: {PinStates[i].ToSymbol()}"));
}
}
}
|
50ec9bc7441256752d9dd3dc29b0bd8697db92a2
|
C#
|
Varbanov/TelerikAcademy
|
/C# Part 1/001. Introduction to programming/09. Members of a sequence/SequenceMembers.cs
| 3.6875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class SequenceMembers
{
//Write a program that prints the first 10 members of the sequence: 2, -3, 4, -5, 6, -7, ...
static void Main()
{
for (int i = 2; i < 12; i++)
{
int num = i * (int) Math.Pow(-1, i);
Console.Write("{0}, ", num);
}
}
}
|
e016ed46be55f81f654c18978c3fb46bfcc1c246
|
C#
|
babann/HOPE
|
/Receptors/HuntTheWumpus/CaveReceptor/CaveReceptor.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Clifton.ExtensionMethods;
using Clifton.Receptor.Interfaces;
using Clifton.SemanticTypeSystem.Interfaces;
namespace HuntTheWumpus
{
public class CaveReceptor : BaseReceptor
{
public override string Name { get { return "Cave"; } }
protected Guid id;
protected int caveNumber;
protected int[] caveNeighbors;
protected bool hasBottomlessPit;
protected bool hasSuperBats;
protected bool hasWumpus;
protected bool hasPlayer;
protected Random rnd;
protected bool HasItemOfInterest
{
get { return hasBottomlessPit || hasSuperBats || hasWumpus; }
}
public CaveReceptor(IReceptorSystem rsys)
: base(rsys)
{
AddReceiveProtocol("HW_YouAre", (signal) => signal.ID == id);
AddReceiveProtocol("HW_MoveTo", (signal) => signal.FromCaveNumber == caveNumber || signal.NewCaveNumber == caveNumber);
AddReceiveProtocol("HW_ShootInto", (signal) => signal.CaveNumber == caveNumber);
AddEmitProtocol("HW_WhereAmI");
AddEmitProtocol("HW_Player");
AddEmitProtocol("Text");
caveNeighbors = new int[3];
rnd = new Random();
}
public override void Initialize()
{
base.Initialize();
id = Guid.NewGuid();
CreateCarrier("HW_WhereAmI", (signal) => signal.ID = id);
}
public override void ProcessCarrier(ICarrier carrier)
{
// Is it the "You are here" protocol?
if (carrier.Protocol.DeclTypeName == "HW_YouAre")
{
// Save our cave # and neighbor cave numbers.
caveNumber = carrier.Signal.CaveNumber;
caveNeighbors[0] = carrier.Signal.AdjoiningCave1;
caveNeighbors[1] = carrier.Signal.AdjoiningCave2;
caveNeighbors[2] = carrier.Signal.AdjoiningCave3;
hasBottomlessPit = carrier.Signal.HasBottomlessPit;
hasSuperBats = carrier.Signal.HasSuperBats;
hasWumpus = carrier.Signal.HasWumpus;
hasPlayer = carrier.Signal.HasPlayer;
// Configure emitters and listeners.
UpdateEmitters();
UpdateListeners();
if (hasPlayer)
{
SayWhoIsNextToUs();
AskAboutOurNeighbors();
TalkToPlayer();
}
}
else if (carrier.Protocol.DeclTypeName.StartsWith("HW_Announce"))
{
if (hasBottomlessPit)
{
CreateCarrier("Text", (outSignal) => outSignal.Value = "I feel a draft!");
}
if (hasSuperBats)
{
CreateCarrier("Text", (outSignal) => outSignal.Value = "I hear flapping!");
}
if (hasWumpus)
{
CreateCarrier("Text", (outSignal) => outSignal.Value = "I smell a Wumpus!");
}
}
else if (carrier.Protocol.DeclTypeName == "HW_MoveTo")
{
if (carrier.Signal.NewCaveNumber == caveNumber)
{
hasPlayer = true;
if (CheckCaveState())
{
SayWhoIsNextToUs();
AskAboutOurNeighbors();
TalkToPlayer();
}
}
else
{
hasPlayer = false;
}
}
else if (carrier.Protocol.DeclTypeName == "HW_ShootInto")
{
if (hasPlayer)
{
CreateCarrier("Text", (outSignal) => outSignal.Value = "Ouch! You shot yourself!!!!!!!!");
CreateCarrier("HW_GameState", (outSignal) => outSignal.PlayerShotSelf = true);
}
// This is my cave the hunter is shooting into!
else if (hasWumpus)
{
CreateCarrier("Text", (outSignal) => outSignal.Value = "Ouch! You shot the Wumpus!!!!!!!!");
CreateCarrier("HW_GameState", (outSignal) => outSignal.WumpusIsDead = true);
}
else
{
int arrowLife = carrier.Signal.RemainingLife;
--arrowLife;
if (arrowLife > 0)
{
// The arrow continues to a random room.
CreateCarrier("HW_ShootInto", (signal) =>
{
signal.CaveNumber = caveNeighbors[rnd.Next(3)];
signal.RemainingLife = arrowLife;
});
}
}
}
}
protected void UpdateEmitters()
{
// I will make ask my neighbors to announce interesting things about themselves.
caveNeighbors.ForEach(cn =>
{
AddEmitProtocol("HW_Announce" + cn);
});
}
protected void UpdateListeners()
{
// I will respond to an announcement request.
AddReceiveProtocol("HW_Announce" + caveNumber);
}
protected void AskAboutOurNeighbors()
{
caveNeighbors.ForEach(cn => CreateCarrier("HW_Announce" + cn, (signal) => { }));
}
protected void SayWhoIsNextToUs()
{
CreateCarrier("Text", (outSignal) => outSignal.Value = "\r\nYou are in cave number "+caveNumber);
CreateCarrier("Text", (outSignal) => outSignal.Value = "Passages lead to " + String.Join(", ", caveNeighbors.Select(cn => cn.ToString())));
}
protected void TalkToPlayer()
{
CreateCarrier("HW_Player", (outSignal) =>
{
outSignal.CaveNumber = caveNumber;
outSignal.AdjoiningCave1 = caveNeighbors[0];
outSignal.AdjoiningCave2 = caveNeighbors[1];
outSignal.AdjoiningCave3 = caveNeighbors[2];
});
}
protected bool CheckCaveState()
{
bool ret = !(hasSuperBats || hasWumpus || hasBottomlessPit);
// Nothing save you from the Wumpus. Test first.
if (hasWumpus)
{
// In the original game, I believe bumping into a wumpus woke him and he either ate you
// or moved to another room.
CreateCarrier("Text", (outSignal) => outSignal.Value = "gnom, gnom, crunch! You've been eaten by the Wumpus!!!!!!!");
CreateCarrier("HW_GameState", (outSignal) => outSignal.PlayerEatenByWumpus = true);
}
else if (hasSuperBats)
{
// Bats will save you from a bottomless pit.
CreateCarrier("Text", (outSignal) => outSignal.Value = "Super-Bat Snatch!!!!!!!");
CreateCarrier("HW_GameState", (outSignal) => outSignal.SuperBatSnatch = true);
}
else if (hasBottomlessPit)
{
CreateCarrier("Text", (outSignal) => outSignal.Value = "AAAAAYYYYyyyyyeeeeeee You fell into a bottomless pit!!!!!!!");
CreateCarrier("HW_GameState", (outSignal) => outSignal.PlayerFellIntoPit = true);
}
return ret;
}
}
}
|
d617eaeb1381267dd6e92101a908e1b742f5d6bf
|
C#
|
inakama/SmallWorld
|
/Services.Test/SmallWorldServiceTest.cs
| 2.953125
| 3
|
using System.Collections.Generic;
using NUnit.Framework;
using SmallWorld.Service.Dtos;
using SmallWorld.Service.Services;
namespace Services.Test
{
public class SmallWorldServiceTest
{
private SmallWorldService smallWorldService;
[SetUp]
public void Setup()
{
this.smallWorldService = new SmallWorldService();
}
[Test]
public void When_ThereAreNoPoints_Expect_NoResults()
{
List<PointInputDto> inputPoints = new List<PointInputDto>();
var closestPoints = this.smallWorldService.GetClosestPoints(inputPoints);
Assert.AreEqual(closestPoints.Count, 0);
}
[Test]
public void When_ThereIsOnlyOnePoint_Expect_NoResults()
{
List<PointInputDto> inputPoints = new List<PointInputDto>() { new PointInputDto() { Id = 1, XCoordinate = 0, YCoordinate = 0 } };
var closestPoints = this.smallWorldService.GetClosestPoints(inputPoints);
Assert.AreEqual(closestPoints[0].ClosestPoints.Length, 0);
}
[Test]
public void When_ThereAreLessThanFivePoints_Expect_EachPointHasLessThanThreePoints()
{
List<PointInputDto> inputPoints = new List<PointInputDto>()
{
new PointInputDto() { Id = 1, XCoordinate = 0, YCoordinate = 0 },
new PointInputDto() { Id = 2, XCoordinate = 1, YCoordinate = 1 }
};
var closestPoints = this.smallWorldService.GetClosestPoints(inputPoints);
Assert.AreEqual(closestPoints.Count, 2);
Assert.AreEqual(closestPoints[0].ClosestPoints.Length, 1);
Assert.AreEqual(closestPoints[0].ClosestPoints[0], 2);
Assert.AreEqual(closestPoints[1].ClosestPoints.Length, 1);
Assert.AreEqual(closestPoints[1].ClosestPoints[0], 1);
}
[Test]
public void When_PointOneThreeAndTwoAreTheClosestFromPointFourInThatOrder_Expect_OnlyThosePointsAreIncludedInTheSameOrder()
{
List<PointInputDto> inputPoints = new List<PointInputDto>()
{
new PointInputDto() { Id = 1, XCoordinate = 1, YCoordinate = 1 },
new PointInputDto() { Id = 2, XCoordinate = 3, YCoordinate = 3 },
new PointInputDto() { Id = 3, XCoordinate = 2, YCoordinate = 2 },
new PointInputDto() { Id = 4, XCoordinate = 0, YCoordinate = 0 },
new PointInputDto() { Id = 5, XCoordinate = 4, YCoordinate = 4 }
};
var closestPoints = this.smallWorldService.GetClosestPoints(inputPoints);
var pointFour = closestPoints.Find(x => x.PointId == 4);
Assert.AreEqual(pointFour.ClosestPoints.Length, 3);
Assert.AreEqual(pointFour.ClosestPoints[0], 1);
Assert.AreEqual(pointFour.ClosestPoints[1], 3);
Assert.AreEqual(pointFour.ClosestPoints[2], 2);
}
}
}
|
7aa10e69c49f9e385b88f5133e28e7ef34d82af8
|
C#
|
matiascc/TP4
|
/Ej2/Program.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ej2
{
class Program
{
static void Main(string[] args)
{
double num1, num2;
Fachada fachada = new Fachada();
Console.Write("Ingrese el primer numero: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
Console.Write("Ingrese el segundo numero: ");
num2 = Convert.ToDouble(Console.ReadLine());
try
{
Console.WriteLine(fachada.Dividir(num1, num2)); //Intenta dividir los 2 nº.
}
catch(DivisionPorCeroException exc)
{
Console.WriteLine("No se puede dividir por cero. \n {0}", exc); //Si se detecta la excepcion DivisionPorCeroException se escribe un msj y se incluye los datos de la excepcion.
}
Console.ReadLine();
}
}
}
|
94c75b0b4cc6a8f34115cc8a7f747d6790946707
|
C#
|
Snjeza2104/Learning-C-
|
/Proizvod/Proizvod/Program.cs
| 3.109375
| 3
|
using System;
using System.Collections;
namespace Proizvod
{
class Program
{
static void Main(string[] args)
{
string naziv;
double cijena;
double marza;
double porez;
//Proizvod proizvod = new Proizvod();
naziv = Console.ReadLine();
Console.WriteLine("Unesi cijenu proizvoda: ");
cijena = double.Parse(Console.ReadLine());
//proizvod.Cijena = double.Parse(Console.ReadLine());
Console.WriteLine("Unesi maržu proizvoda: ");
marza = double.Parse(Console.ReadLine());
//proizvod.Marza = double.Parse(Console.ReadLine());
Console.WriteLine("Unesi porez: ");
porez = double.Parse(Console.ReadLine());
//proizvod.Porez = double.Parse(Console.ReadLine());
Proizvod proizvod = new Proizvod(naziv, cijena, marza, porez);
Console.WriteLine(proizvod.MPC());
proizvod.MPC();
Console.WriteLine(Proizvod.br);
naziv = Console.ReadLine();
/*
if (proizvod.setNaziv(naziv))
Console.WriteLine("OK");
else
Console.WriteLine("False");
*/
Console.WriteLine(proizvod.getNaziv());
proizvod.setNaziv(naziv);
Console.WriteLine(proizvod.getNaziv());
}
}
class Proizvod
{
string Naziv;
double Cijena;
double Marza;
double Porez;
public static int br=0;
public Proizvod()
{
}
public Proizvod(string naziv, double cijena, double marza, double porez)
{
this.Naziv = naziv;
this.Cijena = cijena;
this.Marza = marza;
this.Porez = porez;
}
public double MPC()
{
br++;
return this.Cijena + this.Marza + this.Porez;
}
//Promjena private vrijednosti
public bool setNaziv(string noviNaziv)
{
if (noviNaziv.Length < 10)
{
this.Naziv = noviNaziv;
return true;
}
return false;
}
public string getNaziv()
{
return this.Naziv;
}
}
}
|
226a4a1ccb5ecfeb3985cb9081540fbeb60b8637
|
C#
|
thegrubbsian/MongoDBCSharpDemo
|
/NoRMaticSample/Article.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using NoRMatic;
namespace NoRMaticSample {
public class Article : NoRMaticModel<Article> {
[Required, StringLength(50, MinimumLength = 5)]
public string Title { get; set; }
[Required]
public string Body { get; set; }
[Required]
public string Author { get; set; }
public DateTime DatePosted { get; set; }
private List<Comment> _comments = new List<Comment>();
[ValidateChild]
public List<Comment> Comments {
get { return _comments; }
set { _comments = value; }
}
}
public class Comment {
public DateTime DateAdded { get; set; }
[Required]
public string CommentersName { get; set; }
[Required]
public string Body { get; set; }
}
}
|
9d9baec3486b869ccaee083d96e987fff9c059a3
|
C#
|
letscodewithkalyan/AndroidMLVoiceApp
|
/Voice_App/Voice_App/Adapters/VoiceTextAdapter.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
namespace Voice_App.Adapters
{
public class VoiceTextAdapter : RecyclerView.Adapter
{
List<VoiceString> speechStrings;
const int LEFT_ITEM = 1;
const int RIGHT_ITEM = 2;
Activity context;
public VoiceTextAdapter(Activity context,List<VoiceString> speechStrings)
{
this.context = context;
this.speechStrings = speechStrings;
}
public override int GetItemViewType(int position)
{
if(speechStrings[position].IsFromUser)
{
return RIGHT_ITEM;
}
else
{
return LEFT_ITEM;
}
}
public override int ItemCount => speechStrings?.Count ?? 0;
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if(holder.ItemViewType == RIGHT_ITEM)
{
var rightSideViewHolder = (RightSideViewHolder)holder;
rightSideViewHolder.RightTextView.Text = speechStrings[position].VoiceLabel;
}
else
{
var leftSideViewHolder = (LeftSideViewHolder)holder;
leftSideViewHolder.LeftTextView.Text = speechStrings[position].VoiceLabel;
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
if(viewType == RIGHT_ITEM)
{
var rightCellView = context.LayoutInflater.Inflate(Resource.Layout.listitem_rightcellview, parent, false);
return new RightSideViewHolder(rightCellView);
}
else
{
var leftCellView = context.LayoutInflater.Inflate(Resource.Layout.listitem_leftcellview, parent, false);
return new LeftSideViewHolder(leftCellView);
}
}
class RightSideViewHolder:RecyclerView.ViewHolder
{
public TextView RightTextView;
public RightSideViewHolder(View view):base(view)
{
RightTextView = view.FindViewById<TextView>(Resource.Id.rightTextView);
}
}
class LeftSideViewHolder : RecyclerView.ViewHolder
{
public TextView LeftTextView;
public LeftSideViewHolder(View view):base(view)
{
LeftTextView = view.FindViewById<TextView>(Resource.Id.leftTextView);
}
}
}
}
|
d65c56b9e409db03abd3ef2005ede22e2d6ce9ec
|
C#
|
theajanvin/Admin_Bestilling
|
/oblig1-1/DAL/BestillingRepository.cs
| 2.65625
| 3
|
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using oblig1_1.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Globalization;
using Serilog;
namespace oblig1_1.DAL
{
public class BestillingRepository : IBestillingRepository
{
private readonly BestillingContext _db;
public BestillingRepository(BestillingContext db)
{
_db = db;
}
[HttpPost]
public async Task<List<Bestillinger>> Index()
{
try
{
List<Bestillinger> alleBestillinger = await _db.Bestillinger.Select(best => new Bestillinger
{
ID = best.ID,
Kunde = best.Kunde,
Pris = best.Pris,
Tur = best.Tur,
Retur = best.Retur
}).ToListAsync();
return alleBestillinger;
}
catch (Exception e)
{
Log.Error("Error i Index: {error}", e);
return null;
}
}
public async Task<List<RuteAvgang>> VisAlleRuteAvganger()
{
List<RuteAvgang> ruteavganger = await _db.RuteAvganger.ToListAsync();
return ruteavganger;
}
private bool SammeDato(DateTime dato1, DateTime dato2)
{
Console.WriteLine(dato1 + ", " + dato2);
return dato1.Year == dato2.Year && dato1.Month == dato2.Month && dato1.Day == dato2.Day;
}
//Returnere en liste med ruteavganger
public List<RuteAvgang> FinnEnRuteAvgang(string[] holdeplasserOgDato) //kan ikke være async pga where
{
JsonSerializerOptions serializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
try
{
Holdeplass fra = JsonSerializer.Deserialize<Holdeplass>(holdeplasserOgDato[0], serializerOptions);
Holdeplass til = JsonSerializer.Deserialize<Holdeplass>(holdeplasserOgDato[1], serializerOptions);
Console.WriteLine(fra.ToString() + ", " + til.ToString());
DateTime date = DateTime.ParseExact(holdeplasserOgDato[2], "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(date);
List<RuteAvgang> ruteavganger = new List<RuteAvgang>();
List<Rute> potensielleRuter = new List<Rute>();
//1.Finne rutestopp der holdeplassID tilsvarer holdeplass fraID
//2.Loope rutestopplisten, inni loopen så leter vi etter rutestopp med samme ruteID, som har holdeplassID tilsvarende tilID
//rekkefølgenr større enn fraID sitt rekkefølgenr
//3.Hvis vi finner en eller flere, legger dette til i listen av rutekandidater
foreach (var fraStopp in _db.Rutestopp.Where(r => r.Holdeplass.ID == fra.ID))
{
foreach (var tilStopp in _db.Rutestopp.Where(r => r.Holdeplass.ID == til.ID &&
fraStopp.Rute == r.Rute))
{
potensielleRuter.Add(fraStopp.Rute);
}
/*if (stopp.Holdeplass.ID == til.ID || stopp.Holdeplass.ID>til.ID) {
potensielleRuter.Add(stopp.Rute);
}*/
}
if(potensielleRuter.Count > 0)
{
potensielleRuter.ForEach(pr =>
{
Console.WriteLine("En mulig rute er: " + pr.Navn);
});
}
else
{
Console.WriteLine("Ingen potensielle ruter :(");
}
//4.Looper listen av rutekandidater og finner ruteavganger som bruker ruta
//5. Hvis ruteavgangen har riktig dato, legger den til i listen over ruteavganger
foreach (var rute in potensielleRuter) {
foreach(var ruteavgang in _db.RuteAvganger.Where(ra => ra.Rute.RID == rute.RID))
{
ruteavganger.Add(ruteavgang);
}
}
return ruteavganger;
}
catch (Exception e)
{
Log.Error("Error i SammeDato: {error}", e);
return null;
}
}
public async Task<bool> Slett(int id)
{
try
{
Bestillinger enBestilling = await _db.Bestillinger.FindAsync(id);
_db.Bestillinger.Remove(enBestilling);
await _db.SaveChangesAsync();
Log.Information("Bestilling slettet.");
return true;
}
catch (Exception e)
{
Log.Error("Error i Slett: {error}", e);
return false;
}
}
public async Task<Bestillinger> HentEn(int id)
{
try
{
Console.WriteLine(id);
Bestillinger enBestilling = await _db.Bestillinger.FindAsync(id);
if (enBestilling == null) return null; //finner ikke id i DB
var hentetBestilling = new Bestillinger()
{
ID = enBestilling.ID,
Kunde = enBestilling.Kunde,
Pris = enBestilling.Pris,
Tur = enBestilling.Tur,
Retur = enBestilling.Retur
};
return hentetBestilling;
}
catch (Exception e)
{
Log.Error("Error i HentEn: {error}", e);
Debug.WriteLine(e.Message);
return null;
}
}
public async Task<bool> Endre(Bestillinger endreBestilling)
{
try
{
Bestillinger enBestillling = await _db.Bestillinger.FindAsync(endreBestilling.ID);
enBestillling.Kunde = endreBestilling.Kunde;
enBestillling.Pris = endreBestilling.Pris;
enBestillling.Tur = endreBestilling.Tur;
enBestillling.Retur = endreBestilling.Retur;
await _db.SaveChangesAsync();
Log.Information("Bestilling endret.");
return true;
}
catch (Exception e)
{
Log.Error("Error i Endre: {error}", e);
return false;
}
}
public async Task<List<Holdeplass>> HentAlleHoldeplasser()
{
List<Holdeplass> holdeplasser = await _db.Holdeplasser.ToListAsync();
return holdeplasser;
}
public static byte[] Hashing(string passord, byte[] salt)
{
return KeyDerivation.Pbkdf2(
password: passord,
salt: salt,
prf: KeyDerivationPrf.HMACSHA512,
iterationCount: 1000,
numBytesRequested: 32);
}
public static byte[] Salt()
{
var cryptoSP = new RNGCryptoServiceProvider();
var salt = new byte[24];
cryptoSP.GetBytes(salt);
return salt;
}
public async Task<bool> LoggInn(Bruker bruker)
{
try
{
Brukere funnetBruker = await _db.Brukere.FirstOrDefaultAsync(b => b.Brukernavn == bruker.Brukernavn);
if (funnetBruker == null) return false;
// sjekker om passordet til bruker er riktig
byte[] hash = Hashing(bruker.Passord, funnetBruker.Salt);
bool ok = hash.SequenceEqual(funnetBruker.Passord);
if(ok)
{
Log.Information("Admin logget inn.");
return true;
}
return false;
}
catch(Exception e)
{
Log.Error("Error i LoggInn: {error}", e);
return false;
}
}
public async Task<Holdeplass> HentHoldeplass(int id)
{
try
{
Holdeplass enHoldeplass = await _db.Holdeplasser.FindAsync(id);
var hentetHold = new Holdeplass()
{
ID = enHoldeplass.ID,
Sted = enHoldeplass.Sted,
Sone = enHoldeplass.Sone
};
return hentetHold;
}
catch(Exception e)
{
Log.Error("Error i HentHoldeplass: {error}", e);
return null;
}
}
public async Task<bool> EndreHoldeplass(Holdeplass endreHoldeplass)
{
try
{
var enHoldeplass = await _db.Holdeplasser.FindAsync(endreHoldeplass.ID);
enHoldeplass.Sted = endreHoldeplass.Sted;
enHoldeplass.Sone = endreHoldeplass.Sone;
await _db.SaveChangesAsync();
Log.Information("Holdeplass id: {id} endret.", endreHoldeplass.ID);
return true;
}
catch(Exception e)
{
Log.Error("Error i EndreHoldeplass: {error}", e);
return false;
}
}
public async Task<bool> LagreHoldeplass(Holdeplass innHP)
{
try
{
var nyHS = new Holdeplass();
nyHS.Sted = innHP.Sted;
nyHS.Sone = innHP.Sone;
_db.Holdeplasser.Add(nyHS);
await _db.SaveChangesAsync();
Log.Information("Holdeplass lagt inn: {holdeplass}", innHP.Sted);
return true;
}
catch(Exception e)
{
Log.Error("Error i LagreHoldeplass: {error}", e);
return false;
}
}
public async Task<List<RuteStopp>> HentRuteStopp()
{
List<RuteStopp> alleRuteStopp = await _db.Rutestopp.ToListAsync();
return alleRuteStopp;
}
public async Task<RuteStopp> EtRuteStopp(int id)
{
try
{
RuteStopp etRS = await _db.Rutestopp.FindAsync(id);
Holdeplass holdeplass = await _db.Holdeplasser.FindAsync(etRS.Holdeplass.ID);
var hentetRS = new RuteStopp()
{
ID = etRS.ID,
StoppTid = etRS.StoppTid,
Holdeplass = holdeplass
};
return hentetRS;
}
catch(Exception e)
{
Log.Error("Error i EtRuteStopp: {error}", e);
return null;
}
}
public async Task<bool> SlettRS(int id)
{
try
{
RuteStopp etRS = await _db.Rutestopp.FindAsync(id);
_db.Rutestopp.Remove(etRS);
await _db.SaveChangesAsync();
Log.Information("Rutestopp id: {id} slettet.", id);
return true;
}
catch(Exception e)
{
Log.Error("Error i SLettRS: {error}", e);
return false;
}
}
public async Task<bool> EndreRS(RuteStopp endreRS)
{
try
{
var etRS = await _db.Rutestopp.FindAsync(endreRS.ID);
if (!etRS.Holdeplass.Sted.Equals(endreRS.Holdeplass.Sted))
{
var sjekkHoldeplass = _db.Holdeplasser.Where(s => s.Sted.Contains(etRS.Holdeplass.Sted));
if (sjekkHoldeplass == null)
{
var holdeplassRad = new Holdeplass();
holdeplassRad.Sted = endreRS.Holdeplass.Sted;
holdeplassRad.Sone = endreRS.Holdeplass.Sone;
etRS.Holdeplass = holdeplassRad;
}
else
{
etRS.Holdeplass = endreRS.Holdeplass;
}
}
etRS.StoppTid = endreRS.StoppTid;
await _db.SaveChangesAsync();
Log.Information("Rutestopp id: {id} endret.", endreRS.ID);
return true;
}
catch(Exception e)
{
Log.Error("Error i EndreRS: {error}", e);
return false;
}
}
public RuteStopp NyttRuteStopp(string[] argumenter)
{
Console.WriteLine(argumenter[0]);
Console.WriteLine(argumenter[1]);
Console.WriteLine(argumenter[2]);
string holdeplassNavn = argumenter[0];
string ruteNavn = argumenter[1];
int minutterEtterAvgang = int.Parse(argumenter[2]);
TimeSpan stoppTid = TimeSpan.FromMinutes(minutterEtterAvgang);
Holdeplass holdeplass = _db.Holdeplasser.Where(h => h.Sted == holdeplassNavn).FirstOrDefault();
Rute rute = _db.Ruter.Where(r => r.Navn == ruteNavn).FirstOrDefault();
if (holdeplass != null && rute != null)
{
RuteStopp nyttRuteStopp = new RuteStopp();
nyttRuteStopp.Rute = rute;
nyttRuteStopp.Holdeplass = holdeplass;
nyttRuteStopp.StoppTid = stoppTid;
_db.Rutestopp.Add(nyttRuteStopp);
_db.SaveChanges();
return nyttRuteStopp;
}
Log.Information("Nytt rutestopp lagt til.");
return null;
}
public RuteAvgang NyRuteAvgang(string[] argumenter)
{
string ruteNavn = argumenter[0];
string avgangsTidString = argumenter[1];
DateTime avgangsTid = DateTime.ParseExact(avgangsTidString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Rute rute = _db.Ruter.Where(r => r.Navn == ruteNavn).FirstOrDefault();
if (rute != null)
{
RuteAvgang nyRuteAvgang = new RuteAvgang();
nyRuteAvgang.Rute = rute;
nyRuteAvgang.Dato = avgangsTid;
_db.RuteAvganger.Add(nyRuteAvgang);
_db.SaveChanges();
return nyRuteAvgang;
}
Log.Information("Ny ruteavgang lagt til.");
return null;
}
public async Task<bool> LagreRS(RuteStopp innRS)
{
try
{
var nyRS = new RuteStopp();
nyRS.StoppTid = innRS.StoppTid;
// sjekker om holdeplass allerede ligger i databasen, legger til ny dersom den ikke gjør det
var sjekkHoldeplass = _db.Holdeplasser.Where(navn => navn.Sted.Contains(innRS.Holdeplass.Sted));
if (sjekkHoldeplass == null)
{
// oppretter en ny holdeplass
var nyHoldeplass = new Holdeplass();
nyHoldeplass.Sted = innRS.Holdeplass.Sted;
nyHoldeplass.Sone = innRS.Holdeplass.Sone;
nyRS.Holdeplass = nyHoldeplass;
}
else
{
nyRS.Holdeplass.Sted = innRS.Holdeplass.Sted;
nyRS.Holdeplass.Sone = innRS.Holdeplass.Sone;
}
_db.Rutestopp.Add(nyRS);
await _db.SaveChangesAsync();
Log.Information("Rutestopp lagret.");
return true;
}
catch(Exception e)
{
Log.Error("Error i LagreRS: {error}", e);
return false;
}
}
public async Task<bool> SlettHoldeplass(int id)
{
try
{
Holdeplass enHoldeplass = await _db.Holdeplasser.FindAsync(id);
_db.Holdeplasser.Remove(enHoldeplass);
await _db.SaveChangesAsync();
}
catch(Exception e)
{
Log.Error("Error i SlettHoldeplass: {error}", e);
Console.Write(e.Message);
return false;
}
Log.Information("Holdeplass slettet.");
return true;
}
public async Task<List<Rute>> AlleRuter()
{
try
{
List<Rute> alleRuter = await _db.Ruter.Select(r => new Rute
{
RID = r.RID,
Navn = r.Navn,
RuteStopp = r.RuteStopp
}).ToListAsync();
return alleRuter;
}
catch(Exception e)
{
Log.Error("Error i AlleRuter: {error}", e);
return null;
}
}
public async Task<Rute> EnRute(int id)
{
try
{
Rute enRute = await _db.Ruter.FindAsync(id);
var hentetRute = new Rute()
{
RID = enRute.RID,
Navn = enRute.Navn,
RuteStopp = enRute.RuteStopp
};
return hentetRute;
}
catch(Exception e)
{
Log.Error("Error i EnRute: {error}", e);
return null;
}
}
// lagrer en tom rute
public async Task<bool> LagreRute(string navn)
{
try
{
var nyRute = new Rute();
nyRute.Navn = navn;
List<RuteStopp> tom = new List<RuteStopp>();
nyRute.RuteStopp = tom;
_db.Ruter.Add(nyRute);
await _db.SaveChangesAsync();
Log.Information("Rute lagret.");
return true;
}
catch(Exception e)
{
Log.Error("Error i LagreRute: {error}", e);
return false;
}
}
public async Task<List<Priser>> HentPriser()
{
List<Priser> priser = await _db.Priser.ToListAsync();
return priser;
}
public async Task<Priser> EnPris(int id)
{
try
{
Priser enPris = await _db.Priser.FindAsync(id);
var returPris = new Priser()
{
PrisID = enPris.PrisID,
Prisklasse = enPris.Prisklasse,
Pris1Sone = enPris.Pris1Sone,
Pris2Sone = enPris.Pris2Sone,
Pris3Sone = enPris.Pris3Sone,
Pris4Sone = enPris.Pris4Sone
};
return returPris;
}
catch (Exception e)
{
Log.Error("Error i EnPris: {error}", e);
return null;
}
}
public async Task<bool> EndrePriser(Priser pris)
{
try
{
var endreObjekt = await _db.Priser.FindAsync(pris.PrisID);
endreObjekt.Pris1Sone = pris.Pris1Sone;
endreObjekt.Pris2Sone = pris.Pris2Sone;
endreObjekt.Pris3Sone = pris.Pris3Sone;
endreObjekt.Pris4Sone = pris.Pris4Sone;
await _db.SaveChangesAsync();
Log.Information("Priser endret.");
}
catch (Exception e)
{
Log.Error("Error i EndrePriser: {error}", e);
return false;
}
return true;
}
}
}
|
f6d6df4398c630c374ca2c307976eea645de5199
|
C#
|
bubdm/VectorEditor2
|
/TestEditor/DrawingStruct/IpLine.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace TestEditor
{
public struct LinePic
{
public float x1;
public float y1;
public float x2;
public float y2;
public Pen pen;
public bool selected;
public int layer;
public Pen selectedPen;
private float angle1, angle2;
private float radius1, radius2;
private float hc1, wc1, hc2, wc2;
private float xCent, yCent;
public void SetCenterPoint(float xCenter, float yCenter)
{
xCent = xCenter;
yCent = yCenter;
}
public void CalculateRotationAxes(float xCenter, float yCenter)
{
SetCenterPoint(xCenter, yCenter);
hc1 = yCenter - y1;
wc1 = x1 - xCenter;
hc2 = yCenter - y2;
wc2 = x2 - xCenter;
radius1 = Convert.ToSingle(Math.Sqrt(hc1 * hc1 + wc1 * wc1));
radius2 = Convert.ToSingle(Math.Sqrt(hc2 * hc2 + wc2 * wc2));
angle1 = (float)Math.Atan2(hc1, wc1);
angle2 = (float)Math.Atan2(hc2, wc2);
}
public void RotateLine(float angle)
{
double radAngle1 = Math.PI / 2 + angle + angle1;
double radAngle2 = Math.PI / 2 + angle + angle2;
x2 = xCent + radius2 * (float)Math.Sin(radAngle2);
y2 = yCent + radius2 * (float)Math.Cos(radAngle2);
x1 = xCent + radius1 * (float)Math.Sin(radAngle1);
y1 = yCent + radius1 * (float)Math.Cos(radAngle1);
}
public void AddLine(IpCursor lastCursor, IpCursor selectCursor, Pen pen,int layer)
{
x1 = lastCursor.X;
y1 = lastCursor.Y;
x2 = selectCursor.X;
y2 = selectCursor.Y;
selected = false;
this.pen = pen;
selectedPen = new Pen(Color.Red);
this.layer = layer;
}
public void MirrorX(IpCursor cursor)
{
if (x1 < cursor.X)
x1 = x1 + Math.Abs(cursor.X - x1) * 2;
else
x1 = x1 - Math.Abs(cursor.X - x1) * 2;
if (x2 < cursor.X)
x2 = x2 + Math.Abs(cursor.X - x2) * 2;
else
x2 = x2 - Math.Abs(cursor.X - x2) * 2;
}
public void MirrorY(IpCursor cursor)
{
if (y1 < cursor.Y)
y1 = y1 + Math.Abs(cursor.Y - y1) * 2;
else
y1 = y1 - Math.Abs(cursor.Y - y1) * 2;
if (y2 < cursor.Y)
y2 = y2 + Math.Abs(cursor.Y - y2) * 2;
else
y2 = y2 - Math.Abs(cursor.Y - y2) * 2;
}
public void DrawLine(Graphics buff,float xf,float yf,float coeff)
{
Pen sPen;
if (selected)
sPen = selectedPen;
else
sPen = pen;
sPen.Width = coeff;
buff.DrawLine(sPen, x1*coeff - xf, y1 * coeff - yf, x2 * coeff - xf, y2 * coeff - yf);
}
public static bool operator !=(LinePic c1, LinePic c2)
{
if ((c1.x1 != c2.x2) || (c1.y1 != c2.y1) || (c1.x1 != c2.x2) || (c1.y2 != c2.y2))
return true;
return false;
}
public static bool operator ==(LinePic c1, LinePic c2)
{
if ((c1.x1 == c2.x1) && (c1.y1 == c2.y1) && (c1.x2 == c2.x2) && (c1.y2 == c2.y2))
return true;
return false;
}
public static bool operator !=(LinePic c1, int i2)
{
if ((c1.x1 != i2) || (c1.y1 != i2) || (c1.x1 != i2) || (c1.y2 != i2))
return true;
return false;
}
public static bool operator ==(LinePic c1, int i2)
{
if ((c1.x1 == i2) && (c1.y1 == i2) && (c1.x2 == i2) && (c1.y2 == i2))
return true;
return false;
}
}
}
|
1fb6447c9293aaed99f6cebb107270cbc8d6af35
|
C#
|
etarhan/WPFPortfolio
|
/WPFPortfolio/Calculator/CalculateImput.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFPortfolio.Calculator
{
class CalculateImput
{
public bool DivByZero { get; private set; }
public double AddCalc(double secondNo, double firstNo)
{
return firstNo + secondNo;
}
public double MultiCalc(double secondNo, double firstNo)
{
return firstNo * secondNo;
}
public double SubstCalc(double secondNo, double firstNo)
{
return firstNo - secondNo;
}
public double DivCalc(double secondNo, double firstNo)
{
if (secondNo == 0)
{
DivByZero = true;
return 0;
}
else
{
DivByZero = false;
return firstNo / secondNo;
}
}
}
}
|
d5705f9ad64fac158b0a9b3030474655cc6da931
|
C#
|
MacakM/PB007-PetShop
|
/PetShop/Cat.cs
| 2.875
| 3
|
using System;
namespace PetShop
{
public class Cat : IAnimal
{
public string Name { get; set; }
public string Color { get; set; }
public Food FavouriteFood { get; set; }
public Cat()
{
Name = "Tom";
}
public void MakeSound()
{
Console.WriteLine("Mnau");
}
}
}
|
1b8cac182c2712bb9f784313d5004089793211bd
|
C#
|
Keehyuklee/CSharp7Features
|
/ThrowExpressions.cs
| 3.546875
| 4
|
using System;
namespace CSharp7
{
class ThrowExpressions
{
public int ThrowExceptions()
{
//Throw expressions can be used in conditional operators and null coalescings.
//Null coalescing
String input = Console.ReadLine() ?? throw new Exception("Exception");
//Conditional operator
return int.TryParse("123", out int converted) ? converted : throw new Exception("Error");
}
}
}
|
95100f9c4f0e37f8bace4334c4cfacb8337fb79d
|
C#
|
lgn/CurrentProject
|
/Web/Helpers/StringExtensions.cs
| 3.125
| 3
|
using System.Text.RegularExpressions;
namespace System.Web.Mvc
{
public static class StringExtensions
{
public static string FormattedDayMonth(this int dayMonth) {
var result = dayMonth.ToString();
if (result.Length == 1)
result = "0" + result;
return result;
}
public static string CreateSlug(this string source) {
var regex = new Regex(@"([^a-z0-9\-]?)");
var slug = "";
if (!string.IsNullOrEmpty(source)) {
slug = source.Trim().ToLower();
slug = slug.Replace(' ', '-');
slug = slug.Replace("---", "-");
slug = slug.Replace("--", "-");
if (regex != null)
slug = regex.Replace(slug, "");
if (slug.Length * 2 < source.Length)
return "";
if (slug.Length > 100)
slug = slug.Substring(0, 100);
}
return slug;
}
public static string StripHTML(this string htmlString) {
const string pattern = @"<(.|\n)*?>";
return Regex.Replace(htmlString, pattern, string.Empty);
}
public static string Chop(this string content, string[] separator) {
var strSplitArr = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
return strSplitArr[0];
}
}
}
|
39d54027fc005f3f1fc992fbf0646e9f511b6b8b
|
C#
|
jamdmasud/PharmacyDesktopApplication
|
/PharmacyDesktopApplication/UI/ShowDueDetails.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using PharmacyDesktopApplication.Entities;
using PharmacyDesktopApplication.Models;
namespace PharmacyDesktopApplication.UI
{
partial class ShowDueDetails : Form
{
private readonly string _customerId;
private string currentUser = "0";
public ShowDueDetails(List<SaleDetail> saleDetail, string customerId, string user)
{
currentUser = user;
_customerId = customerId;
InitializeComponent();
dgvSaleDetails.DataSource = saleDetail;
PharmacyDbContext db = new PharmacyDbContext();
lblDue.Text = Convert.ToString(db.Voucher
.Where(x=>x.GLCode == GLCode.AccountReceivable && x.CustomerId == _customerId)
.Sum(a => a.Dr - a.Cr));
}
private void okButton_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void btnPay_Click(object sender, EventArgs e)
{
PharmacyDbContext db = new PharmacyDbContext();
SaveInvoice(db);
db.SaveChanges();
db.Dispose();
MessageBox.Show("Save successful", "Paid!", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
private void SaveInvoice(PharmacyDbContext db)
{
Invoice invoice = new Invoice
{
Id = Guid.NewGuid().ToString(),
IsActive = true,
CreatedBy = currentUser,
CreatedDate = DateTime.Now
};
db.Invoice.Add(invoice);
SaveDuePayment(db, invoice.Id);
UpdateCustomerMain(db);
}
private void UpdateCustomerMain(PharmacyDbContext db)
{
SaleMain main =
db.SaleMain.Where(a => a.CustomerId == _customerId).OrderByDescending(x => x.Id).FirstOrDefault();
main.DuePaid += Convert.ToDecimal(txtDuePay.Text);
db.Entry(main).State = EntityState.Modified;
}
private void SaveDuePayment(PharmacyDbContext db, string invoiceId)
{
decimal amount = Convert.ToDecimal(txtDuePay.Text);
DuePayment due = new DuePayment
{
Amount = amount,
CreatedDate = DateTime.Now,
CreatedBy = currentUser,
CustomerId = _customerId,
Id = Guid.NewGuid().ToString(),
InvoiceId = invoiceId
};
db.DuePayment.Add(due);
SaveVoucher(db, invoiceId, amount);
}
private void SaveVoucher(PharmacyDbContext db, string invoiceId, decimal amount)
{
int count = 1;
//Debit entry
Voucher voucher = new Voucher
{
Id = Guid.NewGuid().ToString(),
CustomerId = _customerId,
EntryNo = count++,
GLCode = GLCode.Cash,
Dr = amount,
Cr = 0,
InvoiceId = invoiceId,
CreatedDate = DateTime.Now,
CreatedBy = currentUser
};
db.Voucher.Add(voucher);
//credit entry
Voucher voucherCr2 = new Voucher
{
Id = Guid.NewGuid().ToString(),
CustomerId = _customerId,
Cr = amount,
GLCode = GLCode.AccountReceivable,
Dr = 0,
InvoiceId = invoiceId,
EntryNo = count,
CreatedDate = DateTime.Now,
CreatedBy = currentUser
};
db.Voucher.Add(voucherCr2);
}
}
}
|
18d1b8b554ee6cbe6f3377b2f69dc3a27940ee6c
|
C#
|
melon1313/Restful_WebAPI_with_DotNetCore
|
/Fake.API/Helper/ObjectExtensions.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Fake.API.Helper
{
public static class ObjectExtensions
{
public static ExpandoObject ShapData<TSource>(this TSource source, string fields)
{
if (source == null) throw new ArgumentNullException(nameof(source));
List<PropertyInfo> propertyInfos = new List<PropertyInfo>();
if (string.IsNullOrEmpty(fields))
{
propertyInfos = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase).ToList();
}
else
{
var fieldInfos = fields.Split(',');
foreach (var field in fieldInfos)
{
var propertyInfo = typeof(TSource).GetProperty(field.Trim(), BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (propertyInfo == null) throw new Exception($"{typeof(TSource)}屬性{field}找不到!");
propertyInfos.Add(propertyInfo);
}
}
ExpandoObject expandoObject = new ExpandoObject();
foreach (var property in propertyInfos)
{
((IDictionary<string, object>)expandoObject).Add(property.Name, property.GetValue(source));
}
return expandoObject;
}
}
}
|
0a14deb20ca60ca21ba9e0ebad4a35287d02f91d
|
C#
|
chaos6631/OOP4200_DurakGame
|
/Durak/DurakLib/AIPlayer.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ch13CardLib;
namespace DurakGameLib
{
class AIPlayer : CardsPlayed
{
#region CLASS MEMBERS
#endregion
#region CONSTRUCTORS
/// <summary>
/// Constructor for the AIPlayer object
/// </summary>
public AIPlayer()
{
aiplayhand = new Cards(); // The ia player cards as a hand
}
#endregion
#region INSTANCE MEMBERS
private Cards aiplayhand;
private Card humanLastCard;
private bool isAttacker; // Is the attacker
private Suit superSuit;
#endregion
#region ACCESSORS & MUTATORS
/// <summary>
/// Getter & Setter for AIplayhand
/// </summary>
public Cards AIplayhand
{
get
{
return aiplayhand; // Returns the ai hand of cards
}
set
{
aiplayhand = value; // Sets the ai hand of cards
}
}
/// <summary>
/// Getter & Setter for Isattacker
/// </summary>
public bool IsAttacker
{
get
{
return isAttacker;
}
set
{
isAttacker = value;
}
}
/// <summary>
/// Getter & Setter for HumanLastCard
/// </summary>
public Card HumanLastCard
{
get
{
return humanLastCard;
}
set
{
humanLastCard = value;
}
}
public Suit SuperSuit
{
get
{
return superSuit;
}
set
{
superSuit = value;
}
}
#endregion
#region METHODS
/// <summary>
/// remove card from ai player's hand
/// </summary>
/// <param name="card"></param>
public void AiPlayCard(Card card)
{
aiplayhand.Remove(card); // Removes the card played from the ai hand
}
/// <summary>
/// Draw cards to the ai player's hand
/// </summary>
/// <param name="card"></param>
public void DrawCards(Card card)
{
aiplayhand.Add(card); // Add each to the players hand
}
/// <summary>
/// basic logic of ai player
/// </summary>
public void BasicAILogic()
{
if (IsAttacker == true)
{
foreach (Card aicard in AIplayhand)
{
if (aicard.Rank == Rank.Two)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Three)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Four)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Five)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Six)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Seven)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Eight)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Nine)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Ten)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Jack)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Queen)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.King)
{
AiPlayCard(aicard);
}
else if (aicard.Rank == Rank.Ace)
{
AiPlayCard(aicard);
}
}
}
else
{
foreach (Card aicard in AIplayhand)
{
if (humanLastCard >= aicard)
{
DrawCards(humanLastCard);
}
if (humanLastCard < aicard || humanLastCard.Suit == aicard.Suit)
{
AiPlayCard(aicard);
}
if (humanLastCard < aicard || aicard.Suit == superSuit)
{
AiPlayCard(aicard);
}
}
}
}
#endregion
}
}
|
dd3a8739b4165d467702bb28def85c226449bb02
|
C#
|
mirkocerati/verifica-22-10-2021
|
/cerati/Reservation.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cerati
{
class Reservation
{
//Parametri
public string Name { get; set; }
public string City { get; set; }
public DateTime CheckInDate { get; set; }
public DateTime CheckOutDate { get; set; }
public int Adults { get; set; }
public int Children { get; set; }
public string RoomType { get; set; }
public int Temp { get; set; }
public string SheetSet { get; set; }
public bool CleanTowelsDaily { get; set; }
public bool OledTv { get; set; }
//Calcola il prezzo con i dati inseriti
public float CalcPrice()
{
float price = 0;
int guests = Adults + Children;
int duration = (int)(CheckOutDate - CheckInDate).Days;
int PricePerNight = 0;
switch(RoomType)
{
case "STANDARD":
PricePerNight = 50;
break;
case "SUPERIOR":
PricePerNight = 75;
break;
case "DELUXE":
PricePerNight = 100;
break;
}
if(duration > 6)
{
int temp = duration - 6;
price += (PricePerNight * Children * 6) / 2;
price += (PricePerNight * Adults * 6);
price += ((PricePerNight * Children * temp) / 2) * 0.95f;
price += ((PricePerNight * Adults * temp)) * 0.95f;
} else
{
price += (PricePerNight * Children * duration) / 2;
price += (PricePerNight * Adults * duration);
}
float optionals = 0;
if (CleanTowelsDaily) optionals += price * 0.10f;
if (OledTv) optionals += price * 0.20f;
return price + optionals;
}
//Crea il testo di conferma prenotazione
public string ConfirmationText()
{
string result = "Booking confirmation\r\n--------------------\r\n";
result += "Guest name: " + Name + ", from " + City + "\r\n";
result += "Check-in: " + CheckInDate.ToShortDateString() + "\r\n";
result += "Check-out: " + CheckOutDate.ToShortDateString() + "\r\n";
result += "Nights: " + (int)(CheckOutDate - CheckInDate).TotalDays + "\r\n";
result += "Number of guests: " + Adults + " adults, " + Children + " children" + "\r\n";
result += "Room type: " + RoomType + ", " + Temp.ToString() + "°" + "\r\n";
result += "Sheet Set: " + SheetSet + "\r\n";
result += "Optionals: ";
if (CleanTowelsDaily) result += "Clean Towels Dayly, ";
if (OledTv) result += "Oled TV";
result += "\r\n\r\n" + "FINAL PRICE: " + CalcPrice() + " EUR";
return result;
}
}
}
|
c9c5efe95290b39badc3d164dd72d4313975cf76
|
C#
|
shendongnian/download4
|
/first_version_download2/548596-51776139-179455640-2.cs
| 3.359375
| 3
|
bool IsMemoryAvailable(int amount)
{
int size = (int)Math.Sqrt(amount) / 2;
try
{
using (Bitmap bmpTest = new Bitmap(size, size))
{
}
GC.Collect();
return true;
}
catch(Exception x)
{
return false;
}
}
|
e709d8604f922a0ca8bcc3d9b8b21d00c85cb8a2
|
C#
|
kuyu7766/Serenity
|
/src/Serenity.Net.Web/Mvc/VirtualPathUtility.cs
| 2.828125
| 3
|
using Microsoft.AspNetCore.Http;
namespace Serenity.Web
{
public static class VirtualPathUtility
{
public static string ToAbsolute(IHttpContextAccessor accessor, string contentPath)
{
return ToAbsolute(accessor?.HttpContext, contentPath);
}
public static string ToAbsolute(HttpContext context, string contentPath)
{
return ToAbsolute(context?.Request?.PathBase ?? PathString.Empty, contentPath);
}
public static string ToAbsolute(PathString pathBase, string path)
{
if (!pathBase.HasValue)
pathBase = PathString.Empty;
if (path.StartsWith("~/", StringComparison.Ordinal))
{
var segment = new PathString(path[1..]);
return pathBase.Add(segment).Value;
}
return path;
}
}
}
|
4b10e9a6b3e6d770ce7c5f9c49ab9c73c675c44b
|
C#
|
jcarlosmrls/reproductorcsharpunlam
|
/Reproductor/Clases/BaseDeDatos.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
namespace Reproductor
{
public class BaseDeDatos
{
private OleDbConnection dbConnection;
private OleDbDataAdapter dbAdapter;
private DataSet dbDataSet;
public BaseDeDatos()
{
dbConnection = new OleDbConnection();
dbAdapter = new OleDbDataAdapter();
dbDataSet = new DataSet();
}
#region Metodos
public void Open(string connectionString)
{
dbConnection.ConnectionString = connectionString;
try
{
dbConnection.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void Close()
{
dbConnection.Close();
}
//lee la columna de una tabla
public string[] Leer_Columna(string tabla, string columna)
{
string[] cadena;
int cant;
OleDbCommand cmdLeer = new OleDbCommand();
DataSet ds = new DataSet();
string cad = "SELECT " + columna + " FROM " + tabla;
cmdLeer.CommandType = CommandType.Text;
cmdLeer.Connection = dbConnection;
cmdLeer.CommandText = cad;
dbAdapter.SelectCommand = cmdLeer;
ds.Clear(); // agregado clear, sino se arma lio con el dataset anterior
try
{
dbAdapter.Fill(ds);
cant = ds.Tables[0].Rows.Count;
cadena = new string[cant];
for (int x = 0; x < cant; x++)
cadena[x] = ds.Tables[0].Rows[x][columna].ToString();
return cadena;
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
return null;
}
}
//lee la columna de una tabla filtrando por un columf con el valor val
public string[] Leer_Columna(string tabla, string columna, string columf, string val)
{
string[] cadena;
int cant;
OleDbCommand cmdLeer = new OleDbCommand();
DataSet ds = new DataSet();
string cad = "SELECT " + columna + " FROM " + tabla + " WHERE " + columf + " = ?";
cmdLeer.CommandType = CommandType.Text;
cmdLeer.Connection = dbConnection;
cmdLeer.Parameters.Add("?", val);
cmdLeer.CommandText = cad;
dbAdapter.SelectCommand = cmdLeer;
ds.Clear();// agregado clear, sino se arma lio con el dataset anterior
try
{
dbAdapter.Fill(ds);
cant = ds.Tables[0].Rows.Count;
cadena = new string[cant];
for (int x = 0; x < cant; x++)
cadena[x] = ds.Tables[0].Rows[x][columna].ToString();
return cadena;
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
return null;
}
}
public string[] Leer_Columna(string tabla, string columna, string columf1, string val1, string columf2, string val2)
{
string[] cadena;
int cant;
OleDbCommand cmdLeer = new OleDbCommand();
string cad = "SELECT " + columna + " FROM " + tabla + " WHERE " + columf1 + " = ? AND " + columf2 + " = ?";
cmdLeer.CommandType = CommandType.Text;
cmdLeer.Connection = dbConnection;
cmdLeer.Parameters.Add("?", val1);
cmdLeer.Parameters.Add("?", val2);
cmdLeer.CommandText = cad;
dbAdapter.SelectCommand = cmdLeer;
dbDataSet.Clear();// agregado clear, sino se arma lio con el dataset anterior
try
{
dbAdapter.Fill(dbDataSet);
cant = dbDataSet.Tables[0].Rows.Count;
cadena = new string[cant];
for (int x = 0; x < cant; x++)
cadena[x] = dbDataSet.Tables[0].Rows[x][columna].ToString();
return cadena;
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
return null;
}
}
public int AddUser(string user, string password)
{
OleDbCommand cmdInsertar = new OleDbCommand();
OleDbCommand cmdPerfil = new OleDbCommand();
OleDbCommand cmdConfiguraciones = new OleDbCommand();
cmdInsertar.Connection = dbConnection;
cmdInsertar.Parameters.Add("?", user);
cmdInsertar.Parameters.Add("?", password);
cmdInsertar.CommandText = @"INSERT INTO Usuario ([Id_Usuario], [Password]) VALUES (?,?)";
try
{
cmdInsertar.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("El nombre de usuario seleccionado ya está en uso. Por favor, elija otro.", "Error");
return -1;
}
return 0;
}
public bool ValidarLogin(string user, string pass)
{
int cant;
OleDbCommand cmdValidar = new OleDbCommand();
cmdValidar.CommandType = CommandType.Text;
cmdValidar.Connection = dbConnection;
cmdValidar.Parameters.Add("?", user);
cmdValidar.CommandText = @"SELECT Password FROM Usuario WHERE Id_usuario = ?";
dbAdapter.SelectCommand = cmdValidar;
dbAdapter.Fill(dbDataSet);
cant = dbDataSet.Tables[0].Rows.Count;
if (cant == 0)
{
MessageBox.Show("El Usuario ingresado no existe :(");
return false;
}
else
{
if (dbDataSet.Tables[0].Rows[0]["Password"].ToString() == pass)
{
MessageBox.Show("Bienvenido al reproductor, que la pase bien.");
return true;
}
else
{
MessageBox.Show("Constraseña erronea, acceso no autorizado");
return false;
}
}
}
public void ActualizarRutaDeArchivos(string user, List<string> paths)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", user);
cmd.CommandText = @"DELETE FROM Ruta_De_Archivos WHERE Id_Usuario = ?";
try
{
cmd.ExecuteNonQuery();
for (int x = 0; x < paths.Count; x++)
{
cmd.Parameters.Clear();
cmd.Parameters.Add("?", user);
cmd.Parameters.Add("?", paths[x]);
cmd.CommandText = @"INSERT INTO Ruta_De_Archivos ([Id_Usuario], [Path]) VALUES (?,?)";
cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
MessageBox.Show("Se producido un error en la base de datos");
}
}
public void AgregarRutaDeArchivos(string user, string path)
{
OleDbCommand cmdAgregar = new OleDbCommand();
cmdAgregar.CommandType = CommandType.Text;
cmdAgregar.Connection = dbConnection;
cmdAgregar.Parameters.Add("?", user);
cmdAgregar.Parameters.Add("?", path);
cmdAgregar.CommandText = @"INSERT INTO Ruta_De_Archivos ([Id_Usuario], [Path]) VALUES (?,?)";
cmdAgregar.ExecuteNonQuery();
}
//metodo agregado
public void QuitarRutaDeArchivos(string user, string path)
{
OleDbCommand cmdQuitar = new OleDbCommand();
cmdQuitar.CommandType = CommandType.Text;
cmdQuitar.Connection = dbConnection;
cmdQuitar.Parameters.Add("?", user);
cmdQuitar.Parameters.Add("?", path);
cmdQuitar.CommandText = @"DELETE FROM Ruta_De_Archivos WHERE Id_Usuario = ? AND Path = ?";
cmdQuitar.ExecuteNonQuery();
}
//metodo que va a generar la lista de canciones en los directorios seleccionados
private List<string> ListaPathsCanciones(string[] paths)
{
List<string> canciones = new List<string>();
foreach (string path in paths)
{
try
{
//obtiene una lista por cada formato
foreach (string cad in Directory.GetFiles(path, "*.mp3", SearchOption.AllDirectories))
{
canciones.Add(cad.ToString());
}
foreach (string cad in Directory.GetFiles(path, "*.wav", SearchOption.AllDirectories))
{
canciones.Add(cad.ToString());
}
foreach (string cad in Directory.GetFiles(path, "*.mid", SearchOption.AllDirectories))
{
canciones.Add(cad.ToString());
}
}
catch (System.UnauthorizedAccessException)
{
MessageBox.Show("Su sistema operativo no le permite acceder a alguno de los subdirectorios de la ruta que ha ingresado.\nLa actualización de la biblioteca se ha cancelado.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (System.IO.DirectoryNotFoundException)
{
MessageBox.Show("Alguna de las rutas ingresadas no existen.");
}
}
return canciones;
}
private bool ExisteCancion(string path)
{
if (Leer_Columna("Cancion", "Path", "Path", path).Length > 0 && File.Exists(path))
{
return true;
}
else
{
return false;
}
}
public string InterpreteId(string nombre)
{
try //controla si el nombre es de tamaño 0 o si es nulo
{
if (nombre.Length == 0)
nombre = "?";
}
catch (Exception)
{
nombre = "?";
}
string[] lista;
lista = Leer_Columna("Interprete", "Id", "Nombre", nombre); //realizo una busqueda en al bd de los interpretes con ese nombre
if (lista.Length == 0)
{
return "";
}
else
{
return lista[0];
}
}
public string AlbumId(string nombre, string idInterprete)
{
try//controla si el nombre es de tamaño 0 o si es nulo
{
if (nombre.Length == 0)
nombre = "?";
}
catch (Exception)
{
nombre = "?";
}
string[] lista;
lista = Leer_Columna("Album", "Id_Album", "Nombre", nombre, "Id_Interprete", idInterprete); //busqueda en la bd de los albunes con ese nombre
if (lista.Length == 0)
{
return "";
}
else
{
return lista[0];
}
}
public string AgregarInterprete(string nombre)
{
try//controla si el nombre es de tamaño 0 o si es nulo
{
if (nombre.Length == 0)
nombre = "?";
}
catch (Exception)
{
nombre = "?";
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", nombre);
cmd.CommandText = @"INSERT INTO Interprete ([Nombre]) VALUES (?)";
cmd.ExecuteNonQuery();
return InterpreteId(nombre);
}
public string AgregarAlbum(Cancion cancion, string idInterprete)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
string album = cancion.Album;
try//controla si el album es de tamaño 0 o si es nulo
{
if (album.Length == 0)
album = "?";
}
catch (Exception)
{
album = "?";
}
cmd.Parameters.Add("?", album);
cmd.Parameters.Add("?", idInterprete);
cmd.Parameters.Add("?", cancion.Genero);
cmd.Parameters.Add("?", cancion.Año);
//cmd.Parameters.Add("?", cancion.Imagen);
cmd.CommandText = @"INSERT INTO Album ([Nombre],[Id_Interprete],[Genero],[Año]) VALUES (?,?,?,?)";
cmd.ExecuteNonQuery();
return AlbumId(cancion.Album, idInterprete);
}
public void AgregarCancion(Cancion cancion, string idAlbum)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", idAlbum);
cmd.Parameters.Add("?", cancion.Nombre);
cmd.Parameters.Add("?", cancion.NumeroDeCancion);
cmd.Parameters.Add("?", cancion.Duracion);
cmd.Parameters.Add("?", cancion.Ruta);
cmd.CommandText = @"INSERT INTO Cancion ([Id_Album],[Titulo],[Numero_Cancion],[Duracion],[Path]) VALUES (?,?,?,?,?)";
cmd.ExecuteNonQuery();
}
/* public void AgregarCancion(string album, string lista, string titulo, uint numero, TimeSpan duracion, string path)
{
OleDbCommand cmd = new OleDbCommand();
//Defino las caracteristicas del comando
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
//Creo los parametros
cmd.Parameters.Add("?", album);
cmd.Parameters.Add("?", lista);
cmd.Parameters.Add("?", titulo);
cmd.Parameters.Add("?", numero);
cmd.Parameters.Add("?", duracion);
cmd.Parameters.Add("?", path);
cmd.CommandText = @"INSERT INTO Cancion ([Id_Album], [Id_Lista], [Titulo], [Numero_Cancion], [Duracion], [Path]) VALUES (?,?,?,?,?,?)";
cmd.ExecuteNonQuery();
}*/
// funcion que actualiza las canciones en la base de datos,
public void ActualizarCanciones(PantallaPrincipal ventana)
{
List<string> canciones;
//obtengo una lista de los paths de canciones en base a los directorios guardados en la base de datos
canciones = ListaPathsCanciones(Leer_Columna("Ruta_De_Archivos", "Path", "Id_Usuario", ventana.UsuarioActual.Id));
foreach (string path in canciones)
{
if (!ExisteCancion(path)) // controlo si el path de la cancion ya esta en la base de datos.
{
try
{
Cancion cancion = new Cancion(path); //creo objeto cancion
string idInterprete = InterpreteId(cancion.Artista);
string idAlbum = AlbumId(cancion.Album, idInterprete); //obtengo los ids de album y interprete.
if (idInterprete == "") // controlo si el interprete no existe
{
idInterprete = AgregarInterprete(cancion.Artista);
idAlbum = AgregarAlbum(cancion, idInterprete);
}
else
{
if (idAlbum == "") //controlo si el album no existe
{
idAlbum = AgregarAlbum(cancion, idInterprete);
}
}
AgregarCancion(cancion, idAlbum);
}
catch (Exception)
{
}
}
ventana.MostrarInterpretes();
}
}
public List<Cancion> CancionDeCadaAlbum(string interprete)
{
List<Cancion> canciones = new List<Cancion>();
string idInteprete = InterpreteId(interprete);
foreach (string idAlbum in Leer_Columna("Album", "Id_Album", "Id_Interprete", idInteprete))
{
string[] aux = Leer_Columna("Cancion", "Path", "Id_Album", idAlbum);
if (aux != null)
{
try
{
canciones.Add(new Cancion(aux[0]));
}
catch (Exception)
{//si tira excepcion aca es porque el erchivo de musca ya no existe
BorrarCancion(idInteprete, idAlbum, aux[0]);
}
}
}
return canciones;
}
public void BorrarCancion(string idInterete, string idAlbum, string path)
{
BorrarRegistro("Cancion", "Path", path);
string[] cadena;
cadena = Leer_Columna("Cancion", "Id_Album", "Id_ALbum", idAlbum);
if (cadena.Length == 0)
{
BorrarRegistro("Album", "Id_Album", idAlbum);
cadena = Leer_Columna("Album", "Id_Interprete", "Id_Interprete", idInterete);
if (cadena.Length == 0)
{
BorrarRegistro("Interprete", "Id", idInterete);
}
}
}
public void BorrarRegistro(string tabla, string columf, string val)
{
OleDbCommand cmdBorrar = new OleDbCommand();
string cad = "DELETE FROM " + tabla + " WHERE " + columf + " = ?";
cmdBorrar.CommandType = CommandType.Text;
cmdBorrar.Connection = dbConnection;
cmdBorrar.Parameters.Add("?", val);
cmdBorrar.CommandText = cad;
try
{
cmdBorrar.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
}
public void DatosInterprete(string id, ref string nombre)
{
string[] aux = Leer_Columna("Interprete", "Nombre", "Id", id);
nombre = aux[0];
}
public void DatosAlbum(string id, ref string nombre, ref string idInterprete, ref string genero, ref string anio)
{
OleDbCommand cmdLeer = new OleDbCommand();
string cad = "SELECT * FROM Album WHERE Id_Album = ?";
cmdLeer.CommandType = CommandType.Text;
cmdLeer.Connection = dbConnection;
cmdLeer.Parameters.Add("?", id);
cmdLeer.CommandText = cad;
dbAdapter.SelectCommand = cmdLeer;
dbDataSet.Clear();// agregado clear, sino se arma lio con el dataset anterior
try
{
dbAdapter.Fill(dbDataSet);
nombre = dbDataSet.Tables[0].Rows[0]["Nombre"].ToString();
idInterprete = dbDataSet.Tables[0].Rows[0]["Id_Interprete"].ToString();
genero = dbDataSet.Tables[0].Rows[0]["Genero"].ToString();
anio = dbDataSet.Tables[0].Rows[0]["Año"].ToString();
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
}
public void DatosCancion(string id, ref string titulo, ref string idAlbum, ref string numero, ref string path)
{
OleDbCommand cmdLeer = new OleDbCommand();
string cad = "SELECT * FROM Cancion WHERE Id_Cancion = ?";
cmdLeer.CommandType = CommandType.Text;
cmdLeer.Connection = dbConnection;
cmdLeer.Parameters.Add("?", id);
cmdLeer.CommandText = cad;
dbAdapter.SelectCommand = cmdLeer;
dbDataSet.Clear();// agregado clear, sino se arma lio con el dataset anterior
try
{
dbAdapter.Fill(dbDataSet);
titulo = dbDataSet.Tables[0].Rows[0]["Titulo"].ToString();
idAlbum = dbDataSet.Tables[0].Rows[0]["Id_Album"].ToString();
numero = dbDataSet.Tables[0].Rows[0]["Numero_Cancion"].ToString();
path = dbDataSet.Tables[0].Rows[0]["Path"].ToString();
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
}
public void AgregarConfiguracionDeUsuario(string idUsuario, string skin, string perfil, string colorClaro, string colorOscuro)
{
//Primero creo el perfil por defecto
CrearNuevoPerfil(idUsuario, perfil);
//Ahora creo el registro en la parte de las ultimas configuraciones utilizadas
OleDbCommand cmdCfg = new OleDbCommand();
cmdCfg.CommandText = "INSERT INTO Configuraciones ([Id_Usuario], [Skin], [Perfil], [ColorClaro], [ColorOscuro]) VALUES (?, ?, ?, ?, ?)";
cmdCfg.Connection = dbConnection;
cmdCfg.Parameters.Add("?", idUsuario);
cmdCfg.Parameters.Add("?", skin);
cmdCfg.Parameters.Add("?", perfil);
cmdCfg.Parameters.Add("?", colorClaro);
cmdCfg.Parameters.Add("?", colorOscuro);
cmdCfg.ExecuteNonQuery();
}
public void CrearNuevoPerfil(string idUsuario, string nombrePerfil)
{
OleDbCommand cmdPerfil = new OleDbCommand();
cmdPerfil.CommandText = "INSERT INTO Perfil ([Id_Usuario], [Nombre]) VALUES (?, ?)";
cmdPerfil.Connection = dbConnection;
cmdPerfil.Parameters.Add("?", idUsuario);
cmdPerfil.Parameters.Add("?", nombrePerfil);
cmdPerfil.ExecuteNonQuery();
}
public void ModificarInterprete(string id, string nombre)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", nombre);
cmd.Parameters.Add("?", id);
cmd.CommandText = "UPDATE Interprete SET Nombre = ? WHERE Id = ?";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
}
public List<Cancion> CancionesDeArtista(string idInterprete)
{
List<Cancion> canciones = new List<Cancion>();
foreach (string idAlbum in Leer_Columna("Album", "Id_Album", "Id_Interprete", idInterprete))
{
foreach (string aux in Leer_Columna("Cancion", "Path", "Id_Album", idAlbum))
if (aux != null)
{
try
{
canciones.Add(new Cancion(aux));
}
catch (Exception)
{//si tira excepcion aca es porque el erchivo de musica ya no existe
BorrarCancion(idInterprete, idAlbum, aux);
}
}
}
return canciones;
}
public void ModificarAlbum(string id, string nombre, string idInterprete, string genero, string anio)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", nombre);
cmd.Parameters.Add("?", idInterprete);
cmd.Parameters.Add("?", genero);
cmd.Parameters.Add("?", anio);
cmd.Parameters.Add("?", id);
cmd.CommandText = "UPDATE Album SET Nombre = ?, Id_Interprete = ?, Genero = ?, Año = ? WHERE Id_Album = ?";
try
{
cmd.ExecuteNonQuery();
OleDbCommand cmdLeer = new OleDbCommand();
string cad = "SELECT * FROM Album WHERE Id_Interprete = ?";
cmdLeer.CommandType = CommandType.Text;
cmdLeer.Connection = dbConnection;
cmdLeer.Parameters.Add("?", idInterprete);
cmdLeer.CommandText = cad;
dbAdapter.SelectCommand = cmdLeer;
dbDataSet.Clear();
dbAdapter.Fill(dbDataSet);
for (int x = 0; x < dbDataSet.Tables[0].Rows.Count; x++)
{
for (int y = x + 1; y < dbDataSet.Tables[0].Rows.Count; y++)
{
if (dbDataSet.Tables[0].Rows[x][0].ToString() == dbDataSet.Tables[0].Rows[y]["Nombre"].ToString())
{
CombinarAlbunes(dbDataSet.Tables[0].Rows[x]["Id_Album"].ToString(), dbDataSet.Tables[0].Rows[y]["Id_Album"].ToString());
}
}
}
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
}
public List<Cancion> CancionesDeAlbum(string idAlbum, string idInterprete)
{
List<Cancion> canciones = new List<Cancion>();
foreach (string aux in Leer_Columna("Cancion", "Path", "Id_Album", idAlbum))
if (aux != null)
{
try
{
canciones.Add(new Cancion(aux));
}
catch (Exception)
{//si tira excepcion aca es porque el erchivo de musica ya no existe
BorrarCancion(idInterprete, idAlbum, aux);
}
}
return canciones;
}
public void ModificarCancion(string id, string titulo, string idAlbum, string numero, string path)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", titulo);
cmd.Parameters.Add("?", idAlbum);
cmd.Parameters.Add("?", numero);
cmd.Parameters.Add("?", path);
cmd.Parameters.Add("?", id);
cmd.CommandText = "UPDATE Cancion SET Titulo = ?, Id_Album = ?, Numero_Cancion = ?, Path = ? WHERE Id_Cancion = ?";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
}
public void CombinarInterpretes(string idOrigen, string idDestino)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", idDestino);
cmd.Parameters.Add("?", idOrigen);
cmd.CommandText = "UPDATE Album SET Id_Interprete = ? WHERE Id_Interprete = ?";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
OleDbCommand cmdLeer = new OleDbCommand();
string cad = "SELECT * FROM Album WHERE Id_Interprete = ?";
cmdLeer.CommandType = CommandType.Text;
cmdLeer.Connection = dbConnection;
cmdLeer.Parameters.Add("?", idDestino);
cmdLeer.CommandText = cad;
dbAdapter.SelectCommand = cmdLeer;
try
{
dbDataSet.Clear();
dbAdapter.Fill(dbDataSet);
for (int x = 0; x < dbDataSet.Tables[0].Rows.Count; x++)
{
for (int y = x + 1; y < dbDataSet.Tables[0].Rows.Count; y++)
{
if (dbDataSet.Tables[0].Rows[x]["Nombre"].ToString() == dbDataSet.Tables[0].Rows[y]["Nombre"].ToString())
{
CombinarAlbunes(dbDataSet.Tables[0].Rows[x]["Id_Album"].ToString(), dbDataSet.Tables[0].Rows[y]["Id_Album"].ToString());
}
}
}
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
BorrarRegistro("Interprete", "Id", idOrigen);
}
public void CombinarAlbunes(string idOrigen, string idDestino)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
cmd.Parameters.Add("?", idDestino);
cmd.Parameters.Add("?", idOrigen);
cmd.CommandText = "UPDATE Cancion SET Id_Album = ? WHERE Id_Album = ?";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Error al abrir la base de datos");
}
BorrarRegistro("Album", "Id_Album", idOrigen);
}
public List<string> Buscar(string cad)
{
List<string> lista = new List<string>();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = dbConnection;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("?", cad);
cmd.Parameters.Add("?", cad);
cmd.Parameters.Add("?", cad);
cmd.Parameters.Add("?", cad);
cmd.CommandText = "SELECT DISTINCT Path FROM Cancion WHERE Titulo LIKE ? OR Id_Album IN (SELECT Id_Album FROM Album WHERE Genero LIKE ?) OR Id_Album IN (SELECT Id_Album FROM Album WHERE Nombre LIKE ?) OR Id_Album IN (SELECT Id_Album FROM Album WHERE Id_Interprete IN (SELECT Id FROM Interprete WHERE Nombre LIKE ?) )";
//
dbDataSet.Clear();
dbAdapter.SelectCommand = cmd;
try
{
dbAdapter.Fill(dbDataSet);
for (int x = 0; x < dbDataSet.Tables[0].Rows.Count; x++)
{
lista.Add(dbDataSet.Tables[0].Rows[x]["Path"].ToString());
}
}
catch (Exception)
{
MessageBox.Show("Error en la base de datos");
}
return lista;
}
public void AgregarListaDeReproduccion(string nombre, string id_perfil, string ruta)
{
OleDbCommand agregar = new OleDbCommand();
// Desarrollo del comando
agregar.Connection = dbConnection;
agregar.Parameters.Add("?", nombre);
agregar.Parameters.Add("?", int.Parse(Leer_Columna("Cancion", "Id_Cancion", "Path", ruta)[0]));
agregar.Parameters.Add("?", int.Parse(id_perfil));
agregar.CommandText = @"INSERT INTO ListaDeReproduccion ([Nombre], [Id_Cancion], [Id_Perfil]) VALUES (?, ?, ?)";
agregar.ExecuteNonQuery();
}
public void ModificarConfiguracionesSkin(string dato, string usuario, string colorClaro, string colorOscuro)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
//cmd.Parameters.Add("?", campo);
cmd.Parameters.Add("?", dato);
cmd.Parameters.Add("?", colorClaro);
cmd.Parameters.Add("?", colorOscuro);
cmd.Parameters.Add("?", usuario);
cmd.CommandText = "UPDATE Configuraciones SET Skin = ?, ColorClaro = ?, ColorOscuro = ? WHERE Id_Usuario = ?";
cmd.ExecuteNonQuery();
}
public void ModificarConfiguracionesPerfil(string dato, string usuario)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = dbConnection;
//cmd.Parameters.Add("?", campo);
cmd.Parameters.Add("?", dato);
cmd.Parameters.Add("?", usuario);
cmd.CommandText = "UPDATE Configuraciones SET Perfil = ? WHERE Id_Usuario = ?";
cmd.ExecuteNonQuery();
}
public void BorrarListaDeReproduccion(string nombre)
{
OleDbCommand cmd = new OleDbCommand();
cmd.Parameters.Add("?", nombre);
cmd.Connection = dbConnection;
cmd.CommandText = "DELETE FROM ListaDeReproduccion WHERE Nombre = ?";
cmd.ExecuteNonQuery();
}
#endregion
}
}
|
1c00b60426b60299f67787d1f8f590a3e456327b
|
C#
|
BeardedMark/SoftForGameCustomElemetns
|
/CustomFilter 1/CustomControls/MenuElement.xaml.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CustomFilter_1.CustomControls
{
/// <summary>
/// Логика взаимодействия для MenuElement.xaml
/// </summary>
public partial class MenuElement : UserControl
{
public MenuElement()
{
InitializeComponent();
}
#region Text
public string ButtonText
{
get { return (string)GetValue(ButtonTextProperty); } // Загружает (возвращает) значение
set { SetValue(ButtonTextProperty, value); } // Сохраняет значение
}
public static readonly DependencyProperty ButtonTextProperty = DependencyProperty.Register( // регистрирует новый элемент для изменеия
"Text", // Ввести имя изменяемого элемента
typeof(string), // Тип в котором он хранится
typeof(MenuElement), // Среда в которой он присутствует
new PropertyMetadata("Text", new PropertyChangedCallback(ButtonTextChanged))); // Дефолтное значение и изменение значения
private static void ButtonTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var twoButton = d as MenuElement;
twoButton.ButtonTextChanged();
}
private void ButtonTextChanged()
{
Text.Text = ButtonText;
}
#endregion
#region Ico
public ImageSource ButtonIco
{
get { return (ImageSource)GetValue(ButtonIcoProperty); } // Загружает (возвращает) значение
set { SetValue(ButtonIcoProperty, value); } // Сохраняет значение
}
public static readonly DependencyProperty ButtonIcoProperty = DependencyProperty.Register( // регистрирует новый элемент для изменеия
"ButtonIco", // Ввести имя изменяемого элемента
typeof(ImageSource), // Тип в котором он хранится
typeof(MenuElement), // Среда в которой он присутствует
new PropertyMetadata(null, new PropertyChangedCallback(ButtonIcoChanged))); // Дефолтное значение и изменение значения
private static void ButtonIcoChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var twoButton = d as MenuElement;
twoButton.ButtonIcoChanged();
}
private void ButtonIcoChanged()
{
Source.Source = ButtonIco;
}
#endregion
private void Trigger_MouseEnter(object sender, MouseEventArgs e)
{
Marker.Visibility = Visibility.Visible;
}
private void Trigger_MouseLeave(object sender, MouseEventArgs e)
{
Marker.Visibility = Visibility.Hidden;
}
}
}
|
d505df954dbd57499f8496644828dae2a74f7bed
|
C#
|
kcassata/KISSMetricNet
|
/KissApiWrapper.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Text;
namespace DaneSolutions.Wrappers
{
public class KissApiWrapper : Dictionary<string, string>
{
private string apiKey;
private bool useSSL;
public KissApiWrapper(string apiKey, bool useSSL)
{
this.apiKey = apiKey;
this.useSSL = useSSL;
}
public KissApiWrapper AddProperty(string key, string value)
{
this.Add(key, value);
return this;
}
private string ConvertToTimestamp(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return ((double)span.TotalSeconds).ToString();
}
public void SendEvent(string eventName, string userName, DateTime? eventDate)
{
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.Append(useSSL ? "https://" : "http://");
urlBuilder.Append("trk.kissmetrics.com/e");
urlBuilder.AppendFormat("?_k={0}", apiKey);
urlBuilder.AppendFormat("&_n={0}", eventName);
urlBuilder.AppendFormat("&_d={0}", eventDate.HasValue ? "1" : "0");
urlBuilder.AppendFormat("&_p={0}", userName);
if (eventDate.HasValue)
urlBuilder.AppendFormat("&_t={0}", ConvertToTimestamp(eventDate.Value));
foreach (string key in this.Keys)
{
urlBuilder.AppendFormat("&{0}={1}", System.Web.HttpUtility.HtmlEncode(key), System.Web.HttpUtility.HtmlEncode(this[key]));
}
GetUrl(urlBuilder.ToString());
this.Clear();
}
public static void GetUrl(string url)
{
HttpWebRequest r = (HttpWebRequest)HttpWebRequest.Create(url);
r.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
r.Headers.Add("Cache-Control", "no-cache");
r.KeepAlive = false;
r.ReadWriteTimeout = 30000;
r.AllowAutoRedirect = true;
r.Timeout = 30000;
string data = string.Empty;
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
{
StreamReader rdr = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
data = rdr.ReadToEnd();
resp.Close();
}
}
}
}
|
a33fa2faf267b4dfdcb1a3f48acca0da114cb1aa
|
C#
|
sudipp/DS-Algo
|
/ConsoleApplication1/DesignPattern/Structural/Composite/Shape.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1.DesignPattern.Structural.Composite
{
public class Shape : IComponent
{
public void Render()
{
Console.WriteLine("Render shape");
}
public void Resize()
{
Console.WriteLine("Resize shape");
}
}
}
|