Datasets:

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
a29a410123c27947c3e681036df366496ac1d86f
C#
princeroshan/C-sharp-Programs
/VariableInitializationType/VariableInitializationType/Program.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VariableInitializationType { class Program { int y; var abcd=103; static void Main() { //compile time Initialization int x = 10; Console.WriteLine("local variable value :{0}", x); //when use "," use {0} Program obj = new Program(); Console.WriteLine("Class Level Variable :"+ obj.y); //use + when no use "," and {0} Console.WriteLine(abcd); } } }
a5fabe277ae94ce04b2a8ae570b69b19fc365ab0
C#
Bovtun/Laba5
/WindowsFormsApplication1/Address.cs
3.375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApplication1 { public class Address { public int Sell1; public int Sell2; public int Sell3; public int Sell4; public Address (int Sell1, int Sell2, int Sell3, int Sell4) { this.Sell1 = Sell1; this.Sell2 = Sell2; this.Sell3 = Sell3; this.Sell4 = Sell4; } public bool Equals(Address X,Address Y) { if (X.Sell1 == Y.Sell1) { if (X.Sell2 == Y.Sell2) { if (X.Sell3 == Y.Sell3) { if (X.Sell4 == Y.Sell4) return true; } } } return false; } public static implicit operator string(Address addr) { return addr.ToString(); } public override string ToString() { string WorkRow = ""; WorkRow = "." + WorkRow.Insert(0, Convert.ToString(this.Sell4)); WorkRow = "." + WorkRow.Insert(0, Convert.ToString(this.Sell3)); WorkRow = "." + WorkRow.Insert(0, Convert.ToString(this.Sell2)); WorkRow = WorkRow.Insert(0, Convert.ToString(this.Sell1)); return WorkRow; } public static bool Check(Address Address) { int i = 0; bool Flag = true; string str = Address; string[] split = str.Split('.'); while (i != 4) { if (Convert.ToInt32(split[i]) > 255) { Flag = false; } i++; } return Flag; } } }
e272aad0f05686191a9019758a6fd39c3677d38c
C#
chantysothy/Compas
/CompasServices/Contractors/ContractorTypesLogic.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Compas.Model; namespace Compas.Logic.Contractors { /// <summary> /// Упавління довідником типів контрагентів /// </summary> public class ContractorTypesLogic : IGenericInterface<ContractorType> { private CompasDataContext context; public ContractorTypesLogic(ContextManager contextManager) { context = contextManager.Context; } public ContractorType Get(int ID) { ContractorType result; result = (from a in context.ContractorTypes where a.ID == ID select a).FirstOrDefault(); return result; } public List<ContractorType> GetAll() { List<ContractorType> result; result = (from a in context.ContractorTypes select a).ToList().OrderBy(a => a.Name).ToList(); return result; } public int Create(string Name) { int result = 1; ContractorType sr = ContractorType.CreateContractorType(1, Name); context.AddToContractorTypes(sr); return result; } public int Update(int ID, string Name) { int result = 1; ContractorType sr = (from a in context.ContractorTypes where a.ID == ID select a).FirstOrDefault(); sr.Name = Name; return result; } public int Delete(int ID) { int result = 1; ContractorType sr = (from a in context.ContractorTypes where a.ID == ID select a).FirstOrDefault(); if (sr != null) context.ContractorTypes.DeleteObject(sr); return result; } } }
42bfac4d6f3048d3e8f1e0a50186ea94cccd6bdc
C#
PavloVoitenko/timeTracker
/TimeTracker/TimeTracker.Dto/TrackingDto.cs
2.765625
3
using System; using TimeTracker.Model.Entities; namespace TimeTracker.DTOs { public class TrackingDto { public int? TrackingId { get; set; } public string ProjectName { get; set; } public string TaskName { get; set; } public string TaskDescription { get; set; } public TaskType TaskType { get; set; } public DateTime TrackingDate { get; set; } public TimeDto StartTime { get; set; } public TimeDto EndTime { get; set; } } public class TimeDto { public int Hours { get; set; } public int Minutes { get; set; } public TimeSpan ToSpan() { return new TimeSpan(Hours, Minutes, 0); } } }
fae48a714abdfa2c1a2f6e556da5e5b29248abc2
C#
kwaclaw/EtwStream
/EtwStream/SubscriptionContainer.cs
2.640625
3
using System; using System.Reactive.Disposables; namespace EtwStream { public interface ISubscriptionContainer { void Add(IDisposable subscription); } public class SubscriptionContainer : ISubscriptionContainer { readonly CompositeDisposable subscriptions = new CompositeDisposable(); public void Add(IDisposable subscription) { subscriptions.Add(subscription); } public void Dispose() { subscriptions.Dispose(); } } public static class EtwStreamSubscriptionContainerExtensions { public static void AddTo(this IDisposable subscription, ISubscriptionContainer container) { container.Add(subscription); } } }
4434cb0d3fa3607ed73b05e0ac2420365c23b7b9
C#
asz3740/CDB
/MembAs.cs
2.5625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WINTEST { public partial class MembAs : Form { private string id; private string name; private string city; private string dong; private string detail; private string phone; private int selectedRowIndex; public MembAs() { InitializeComponent(); } public MembAs(int selectedRowIndex, string v1, string v2, string v3, string v4, string v5, string v6) { InitializeComponent(); this.selectedRowIndex = selectedRowIndex; this.id = v1; this.name = v2; this.city = v3; this.dong = v4; this.detail = v5; this.phone = v6; } Memb mainForm; private void Form5_Load(object sender, EventArgs e) { txtId.Text = id; txtName.Text = name; txtCity.Text = city; txtDong.Text = dong; txtDetail.Text = detail; txtPhone.Text = phone; if (Owner != null) { mainForm = Owner as Memb; } } private void btnInsert_Click(object sender, EventArgs e) { string[] rowDatas = { txtName.Text, txtCity.Text, txtDong.Text, txtDetail.Text, txtPhone.Text}; mainForm.InsertRow(rowDatas); this.Close(); } private void btnUpdate_Click(object sender, EventArgs e) { string[] rowDatas = { txtId.Text, txtName.Text, txtCity.Text, txtDong.Text, txtDetail.Text, txtPhone.Text}; mainForm.UpdateRow(rowDatas); this.Close(); } private void btnDelete_Click(object sender, EventArgs e) { var result = MessageBox.Show("주문 내역에 삭제하려는 고객의 정보가 있을 수 있습니다.. 그래도 삭제하시겠습니까?", "삭제확인창", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { mainForm.DeleteRow(id); this.Close(); } } private void btnTextBoxClear_Click(object sender, EventArgs e) { txtId.Clear(); txtName.Clear(); txtCity.Clear(); txtDong.Clear(); txtDetail.Clear(); txtPhone.Clear(); } } }
558ac271459e011c2ddce379a01e15c49c9c6752
C#
karunyam90/Code_Practice
/Graphs_UniqueRegions_InBooleanMatrix/Program.cs
3.328125
3
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; //Eugune session problem. Check book for diagrams // Matrix (eg., 4X4) of bools where True represent / and False represent \. Then find unique regions (areas) separated in that matrix. /* lest take 4 X 4 \ \ / / \ / / \ / \ \ / \ / \ \ \ => false / => true Answer is => 10 unique regions */ using System.Xml; namespace Graphs_UniqueRegions_InBooleanMatrix { class Program { static void Main(string[] args) { bool[,] matrix = new bool[4, 4] { {false, false, true, true}, {false, true, true, false}, {true, false, false, true}, {false, true, false, false} }; int uniqueRegions = FindUniqueRegions(matrix); Console.WriteLine("Unique Regions : "+uniqueRegions); Console.ReadKey(); } private static int FindUniqueRegions(bool[,] matrix) { int uniqueRegions = 0; int matrixRows = matrix.GetLength(0); int matrixColumns = matrix.GetLength(1); //We have to image each triangle as a node in the graph and we have to connect then based on true / or false \ edges. //Lets build the graph with 3-dimensional array Node[, ,] graph = new Node[matrixRows, matrixColumns, 2]; //Lets create all the nodes first. for (int i = 0; i < matrixRows; i++) { for (int j = 0; j < matrixColumns; j++) { for (int k = 0; k < 2; k++) { graph[i,j,k] = new Node(); } } } //If two triangles of 1str cell if A1 and A2 and second cell is B1 and B2, then A2 and 1 will always connected. Lets do similar connections across the graph for (int i = 0; i < matrixRows; i++) { for (int j = 0; j < matrixColumns-1; j++) { var firstTriangle = graph[i, j, 1]; //Right side triangle in left side cell var secondTriangle = graph[i, j + 1, 0]; // Left side triangle of the right side cell //Connect above nodes both ways firstTriangle.AdjacentNodes.Add(secondTriangle); secondTriangle.AdjacentNodes.Add(firstTriangle); } } //Now connect nodes/triangles with their below triangles based on current cell value. for (int i = 0; i < matrixRows-1; i++) { for (int j = 0; j < matrixColumns; j++) { Node topTriangle = null; Node bottomTriangle = null; if(matrix[i, j]) //Top cell topTriangle = graph[i, j, 1]; //Take A2 if cell value is true else topTriangle = graph[i, j, 0]; //Take A1 if cell value is false if(matrix[i + 1, j]) //Bottom cell bottomTriangle = graph[i + 1, j, 0]; //Take B1 if cell value if true else bottomTriangle = graph[i + 1, j, 1]; //Take B2 if cell value if false //Now connect both of those nodes topTriangle.AdjacentNodes.Add(bottomTriangle); bottomTriangle.AdjacentNodes.Add(topTriangle); } } //Now we have to find number of unique regions (connected components) HashSet<Node> h = new HashSet<Node>(); for (int i = 0; i < matrixRows; i++) { for (int j = 0; j < matrixColumns; j++) { for (int k = 0; k <= 1; k++) { if (!h.Contains(graph[i, j, k])) { uniqueRegions++; h.Add(graph[i,j,k]); ProcessPath(graph[i, j, k],h); } } } } return uniqueRegions; } //BFS private static void ProcessPath(Node node, HashSet<Node> h) { Queue<Node> q = new Queue<Node>(); q.Enqueue(node); while (q.Count() !=0) { var n = q.Dequeue(); foreach (var adjacentNode in n.AdjacentNodes) { if (!h.Contains(adjacentNode)) { h.Add(adjacentNode); q.Enqueue(adjacentNode); } } } } } public class Node { public List<Node> AdjacentNodes = new List<Node>(); } }
0b9c4cc38d8a5796501e2cca86a2232f80fd8d96
C#
charygao/Net4.5ConsoleAppTest
/Net4.5ConsoleAppTest/codes/No000004SortedList.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; namespace Chinese中文排序Sort { internal class Program { private static void Main(string[] args) { var tmpDic = new SortedList<string, string>(); tmpDic.Add("a", "a"); tmpDic.Add("1", "1"); tmpDic.Add("2", "2"); tmpDic.Add("b", "b"); //tmpDic.Reverse();//12ab foreach (var item in tmpDic.Keys.Reverse())//ba21 { Console.WriteLine(item); } var firstSortWord = new SortedList<string, string>(); tmpDic.Add("a", "a"); tmpDic.Add("1", "1"); tmpDic.Add("2", "2"); tmpDic.Add("b", "b"); Console.ReadKey(); } } }
421718603349320ebe0c0c66b1ec645a86ad9856
C#
shauryamalik/ImplementML
/ImplementML/KernelLogisticProgram.cs
3.109375
3
using System; namespace ImplementML { class KernelLogisticProgram { static Random rnd = new Random(0); public static void MainFunc() { Console.WriteLine("\nBegin kernel logistic regression demo \n"); int numFeatures = 2; Console.WriteLine("Goal is binary classification (0/1) \n"); Console.WriteLine("Setting up 21 training and 4 test data items \n"); // donut-like data (not linearly separable) double[][] trainData = new double[21][]; trainData[0] = new double[] { 2.0, 3.0, 0 }; trainData[1] = new double[] { 1.0, 5.0, 0 }; trainData[2] = new double[] { 2.0, 7.0, 0 }; trainData[3] = new double[] { 3.0, 2.0, 0 }; trainData[4] = new double[] { 3.0, 8.0, 0 }; trainData[5] = new double[] { 4.0, 2.0, 0 }; trainData[6] = new double[] { 4.0, 8.0, 0 }; trainData[7] = new double[] { 5.0, 2.0, 0 }; trainData[8] = new double[] { 5.0, 8.0, 0 }; trainData[9] = new double[] { 6.0, 3.0, 0 }; trainData[10] = new double[] { 7.0, 5.0, 0 }; trainData[11] = new double[] { 6.0, 7.0, 0 }; trainData[12] = new double[] { 3.0, 4.0, 1 }; trainData[13] = new double[] { 3.0, 5.0, 1 }; trainData[14] = new double[] { 3.0, 6.0, 1 }; trainData[15] = new double[] { 4.0, 4.0, 1 }; trainData[16] = new double[] { 4.0, 5.0, 1 }; trainData[17] = new double[] { 4.0, 6.0, 1 }; trainData[18] = new double[] { 5.0, 4.0, 1 }; trainData[19] = new double[] { 5.0, 5.0, 1 }; trainData[20] = new double[] { 5.0, 6.0, 1 }; // test data double[][] testData = new double[4][]; testData[0] = new double[] { 1.5, 4.5, 0 }; testData[1] = new double[] { 7.0, 6.5, 0 }; testData[2] = new double[] { 3.5, 4.5, +1 }; testData[3] = new double[] { 5.5, 5.5, +1 }; Console.WriteLine("training [0] = (2.0, 3.0, 0)"); Console.WriteLine("training [1] = (1.0, 5.0, 0)"); Console.WriteLine(" . . . "); Console.WriteLine("training [20] = (5.0, 6.0, 1)"); //// a super-tiny dataset //double[][] trainData = new double[4][]; //trainData[0] = new double[] { 2.0, 4.0, 0 }; //trainData[1] = new double[] { 4.0, 1.0, 1 }; //trainData[2] = new double[] { 5.0, 3.0, 0 }; //trainData[3] = new double[] { 6.0, 7.0, 1 }; //double[][] testData = new double[1][]; //testData[0] = new double[] { 3.0, 5.0, 0 }; int numTrain = trainData.Length; int numTest = testData.Length; double[] alphas = new double[numTrain + 1]; // one alpha weight for each train item, plus bias at end for (int i = 0; i < alphas.Length; ++i) alphas[i] = 0.0; // pre-compute all kernels - only viable if numTrain is not huge double[][] kernelMatrix = new double[numTrain][]; // item-item similarity for (int i = 0; i < kernelMatrix.Length; ++i) kernelMatrix[i] = new double[numTrain]; double sigma = 1.0; for (int i = 0; i < numTrain; ++i) // pre-compute all Kernel { for (int j = 0; j < numTrain; ++j) { double k = Kernel(trainData[i], trainData[j], sigma); kernelMatrix[i][j] = kernelMatrix[j][i] = k; } } //// display kernel matrix //Console.WriteLine("\n-------------\n"); //for (int i = 0; i < numTrain; ++i) // pre-compute all Kernel //{ // for (int j = 0; j < numTrain; ++j) // { // Console.Write(kernelMatrix[i][j].ToString("F8") + " "); // } // Console.WriteLine(""); //} //Console.WriteLine("\n-------------\n"); // train. aj = aj + eta(t - y) * K(i,j) double eta = 0.001; // aka learning-rate int iter = 0; int maxIter = 1000; int[] indices = new int[numTrain]; for (int i = 0; i < indices.Length; ++i) indices[i] = i; Console.WriteLine("\nStarting training"); Console.WriteLine("Using RBF kernel() with sigma = " + sigma.ToString("F1")); Console.WriteLine("Using SGD with eta = " + eta + " and maxIter = " + maxIter); while (iter < maxIter) { Shuffle(indices); // visit train data in random order for (int idx = 0; idx < indices.Length; ++idx) // each 'from' train data { int i = indices[idx]; // current train data index double sum = 0.0; // sum of alpha-i * kernel-i for (int j = 0; j < alphas.Length - 1; ++j) // not the bias sum += alphas[j] * kernelMatrix[i][j]; sum += alphas[alphas.Length - 1]; // add bias (last alpha) -- 'input' is dummy 1.0 double y = 1.0 / (1.0 + Math.Exp(-sum)); double t = trainData[i][numFeatures]; // last col holds target value // update each alpha for (int j = 0; j < alphas.Length - 1; ++j) alphas[j] = alphas[j] + (eta * (t - y) * kernelMatrix[i][j]); // update the bias alphas[alphas.Length - 1] = alphas[alphas.Length - 1] + (eta * (t - y)) * 1; // dummy input } ++iter; } // while (train) Console.WriteLine("\nTraining complete"); Console.WriteLine("\nTrained model alpha values: \n"); for (int i = 0; i < 3; ++i) Console.WriteLine(" [" + i + "] " + alphas[i].ToString("F4")); Console.WriteLine(" . . ."); for (int i = alphas.Length - 3; i < alphas.Length - 1; ++i) Console.WriteLine(" [" + i + "] " + alphas[i].ToString("F4")); Console.WriteLine(" [" + (alphas.Length - 1) + "] (bias) " + alphas[alphas.Length - 1].ToString("F4")); Console.WriteLine(""); Console.WriteLine("Evalating model accuracy on train data"); double accTrain = Accuracy(trainData, trainData, alphas, sigma, false); Console.WriteLine("accuracy = " + accTrain.ToString("F4") + "\n"); Console.WriteLine("Evalating model accuracy on test data"); double accTest = Accuracy(testData, trainData, alphas, sigma, true); // verbose //Console.WriteLine("accuracy = " + accTest.ToString("F4")); Console.WriteLine("\nEnd kernel logistic regression demo "); Console.ReadLine(); } // Main static double Accuracy(double[][] data, double[][] trainData, double[] alphas, double sigma, bool verbose) { int numCorrect = 0; int numWrong = 0; int numTrain = trainData.Length; int numFeatures = trainData[0].Length - 1; for (int i = 0; i < data.Length; ++i) // i index into data to predict { // compare currr against all trainData double sum = 0.0; for (int j = 0; j < alphas.Length - 1; ++j) { double k = Kernel(data[i], trainData[j], sigma); sum += alphas[j] * k; // (cannot pre-compute) } sum += alphas[alphas.Length - 1] * 1; // add the bias double y = 1.0 / (1.0 + Math.Exp(-sum)); double t = data[i][numFeatures]; double pred = 0; if (y > 0.5) pred = 1; if (verbose) { Console.Write(" input = ("); for (int j = 0; j < data[i].Length - 2; ++j) { Console.Write(data[i][j].ToString("F1") + ", "); } Console.Write(data[i][data[i].Length - 2].ToString("F1")); Console.Write(")"); Console.Write(" actual = " + t + " calc y = " + y.ToString("F4") + " pred = " + pred.ToString("F0")); if (y <= 0.5 && t == 0.0 || y > 0.5 && t == 1.0) { ++numCorrect; Console.WriteLine(" correct"); } else { ++numWrong; Console.WriteLine(" WRONG"); } } else // not verbose { if (y <= 0.5 && t == 0.0 || y > 0.5 && t == 1.0) ++numCorrect; else ++numWrong; } } // each test data if (verbose) Console.WriteLine("numCorrect = " + numCorrect + " numWrong = " + numWrong); return (1.0 * numCorrect) / (numCorrect + numWrong); } static double Kernel(double[] v1, double[] v2, double sigma) { // RBF kernel. v1 & v2 have class label in last cell double num = 0.0; for (int i = 0; i < v1.Length - 1; ++i) // not last cell num += (v1[i] - v2[i]) * (v1[i] - v2[i]); double denom = 2.0 * sigma * sigma; double z = num / denom; return Math.Exp(-z); } static void Shuffle(int[] indices) { // assumes class-scope Random object rnd for (int i = 0; i < indices.Length; ++i) { int ri = rnd.Next(i, indices.Length); int tmp = indices[i]; indices[i] = indices[ri]; indices[ri] = tmp; } } } // Program } // ns // a bit more interesting data: //double[][] trainData = new double[100][]; //trainData[0] = new double[] { -7.5, 5.5, 0 }; //trainData[1] = new double[] { 3.0, 9.5, 0 }; //trainData[2] = new double[] { 2.5, -1.0, 1 }; //trainData[3] = new double[] { -5.0, 9.0, 0 }; //trainData[4] = new double[] { 0.0, 2.5, 1 }; //trainData[5] = new double[] { -9.5, 1.5, 0 }; //trainData[6] = new double[] { 3.0, 1.0, 1 }; //trainData[7] = new double[] { 2.5, -1.5, 1 }; //trainData[8] = new double[] { 4.5, -9.0, 0 }; //trainData[9] = new double[] { 8.0, -3.0, 0 }; //trainData[10] = new double[] { 6.0, -7.0, 0 }; //trainData[11] = new double[] { 9.5, 3.0, 0 }; //trainData[12] = new double[] { 2.0, -1.5, 1 }; //trainData[13] = new double[] { -10.0, -1.5, 0 }; //trainData[14] = new double[] { 0.0, 10.0, 0 }; //trainData[15] = new double[] { -0.5, -9.5, 0 }; //trainData[16] = new double[] { -1.5, 9.5, 0 }; //trainData[17] = new double[] { -7.5, -4.5, 0 }; //trainData[18] = new double[] { -3.0, -9.0, 0 }; //trainData[19] = new double[] { 2.0, 1.5, 1 }; //trainData[20] = new double[] { -1.0, -1.5, 1 }; //trainData[21] = new double[] { 9.0, 4.5, 0 }; //trainData[22] = new double[] { -2.0, -1.5, 1 }; //trainData[23] = new double[] { -2.0, -0.5, 1 }; //trainData[24] = new double[] { -1.5, -1.0, 1 }; //trainData[25] = new double[] { 1.0, 2.5, 1 }; //trainData[26] = new double[] { 8.5, 5.5, 0 }; //trainData[27] = new double[] { -1.5, 1.0, 1 }; //trainData[28] = new double[] { -2.5, 1.0, 1 }; //trainData[29] = new double[] { -6.5, 6.0, 0 }; //trainData[30] = new double[] { -0.5, 3.0, 1 }; //trainData[31] = new double[] { 0.5, 2.0, 1 }; //trainData[32] = new double[] { -9.5, -3.0, 0 }; //trainData[33] = new double[] { -2.5, 0.0, 1 }; //trainData[34] = new double[] { 1.0, 2.5, 1 }; //trainData[35] = new double[] { -2.0, -0.5, 1 }; //trainData[36] = new double[] { -6.5, 6.0, 0 }; //trainData[37] = new double[] { 0.0, -3.0, 1 }; //trainData[38] = new double[] { 6.0, 7.0, 0 }; //trainData[39] = new double[] { 1.5, -10.0, 0 }; //trainData[40] = new double[] { 6.5, 6.0, 0 }; //trainData[41] = new double[] { -3.0, -1.5, 1 }; //trainData[42] = new double[] { 1.5, 9.0, 0 }; //trainData[43] = new double[] { 1.0, 2.0, 1 }; //trainData[44] = new double[] { -9.0, 3.5, 0 }; //trainData[45] = new double[] { 2.0, -2.5, 1 }; //trainData[46] = new double[] { -8.5, 2.0, 0 }; //trainData[47] = new double[] { 0.5, 9.5, 0 }; //trainData[48] = new double[] { 2.0, -2.0, 1 }; //trainData[49] = new double[] { -10.5, 0.0, 0 }; //trainData[50] = new double[] { -1.5, -2.5, 1 }; //trainData[51] = new double[] { 9.0, -2.5, 0 }; //trainData[52] = new double[] { -5.5, 8.5, 0 }; //trainData[53] = new double[] { -1.0, 2.0, 1 }; //trainData[54] = new double[] { -7.0, -6.0, 0 }; //trainData[55] = new double[] { -4.0, -9.5, 0 }; //trainData[56] = new double[] { -3.0, 10.0, 0 }; //trainData[57] = new double[] { 2.5, 0.0, 1 }; //trainData[58] = new double[] { -0.5, -3.5, 1 }; //trainData[59] = new double[] { -2.0, -2.5, 1 }; //trainData[60] = new double[] { -9.0, -3.0, 0 }; //trainData[61] = new double[] { -0.5, 2.5, 1 }; //trainData[62] = new double[] { -2.0, 3.0, 1 }; //trainData[63] = new double[] { -5.5, -8.0, 0 }; //trainData[64] = new double[] { 8.0, -4.5, 0 }; //trainData[65] = new double[] { 5.5, -9.0, 0 }; //trainData[66] = new double[] { 3.5, -9.5, 0 }; //trainData[67] = new double[] { -7.0, -8.0, 0 }; //trainData[68] = new double[] { 1.5, -2.5, 1 }; //trainData[69] = new double[] { -2.5, 1.0, 1 }; //trainData[70] = new double[] { 10.0, -0.5, 0 }; //trainData[71] = new double[] { 5.5, 7.5, 0 }; //trainData[72] = new double[] { -7.5, -6.0, 0 }; //trainData[73] = new double[] { 3.5, 0.0, 1 }; //trainData[74] = new double[] { -1.5, 2.5, 1 }; //trainData[75] = new double[] { 2.0, 1.5, 1 }; //trainData[76] = new double[] { -0.5, -2.5, 1 }; //trainData[77] = new double[] { -3.0, 0.5, 1 }; //trainData[78] = new double[] { -2.5, -0.5, 1 }; //trainData[79] = new double[] { -8.0, 4.0, 0 }; //trainData[80] = new double[] { 0.5, -3.5, 1 }; //trainData[81] = new double[] { 9.5, 0.0, 0 }; //trainData[82] = new double[] { 9.0, 3.5, 0 }; //trainData[83] = new double[] { 1.5, 1.0, 1 }; //trainData[84] = new double[] { 0.0, -9.5, 0 }; //trainData[85] = new double[] { 7.0, -6.5, 0 }; //trainData[86] = new double[] { 1.5, -1.5, 1 }; //trainData[87] = new double[] { -1.5, -9.5, 0 }; //trainData[88] = new double[] { 1.5, 2.0, 1 }; //trainData[89] = new double[] { 1.0, -2.0, 1 }; //trainData[90] = new double[] { 1.5, -0.5, 1 }; //trainData[91] = new double[] { 2.0, 2.0, 1 }; //trainData[92] = new double[] { 4.0, 9.5, 0 }; //trainData[93] = new double[] { 2.5, 0.0, 1 }; //trainData[94] = new double[] { -3.0, 1.5, 1 }; //trainData[95] = new double[] { 0.0, -2.0, 1 }; //trainData[96] = new double[] { 9.5, 1.0, 0 }; //trainData[97] = new double[] { -2.0, 1.5, 1 }; //trainData[98] = new double[] { 2.5, 1.0, 1 }; //trainData[99] = new double[] { 9.5, -4.5, 0 }; //double[][] testData = new double[20][]; //testData[0] = new double[] { 2.5, 8.5, 0 }; //testData[1] = new double[] { -9.5, -0.5, 0 }; //testData[2] = new double[] { 0.0, -2.0, 1 }; //testData[3] = new double[] { 1.5, -2.0, 1 }; //testData[4] = new double[] { 0.5, 2.0, 1 }; //testData[5] = new double[] { 7.5, 5.5, 0 }; //testData[6] = new double[] { 2.5, 1.0, 1 }; ////testData[7] = new double[] { 4.0, 0.0, 1 }; //testData[7] = new double[] { 4.5, 0.0, 1 }; // to get an error! //testData[8] = new double[] { -0.5, 2.5, 1 }; //testData[9] = new double[] { 1.0, -2.5, 1 }; //testData[10] = new double[] { -2.0, -9.5, 0 }; //testData[11] = new double[] { -7.0, 6.0, 0 }; //testData[12] = new double[] { 2.5, -9.5, 0 }; //testData[13] = new double[] { 8.5, -5.5, 0 }; //testData[14] = new double[] { 10.5, 0.0, 0 }; //testData[15] = new double[] { -2.5, -2.0, 1 }; //testData[16] = new double[] { -8.0, -6.0, 0 }; //testData[17] = new double[] { -3.0, -0.5, 1 }; //testData[18] = new double[] { -2.0, 1.0, 1 }; //testData[19] = new double[] { -2.0, 8.5, 0 };
60f797c80e6b070a5efe6fcb1ad26049a43d31a1
C#
ojpbay/CodeWars
/SpacesRemover.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CodeWars { public static class SpacesRemover { public static string NoSpace(string input) { return new string(input.ToCharArray().Where(c => c.ToString() != " ").ToArray()); } } }
e0c2fea1ca15fa82367e1451ad8f250d447d0294
C#
kimyoungsun3/_Lesson_ScriptTest6
/Assets/100/130 Fun(Array)/ArrayFloat.cs
3.046875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ArrayTest { public class ArrayFloat : MonoBehaviour { public float[] array = new float[2]; void Start() { Display<float>("Start1", array); Fun1(array); Display<float>("Start2", array); } void Fun1(float[] _array) { Display<float>(" Fun11", _array); for (int i = 0; i < _array.Length; i++) _array[i] *= 10; Display<float>(" Fun12", _array); } void Display<T>(string _msg, T[] _t) { for (int i = 0; i < _t.Length; i++) Debug.Log(_msg + " " + i + " > " + _t[i]); } } }
664c3a9a3452e974576c72e978cb5874a87aeb74
C#
B-166ER/3DPinBallDemo
/3DPingPong/Assets/BallBehaviour.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallBehaviour : MonoBehaviour { Rigidbody selfRigidBody; [SerializeField] float anyDirectionLimit; [SerializeField] float breakAmount; [SerializeField] float zVelocity; [SerializeField] float yMaxVelocity; float newVelocity; Vector3 velocityCache; void Start() { selfRigidBody = gameObject.GetComponent<Rigidbody>(); // which value should apply when velocity passes the threshold. newVelocity = anyDirectionLimit - breakAmount; // push the ball at the begining. selfRigidBody.AddForce(0f, 0f, 100f); } //Bounciness gets inifintly fast. //Limiting Velocity. private void FixedUpdate() { // dont make triple each update. try else if 3 frames to set velocities enough velocityCache = selfRigidBody.velocity; if (velocityCache.x > anyDirectionLimit) velocityCache.x = newVelocity; if (Mathf.Abs( velocityCache.y ) > yMaxVelocity) velocityCache.y = yMaxVelocity * Mathf.Sign(velocityCache.y); if (velocityCache.z < 0) velocityCache.z = -newVelocity; if (velocityCache.z > 0) velocityCache.z = newVelocity; selfRigidBody.velocity = velocityCache; } void Update() { } }
7852825dbc7be208b3c5e18cd4b8f83fea8e303a
C#
pranayapragyan/RoyalCottage
/src/Platform/Nandalala.Paas.Core/Broker.cs
2.5625
3
using SimpleInjector; using Nandalala.Paas.Core.Command; using Nandalala.Paas.Core.Eventing; using Nandalala.Paas.Core.Query; using System; namespace Nandalala.Paas.Core { public class Broker : IBroker { private readonly Container _container; public Broker(Container container) { _container = container; } public TResult Execute<TResult>(QueryBase<TResult> queryBase) { var handlerType = typeof(IQueryHandler<,>).MakeGenericType(queryBase.GetType(), typeof(TResult)); dynamic handler = _container.GetInstance(handlerType); try { return handler.Handle((dynamic)queryBase); } catch (Exception) { throw; } } public void Dispatch<TCommand>(TCommand command) where TCommand : CommandBase { var handler = _container.GetInstance<ICommandHandler<TCommand>>(); try { handler.Handle(command); } catch (Exception) { throw; } } public void Raise<TEvent>(TEvent eventToHandle) where TEvent : IEvent { var handlers = _container.GetAllInstances<IEventHandler<TEvent>>(); try { foreach (var handler in handlers) { handler.Handle(eventToHandle); } } catch (Exception) { throw; } } } }
34954c78c00b4b6e10a91ab60402eef733d4e4df
C#
VERNADOM/newmail_OutlookCOM
/newmail_OutlookCOM/IMAP.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Net; using System.Net.Sockets; using System.Net.Security; using System.IO; namespace newmail_OutlookCOM { class Imap { protected TcpClient _tcpClient; protected StreamReader _reader; protected StreamWriter _writer; protected string _selectedFolder = string.Empty; protected int _prefix = 1; public Imap(string host, int port, bool ssl = false) { try { _tcpClient = new TcpClient(host, port); if (ssl) { var stream = new SslStream(_tcpClient.GetStream()); stream.AuthenticateAsClient(host); _reader = new StreamReader(stream); _writer = new StreamWriter(stream); } else { var stream = _tcpClient.GetStream(); _reader = new StreamReader(stream); _writer = new StreamWriter(stream); } string greeting = _reader.ReadLine(); } catch (Exception e) { Console.WriteLine(e.Message); } } public void Authenicate(string user, string pass) { this.SendCommand(string.Format("LOGIN {0} {1}", user, pass)); string response = this.GetResponse(); } public void SelectFolder(string folderName) { this._selectedFolder = folderName; this.SendCommand("SELECT " + folderName); string response = this.GetResponse(); } public int GetUnseenMessageCount() { this.SendCommand("STATUS " + this._selectedFolder + " (unseen)"); string response = this.GetResponse(); Match m = Regex.Match(response, "[0-9]*[0-9]"); return Convert.ToInt32(m.ToString()); } protected void SendCommand(string cmd) { _writer.WriteLine("A" + _prefix.ToString() + " " + cmd); _writer.Flush(); _prefix++; } protected string GetResponse() { string response = string.Empty; while (true) { string line = _reader.ReadLine(); string[] tags = line.Split(new char[] { ' ' }); response += line + Environment.NewLine; if (tags[0].Substring(0, 1) == "A" && tags[1].Trim() == "OK" || tags[1].Trim() == "BAD" || tags[1].Trim() == "NO") { break; } } return response; } } }
96884dc3f3e85d7cdb047b313665c48fa5c66d68
C#
harpagornis/coding.abel.nu
/TestLib/Tuples/GoodTupleSamples.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestLib.Tuples { public class GoodTupleSamples { public struct TirePressureInfo { readonly double front, back; public TirePressureInfo(double front, double back) { this.front = front; this.back = back; } public double PressureFront { get { return front; } } public double PressuerBack { get { return back; } } } public TirePressureInfo TirePressuer { get { return new TirePressureInfo(2.0, 2.4); } } public IEnumerable<int> KmSinceRefueling { get { return null; } } public static double AggregatedAverage(IEnumerable<IEnumerable<int>> values) { var firstLevel = values.Select(s => new { Average = s.Average(), Count = s.Count() }); return firstLevel.Select(fl => fl.Average * fl.Count).Sum() / firstLevel.Sum(fl => fl.Count); } } }
d301cad792210b35f65a272cfda3f5b7364193d1
C#
TeamDve/LearnIt
/LearnIt/LearnIt.Tests/Services/DataServices/CourseServiceTests/GetCourseById_Should.cs
2.5625
3
using LearnIt.Data.Context; using LearnIt.Data.Models; using LearnIt.Data.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace LearnIt.Tests.Services.DataServices.CourseServiceTests { [TestClass] public class GetCourseById_Should { [TestMethod] public void ReturnCourse_WhenCourseIdIsCorrect() { //Arrange var dateTime = DateTime.Now; int idConst = 12; var dbContextMock = new Mock<ApplicationDbContext>(); List<Course> courseList = new List<Course>() { new Course() { Id = idConst, Name = "eklerEkler", Description = "NeshtoSiNeshtoSi", DateAdded = dateTime, Required = true, ScoreToPass = 40 } }; var courseDbSetMock = new Mock<DbSet<Course>>().SetupData(courseList); dbContextMock.SetupGet<IDbSet<Course>>(x=>x.Courses).Returns(courseDbSetMock.Object); //Act CourseService courseService = new CourseService(dbContextMock.Object); //Assert Assert.AreEqual(courseList.First(),courseService.GetCourseById(idConst)); } [TestMethod] public void ReturnEmptyCourse_WhenNoCourseIsFound() { //Arrange var dateTime = DateTime.Now; int idConst = 12; var dbContextMock = new Mock<ApplicationDbContext>(); List<Course> courseList = new List<Course>() { }; var courseDbSetMock = new Mock<DbSet<Course>>().SetupData(courseList); dbContextMock.SetupGet<IDbSet<Course>>(x => x.Courses).Returns(courseDbSetMock.Object); //Act CourseService courseService = new CourseService(dbContextMock.Object); //Assert Assert.IsNull(courseService.GetCourseById(idConst)); } } }
112ea1e74955e1268710c7eef26072b3704f699c
C#
liangshulsh/src
/Ai/Control/MenuItem.cs
2.703125
3
// Ai Software Control Library. using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; namespace Ai.Control { /// <summary> /// Provide a base class for all menu item used in TabbedMenu control. /// </summary> public abstract class MenuItem { /// <summary> /// Define how a MenuItem must be resized. /// </summary> public enum ItemSizeType { Small, Large } #region Internal Declarations internal string _name = "MenuItem"; internal string _text = "MenuItem"; internal System.Drawing.Image _image = null; internal bool _visible = true; internal bool _enabled = true; internal string _tooltip = ""; internal string _tooltipTitle = ""; internal System.Drawing.Image _tooltipImage = null; internal ItemSizeType _sizeType = ItemSizeType.Small; internal object _tag = null; internal MenuItem _parent = null; internal TabbedMenu _owner = null; #endregion #region Public Properties /// <summary> /// Gets or sets the SizeType of the MenuItem object. /// </summary> [Description("Gets or sets the SizeType of the MenuItem object."), DefaultValue(typeof(ItemSizeType), "Small")] public virtual ItemSizeType SizeType { get { return _sizeType; } set { _sizeType = value; } } /// <summary> /// Gets or sets the name of the MenuItem object. /// </summary> [DefaultValue("MenuItem"), Description("Gets or sets the name of the MenuItem object.")] public virtual string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets or sets the text associated with MenuItem. /// </summary> [DefaultValue("MenuItem"), Description("Gets or sets the text associated with MenuItem.")] public virtual string Text { get { return _text; } set { _text = value; } } /// <summary> /// Gets or sets a value indicating whether the MenuItem can respond to user interaction. /// </summary> [DefaultValue(true), Description("Gets or sets a value indicating whether the MenuItem can respond to user interaction.")] public virtual bool Enabled { get { return _enabled; } set { _enabled = value; } } /// <summary> /// Gets or sets a value indicating whether the MenuItem are displayed. /// </summary> [DefaultValue(true), Description("Gets or sets a value indicating whether the MenuItem are displayed.")] public virtual bool Visible { get { return _visible; } set { _visible = value; } } /// <summary> /// Gets or sets the image that is displayed on a MenuItem. /// </summary> [DefaultValue(typeof(System.Drawing.Image), "null"), Description("Gets or sets the image that is displayed on a MenuItem.")] public virtual System.Drawing.Image Image { get { return _image; } set { _image = value; } } /// <summary> /// Gets or sets a text displayed on the ToolTip window. /// </summary> [DefaultValue(""), Description("Gets or sets a text displayed on the ToolTip window.")] public string ToolTip { get { return _tooltip; } set { _tooltip = value; } } /// <summary> /// Gets or sets a title displayed on the ToolTip window. /// </summary> [DefaultValue(""), Description("Gets or sets a title displayed on the ToolTip window.")] public string ToolTIpTitle { get { return _tooltipTitle; } set { _tooltipTitle = value; } } /// <summary> /// Gets or sets an image displayed on the ToolTip window. /// </summary> [DefaultValue(typeof(System.Drawing.Image), "null"), Description("Gets or sets an image displayed on the ToolTip window.")] public System.Drawing.Image ToolTipImage { get { return _tooltipImage; } set { _tooltipImage = value; } } /// <summary> /// Determine an object data associated with MenuItem object. /// </summary> [DefaultValue(""), TypeConverter(typeof(StringConverter)), Description("Determine an object data associated with MenuItem object.")] public object Tag { get { return _tag; } set { _tag = value; } } #endregion #region Constructor public MenuItem() { _parent = null; _owner = new TabbedMenu(); } #endregion } }
33ba66fc4380ebb6e23e7d3a70950a8000292707
C#
Vory7/sibsutis
/4 семестр/VirtualProgramming/Лабораторные работы/laboratoryWork_5/laboratoryWork_5/FormMain.cs
2.765625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace laboratoryWork_5 { public partial class FormMain : Form { private Rectangle rectangle, circle, square; private bool bool_rectangle, bool_circle, bool_square; private bool bool_rounded_rectangle, bool_rounded_circle, bool_rounded_square; private int rectangleZ, circleZ, squareZ; private bool dragging; private int oldX, oldY; public FormMain() { InitializeComponent(); rectangle = new Rectangle(10, 10, 300, 150); rectangleZ = 1; bool_rounded_rectangle = false; circle = new Rectangle(420, 10, 150, 150); circleZ = 2; bool_rounded_circle = true; square = new Rectangle(630, 10, 150, 150); squareZ = 3; bool_rounded_square = false; dragging = false; } private void pictureBox_Paint(object sender, PaintEventArgs e) { if (rectangleZ < circleZ && rectangleZ < squareZ) { if (bool_rounded_rectangle) e.Graphics.FillEllipse(Brushes.Yellow, rectangle); else e.Graphics.FillRectangle(Brushes.Yellow, rectangle); if (circleZ < squareZ) { if (bool_rounded_circle) e.Graphics.FillEllipse(Brushes.Red, circle); else e.Graphics.FillRectangle(Brushes.Red, circle); if (bool_rounded_square) e.Graphics.FillEllipse(Brushes.Blue, square); else e.Graphics.FillRectangle(Brushes.Blue, square); } else { if (bool_rounded_square) e.Graphics.FillEllipse(Brushes.Blue, square); else e.Graphics.FillRectangle(Brushes.Blue, square); if (bool_rounded_circle) e.Graphics.FillEllipse(Brushes.Red, circle); else e.Graphics.FillRectangle(Brushes.Red, circle); } } else if (circleZ < rectangleZ && circleZ < squareZ) { if (bool_rounded_circle) e.Graphics.FillEllipse(Brushes.Red, circle); else e.Graphics.FillRectangle(Brushes.Red, circle); if (rectangleZ < squareZ) { if (bool_rounded_rectangle) e.Graphics.FillEllipse(Brushes.Yellow, rectangle); else e.Graphics.FillRectangle(Brushes.Yellow, rectangle); if (bool_rounded_square) e.Graphics.FillEllipse(Brushes.Blue, square); else e.Graphics.FillRectangle(Brushes.Blue, square); } else { if (bool_rounded_square) e.Graphics.FillEllipse(Brushes.Blue, square); else e.Graphics.FillRectangle(Brushes.Blue, square); if (bool_rounded_rectangle) e.Graphics.FillEllipse(Brushes.Yellow, rectangle); else e.Graphics.FillRectangle(Brushes.Yellow, rectangle); } } else { if (bool_rounded_square) e.Graphics.FillEllipse(Brushes.Blue, square); else e.Graphics.FillRectangle(Brushes.Blue, square); if (circleZ < rectangleZ) { if (bool_rounded_circle) e.Graphics.FillEllipse(Brushes.Red, circle); else e.Graphics.FillRectangle(Brushes.Red, circle); if (bool_rounded_rectangle) e.Graphics.FillEllipse(Brushes.Yellow, rectangle); else e.Graphics.FillRectangle(Brushes.Yellow, rectangle); } else { if (bool_rounded_rectangle) e.Graphics.FillEllipse(Brushes.Yellow, rectangle); else e.Graphics.FillRectangle(Brushes.Yellow, rectangle); if (bool_rounded_circle) e.Graphics.FillEllipse(Brushes.Red, circle); else e.Graphics.FillRectangle(Brushes.Red, circle); } } } private void pictureBox_MouseDown(object sender, MouseEventArgs e) { oldX = e.X; oldY = e.Y; int tmp = 0; if (oldX >= rectangle.X && oldX <= rectangle.X + rectangle.Width && oldY >= rectangle.Y && oldY <= rectangle.Y + rectangle.Height) { tmp = rectangleZ; } if (oldX >= circle.X && oldX <= circle.X + circle.Width && oldY >= circle.Y && oldY <= circle.Y + circle.Height) { if (tmp < circleZ) { tmp = circleZ; } } if (oldX >= square.X && oldX <= square.X + square.Width && oldY >= square.Y && oldY <= square.Y + square.Height) { if (tmp < squareZ) { tmp = squareZ; } } if (tmp != 0) { dragging = true; if (tmp == rectangleZ) { bool_rectangle = true; rectangleZ = 3; if (circleZ > squareZ) { circleZ = 2; squareZ = 1; } else { squareZ = 2; circleZ = 1; } } else if (tmp == circleZ) { bool_circle = true; circleZ = 3; if (rectangleZ > squareZ) { rectangleZ = 2; squareZ = 1; } else { squareZ = 2; rectangleZ = 1; } } else { bool_square = true; squareZ = 3; if (circleZ > rectangleZ) { circleZ = 2; rectangleZ = 1; } else { rectangleZ = 2; circleZ = 1; } } } } private void pictureBox_MouseMove(object sender, MouseEventArgs e) { if (dragging) { if (bool_rectangle) { rectangle.X = e.X - (oldX - rectangle.X); rectangle.Y = e.Y - (oldY - rectangle.Y); if ( ((labelView.Location.X < rectangle.X + rectangle.Width) && (labelView.Location.X > rectangle.X) && (labelView.Location.Y < rectangle.Y + rectangle.Height) && (labelView.Location.Y > rectangle.Y) ) || ((labelView.Location.X + labelView.Width < rectangle.X + rectangle.Width) && (labelView.Location.X + labelView.Width > rectangle.X) && (labelView.Location.Y < rectangle.Y + rectangle.Height) && (labelView.Location.Y > rectangle.Y) ) ) { labelInfo.Text = "Жёлтый "; if (bool_rounded_rectangle) labelInfo.Text += "овал"; else labelInfo.Text += "прямоугольник"; } } else if (bool_circle) { circle.X = e.X - (oldX - circle.X); circle.Y = e.Y - (oldY - circle.Y); if ( ((labelView.Location.X < circle.X + circle.Width) && (labelView.Location.X > circle.X) && (labelView.Location.Y < circle.Y + circle.Height) && (labelView.Location.Y > circle.Y) ) || ((labelView.Location.X + labelView.Width < circle.X + circle.Width) && (labelView.Location.X + labelView.Width > circle.X) && (labelView.Location.Y < circle.Y + circle.Height) && (labelView.Location.Y > circle.Y) ) ) { labelInfo.Text = "Красный "; if (bool_rounded_circle) labelInfo.Text += "круг"; else labelInfo.Text += "квадрат"; } } else { square.X = e.X - (oldX - square.X); square.Y = e.Y - (oldY - square.Y); if ( ((labelView.Location.X < square.X + square.Width) && (labelView.Location.X > square.X) && (labelView.Location.Y < square.Y + square.Height) && (labelView.Location.Y > square.Y) ) || ((labelView.Location.X + labelView.Width < square.X + square.Width) && (labelView.Location.X + labelView.Width > square.X) && (labelView.Location.Y < square.Y + square.Height) && (labelView.Location.Y > square.Y) ) ) { labelInfo.Text = "Синий "; if (bool_rounded_square) labelInfo.Text += "круг"; else labelInfo.Text += "квадрат"; } } oldX = e.X; oldY = e.Y; } pictureBox.Invalidate(); } private void pictureBox_MouseUp(object sender, MouseEventArgs e) { if (dragging) { if (bool_rectangle) { if ( ((labelForm.Location.X < rectangle.X + rectangle.Width) && (labelForm.Location.X > rectangle.X) && (labelForm.Location.Y < rectangle.Y + rectangle.Height) && (labelForm.Location.Y > rectangle.Y) ) || ((labelForm.Location.X + labelForm.Width < rectangle.X + rectangle.Width) && (labelForm.Location.X + labelForm.Width > rectangle.X) && (labelForm.Location.Y < rectangle.Y + rectangle.Height) && (labelForm.Location.Y > rectangle.Y) ) ) bool_rounded_rectangle = !bool_rounded_rectangle; bool_rectangle = false; } else if (bool_circle) { if ( ((labelForm.Location.X < circle.X + circle.Width) && (labelForm.Location.X > circle.X) && (labelForm.Location.Y < circle.Y + circle.Height) && (labelForm.Location.Y > circle.Y) ) || ((labelForm.Location.X + labelForm.Width < circle.X + circle.Width) && (labelForm.Location.X + labelForm.Width > circle.X) && (labelForm.Location.Y < circle.Y + circle.Height) && (labelForm.Location.Y > circle.Y) ) ) bool_rounded_circle = !bool_rounded_circle; bool_circle = false; } else { if ( ((labelForm.Location.X < square.X + square.Width) && (labelForm.Location.X > square.X) && (labelForm.Location.Y < square.Y + square.Height) && (labelForm.Location.Y > square.Y) ) || ((labelForm.Location.X + labelForm.Width < square.X + square.Width) && (labelForm.Location.X + labelForm.Width > square.X) && (labelForm.Location.Y < square.Y + square.Height) && (labelForm.Location.Y > square.Y) ) ) bool_rounded_square = !bool_rounded_square; bool_square = false; } } pictureBox.Invalidate(); dragging = false; } } }
c0fcac93bb69c4afcfa2698b0383ef96229bc770
C#
pete0877/MindHub
/MindHub/Engine/Environment.cs
2.859375
3
using System; namespace Engine { /// <summary> /// Responsible for ecapsulating application-environment parameters such as DB connection specs, UI paths, etc. /// </summary> [Serializable] public class Environment { /// <summary> /// Environment ID /// </summary> public string ID; /// <summary> /// DNS connection string used by ADO.NET to establish connection /// </summary> public string DNS; /// <summary> /// Path to UI temaplates in the operating system (e.g. "D:\MindHub\Dev\WebRoot\Fake\"). Should end with slash. /// </summary> public string UIPathOS; /// <summary> /// Path to UI temaplates on the web server (e.g. "/Fake/"). Should end with slash. /// </summary> public string UIPathWeb; /// <summary> /// DB connection type of the environment's database /// </summary> public DBConnection.DBType DBType; /// <summary> /// Constructor. Initializes the environment properties. /// </summary> /// <param name="envID">Environment ID</param> /// <param name="envDBType">DB connection type</param> /// <param name="envDNS">DB connection DNS for ADO.NET</param> /// <param name="envUIPath">Path to UI templates</param> /// <exception cref="EInvalidParameter">If any of the parameters are null</exception> public Environment(string environmentID, DBConnection.DBType envDBType, string environmentDNS, string environmentUIPathOS, string environmentUIPathWeb) { if (environmentID == null) throw new EInvalidParameter(this, "ID"); if (environmentDNS == null) throw new EInvalidParameter(this, "environmentDNS"); if (environmentUIPathOS == null) throw new EInvalidParameter(this, "environmentUIPathOS"); if (environmentUIPathWeb == null) throw new EInvalidParameter(this, "environmentUIPathWeb"); ID = string.Copy(environmentID); DBType = envDBType; DNS = string.Copy(environmentDNS); UIPathOS = string.Copy(environmentUIPathOS); UIPathWeb = string.Copy(environmentUIPathWeb); } /// <summary> /// Constructor. Initializes the environment properties based on another environment. /// </summary> /// <param name="environment">Copy-from environment instance</param> /// <exception cref="EInvalidParameter">If environment is null</exception> public Environment(Environment environment) { if (environment == null) throw new EInvalidParameter(this, "environment"); ID = string.Copy(environment.ID); DBType = environment.DBType; DNS = string.Copy(environment.DNS); UIPathOS = string.Copy(environment.UIPathOS); UIPathWeb = string.Copy(environment.UIPathWeb); } } }
ed12da15be3e3ea876b6e5bd025cfa2f15fbeec6
C#
kierannichol/Time.NET
/Time.Tests/IntervalTest.cs
2.78125
3
using NUnit.Framework; namespace Time.Tests { [TestFixture] public class IntervalTest { [Test] public void IsEmptyTests() { var emptyInterval = Interval<int>.Open(1,1); var smallOpenInterval = Interval<int>.Open(1,2); var singleValueInterval = Interval<int>.Closed(1,1); Assert.That(emptyInterval.IsEmpty, Is.True); Assert.That(smallOpenInterval.IsEmpty, Is.False); Assert.That(singleValueInterval.IsEmpty, Is.False); } [Test] public void IsDegenerateTests() { var emptyInterval = Interval<int>.Open(1,1); var smallOpenInterval = Interval<int>.Open(1,2); var singleValueInterval = Interval<int>.Closed(1,1); Assert.That(emptyInterval.IsDegenerate, Is.False); Assert.That(smallOpenInterval.IsDegenerate, Is.False); Assert.That(singleValueInterval.IsDegenerate, Is.True); } [Test] public void ToStringTests() { var emptyInterval = Interval<int>.Open(0,0); var openInterval = Interval<int>.Open(1, 10); var closedInterval = Interval<int>.Closed(2, 5); var leftClosedRightOpen = Interval<int>.LeftClosedRightOpen(1, 2); var leftOpenRightClosed = Interval<int>.LeftOpenRightClosed(3, 5); var leftBoundedRightUnbounded = Interval<int>.LeftClosed(1); var leftUnboundedRightBounded = Interval<int>.RightOpen(5); Assert.That(emptyInterval.ToString(), Is.EqualTo("{}")); Assert.That(openInterval.ToString(), Is.EqualTo("(1,10)")); Assert.That(closedInterval.ToString(), Is.EqualTo("[2,5]")); Assert.That(leftClosedRightOpen.ToString(), Is.EqualTo("[1,2)")); Assert.That(leftOpenRightClosed.ToString(), Is.EqualTo("(3,5]")); Assert.That(leftBoundedRightUnbounded.ToString(), Is.EqualTo("[1,∞)")); Assert.That(leftUnboundedRightBounded.ToString(), Is.EqualTo("(-∞,5)")); } [Test] public void EqualsTests() { var emptyInterval1 = Interval<int>.Open(0,0); var emptyInterval2 = Interval<int>.Open(10,10); var openInterval1 = Interval<int>.Open(5, 10); var openInterval2 = Interval<int>.Open(5, 10); var closedInterval1 = Interval<int>.Closed(5, 10); var closedInterval2 = Interval<int>.Closed(5, 10); Assert.That(emptyInterval1, Is.EqualTo(emptyInterval2)); Assert.That(openInterval1, Is.EqualTo(openInterval2)); Assert.That(closedInterval1, Is.EqualTo(closedInterval2)); } [Test] public void ContainsTests() { var openInterval = Interval<int>.Open(2,5); var closedInterval = Interval<int>.Closed(2,5); var infiniteInterval = Interval<int>.Unbound; var emptyInterval = Interval<int>.Open(5,5); var leftOpenRightClosed = Interval<int>.LeftOpenRightClosed(3, 5); var leftBoundedRightUnbounded = Interval<int>.LeftClosed(1); Assert.That(openInterval.Contains(1), Is.False); Assert.That(openInterval.Contains(2), Is.False); Assert.That(openInterval.Contains(3), Is.True); Assert.That(openInterval.Contains(4), Is.True); Assert.That(openInterval.Contains(5), Is.False); Assert.That(openInterval.Contains(6), Is.False); Assert.That(closedInterval.Contains(1), Is.False); Assert.That(closedInterval.Contains(2), Is.True); Assert.That(closedInterval.Contains(3), Is.True); Assert.That(closedInterval.Contains(4), Is.True); Assert.That(closedInterval.Contains(5), Is.True); Assert.That(closedInterval.Contains(6), Is.False); Assert.That(infiniteInterval.Contains(int.MinValue), Is.True); Assert.That(infiniteInterval.Contains(0), Is.True); Assert.That(infiniteInterval.Contains(int.MaxValue), Is.True); Assert.That(emptyInterval.Contains(4), Is.False); Assert.That(emptyInterval.Contains(5), Is.False); Assert.That(emptyInterval.Contains(6), Is.False); Assert.That(leftOpenRightClosed.Contains(2), Is.False); Assert.That(leftOpenRightClosed.Contains(3), Is.False); Assert.That(leftOpenRightClosed.Contains(4), Is.True); Assert.That(leftOpenRightClosed.Contains(5), Is.True); Assert.That(leftOpenRightClosed.Contains(6), Is.False); Assert.That(leftBoundedRightUnbounded.Contains(0), Is.False); Assert.That(leftBoundedRightUnbounded.Contains(1), Is.True); Assert.That(leftBoundedRightUnbounded.Contains(int.MaxValue), Is.True); } } }
b51790af8485befc7f45ee8d3607105af1af730d
C#
sreenandini/test_buildscripts
/Common/BMC.CoreLib/Tasks/IRunnableObject.cs
2.59375
3
/* ================================================================================= * Purpose : Runnable Object Interface * File Name : IRunnableObject.cs * Author : A.Vinod Kumar * Created : 20/12/2010 * ================================================================================= * Revision History : * ================================================================================= * 20/12/2010 A.Vinod Kumar Initial Version * ===============================================================================*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BMC.CoreLib.Tasks { /// <summary> /// Runnable Object Interface /// </summary> public interface IRunnableObject { /// <summary> /// Occurs when [before start]. /// </summary> event MethodInvokedHandler BeforeStart; /// <summary> /// Occurs when [after start]. /// </summary> event MethodInvokedHandler AfterStart; /// <summary> /// Occurs when [before stop]. /// </summary> event MethodInvokedHandler BeforeStop; /// <summary> /// Occurs when [after stop]. /// </summary> event MethodInvokedHandler AfterStop; /// <summary> /// Starts this instance. /// </summary> void Start(); /// <summary> /// Stops this instance. /// </summary> void Stop(); } }
98bf590a86261186e58e001e42b0ddfce25cf649
C#
TopShares/CSharp-Study
/高级进阶-02期/第04次课:OOP三大特性封装继承接口多态等案例分析/授课笔记和源码(现场)/DPTeachDem/Law-of-Demeter/Program.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Law_of_Demeter { class Program { static void Main(string[] args) { //IPrinter printer = new HPPrinter(); IPrinter printer = SimpleFactory.CreatePrinter();//这个方法具体返回何种对象,我们不关心,知道的最少! printer.Print(); Console.Read(); } } }
3e0bf2ce14c86e03c08ebbd128d8305ecc1edc2d
C#
944095635/NavigatorToolkit
/NavigatorToolkit/Navigator.cs
3.140625
3
using System; using System.Collections.Generic; namespace NavigatorToolkit { public class Navigator { /// <summary> /// 页面集合 /// </summary> private static readonly Dictionary<object, object> views = new Dictionary<object, object>(); /// <summary> /// 注册事件 /// </summary> public static event EventHandler<object> RegisterCallback; /// <summary> /// 注册跳转页面 /// </summary> /// <param name="key">跳转页面的Key</param> /// <param name="value">跳转传的参数</param> public static void RegisterView(object key, object value) { if (!views.ContainsKey(key)) { views.Add(key, value); } } /// <summary> /// 跳转页面 /// </summary> /// <param name="key">跳转页面的Key</param> /// <param name="value">跳转传的参数</param> public static void Navigat(object key, object value = null) { if (views.ContainsKey(key)) { object view = views[key]; //页面分为 Uri 或者 类型 或者 对象 if (view is Uri) { RegisterCallback?.Invoke(null, view); } } } } }
bdb9797ddd85860256c31be2acee18d640733207
C#
AliumFX/Framework
/src/Alium.Core.Abstractions/Tenancy/TenantId.cs
3.046875
3
// Copyright (c) Alium FX. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Alium.Tenancy { using System; using System.Diagnostics; /// <summary> /// Represents a tenant id. /// </summary> [DebuggerDisplay("Tenant Id: {Value}")] public readonly struct TenantId : IComparable<string?>, IComparable<TenantId>, IEquatable<string?>, IEquatable<TenantId> { /// <summary> /// Represents the defualt tenant id. /// </summary> public static readonly TenantId Default = new TenantId("default"); /// <summary> /// Represents an empty tenant id. /// </summary> public static readonly TenantId Empty = new TenantId(); /// <summary> /// Initialises a new instance of <see cref="TenantId"/>. /// </summary> /// <param name="value">The tenant id value.</param> public TenantId(string value) { HasValue = true; Value = Ensure.IsNotNullOrEmpty(value, nameof(value)); } /// <summary> /// Gets whether the current instance has a value. /// </summary> public bool HasValue { get; } /// <summary> /// Gets the tenant id value. /// </summary> public string Value { get; } /// <inheritdoc /> public int CompareTo(string? other) { if (HasValue) { int stringCompare = StringComparer.OrdinalIgnoreCase.Compare(Value, other); return stringCompare < 0 ? -1 : stringCompare == 0 ? 0 : 1; } if (string.IsNullOrEmpty(other)) { return 1; } return 0; } /// <inheritdoc /> public int CompareTo(TenantId other) { if (other.HasValue) { return CompareTo(other.Value); } if (HasValue) { return 1; } return 0; } /// <inheritdoc /> public bool Equals(string? other) => CompareTo(other) == 0; /// <inheritdoc /> public bool Equals(TenantId other) => CompareTo(other) == 0; /// <inheritdoc /> public override bool Equals(object obj) { if (obj is TenantId t) { return Equals(t); } if (obj is string s) { return Equals(s); } return false; } /// <inheritdoc /> public override int GetHashCode() => HasValue ? Value.GetHashCode() : 0; /// <inheritdoc /> public override string ToString() => Value; /// <summary> /// Converts from a <see cref="TenantId"/> to a <see cref="string"/>. /// </summary> /// <param name="tenantId">The <see cref="TenantId"/>.</param> public static explicit operator string(TenantId tenantId) => tenantId.Value; /// <summary> /// Converts from a <see cref="string"/> to a <see cref="TenantId"/>. /// </summary> /// <param name="value">The <see cref="string"/> value.</param> public static explicit operator TenantId(string value) => string.IsNullOrEmpty(value) ? Empty : new TenantId(value); } }
02026b62503a2110aa0626b8ce69332aa999e04e
C#
shendongnian/download4
/first_version_download2/411029-35929420-112934500-2.cs
3.71875
4
static void Main(String[] args) { foreach (var column in GetColumns().Take(52)) { Console.WriteLine(column); } Console.ReadLine(); } public static IEnumerable<string> GetColumns() { const string Alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int index = 1; ; index++) { if (index % Alphabet.Length == 0) { continue; } var columnName = string.Empty; int value = index; do { columnName = Alphabet[value % Alphabet.Length] + columnName; value = value / Alphabet.Length; } while (value > 0); yield return columnName; } }
92aa910a882252dc633c20378d144c9d5ee90c81
C#
n1k0s79/ConfigurableAngularComponent
/Controllers/GenericEntityController.cs
2.703125
3
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using QualcoApp.Models; using System; using System.Collections.Generic; using System.Linq; namespace QualcoApp.Controllers { [ApiController] [Route("[controller]")] public class GenericEntityController : ControllerBase { private readonly DataContext context; public GenericEntityController(DataContext context) => this.context = context; [HttpGet] public GenericEntityDescriptor Get([FromQuery] string entityTypeName, [FromQuery] int id) { if (!EntityFetchers.ContainsKey(entityTypeName)) return null; var entity = EntityFetchers[entityTypeName](id); return entity.GetDescriptor(); } private Dictionary<string, Func<int, GenericEntity>> EntityFetchers => new Dictionary<string, Func<int, GenericEntity>>() { {"Customer", id => context.Customers.FirstOrDefault(c => c.Id == id) }, {"Product", id => context.Products.FirstOrDefault(p => p.Id == id) } // ... }; } }
dac42f9934e118c2d5f144a446af75ec5c1c7f38
C#
JMILI/DatabaseDesign
/TheProgramSRC/DatabaseDesignOFBank/TestBank/SqlBank/ViewContext.cs
2.84375
3
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace TestBank.SqlBank { class ViewContext:bankContext { /// <summary> /// 定义一个DbSet<Information>的集合属性Information,EF Core会自动为其赋值,然后可以利用ViewContextt.Information属性来读取数据库中Information视图的数据 /// </summary> public virtual DbSet<Information> Information { get; set; } /// <summary> /// 在重写的OnModelCreating方法中,使用Fluent API来设置实体Information和数据库中Information视图的关系 /// </summary> protected override void OnModelCreating(ModelBuilder modelBuilder) { //先调用基类的OnModelCreating方法,设置数据库中其它表和实体的映射关系 base.OnModelCreating(modelBuilder); //接着设置实体Information和数据库中Information视图的关系 modelBuilder.Entity<Information>(entity => { //告诉EF Core实体Information对应数据库中的Information视图,这里使用entity.ToTable方法后,上面的DbSet<Information> Information集合属性可以叫任何名字,比如我们可以将其定义为DbSet<Information> V_People也可以,如果不使用entity.ToTable方法,那么DbSet<Information> Information的属性名字必须和数据库视图Information的名字相同,否则EF Core会报错 entity.ToTable("Information"); //设置实体的唯一属性,因为我们知道数据库中Information视图的ID列值是唯一的,所以这里我们设置实体Information的Id属性为唯一属性 entity.HasKey(e => e.Icid); //利用Fluent API将实体Information的每一列映射到数据库视图的每一列 entity.Property(e => e.Iuid).HasColumnName("Iuid"); entity.Property(e => e.Ioldtime).HasColumnName("Ioldtime"); entity.Property(e => e.IflowBalance).HasColumnName("IflowBalance"); entity.Property(e => e.IfixBalance).HasColumnName("IfixBalance"); entity.Property(e => e.Iname).HasColumnName("Iname"); entity.Property(e => e.Istatus).HasColumnName("Istatus"); }); } } }
c817baab5b5dec4ad685328edb7a270baa766256
C#
EppuHeilimo/ASPRealTimeTest
/MoveShape/MoveShape.cs
2.609375
3
using System; using System.Threading; using Microsoft.AspNet.SignalR; using Newtonsoft.Json; using System.Collections.Generic; namespace Hatsoff { public class Broadcaster { private readonly static Lazy<Broadcaster> _instance = new Lazy<Broadcaster>(() => new Broadcaster()); // We're going to broadcast to all clients a maximum of 25 times per second private readonly TimeSpan BroadcastInterval = TimeSpan.FromMilliseconds(16); private readonly IHubContext _hubContext; private Timer _broadcastLoop; private ShapeModel _model; private int _shapeID; private bool _modelUpdated; public int newID = 0; private Dictionary<string, RemotePlayer> connectedPlayers; private List<ShapeModel> updatedmodels = new List<ShapeModel>(); public Broadcaster() { // Save our hub context so we can easily use it // to send to its connected clients _hubContext = GlobalHost.ConnectionManager.GetHubContext<MoveShapeHub>(); _model = new ShapeModel(); _modelUpdated = false; connectedPlayers = new Dictionary<string, RemotePlayer>(); // Start the broadcast loop _broadcastLoop = new Timer( Broadcast, null, BroadcastInterval, BroadcastInterval); } public void Broadcast(object state) { // This is how we can access the Clients property // in a static hub method or outside of the hub entirely if(_modelUpdated) { ShapeModel[] array = updatedmodels.ToArray(); _hubContext.Clients.All.updateShapes(array); _modelUpdated = false; updatedmodels.Clear(); } } public int NewID() { newID++; return newID; } public void UpdateShape(ShapeModel clientModel) { updatedmodels.Add(clientModel); _modelUpdated = true; } public void AddPlayer(string connectionid) { int id = NewID(); RemotePlayer newplayer = new RemotePlayer(connectionid, id); connectedPlayers.Add(connectionid, newplayer); _hubContext.Clients.AllExcept(connectionid).addPlayer(newplayer.getPlayerShape()); _hubContext.Clients.Client(connectionid).getMyID(id); } public static Broadcaster Instance { get { return _instance.Value; } } internal void SendPlayersListTo(string connectionId) { List<ShapeModel> playerlist = new List<ShapeModel>(); if(connectedPlayers.Count > 1) { foreach (KeyValuePair<string, RemotePlayer> p in connectedPlayers) { if (p.Key == connectionId) continue; else { playerlist.Add(p.Value.getPlayerShape()); } } _hubContext.Clients.Client(connectionId).addPlayers(playerlist); } } } public class MoveShapeHub : Hub { // Is set via the constructor on each creation private Broadcaster _broadcaster; public MoveShapeHub() : this(Broadcaster.Instance) { } public MoveShapeHub(Broadcaster broadcaster) { _broadcaster = broadcaster; } public void UpdateModel(ShapeModel clientModel) { clientModel.LastUpdatedBy = Context.ConnectionId; // Update the shape model within our broadcaster _broadcaster.UpdateShape(clientModel); } public void AddPlayer() { _broadcaster.AddPlayer(Context.ConnectionId); } public void GetPlayers() { _broadcaster.SendPlayersListTo(Context.ConnectionId); } } public class ShapeModel { // We declare Left and Top as lowercase with // JsonProperty to sync the client and server models [JsonProperty("left")] public double Left { get; set; } [JsonProperty("top")] public double Top { get; set; } // We don't want the client to get the "LastUpdatedBy" property [JsonIgnore] public string LastUpdatedBy { get; set; } [JsonProperty("id")] public double id { get; set; } } public class RemotePlayer { ShapeModel _playerShape; string _connectionID; int _ID; public RemotePlayer(string connectionID, int ID) { _connectionID = connectionID; _playerShape = new ShapeModel(); _playerShape.Left = 0; _playerShape.Top = 0; _playerShape.LastUpdatedBy = connectionID; _ID = ID; _playerShape.id = ID; } public ShapeModel getPlayerShape() { return _playerShape; } } }
5f331e8ddae351711fbbf0fd4b3d171bce812c8b
C#
lordofduct/spacepuppy-unity-framework
/SpacepuppyBase/Utils/LayerUtil.cs
2.578125
3
using UnityEngine; using System.Collections.Generic; namespace com.spacepuppy.Utils { public static class LayerUtil { private static List<int> layerNumbers; private static List<string> layerNames; private static long lastUpdateTick; private static void TestUpdateLayers() { if (layerNumbers == null || (System.DateTime.UtcNow.Ticks - lastUpdateTick > 10000000L && Event.current.type == EventType.Layout)) { lastUpdateTick = System.DateTime.UtcNow.Ticks; if (layerNumbers == null) { layerNumbers = new List<int>(); layerNames = new List<string>(); } else { layerNumbers.Clear(); layerNames.Clear(); } for (int i = 0; i < 32; i++) { string layerName = LayerMask.LayerToName(i); if (layerName != "") { layerNumbers.Add(i); layerNames.Add(layerName); } } } } public static string[] GetLayerNames() { TestUpdateLayers(); return layerNames.ToArray(); } public static string[] GetAllLayerNames() { TestUpdateLayers(); string[] names = new string[32]; for (int i = 0; i < 32; i++) { if (layerNumbers.Contains(i)) { names[i] = LayerMask.LayerToName(i); } else { names[i] = "Layer " + i.ToString(); } } return names; } public static bool Intersects(this LayerMask mask, int layer) { return (mask.value & (1 << layer)) != 0; } public static bool Intersects(this LayerMask mask, GameObject go) { return (mask.value & (1 << go.layer)) != 0; } public static bool Intersects(this LayerMask mask, Component c) { return (mask.value & (1 << c.gameObject.layer)) != 0; } } }
863b72e580009dfcd68afddd86e7b4ea79669e33
C#
camotts/383-Api
/GameingStoreAPI/Controllers/TagsController.cs
2.59375
3
using GamingStoreAPI.Models; using GamingStoreAPI.Models.DTOS; using GamingStoreAPI.Services; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace GamingStoreAPI.Controllers { [Authorize(Roles = "Employee, StoreAdmin")] public class TagsController : BaseApiController { private ITagRepository repo = new TagRepository(); // GET api/Tags [AllowAnonymous] public HttpResponseMessage GetTags() { List<TagDTO> ListOfTags = new List<TagDTO>(); foreach (var item in repo.getListOfTags()) { ListOfTags.Add(TheFactory.Create(item)); } return Request.CreateResponse(HttpStatusCode.OK, ListOfTags); } // GET api/Tags/5 [AllowAnonymous] public HttpResponseMessage GetTag(int id) { Tags tag = repo.getTagById(id); if (tag == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } TagDTO factoredTag = TheFactory.Create(tag); return Request.CreateResponse(HttpStatusCode.OK, factoredTag); } [Authorize(Roles = "StoreAdmin")] public HttpResponseMessage PostTags(Tags tag) { if (ModelState.IsValid) { repo.createTag(tag); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, tag); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = tag.ID })); TagDTO factoredTag = TheFactory.Create(tag); return Request.CreateResponse(HttpStatusCode.OK, factoredTag); } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } } // PUT api/Sales/5 [Authorize(Roles = "Employee, StoreAdmin")] public HttpResponseMessage PutTag(int id, Tags tag) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != tag.ID) { return Request.CreateResponse(HttpStatusCode.BadRequest); } repo.putTag(id, tag); TagDTO factoredTag = TheFactory.Create(tag); return Request.CreateResponse(HttpStatusCode.OK, factoredTag); } [Authorize(Roles = "StoreAdmin")] public HttpResponseMessage DeleteTag(int id) { Tags tag = repo.getTagById(id); if (tag == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } repo.deleteTag(tag); return Request.CreateResponse(HttpStatusCode.OK, tag); } } }
91e9955e6cda45f20c7658942a09a8fc86afb523
C#
JC-85/DesignPatterns
/DesignPatterns/SoftwareDesignPattern/Behavioral/TemplateMethod/TemplateMethodPatternSample.cs
3.046875
3
using System; namespace DesignPatterns.SoftwareDesignPattern.Behavioral.TemplateMethod { // Defines the skeleton of an Algorithm in a operation deferring some steps to subclases. // Template method lets subclasses redefine certain steps of the algorithm // without changing the algorithm structure. public class TemplateMethodPatternSample : IDesignPatternSample { public void ShowSample() { var templateMethod = new ConcreteTemplateMethod(); Console.WriteLine(templateMethod.TemplateMethod()); } } }
3e192e5a1eb7f34cd789df882ac34c6594463486
C#
karthik25/taskable
/src/Taskable/Taskable.ScriptCs.Contracts/Parameters/ActionParameterFluentExtensions.cs
2.96875
3
using System; using System.Linq; using TaskableScriptCs.Contracts; namespace TaskableScriptCs.Contracts.Parameters { public static class ActionParameterFluentExtensions { public static TConcrete Bind<TConcrete>(this string[] args) where TConcrete : class { return (TConcrete) Bind(typeof(TConcrete), args); } public static object Bind(this Type type, string[] args) { var propertiesWithParameterAttr = type.GetProperties() .Where(p => p.GetCustomAttributes(false) .OfType<ParameterIndexAttribute>() .Any()); if (propertiesWithParameterAttr.Count() != args.Length) throw new Exception("Count of properties with the ParameterIndexAttribute does not match the count for the arguments array"); var instance = Activator.CreateInstance(type); for (int i = 0; i < args.Length; i++) { var requiredProperty = propertiesWithParameterAttr.SingleOrDefault( p => p.GetCustomAttributes(false) .OfType<ParameterIndexAttribute>() .Any(a => a.Index == i)); if (requiredProperty == null) throw new Exception("Unable to find a mapping parameter with index " + i); if (typeof(IConvertible).IsAssignableFrom(requiredProperty.PropertyType)) { var value = Convert.ChangeType(args[i], requiredProperty.PropertyType); requiredProperty.SetValue(instance, value); } } return instance; } } }
aa195ae1cd30f222537b0c6e702eb7084aaf11dc
C#
Sseriously/Sharpcoderepo
/Stackoverflow/ActivateCube.cs
2.96875
3
using UnityEngine; public class ActivateCube : MonoBehaviour { //Create an array to hold any number of cubes you want public GameObject[] cubeArray = new GameObject[10]; //initialize the array for e.g. 10 cubes //Holds the index of the cubeArray, which corresponds to the next cube to be activated private int activateNext = 0; // Use this for initialization void Start () { for (int i = 0; i < cubeArray.Length; i++) { cubeArray[i].SetActive(false); } } // Update is called once per frame void Update () { //whenever a click occurs, and as long as activateNext is less than the length of the array... if (Input.GetButtonDown("Fire1") && activateNext < cubeArray.Length) { //... activate next cube cubeArray[activateNext].SetActive(true); activateNext++; } } }
e08ade20edf2f1fd5839748cfe312e4ce97639d1
C#
awesomedotnetcore/mbrace.stockticker
/mbrace.stockticker/StockDataConverter.cs
2.921875
3
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace mbrace.stockticker { public class StockDataConverter { public async Task<string> Run(string symbol) { var dataInfo = await Get(symbol); var rows = GetRows(dataInfo); var stringified = GetIndividualJson(rows); return stringified; } private string GetIndividualJson(StockDataRow[] rows) { var sbOutput = new StringBuilder(); foreach (var item in rows) { sbOutput.AppendLine(JObject.FromObject(item).ToString(Formatting.None)); } return sbOutput.ToString(); } public async Task<StockDataInfo> Get(string symbol) { using (var webClient = new WebClient()) { var data = await webClient.DownloadStringTaskAsync(string.Format("http://real-chart.finance.yahoo.com/table.csv?s={0}&d=3&e=13&f=2015&g=d&a=7&b=9&c=1996&ignore=.csv", symbol)); return new StockDataInfo(data); } } public StockDataRow[] GetRows(StockDataInfo yahooFinance) { var csv = yahooFinance.Data; List<StockDataRow> rows = new List<StockDataRow>(); var csvDocument = csv.Split('\n'); foreach (var csvRow in csvDocument) { if (!IsHeaderRow(csvRow)) rows.Add(ConvertToJson(csvRow)); } return rows.ToArray(); } public StockDataRow ConvertToJson(string csv) { if (!IsHeaderRow(csv)) { try { var values = csv.Split(','); var rowData = new StockDataRow(); rowData.Date = DateTime.ParseExact(values[0], "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); rowData.Open = float.Parse(values[1]); rowData.High = float.Parse(values[2]); rowData.Low = float.Parse(values[3]); rowData.Close = float.Parse(values[4]); rowData.Volume = int.Parse(values[5]); rowData.AdjClose = float.Parse(values[6]); return rowData; } catch (Exception ex) { throw; } } return null; } private static bool IsHeaderRow(string csv) { return string.IsNullOrEmpty(csv) || csv.StartsWith("Date"); } } }
58a22de111a6c804128e779ab33523c5dc5935fb
C#
Smytt/SoftUni-Homeworks
/05 2017 - Progframming Fundamentals/06 02 - Data Types and Variables - More Exercises/12. Beer Kegs/Program.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _12.Beer_Kegs { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); double biggestVolume = 0; string biggestModel = ""; for (int i = 1; i <= n; i++) { string model = Console.ReadLine(); double r = double.Parse(Console.ReadLine()); int h = int.Parse(Console.ReadLine()); double volume = Math.PI * r * r * h; if (i == 1) { biggestModel = model; biggestVolume = volume; } else { if (volume > biggestVolume) { biggestVolume = volume; biggestModel = model; } } } Console.WriteLine(biggestModel); } } }
f4c9eb8af301889014a3444ebba9d745cd72494a
C#
alexger97/Finvitamin-Manager
/FinVitamin Manager/Service/CourerTaskManager.cs
2.5625
3
using FinVitamin_Manager.Models; using FinVitamin_Manager.Models.Context; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FinVitamin_Manager.Service { public class CourerTaskManager { public static ProductContext ProductContext; public static List<CourerTask> CourerTasksST { get { return ProductContext.CourerTasks.ToList(); } } public Dictionary<int, CourerTask> CourerTaskDictonary { get => ProductContext.CourerTasks.ToDictionary((x) => x.OrderSpb.Id); } public CourerTaskManager(ProductContext pc) { ProductContext = pc; } public CourerTaskManager() { } public void AddTask(int orderid, int courerid) { if (!CourerTaskDictonary.ContainsKey(orderid)) { ProductContext.CourerTasks.Add(new CourerTask { OrderSpb = ProductContext.OrdersSpb.First(x => x.Id == orderid), Courer=ProductContext.Courers.First(x=>x.Id==courerid) }); ProductContext.SaveChanges(); } } public CourerTask GetCourerTask(int id) { try { return ProductContext.CourerTasks.First(x=>x.CourerId==id); } catch { return null; } } } }
d3c44076dcdb912133d6d33a3323939f8c3c8b0d
C#
cbjmars/Study
/Core30.WebApi.Sample/Controllers/TbTestApisController.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Core30.WebApi.Sample.Models; using Core30.WebApi.Sample.Services; namespace Core30.WebApi.Sample.Controllers { [ApiController] //[ApiController] 특성을 특정 컨트롤러에 적용 - 아래와 [Route("api/[controller]")] 같이 특성 라우팅을 요구 [Route("api/[controller]")]//컨트롤러 또는 작업의 개별 URL 패턴을 지정합니다 public class TbTestApisController : ControllerBase { private readonly ITestApiService _testApiService; public TbTestApisController(ITestApiService testApiService) { _testApiService = testApiService; } // GET: api/TbTestApis // ActionResult<T>는 반환 형식이며 여기서 사용중인 Task<ActionResult<T>>는 비동기 반환 형식이다. // IEnumerable<T> 지원된 형식의 컬렉션(Serializer에 의한 동기 컬렉션)을 단순하게 반복할 수 있도록 지원하는 열거자 // : TbTestApi List를 열거하여 비동기로 반환하는 메서드 [HttpGet]//HTTP GET 동작 식별 public async Task<ActionResult<IEnumerable<TbTestApi>>> GetTbTestApis() { var result = await _testApiService.GetTestApiList(); return result; } // GET: api/TbTestApis/5 [HttpGet("{id}")] public async Task<ActionResult<TbTestApi>> GetTbTestApi(int id) { var result = await _testApiService.GetTestApiItem(id); if (result == null) { // 404 (요청 결과 찾을 수 없음) return NotFound(); } return result; } // PUT: api/TbTestApis/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. // IActionResult는 반환 형식이 여러개의 작업인 경우 사용하며 수행된 작업의 결과에 따라 서로 다른 HTTP 상태 코드를 반환한다 // 여기서 사용중인 Task<IActionResult>는 비동기 반환 형식이다. [HttpPut("{id}")] public async Task<IActionResult> PutTbTestApi(int id, TbTestApi tbTestApi) { // tbTestApi.Seq에 요청 id가 없는 경우 if (id != tbTestApi.Seq) { // 400 (요청사항 인식 오류) return BadRequest(); } try { await _testApiService.PutTestApiItem(id, tbTestApi); } catch (DbUpdateConcurrencyException) { if (!_testApiService.GetTestApiExists(id)) { return NotFound(); } else { throw; } } // 202 (요청은 접수했지만 아직 처리하지 않음) return NoContent(); } // POST: api/TbTestApis // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPost] public async Task<ActionResult<TbTestApi>> PostTbTestApi(TbTestApi tbTestApi) { await _testApiService.PostTestApi(tbTestApi); // 201(요청받은 작업을 성공함) return CreatedAtAction("GetTbTestApi", new { id = tbTestApi.Seq }, tbTestApi); } // DELETE: api/TbTestApis/5 [HttpDelete("{id}")] public async Task<ActionResult<TbTestApi>> DeleteTbTestApi(int id) { var tbTestApi = await _testApiService.DeleteTestApiItem(id); if (tbTestApi == null) { return NotFound(); } return tbTestApi; } } }
6844e09bee8ffbf91bce2a58542288bb7020170a
C#
stevenmatetch/PIzzaApplikation
/Resto/ViewModels/PizzaViewModel.cs
2.59375
3
using Newtonsoft.Json; using Resto.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace Resto.ViewModels { public class PizzaViewModel { public ObservableCollection<Pizza> pizzorB; public ObservableCollection<Pizza> pizzor { get; set; } public ObservableCollection<Order> Ordrar { get; set; } static HttpClient httpClient = new HttpClient(); static string url = "http://localhost:57638/api/"; public PizzaViewModel() { pizzorB = new ObservableCollection<Pizza>(); pizzor = new ObservableCollection<Pizza>(); Ordrar = new ObservableCollection<Order>(); } public async Task<ObservableCollection<Pizza>> GetPizzorAsync() { ObservableCollection<Pizza> pizzorr = new ObservableCollection<Pizza>(); var jsonPizzor = await httpClient.GetStringAsync(url + "PizzaMenus"); pizzorr = JsonConvert.DeserializeObject<ObservableCollection<Pizza>>(jsonPizzor); return pizzorr; } public async Task<ObservableCollection<Order>> GetOrdersAsync() { ObservableCollection<Order> Orders = new ObservableCollection<Order>(); var jasonOrder = await httpClient.GetStringAsync(url + "Orders"); Orders = JsonConvert.DeserializeObject<ObservableCollection<Order>>(jasonOrder); return Orders; } //public static async Task<int> DeleteOrderAsync(int id) //{ // var httpClient = new System.Net.Http.HttpClient(); // var result = await httpClient.DeleteAsync(url + "Orders" + id); // return int.Parse(await result.Content.ReadAsStringAsync()); //} public async Task DeleteOrderAsync(int id) { var httpClient = new System.Net.Http.HttpClient(); await httpClient.DeleteAsync(url + "Orders" + id); } //private static HttpResponseMessage ClientDeleteRequest(string RequestURI) //{ // HttpClient client = new HttpClient(); // client.DefaultRequestHeaders.Accept.Clear(); // HttpResponseMessage response = client.DeleteAsync(RequestURI).Result; // return response; //} //public HttpResponseMessage DeleteEmployee(int id) //{ // Order or = GetOrdersAsync(); // if (or == null) // { // throw new HttpResponseException(HttpStatusCode.NotFound); // } // Ordrar.Remove(or); // var response = new HttpResponseMessage(); // response.Headers.Add("DeleteMessage", "Succsessfuly Deleted!!!"); // return response; //} public static async Task<int> AddOrderAsync(Order o) { using (HttpClient client = new HttpClient()) { var order = JsonConvert.SerializeObject(o); HttpContent httpContent = new StringContent(order); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await client.PostAsync(url + "Orders", httpContent); return int.Parse(await result.Content.ReadAsStringAsync()); } } public static async Task<List<Pizza>> AddPizzasAsync(List<Pizza> po) { List<Pizza> response = new List<Pizza>(); using (HttpClient client = new HttpClient()) { var order = JsonConvert.SerializeObject(po); HttpContent httpContent = new StringContent(order); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await client.PostAsync(url + "Pizzas", httpContent); var pizzas = await result.Content.ReadAsStringAsync(); if (pizzas != null) { response = JsonConvert.DeserializeObject<List<Pizza>>(pizzas); } return response; } } public static async Task AddPizzaOrderAsync(int a, List<Pizza> pizzalist) { List<PizzaOrder> temp = new List<PizzaOrder>(); foreach (var piz in pizzalist) { temp.Add(new PizzaOrder() { OrderId = a, PizzaId = piz.Id }); } var order = JsonConvert.SerializeObject(temp); HttpContent httpContent = new StringContent(order); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); await httpClient.PostAsync(url + "PizzaOrders", httpContent); } internal void AddPizza(Pizza pizza) { pizzorB.Add(pizza); } internal void RemovePizza(Pizza pizza) { pizzorB.Remove(pizza); } } }
da1278e7fd4fd51399e6fe12460bfc60c6b1eb09
C#
ScreeM92/Software-University
/Level #2/High Quality Code/High-Quality Code Exam Preparation/TravelAgency/TicketCatalog.cs
2.6875
3
namespace TravelAgency { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using TravelAgency.Tickets; using TravelAgency.Utilities; using Wintellect.PowerCollections; public class TicketCatalog : ITicketCatalog { private Dictionary<string, Ticket> ticketsByUniqueKey = new Dictionary<string, Ticket>(); private MultiDictionary<string, Ticket> ticketsByFromToKey = new MultiDictionary<string, Ticket>(true); private OrderedMultiDictionary<DateTime, Ticket> ticketsByDepartureTime = new OrderedMultiDictionary<DateTime, Ticket>(true); private Dictionary<TicketType, int> ticketsCount = new Dictionary<TicketType, int>(); public TicketCatalog() { this.ticketsCount[TicketType.Air] = 0; this.ticketsCount[TicketType.Train] = 0; this.ticketsCount[TicketType.Bus] = 0; } public int GetTicketsCount(TicketType type) { if (!this.ticketsCount.ContainsKey(type)) { throw new InvalidOperationException("Invalid ticket type"); } else { return this.ticketsCount[type]; } } [ExcludeFromCodeCoverage] public string ParseCommand(string line) { string[] commandParts = CommandUtilities.ParseCommandWithParameters(line); string commandName = commandParts[0]; string[] commandParameters = new string[commandParts.Length - 1]; for (int i = 1; i < commandParts.Length; i++) { commandParameters[i - 1] = commandParts[i]; } string commandResult = "Invalid command!"; switch (commandName) { case "AddAir": commandResult = this.AddAirTicket( flightNumber: commandParameters[0], from: commandParameters[1], to: commandParameters[2], airline: commandParameters[3], dateTime: Parser.ParseDateTime(commandParameters[4]), price: decimal.Parse(commandParameters[5])); break; case "DeleteAir": commandResult = this.DeleteAirTicket( commandParameters[0]); break; case "AddTrain": commandResult = this.AddTrainTicket( commandParameters[0], commandParameters[1], Parser.ParseDateTime(commandParameters[2]), decimal.Parse(commandParameters[3]), decimal.Parse(commandParameters[4])); break; case "DeleteTrain": commandResult = this.DeleteTrainTicket( commandParameters[0], commandParameters[1], Parser.ParseDateTime(commandParameters[2])); break; case "AddBus": commandResult = this.AddBusTicket( commandParameters[0], commandParameters[1], commandParameters[2], Parser.ParseDateTime(commandParameters[3]), decimal.Parse(commandParameters[4])); break; case "DeleteBus": commandResult = this.DeleteBusTicket( commandParameters[0], commandParameters[1], commandParameters[2], Parser.ParseDateTime(commandParameters[3])); break; case "FindTickets": commandResult = this.FindTickets( commandParameters[0], commandParameters[1]); break; case "FindTicketsInInterval": commandResult = this.FindTicketsInInterval( Parser.ParseDateTime(commandParameters[0]), Parser.ParseDateTime(commandParameters[1])); break; } return commandResult; } public string AddAirTicket( string flightNumber, string from, string to, string airline, DateTime dateTime, decimal price) { var ticket = new AirTicket( flightNumber, from, to, airline, dateTime, price); string result = this.AddTicket(ticket); return result; } public string DeleteAirTicket(string flightNumber) { var ticket = new AirTicket(flightNumber); string result = this.DeleteTicketByUniqueKey(ticket.UniqueKey); return result; } public string AddTrainTicket( string from, string to, DateTime dateAndTime, decimal price, decimal studentPrice) { var ticket = new TrainTicket(from, to, dateAndTime, price, studentPrice); string result = this.AddTicket(ticket); return result; } public string DeleteTrainTicket(string from, string to, DateTime dateAndTime) { TrainTicket ticket = new TrainTicket(from, to, dateAndTime); string result = this.DeleteTicketByUniqueKey(ticket.UniqueKey); return result; } public string AddBusTicket( string from, string to, string company, DateTime dateAndTime, decimal price) { BusTicket ticket = new BusTicket(from, to, company, dateAndTime, price); string result = this.AddTicket(ticket); return result; } public string DeleteBusTicket( string from, string to, string company, DateTime dateAndTime) { BusTicket ticket = new BusTicket(from, to, company, dateAndTime); string result = this.DeleteTicketByUniqueKey(ticket.UniqueKey); return result; } public string FindTickets(string from, string to) { string fromToKey = Ticket.CreateFromToKey(from, to); if (this.ticketsByFromToKey.ContainsKey(fromToKey)) { string ticketsAsString = this.FormatTicketsForPrinting(this.ticketsByFromToKey[fromToKey]); return ticketsAsString; } else { return "Not found"; } } public string FindTicketsInInterval( DateTime startDateTime, DateTime endDateTime) { var ticketsFound = this.ticketsByDepartureTime.Range(startDateTime, true, endDateTime, true).Values; if (ticketsFound.Count > 0) { string ticketsAsString = this.FormatTicketsForPrinting(ticketsFound); return ticketsAsString; } else { return "Not found"; } } private string AddTicket(Ticket ticket) { string key = ticket.UniqueKey; if (this.ticketsByUniqueKey.ContainsKey(key)) { return "Duplicate ticket"; } else { this.ticketsByUniqueKey.Add( key, ticket); string fromToKey = ticket.FromToKey; this.ticketsByFromToKey.Add( fromToKey, ticket); this.ticketsByDepartureTime.Add( ticket.DateAndTime, ticket); this.ticketsCount[ticket.Type]++; return "Ticket added"; } } private string DeleteTicketByUniqueKey(string uniqueKey) { if (this.ticketsByUniqueKey.ContainsKey(uniqueKey)) { var ticket = this.ticketsByUniqueKey[uniqueKey]; this.ticketsByUniqueKey.Remove(uniqueKey); string fromToKey = ticket.FromToKey; this.ticketsByFromToKey.Remove(fromToKey, ticket); this.ticketsByDepartureTime.Remove(ticket.DateAndTime, ticket); this.ticketsCount[ticket.Type]--; return "Ticket deleted"; } else { return "Ticket does not exist"; } } private string FormatTicketsForPrinting(ICollection<Ticket> tickets) { List<Ticket> sortedTickets = new List<Ticket>(tickets); sortedTickets.Sort(); string result = string.Join( " ", sortedTickets.Select(t => t.ToString())); return result; } } }
56edd5d350c82e78d73744d593cbad8fdce035ab
C#
amjad-Alhusseini/ToDoSampleWithAuth
/PerToDo/Pages/MainPage.xaml.cs
2.53125
3
using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; namespace PerToDo { public partial class MainPage : ContentPage { //List<ToDoItem> todoList; ToDoRepository todoRepo = new ToDoRepository(new ToDoService()); public MainPage() { InitializeComponent(); configurePage(); } private void configurePage() { Title = "To do list"; AddTaskButton.Clicked += AddTaskButton_Clicked; NavigationPage.SetHasBackButton(this, false); } protected override void OnAppearing() { base.OnAppearing(); var _ = configureTodoList(); } private async Task configureTodoList() { todoListView.ItemsSource = await todoRepo.GetToDoList(); } void AddTaskButton_Clicked(object sender, EventArgs e) { Navigation.PushAsync(new ItemDetailsPage(new ToDoItem())); } void todoListView_ItemSelected(object sender, Xamarin.Forms.SelectedItemChangedEventArgs e) { var todoItem = e.SelectedItem as ToDoItem; var itemDetailsPage = new ItemDetailsPage(todoItem) { BindingContext = todoItem }; Navigation.PushAsync(itemDetailsPage); } public async void OnTaskDelete(object sender, EventArgs e) { var menuItem = ((MenuItem)sender); var taskId = (Int32)menuItem.CommandParameter; var isConfirmed = await DisplayAlert("Delete Confirmation", "Are you sure you want to delete this task?" ,"Confirm", "Cancel"); if (isConfirmed) { await todoRepo.DeleteToDoItem(taskId); await configureTodoList(); } } } }
8468a0f2ddbf9d8c19645fb32bbec09a17dbc865
C#
CasperGuo/ExcelDataReader
/src/ExcelDataReader/Core/BinaryFormat/XlsBiffSST.cs
3.1875
3
using System; using System.Collections.Generic; using System.Text; namespace ExcelDataReader.Core.BinaryFormat { /// <summary> /// Represents a Shared String Table in BIFF8 format /// </summary> internal class XlsBiffSST : XlsBiffRecord { private readonly List<IXlsString> _strings; internal XlsBiffSST(byte[] bytes, uint offset) : base(bytes, offset) { _strings = new List<IXlsString>(); } /// <summary> /// Gets the number of strings in SST /// </summary> public uint Count => ReadUInt32(0x0); /// <summary> /// Gets the count of unique strings in SST /// </summary> public uint UniqueCount => ReadUInt32(0x4); /// <summary> /// Parses strings out of the SST record and subsequent Continue records from the BIFF stream /// </summary> public void ReadStrings(XlsBiffStream biffStream) { var reader = new XlsSSTReader(this, biffStream); for (var i = 0; i < UniqueCount; i++) { var s = reader.ReadString(); _strings.Add(s); } } /// <summary> /// Returns string at specified index /// </summary> /// <param name="sstIndex">Index of string to get</param> /// <param name="encoding">Workbook encoding</param> /// <returns>string value if it was found, empty string otherwise</returns> public string GetString(uint sstIndex, Encoding encoding) { if (sstIndex < _strings.Count) return _strings[(int)sstIndex].GetValue(encoding); return string.Empty; } } }
f717990c3a0ddada03c0d19747882061d25dc38f
C#
hackf5/xamlr
/src/Xamlr.Core.Test/StringDiff.cs
2.65625
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="StringDiff.cs" company="Xamlr"> // The MIT License (MIT) // // Copyright (c) 2019 Brian Tyler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // </copyright> // <summary> // Defines the StringDiff type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Xamlr.Core.Test { using System; using System.Linq; internal static class StringDiff { public static StringDiffResult Compare(string expected, string actual) { if (expected == null) { throw new ArgumentNullException(nameof(expected)); } if (actual == null) { throw new ArgumentNullException(nameof(actual)); } var length = Math.Min(expected.Length, actual.Length); var comparison = Enumerable .Range(0, length) .Zip(expected, (i, c) => new { I = i, Expected = c }) .Zip(actual, (z, c) => new { z.I, AreEqual = c.Equals(z.Expected) }) .ToArray(); var areEqual = expected.Length == actual.Length && comparison.All(x => x.AreEqual); if (areEqual) { return new StringDiffResult(true); } var firstDifference = comparison.FirstOrDefault(x => !x.AreEqual); var firstDifferenceIndex = firstDifference == null ? length : firstDifference.I; return StringDiff.CreateResult(expected, actual, firstDifferenceIndex); } private static string CreateAroundIndex(string value, int index) { var window = 20; var start = Math.Max(index - window, 0); var end = Math.Min(index + window, value.Length - 1); var substr = value.Substring(start, end - start).Replace('\n', '·').Replace('\r', '·').Replace('\t', '·'); return $"{substr}\n{new string(' ', Math.Min(index, window))}^"; } private static StringDiffResult CreateResult(string expected, string actual, int firstDifferenceIndex) { var details = $"Expected:\n{StringDiff.CreateAroundIndex(expected, firstDifferenceIndex)}\nActual:\n{StringDiff.CreateAroundIndex(actual, firstDifferenceIndex)}"; return new StringDiffResult(false, firstDifferenceIndex, details); } } }
9db6ff2474f1ce035db1882dac9e7d081790ecc3
C#
Rezasanjari1996/Store
/myweb/Models/kala.cs
2.515625
3
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace myweb.Models.DomainModel { [MetadataType(typeof(UserDto))] public partial class user { [Display(Name = "تکرار پسورد")] [Required(ErrorMessage = "لطفا تکرار پسورد راوارد کنید")] [DataType(DataType.Password)] [Compare("Password",ErrorMessage ="رمز عبور یکسان نیست")] public string ConfirmPassword { get; set; } } } namespace myweb.Models { internal class UserDto { public int Id { get; set; } [Display(Name ="نام")] [Required(ErrorMessage ="لطفا نام راوارد کنید")] [RegularExpression(@"^[آ-ی ء چ]+$", ErrorMessage ="حروف فارسی وارد کنید")] public string Name { get; set; } [Display(Name = " نام کاربری")] [Required(ErrorMessage = "لطفا نام خانوادگی راوارد کنید")] [RegularExpression(@"^[a-zA-Z].*@[a-zA-Z]+\.com")] public string UserName { get; set; } [Display(Name = "پسورد")] [Required(ErrorMessage = "لطفا پسورد راوارد کنید")] [MinLength(8,ErrorMessage ="حداکثر هشت کارکتر وارد کنید")] [RegularExpression(@"^[A-Za-z0-9_]+$")] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "تاریخ تولد")] [DataType(DataType.Date)] public Nullable<System.DateTime> BrithDay { get; set; } [Display(Name = "موبایل")] [RegularExpression(@"09\d{9}",ErrorMessage ="09*********")] public string Mobile { get; set; } [Display(Name = "تلفن")] public string Tell { get; set; } [Display(Name = "جنسیت")] public bool Gender { get; set; } [Display(Name = "وضعیت")] public Nullable<byte> Status { get; set; } } }
72163310f2b1d5651e0f1205250af6bcd924fa46
C#
SokratisV/Virtual-Keyboard-2018.4
/Assets/Virtual Keyboard/Scripts/Misc/ReceiveInput.cs
2.875
3
using System.Collections.Generic; using TMPro; using UnityEngine; namespace VirtualKeyboard { public class ReceiveInput : MonoBehaviour { TextMeshProUGUI textComponent; Dictionary<string, string> greekToEnglishDict = new Dictionary<string, string>() { {"διαγραφή", "backspace"}, {"διαγραφή όλων","clear all"}, {"κεφαλαία", "caps lock"}, {"τόνοι", "shift"} }; private void OnEnable() { KeyPressEventSender.onKeyPress += Receive; } private void OnDisable() { KeyPressEventSender.onKeyPress -= Receive; } private void Start() { textComponent = GetComponentInChildren<TextMeshProUGUI>(); } public void Receive(string value) { string newValue; //check if it exists in the dictionary if (!greekToEnglishDict.TryGetValue(value.ToLower(), out newValue)) { newValue = value; } switch (newValue.ToLower()) { case "backspace": DeleteLetter(); break; case " ": AddSpace(); break; case "clear all": DeleteEverything(); break; case "enter": break; case "caps lock": break; case "shift": break; default: PrintLetter(value); break; } } private void PrintLetter(string letter) { textComponent.text += letter; } private void DeleteLetter() { var text = textComponent.text; if (text.Length <= 0) return; textComponent.text = text.Remove(text.Length - 1, 1); } private void AddSpace() { textComponent.text += " "; } private void DeleteEverything() { textComponent.text = ""; } } }
cf9a82f8834fdfb3876daff8e6245412f5e65b9b
C#
sono8stream/AtPractice
/AtTest/400Problems(remain)/Tenka2016B_B.cs
3.203125
3
using System; using System.Collections.Generic; using System.Text; namespace AtTest._400Problems_remain_ { class Tenka2016B_B { static void ain(string[] args) { Method(args); Console.ReadLine(); } static void Method(string[] args) { string s = Read(); int length = s.Length; var dp = new int[105, 105,105]; int inf = int.MaxValue / 2; //iマスまで見てカーソル位置がj,(の数-)の数がkの操作数 for (int i = 0; i < 101; i++) { for(int j = 0; j < 101; j++) { for (int k = 0; k < 101; k++) { dp[i, j, k] = inf; } } } dp[0, 0, 0] = 0; for(int i = 0; i < length; i++) { for(int j = 0; j < length; j++) { for(int k = 0; k <= length; k++) { if (dp[i, j, k] == int.MaxValue) continue; if (s[i] == '(') { dp[i + 1, j,k + 1] = Math.Min(dp[i + 1, j, k + 1], dp[i, j, k]); if (0 < k) { dp[i + 1, i, k - 1] = Math.Min(dp[i + 1, i, k - 1], dp[i, j, k] + 1); } } else { dp[i + 1, i, k + 1] = Math.Min(dp[i + 1, i, k + 1], dp[i, j, k] + 1); if (0 < k) { dp[i + 1, j, k - 1] = Math.Min(dp[i + 1, j, k - 1], dp[i, j, k]); } } } } } int res = inf; for(int i = 0; i < length; i++) { res = Math.Min(res, dp[length, i, 0] + i); } Console.WriteLine(res); } private static string Read() { return Console.ReadLine(); } private static int ReadInt() { return int.Parse(Read()); } private static long ReadLong() { return long.Parse(Read()); } private static double ReadDouble() { return double.Parse(Read()); } private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); } private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); } private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); } } }
0e9595de1760d45429fecbe24f9f320a0f5fd2b3
C#
loai007/last_group_26
/WindowsFormsApp1Tests/Form1Tests.cs
2.625
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using WindowsFormsApp1; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace WindowsFormsApp1.Tests { [TestClass()] public class Form1Tests { [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void SignInTest() { var newform1 = new Form1(); string unWrong = "", unRight = "any"; string psWrong = "", psRight = "any"; newform1.checkUsernamePassword(unWrong, psRight); newform1.checkUsernamePassword(unWrong, psWrong); newform1.checkUsernamePassword(unRight, psWrong); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void creatdocTestLine() { var newform1 = new Form1(); string rightPath = "user.txt", emptyline =""; newform1.creatdoc(emptyline, rightPath); } } [TestClass()] public class StudentAddCourseTest { [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void WriteTOFile_shouldntWork() { var student = new StudentAddCourse(); string rightPath = "user.txt", emptyline = ""; student.writeToFile(rightPath, emptyline); } [TestMethod()] public void checkIsEmpty_shouldWork() { var student = new StudentAddCourse(); string[] obj = {"hii"}; string[] obj1 = { "hii there" }; bool actual=student.makesureNotEmpty(obj,obj1); Assert.IsTrue(actual); } } [TestClass()] public class studentMainTests { [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void GetUserNameTest_trowExiption() { var GetName = new studentMain(); GetName.GetUserName(""); } [TestMethod()] public void userNameCorrect() { var GetName = new studentMain(); string objA = "my name"; string objB = GetName.GetUserName("my name"); Assert.AreEqual(objA, objB); } [TestMethod()] public void LogOutTest() { var GetName = new studentMain(); bool expeted = true; bool actual=GetName.isLineEmpty(""); Assert.AreEqual(expeted ,actual); } } [TestClass()] public class IstructorShowCourseTest { [TestMethod()] public void DayPrintCorrect() { InstructorShowCourse day = new InstructorShowCourse(); string expicted = "Sunday"; string expicted1 = ""; string actual = day.dayofweek(1); string actual1 = day.dayofweek(0); Assert.AreEqual(expicted, actual); Assert.AreEqual(expicted1, actual1); } } [TestClass()] public class IstructorMainTest { [TestMethod()] public void LogOutTest() { InstructorMain obj = new InstructorMain(); bool actual=obj.fileIsWhiteSpace(""); Assert.IsTrue(actual); } } [TestClass()] public class StudentRemoveCourseTest { [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void DataTableIsInsulized() { StudentRemoveCourse obj = new StudentRemoveCourse(); obj. Datatableisempty(null); } } [TestClass()] public class ManagerMainTest { [TestMethod()] public void LogOutTest() { ManagerMain obj = new ManagerMain(); bool actual = obj.LogOutChick(""); Assert.IsTrue(actual); } } [TestClass()] public class ManagerAddCourseTest { [TestMethod()] public void AddCourseDataTest() { ManagerAddCourse obj = new ManagerAddCourse(); bool actual = obj.CheckInputs(""); Assert.IsFalse(actual); } } [TestClass()] public class ManagerDeleteCourseTest { [TestMethod()] public void falseTest() { Assert.IsFalse(false); } } }
c41151d7ecd9ef24db64c2edce6d826830ece61f
C#
Team-5-Jellyfish-Store/Jellyfish-Store
/OnlineStore/OnlineStore.Providers/Providers/PDFExporter.cs
2.8125
3
using iTextSharp.text; using iTextSharp.text.pdf; using OnlineStore.DTO.OrderModels.Constracts; using OnlineStore.DTO.ProductModels.Contracts; using OnlineStore.Providers.Contracts; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace OnlineStore.Providers.Providers { public class PDFExporter : IPDFExporter { public void ExportProducts(IEnumerable<IProductModel> products) { string uniqueName = ($"y{DateTime.Now.Year}m{DateTime.Now.Month}d{DateTime.Now.Day}" + $"h{DateTime.Now.Hour}m{DateTime.Now.Minute}s{DateTime.Now.Second}.pdf"); string fileName = $"../../../PDFReports/ProductsReport{uniqueName}"; FileStream fs = new FileStream(fileName, FileMode.Create); // Create an instance of the document class which represents the PDF document itself. Document document = new Document(PageSize.A4, 25, 25, 30, 30); // Create an instance to the PDF file by creating an instance of the PDF // Writer class using the document and the filestrem in the constructor. PdfWriter writer = PdfWriter.GetInstance(document, fs); document.AddSubject("This is a PDF showing current products"); // Open the document to enable you to write to the document document.Open(); // Add a simple and wellknown phrase to the document in a flow layout manner document.Add(new Paragraph("Those are the current products:")); document.Add(new Paragraph(Environment.NewLine)); if (!products.Any()) { document.Add(new Paragraph("No products at the moment")); } else { foreach (var product in products.Where(w => w.Quantity > 0)) { document.Add(new Paragraph($"Name: {product.Name}\r\nCategory: {product.CategoryName}\r\nAvailable quantity: {product.Quantity}\r\nSelling price: ${product.SellingPrice}")); document.Add(new Paragraph(Environment.NewLine)); } } // Close the document document.Close(); // Close the writer instance writer.Close(); // Always close open filehandles explicity fs.Close(); } public void ExportOrders(IEnumerable<IOrderModel> orders) { string uniqueName = ($"y{DateTime.Now.Year}m{DateTime.Now.Month}d{DateTime.Now.Day}" + $"h{DateTime.Now.Hour}m{DateTime.Now.Minute}s{DateTime.Now.Second}.pdf"); string fileName = $"../../../PDFReports/OrdersReport{uniqueName}"; FileStream fs = new FileStream(fileName, FileMode.Create); Document document = new Document(PageSize.A4, 25, 25, 30, 30); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.AddSubject("This is a PDF showing current orders"); document.Open(); document.Add(new Paragraph("Those are the current orders:")); document.Add(new Paragraph(Environment.NewLine)); if (!orders.Any()) { document.Add(new Paragraph("No orders at the moment")); } else { foreach (var item in orders) { document.Add(new Paragraph($"Comment: {item.Comment}\r\nClient name: {item.Username}\r\nDate of order: {item.OrderedOn}")); document.Add(new Paragraph(Environment.NewLine)); } } document.Close(); writer.Close(); fs.Close(); } } }
b57b0e7832e53a1217146efe3f282bc34d5bbd3f
C#
mohi-othman/ray-tracer-c-sharp-teaching
/RayTraceLearning/Units/Vector3D.cs
3.515625
4
//Struct to represent a three dimensional vector value using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SystemDown.RayTracer { public struct Vector3D { //Properties public double x { get; set; } public double y { get; set; } public double z { get; set; } //Constructor public Vector3D(double X, double Y, double Z):this() { x = X; y = Y; z = Z; } //Dot product of two vectors public static double operator *(Vector3D a, Vector3D b) { return (a.x * b.x) + (a.y * b.y) + (a.z * b.z); } //Cross product of two vectors public static Vector3D Cross(Vector3D a, Vector3D b) { var x = a.y * b.z - b.y * a.z; var y = a.z * b.x - b.z * a.x; var z = a.x * b.y - b.x * a.y; return new Vector3D(x, y, z); } //Vector arithmatic public static Vector3D operator *(double scalar, Vector3D vector) { var xd = scalar * vector.x; var yd = scalar * vector.y; var zd = scalar * vector.z; return new Vector3D(xd, yd, zd); } public static Vector3D operator *(Vector3D vector, double scalar) { return scalar * vector; } public static Vector3D operator -(Vector3D vector) { return new Vector3D(-vector.x, -vector.y, -vector.z); } public static Vector3D operator -(Vector3D start, Vector3D finish) { var xd = start.x - finish.x; var yd = start.y - finish.y; var zd = start.z - finish.z; return new Vector3D(xd, yd, zd); } public static Vector3D operator +(Vector3D start, Vector3D finish) { var xd = start.x + finish.x; var yd = start.y + finish.y; var zd = start.z + finish.z; return new Vector3D(xd, yd, zd); } //Distance between two coordinates public static double Distance(Vector3D start, Vector3D finish) { var xd = start.x - finish.x; var yd = start.y - finish.y; var zd = start.z - finish.z; return Math.Sqrt(xd * xd + yd * yd + zd * zd); } //Returns magnitude of a vector public double Magnitude() { return Math.Sqrt(x * x + y * y + z * z); } //Returns a normalized vector (i.e. make it's magnitude equal to 1) public Vector3D Normalize() { var a = this.Magnitude(); if (a == 0) return this; else return new Vector3D(x / a, y / a, z / a); } //Returns length of a vector public double Length() { return Math.Sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } } }
7f980d09d7f7c894022e7ad4a7cb97aea7a636e3
C#
MCR2601/ConsoleRenderingFramework
/CRFVideoTools/Extensions.cs
2.953125
3
using FFMediaToolkit.Graphics; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace CRFVideoTools { public static class Extensions { // ImageData -> Bitmap (unsafe) public static unsafe Bitmap ToBitmap(this ImageData bitmap) { fixed (byte* p = bitmap.Data) { return new Bitmap(bitmap.ImageSize.Width, bitmap.ImageSize.Height, bitmap.Stride, PixelFormat.Format24bppRgb, new IntPtr(p)); } } public static Bitmap ImageSmooth(this Bitmap image) { int w = image.Width; int h = image.Height; BitmapData image_data = image.LockBits( new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); int bytes = image_data.Stride * image_data.Height; byte[] buffer = new byte[bytes]; byte[] result = new byte[bytes]; Marshal.Copy(image_data.Scan0, buffer, 0, bytes); image.UnlockBits(image_data); for (int i = 2; i < w - 2; i++) { for (int j = 2; j < h - 2; j++) { int p = i * 3 + j * image_data.Stride; for (int k = 0; k < 3; k++) { List<int> vals = new List<int>(); for (int xkernel = -2; xkernel < 3; xkernel++) { for (int ykernel = -2; ykernel < 3; ykernel++) { int kernel_p = k + p + xkernel * 3 + ykernel * image_data.Stride; vals.Add(buffer[kernel_p]); } } result[p + k] = (byte)(vals.Sum() / vals.Count); } } } Bitmap res_img = new Bitmap(w, h); BitmapData res_data = res_img.LockBits( new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); Marshal.Copy(result, 0, res_data.Scan0, bytes); res_img.UnlockBits(res_data); return res_img; } } }
8e11546b775955baeedb79af75575b02bea7121d
C#
xAmaris/questionnaire
/questionnaire.Infrastructure/Repositories/QuestionRepository.cs
2.578125
3
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using questionnaire.Core.Domains.Surveys; using questionnaire.Infrastructure.Data; using questionnaire.Infrastructure.Repositories.Interfaces; using Microsoft.EntityFrameworkCore; namespace questionnaire.Infrastructure.Repositories { public class QuestionRepository : IQuestionRepository { private readonly QuestionnaireContext _context; public QuestionRepository (QuestionnaireContext context) { _context = context; } public async Task AddAsync (Question question) { await _context.Questions.AddAsync (question); await _context.SaveChangesAsync (); } public async Task<Question> GetByIdAsync (int id, bool isTracking = true) { if (isTracking) { return await _context.Questions .AsTracking () .SingleOrDefaultAsync (x => x.Id == id); } return await _context.Questions .AsNoTracking () .SingleOrDefaultAsync (x => x.Id == id); } } }
2b222adf8560ab5a2cfd0a02d3255a30c47495b5
C#
dhutchinson5/TestConsole
/TestConsole/Program.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestConsole { class Program { static void Main(string[] args) { // Generate Random Number var number = new Random((int)DateTime.Now.Ticks).Next(0, 500); // Write Random Number Console.WriteLine(number); } } }
5191b33245a0cd9806a012ac21b0cfbb3148e29a
C#
182648820/Three_Framework
/applyFrame/Form1.cs
2.765625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MyBll; using MyModel; namespace applyFrame { public partial class Form1 : Form { public Form1() { InitializeComponent(); } MyBllDemo bllDemo = new MyBllDemo(); //定义一个BLL层的类 private void btnAdd_Click(object sender, EventArgs e) { #region 面向过程:任务逐语句执行 //if(bllDemo.Operate(pName.Text, Age.Text, Sex.Text) > 0) //{ // MessageBox.Show("添加成功"); // pName.Clear(); // Age.Clear(); // Sex.Clear(); //} #endregion //面向对象:逐过程 InitData(); MyModelDemo model = new MyModelDemo(); if (bllDemo.Operate() > 0) { MessageBox.Show("添加成功"); pName.Clear(); Age.Clear(); Sex.Clear(); } Update(); } private void btnDelete_Click(object sender, EventArgs e) { InitData(); if (bllDemo.Delet()>0) { MessageBox.Show(MyModelDemo.PNames+"相关信息删除成功"); Update(); } } private void Form1_Load(object sender, EventArgs e) { Update(); } #region 更新/初始化 public void Update() //更新 { dataView.DataSource = bllDemo.Selet(); } public void InitData() { MyModelDemo.PNames = pName.Text; MyModelDemo.PAges = Age.Text; MyModelDemo.PSexs = Sex.Text; } #endregion private void btnModify_Click(object sender, EventArgs e) { InitData(); if(bllDemo.Modify()>0) { MessageBox.Show(MyModelDemo.PNames+"的信息修改成功"); Update(); } } //这个功能实现点击dataView某行时 将这一行的一些信息送到其他文本框中 private void dataView_CellClick(object sender, DataGridViewCellEventArgs e) { var Row = dataView.Rows[e.RowIndex]; //获取dataView表的当前操作行 pName.Text = Row.Cells[1].Value.ToString(); Age.Text = Row.Cells[2].Value.ToString(); Sex.Text = Row.Cells[3].Value.ToString(); } } }
3d59036a5236fe64e77e718634c92e815c76d100
C#
Yurii-Yanovitsky/c--essential-homework
/Lesson1/Task3/Program.cs
3.125
3
using System; namespace Task3 { public class Program { static void Main(string[] args) { Console.WriteLine("Creat a book"); Console.WriteLine("Input: title, author, content"); string title = Console.ReadLine(); string author = Console.ReadLine(); string content = Console.ReadLine(); Book book = new Book(title, author, content); book.Show(); Console.ReadKey(); } } }
8cb93a0380ae3951d9e327c6bc23f7851b70332b
C#
rkelkka/receiptparser
/src/ReceiptParser/ReceiptParser.Interface/IReceiptParser.cs
2.515625
3
using ReceiptParser.ReceiptParser.Interface.Input; namespace ReceiptParser.ReceiptParser.Interface { interface IReceiptParser { /// <summary> /// Attempt to parse a receipt. /// </summary> /// <param name="receipt"></param> /// <returns>T</returns> /// <exception cref="InvalidArgumentException">when input data is unsupported format</exception> T ParseReceipt<T>(ReceiptDataIn receipt); } }
4062ebb0fa0d9a0ecfd858dbcaf98bcce0f3e2a0
C#
Dorrro/CSharp_Advanced_Historical_Repo
/CSharp.Advanced.Sii.Trainings.Tests/Reflection/Refl1.cs
3.234375
3
namespace CSharp.Advanced.Sii.Trainings.Tests.Reflection { using System; public class Refl1 { public string Output() { return "Test-Output"; } public int AddInts(int i1, int i2) { return i1 + i2; } static void Main(string[] args) { Console.WriteLine(new Refl1().Output()); Console.WriteLine(new Refl1().AddInts(1, 2)); } } }
48aa48b8161d21a92b1e105c16f3ea1d425db286
C#
will14smith/Crypto
/Crypto/Encryption/AEADCipherAdapter.cs
2.78125
3
using Crypto.Encryption.AEAD; using Crypto.Encryption.Parameters; namespace Crypto.Encryption { public class AEADCipherAdapter : ICipher { public IAEADBlockCipher Cipher { get; } public AEADCipherAdapter(IAEADBlockCipher cipher) { this.Cipher = cipher; } public int KeySize => Cipher.KeySize; public int BlockLength => Cipher.BlockLength; public int TagLength => Cipher.TagLength; public void Init(ICipherParameters parameters) { Cipher.Init(parameters); } public void Encrypt(byte[] input, int inputOffset, byte[] output, int outputOffset, int length) { var offset = Cipher.Encrypt(input, inputOffset, output, outputOffset, length); Cipher.EncryptFinal(output, outputOffset + offset); } public void Decrypt(byte[] input, int inputOffset, byte[] output, int outputOffset, int length) { var offset = Cipher.Decrypt(input, inputOffset, output, outputOffset, length); Cipher.DecryptFinal(input, inputOffset + offset, output, outputOffset + offset); } } }
5254eef858909149e04a1592b9b43fb89a20dbb8
C#
ahaase/CS1
/Assignment5 C#1/Assignment5/ContactFiles/Contact.cs
3.546875
4
using System; using System.Collections.Generic; using System.Text; /// <summary> /// Haase /// </summary> namespace Assignment5 { /// <summary> /// Klass som beskriver ett Contact objekt. /// </summary> public class Contact { private Phone phone; private Email email; private Address address; private string firstName; private string lastName; /// <summary> /// Telefon. /// </summary> public Phone Phone { get { return phone; } set { phone = value; } } /// <summary> /// Email. /// </summary> public Email Email { get { return email; } set { email = value; } } /// <summary> /// Address. /// </summary> public Address Address { get { return address; } set { address = value; } } /// <summary> /// Förnamn. /// </summary> public string FirstName { get { return firstName; } set { firstName = value; } } /// <summary> /// Efternamn. /// </summary> public string LastName { get { return lastName; } set { lastName = value; } } /// <summary> /// Kontrollerar att inget värde är null. /// </summary> /// <returns>Om datan går att använda.</returns> public bool CheckData() { if(email == null || phone == null || address == null || firstName == null || lastName == null) { return false; } return true; } /// <summary> /// Standardkonstruktor. /// </summary> public Contact() { } /// <summary> /// Konstruktor för att kopiera en Contact. /// </summary> /// <param name="theOther">Den andra contact.</param> public Contact(Contact theOther) { firstName = theOther.firstName; lastName = theOther.lastName; phone = theOther.phone; email = theOther.email; address = theOther.address; } /// <summary> /// Konstruktor för att göra en ny contact med nya värden. /// </summary> /// <param name="firstName">Förnamn.</param> /// <param name="lastName">Efternamn.</param> /// <param name="address">Address.</param> /// <param name="email">Email.</param> /// <param name="phone">Telefon.</param> public Contact(string firstName, string lastName, Address address, Email email, Phone phone) { this.firstName = firstName; this.lastName = lastName; this.phone = phone; this.email = email; this.address = address; } } }
d1bcb6a0cc122dd192812f65d2d96ebe5f088120
C#
nasa03/tesserae
/Tesserae/src/Helpers/ComponentCacheBase.cs
3.0625
3
using System.Collections.Generic; using System.Linq; namespace Tesserae { public abstract class ComponentCacheBase<TComponent> where TComponent : class { protected readonly List<(int Key, TComponent Component)> _componentsAndKeys; protected ComponentCacheBase() { _componentsAndKeys = new List<(int Key, TComponent Component)>(); } public int ComponentsCount => _componentsAndKeys.Count; public bool HasComponents => _componentsAndKeys.Any(); protected void AddToComponents(IEnumerable<TComponent> components) { var componentsCount = ComponentsCount; var componentsToAdd = components.Select((component, index) => new { component, key = index + componentsCount + 1 }); foreach (var componentToAdd in componentsToAdd) { _componentsAndKeys.Add((componentToAdd.key, componentToAdd.component)); } } } }
c1f4ea2307f429a441a1e718232cedde848580cd
C#
sid22seth/HotelReservation
/HotelReservationTest/UnitTest1.cs
2.578125
3
using Microsoft.VisualStudio.TestTools.UnitTesting; using HotelReservation; namespace HotelReservationTest { [TestClass] public class UnitTest1 { [TestMethod] public void GivenRegularCustomerTypeAndValidDates_ShouldReturn_CheapestHotelWithHighestRating() { CustomerServices services = new CustomerServices(); HotelType hotel = services.FindCheapHotel("11/09/2020", "12/09/2020", CustomerType.NORMAL); Assert.AreEqual(hotel, HotelType.BRIDGEWOOD); } [TestMethod] public void GivenRewardCustomerTypeAndValidDates_ShouldReturn_CheapestHotelWithHighestRating() { CustomerServices services = new CustomerServices(); HotelType hotel = services.FindCheapHotel("11/09/2020", "12/09/2020", CustomerType.REWARD); Assert.AreEqual(hotel, HotelType.RIDGEWOOD); } [TestMethod] public void GivenRegularCustomerTypeAndValidDates_ShouldReturn_HotelWithHighestRating() { CustomerServices services = new CustomerServices(); HotelType hotel = services.FindBestRatedHotel("11/09/2020", "12/09/2020", CustomerType.NORMAL); Assert.AreEqual(hotel, HotelType.RIDGEWOOD); } [TestMethod] public void GivenRewardCustomerTypeAndValidDates_ShouldReturn_HotelWithHighestRating() { CustomerServices services = new CustomerServices(); HotelType hotel = services.FindBestRatedHotel("11/09/2020", "12/09/2020", CustomerType.REWARD); Assert.AreEqual(hotel, HotelType.RIDGEWOOD); } [TestMethod] public void GivenRegularCustomerTypeAndValidDatesForHotelLakewood_ShouldReturn_HotelRates() { Hotel hotel = new Hotel(HotelType.LAKEWOOD, CustomerType.NORMAL); double expected = 200; double actual = hotel.FindRate("11/09/2020", "12/09/2020"); Assert.AreEqual(expected, actual); } [TestMethod] public void GivenRegularCustomerTypeAndValidDatesForHotelBridgewood_ShouldReturn_HotelRates() { Hotel hotel = new Hotel(HotelType.BRIDGEWOOD, CustomerType.NORMAL); double expected = 200; double actual = hotel.FindRate("11/09/2020", "12/09/2020"); Assert.AreEqual(expected, actual); } [TestMethod] public void GivenRegularCustomerTypeAndValidDatesForHotelRidgewood_ShouldReturn_HotelRates() { Hotel hotel = new Hotel(HotelType.RIDGEWOOD, CustomerType.NORMAL); double expected = 370; double actual = hotel.FindRate("11/09/2020", "12/09/2020"); Assert.AreEqual(expected, actual); } [TestMethod] public void GivenRewardCustomerTypeAndValidDatesForHotelLakewood_ShouldReturn_HotelRates() { Hotel hotel = new Hotel(HotelType.LAKEWOOD, CustomerType.REWARD); double expected = 160; double actual = hotel.FindRate("11/09/2020", "12/09/2020"); Assert.AreEqual(expected, actual); } [TestMethod] public void GivenRewardCustomerTypeAndValidDatesForHotelBridgewood_ShouldReturn_HotelRates() { Hotel hotel = new Hotel(HotelType.BRIDGEWOOD, CustomerType.REWARD); double expected = 160; double actual = hotel.FindRate("11/09/2020", "12/09/2020"); Assert.AreEqual(expected, actual); } [TestMethod] public void GivenRewardCustomerTypeAndValidDatesForHotelRidgewood_ShouldReturn_HotelRates() { Hotel hotel = new Hotel(HotelType.RIDGEWOOD, CustomerType.REWARD); double expected = 140; double actual = hotel.FindRate("11/09/2020", "12/09/2020"); Assert.AreEqual(expected, actual); } [TestMethod] public void GivenNormalCustomerTypeAndInvalidDates_ShouldThrow_CustomException() { Hotel hotel = new Hotel(HotelType.RIDGEWOOD, CustomerType.REWARD); string expectedMessage = "Invalid date entered"; string actualMessage = ""; try { double actual = hotel.FindRate("0000000", "12/09/2020"); } catch (HotelReservationException exception) { actualMessage = exception.Message; } Assert.AreEqual(expectedMessage, actualMessage); } [TestMethod] public void GivenNormalString_WhenValidated_ShouldReturn_NormalCustomerType() { CustomerServices service = new CustomerServices(); CustomerType expected = service.Validate("Normal"); CustomerType actual = CustomerType.NORMAL; Assert.AreEqual(expected, actual); } [TestMethod] public void GivenRewardString_WhenValidated_ShouldReturn_RewardCustomerType() { CustomerServices service = new CustomerServices(); CustomerType expected = service.Validate("Reward"); CustomerType actual = CustomerType.REWARD; Assert.AreEqual(expected, actual); } [TestMethod] public void GivenInvalidString_WhenValidated_ShouldReturn_CustomExcetion() { CustomerServices service = new CustomerServices(); string actual = ""; string message = "Invalid customer type"; try { CustomerType expected = service.Validate("regular"); } catch (HotelReservationException exception) { actual = exception.Message; } Assert.AreEqual(message, actual); } } }
f9f1b052bcdc3bb4568e13252982cce726e9f3fe
C#
rebus-org/Rebus
/Rebus/Persistence/InMem/InMemorySagaStorage.cs
2.78125
3
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using Rebus.Exceptions; using Rebus.Reflection; using Rebus.Sagas; #pragma warning disable 1998 namespace Rebus.Persistence.InMem; /// <summary> /// Implementation of <see cref="ISagaStorage"/> that "persists" saga data in memory. Saga data is serialized/deserialized using Newtonsoft JSON.NET /// with some pretty robust settings, so inheritance and interfaces etc. can be used in the saga data. /// </summary> public class InMemorySagaStorage : ISagaStorage { readonly ConcurrentDictionary<Guid, ISagaData> _data = new(); readonly object _lock = new(); readonly JsonSerializerSettings _serializerSettings = new() { TypeNameHandling = TypeNameHandling.All }; /// <summary> /// Returns all stored saga data instances. /// </summary> public IEnumerable<ISagaData> Instances { get { lock (_data) { return _data.Values.ToList(); } } } internal void AddInstance(ISagaData sagaData) { lock (_lock) { var instance = Clone(sagaData); if (instance.Id == Guid.Empty) { instance.Id = Guid.NewGuid(); } _data[instance.Id] = instance; } } internal event Action<ISagaData> Created; internal event Action<ISagaData> Updated; internal event Action<ISagaData> Deleted; internal event Action<ISagaData> Correlated; internal event Action CouldNotCorrelate; /// <summary> /// Looks up an existing saga data of the given type with a property of the specified name and the specified value /// </summary> public async Task<ISagaData> Find(Type sagaDataType, string propertyName, object propertyValue) { lock (_lock) { var valueFromMessage = (propertyValue ?? "").ToString(); foreach (var data in _data.Values) { if (data.GetType() != sagaDataType) continue; var sagaValue = Reflect.Value(data, propertyName); var valueFromSaga = (sagaValue ?? "").ToString(); if (valueFromMessage.Equals(valueFromSaga)) { var clone = Clone(data); Correlated?.Invoke(clone); return clone; } } CouldNotCorrelate?.Invoke(); return null; } } /// <summary> /// Saves the given saga data, throwing an exception if the instance already exists /// </summary> public async Task Insert(ISagaData sagaData, IEnumerable<ISagaCorrelationProperty> correlationProperties) { var id = GetId(sagaData); lock (_lock) { if (_data.ContainsKey(id)) { throw new ConcurrencyException($"Saga data with ID {id} already exists!"); } VerifyCorrelationPropertyUniqueness(sagaData, correlationProperties); if (sagaData.Revision != 0) { throw new InvalidOperationException($"Attempted to insert saga data with ID {id} and revision {sagaData.Revision}, but revision must be 0 on first insert!"); } var clone = Clone(sagaData); _data[id] = clone; Created?.Invoke(clone); } } /// <summary> /// Updates the saga data /// </summary> public async Task Update(ISagaData sagaData, IEnumerable<ISagaCorrelationProperty> correlationProperties) { var id = GetId(sagaData); lock (_lock) { if (!_data.ContainsKey(id)) { throw new ConcurrencyException($"Saga data with ID {id} no longer exists and cannot be updated"); } VerifyCorrelationPropertyUniqueness(sagaData, correlationProperties); var existingCopy = _data[id]; if (existingCopy.Revision != sagaData.Revision) { throw new ConcurrencyException($"Attempted to update saga data with ID {id} with revision {sagaData.Revision}, but the existing data was updated to revision {existingCopy.Revision}"); } var clone = Clone(sagaData); clone.Revision++; _data[id] = clone; Updated?.Invoke(clone); sagaData.Revision++; } } void VerifyCorrelationPropertyUniqueness(ISagaData sagaData, IEnumerable<ISagaCorrelationProperty> correlationProperties) { foreach (var property in correlationProperties) { var valueFromSagaData = Reflect.Value(sagaData, property.PropertyName); foreach (var existingSagaData in _data.Values) { if (existingSagaData.Id == sagaData.Id) continue; if (existingSagaData.GetType() != sagaData.GetType()) continue; var valueFromExistingInstance = Reflect.Value(existingSagaData, property.PropertyName); if (Equals(valueFromSagaData, valueFromExistingInstance)) { throw new ConcurrencyException($"Correlation property '{property.PropertyName}' has value '{valueFromExistingInstance}' in existing saga data with ID {existingSagaData.Id}"); } } } } /// <summary> /// Deletes the given saga data /// </summary> public async Task Delete(ISagaData sagaData) { var id = GetId(sagaData); lock (_lock) { if (!_data.ContainsKey(id)) { throw new ConcurrencyException($"Saga data with ID {id} no longer exists and cannot be deleted"); } if (_data.TryRemove(id, out var temp)) { Deleted?.Invoke(temp); } sagaData.Revision++; } } /// <summary> /// Resets the saga storage (i.e. all stored saga data instances are deleted) /// </summary> public void Reset() { lock (_data) { foreach (var id in _data.Keys.ToList()) { if (_data.TryRemove(id, out var sagaData)) { Deleted?.Invoke(sagaData); } } } } static Guid GetId(ISagaData sagaData) { var id = sagaData.Id; if (id != Guid.Empty) return id; throw new InvalidOperationException("Saga data must be provided with an ID in order to do this!"); } ISagaData Clone(ISagaData sagaData) { var serializedObject = JsonConvert.SerializeObject(sagaData, _serializerSettings); return JsonConvert.DeserializeObject<ISagaData>(serializedObject, _serializerSettings); } }
d6ebfdde25806526ba38f025d13bba80c0211e54
C#
Skeen/ATC
/ATC_Tests/DirectionTest.cs
3.28125
3
using ATC; namespace ATC_Tests { using NUnit.Framework; [TestFixture] class DirectionTest { [Test] public void constructionTest() { Direction direction = new Direction(Direction.DirectionType.NORTH); Assert.AreEqual(Direction.DirectionType.NORTH, direction.direction); } [Test] public void oppositeDirectionTest() { Direction direction1 = new Direction(Direction.DirectionType.NORTH); Direction opposite1 = direction1.getOppositeDirection(); Assert.AreEqual(Direction.DirectionType.SOUTH, opposite1.direction); Direction direction2 = new Direction(Direction.DirectionType.EAST); Direction opposite2 = direction2.getOppositeDirection(); Assert.AreEqual(Direction.DirectionType.WEST, opposite2.direction); } [Test] public void toStringTest() { Direction direction1 = new Direction(Direction.DirectionType.NORTH); string str1 = direction1.ToString(); Assert.AreEqual("NORTH", str1); Direction direction2 = new Direction(Direction.DirectionType.WEST); string str2 = direction2.ToString(); Assert.AreEqual("WEST", str2); } } }
d2df4d18f7e95ca73133b1bc926b149be26e1501
C#
PBotusan/Prototype-2d-rpg
/topdown rpg/Assets/Script/Rooms/DungeonEnemyRoom.cs
2.8125
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class DungeonEnemyRoom : Room { [SerializeField] Door[] doors; [SerializeField] GameObject door; int count; /// <summary> /// Check if the enemies are still alive. /// </summary> public void CheckEnemies() { for (int i = 0; i < enemies.Length; i++) { //if enemies are active do nothing, if not open the door again. if (enemies[i].gameObject.activeInHierarchy && i < enemies.Length) { count += 1; if (count == enemies.Length) { OpenDoors(); } return; } } } /// <summary> /// Close door when needed /// </summary> private void CloseDoors() { StartCoroutine(CloseDoorCoroutine()); } private IEnumerator CloseDoorCoroutine() { yield return new WaitForSeconds(.5f); door.SetActive(true); } /// <summary> /// Open the door after completing task. /// </summary> private void OpenDoors() { door.SetActive(false); count = 0; // reset count for the enemy door, reset when entering again. } //==================================Overrides from Room Class=========================================\\ // ChangeActivation inherited by DungeonRoom -> Room. protected override void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player") && !collision.isTrigger) { //activate the enemies and destructables. for (int i = 0; i < enemies.Length; i++) { ChangeActivation(enemies[i], true); } for (int i = 0; i < breakables.Length; i++) { ChangeActivation(breakables[i], true); } virtualCamera.SetActive(true); CloseDoors(); } } /// <summary> /// When player leaves room deactivate enemies and breakables. /// </summary> /// <param name="collision"></param> protected override void OnTriggerExit2D(Collider2D collision) { if (collision.CompareTag("Player") && !collision.isTrigger) { //Deactivate the enemies and destructables. for (int i = 0; i < enemies.Length; i++) { ChangeActivation(enemies[i], false); } for (int i = 0; i < breakables.Length; i++) { ChangeActivation(breakables[i], false); } OpenDoors(); } } }
d3df536bb83edad78223e01e4815153e157ba5b8
C#
LiuyangRY/BlogCore
/Blog.Core.Repository/Base/IBaseRepository.cs
2.703125
3
using System; using System.Data; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using SqlSugar; using Blog.Core.Model.Models; namespace Blog.Core.Repository.Base { public interface IBaseRepository<TEntity> where TEntity : class { /// <summary> /// 根据主键查询 /// </summary> /// <param name="objId">主键</param> /// <returns>查询结果</returns> Task<TEntity> QueryByID(object objId); /// <summary> /// 根据主键查询 /// </summary> /// <param name="objId">主键</param> /// <param name="useCache">是否使用缓存(默认不使用)</param> /// <returns>查询结果</returns> Task<TEntity> QueryByID(object objId, bool useCache = false); /// <summary> /// 根据多个主键查询结果集 /// </summary> /// <param name="objIds">主键数组</param> /// <returns>查询结果集</returns> Task<IEnumerable<TEntity>> QueryByIDs(object[] objIds); /// <summary> /// 新增 /// </summary> /// <param name="model">模型</param> /// <returns>新增数量</returns> Task<int> Add(TEntity model); /// <summary> /// 批量新增 /// </summary> /// <param name="models">模型集合</param> /// <returns>新增数量</returns> Task<int> AddRange(IEnumerable<TEntity> models); /// <summary> /// 根据主键删除 /// </summary> /// <param name="objId">主键</param> /// <returns>删除的数量</returns> Task<int> DeleteByID(object objId); /// <summary> /// 根据实体删除 /// </summary> /// <param name="model">需要删除的实体</param> /// <returns>删除的数量</returns> Task<int> Delete(TEntity model); /// <summary> /// 根据多个主键删除 /// </summary> /// <param name="objIds">主键数组</param> /// <returns>删除的数量</returns> Task<int> DeleteByIDs(object[] objIds); /// <summary> /// 根据实体更新 /// </summary> /// <param name="model">更新实体</param> /// <returns>更新的数量</returns> Task<int> Update(TEntity model); /// <summary> /// 根据实体和条件更新 /// </summary> /// <param name="model">更新实体</param> /// <param name="where">更新条件</param> /// <returns>更新的数量</returns> Task<int> Update(TEntity model, string where); /// <summary> /// 更新匿名对象 /// </summary> /// <param name="operateAnonymousObjects">匿名对象</param> /// <returns>更新的数量</returns> Task<int> Update(object operateAnonymousObjects); /// <summary> /// 更新实体 /// </summary> /// <param name="model">实体</param> /// <param name="columns">更新列(默认为null)</param> /// <param name="ignoreColumn">忽略列(默认为null)</param> /// <param name="where">更新条件(默认为null)</param> /// <returns>更新的数量</returns> Task<int> Update(TEntity model, List<string> columns = null, List<string> ignoreColumn = null, string where = null); /// <summary> /// 查询所有 /// </summary> /// <returns>所有实体</returns> Task<IEnumerable<TEntity>> Query(); /// <summary> /// 根据条件查询 /// </summary> /// <param name="where">查询条件</param> /// <returns>符合条件的结果集</returns> Task<IEnumerable<TEntity>> Query(string where); /// <summary> /// 根据条件查询 /// </summary> /// <param name="whereExpression">条件表达式</param> /// <returns>符合条件的结果集</returns> Task<IEnumerable<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression); /// <summary> /// 根据条件查询并排序 /// </summary> /// <param name="whereExpression">条件表达式</param> /// <param name="orderFields">排序字段(多个字段间用“,”进行分隔(英文字符))</param> /// <returns>符合条件的排序结果集</returns> Task<IEnumerable<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, string orderFields); /// <summary> /// 根据条件和排序规则查询 /// </summary> /// <param name="whereExpression">查询条件</param> /// <param name="orderExpression">排序规则</param> /// <param name="isAsc">是否升序(默认升序)</param> /// <returns>符合条件的排序结果集</returns> Task<IEnumerable<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderExpression, bool isAsc = true); /// <summary> /// 根据条件查询,并按指定字段排序 /// </summary> /// <param name="where">查询条件</param> /// <param name="orderFields">排序字段(多个字段间用“,”进行分隔(英文字符))</param> /// <returns>符合条件的排序结果集</returns> Task<IEnumerable<TEntity>> Query(string where, string orderFields); /// <summary> /// 根据条件查询,并根据指定字段排序后取指定数量结果集 /// </summary> /// <param name="whereExpression">查询条件</param> /// <param name="top">指定查询数量</param> /// <param name="orderFields">排序字段(多个字段间用“,”进行分隔(英文字符))</param> /// <returns>符合条件的指定数量排序结果集</returns> Task<IEnumerable<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int top, string orderFields); /// <summary> /// 根据条件查询,并根据指定字段排序后取指定数量结果集 /// </summary> /// <param name="where">查询条件</param> /// <param name="top">指定查询数量</param> /// <param name="orderFields">排序字段(多个字段间用“,”进行分隔(英文字符))</param> /// <returns>符合条件的指定数量排序结果集</returns> Task<IEnumerable<TEntity>> Query(string where, int top, string orderFields); /// <summary> /// 根据Sql语句进行查询 /// </summary> /// <param name="sql">sql语句</param> /// <param name="parameters">参数</param> /// <returns>查询结果集</returns> Task<IEnumerable<TEntity>> QuerySql(string sql, SugarParameter[] parameters = null); /// <summary> /// 根据Sql语句查询DataTable结果集 /// </summary> /// <param name="sql">Sql语句</param> /// <param name="parameters">参数</param> /// <returns>DataTable结果集</returns> Task<DataTable> QueryTable(string sql, SugarParameter[] parameters = null); /// <summary> /// 根据条件查询,并按指定字段排序后取分页结果集 /// </summary> /// <param name="whereExpression">查询条件</param> /// <param name="pageIndex">分页页码索引</param> /// <param name="pageSize">页面数据数量</param> /// <param name="orderFields">排序字段</param> /// <returns>符合条件按指定字段排序的分页结果集</returns> Task<IEnumerable<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int pageIndex, int pageSize, string orderFields); /// <summary> /// 根据条件查询,并按指定字段排序后取分页结果集 /// </summary> /// <param name="where">查询条件</param> /// <param name="pageIndex">分页页码索引</param> /// <param name="pageSize">页面数据数量</param> /// <param name="orderFields">排序字段(多个字段间用“,”进行分隔(英文字符))</param> /// <returns>符合条件按指定字段排序的分页结果集</returns> Task<IEnumerable<TEntity>> Query(string where, int pageIndex, int pageSize, string orderFields); /// <summary> /// 根据条件查询,并按指定字段排序后取分页结果集 /// </summary> /// <param name="whereExpression">查询条件</param> /// <param name="pageIndex">分页页码索引(默认为0)</param> /// <param name="pageSize">页面数据数量(默认为20)</param> /// <param name="orderFields">排序字段(多个字段间用“,”进行分隔(英文字符))(默认为null)</param> /// <returns>符合条件按指定字段排序的分页结果集</returns> Task<PageModel<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, int pageIndex = 0, int pageSize = 20, string orderFields = null); /// <summary> /// 多表查询 /// </summary> /// <param name="joinExpression">连接表达式</param> /// <param name="selectExpression">选择表达式</param> /// <param name="whereExpression">条件表达式</param> /// <typeparam name="T1">泛型类型</typeparam> /// <typeparam name="T2">泛型类型</typeparam> /// <typeparam name="T3">泛型类型</typeparam> /// <typeparam name="TResult">泛型类型</typeparam> /// <returns>多表查询结果集</returns> Task<IEnumerable<TResult>> QueryMuch<T1, T2, T3, TResult>(Expression<Func<T1, T2, T3, object[]>> joinExpression, Expression<Func<T1, T2, T3, TResult>> selectExpression, Expression<Func<T1, T2, T3, bool>> whereExpression) where T1 : class, new(); } }
e37e7080e2ae2e6e7c6ab4d32b0301be5de4d758
C#
nagyist/WinDesktop-FlashAir-SnowyImageCopy
/Source/SnowyImageCopy.Lexicon/ResourceService.cs
2.734375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using SnowyImageCopy.Lexicon.Properties; namespace SnowyImageCopy.Lexicon { /// <summary> /// Switches this application's language Resources. /// </summary> /// <remarks> /// This logic is based on http://grabacr.net/archives/1647 /// </remarks> public class ResourceService : INotifyPropertyChanged { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); #endregion public static ResourceService Current { get; } = new ResourceService(); private ResourceService() { } /// <summary> /// Resources to be referred for binding /// </summary> public Resources Resources { get; } = new Resources(); /// <summary> /// Supported Culture names /// </summary> private static readonly string[] _supportedCultureNames = { "en", // Resources.resx "ja-JP", // Resources.ja-JP.resx (Only "ja" is not enough to load this resource file) }; /// <summary> /// Supported Cultures /// </summary> public IReadOnlyCollection<CultureInfo> SupportedCultures { get => _supportedCultures ??= _supportedCultureNames .Select(x => { try { return CultureInfo.GetCultureInfo(x); } catch (CultureNotFoundException) { return null; } }) .Where(x => x is not null) .ToArray(); } private CultureInfo[] _supportedCultures; /// <summary> /// Culture name currently used by this application's Resources /// </summary> public string CultureName => Resources.Culture?.Name; /// <summary> /// Changes Culture of this application's Resources by Culture name. /// </summary> /// <param name="cultureName">Culture name</param> public void ChangeCulture(string cultureName) { var culture = SupportedCultures.SingleOrDefault(x => x.Name == cultureName); // If culture is null, Culture of this application's Resources will be automatically selected. // Since Culture property is static, setting this property will change culture of all instances. Resources.Culture = culture; // Notify this application's Resources is changed. OnPropertyChanged(nameof(Resources)); } } }
63b586eb88bdb9e08f0921c79c2d8ec876043fb0
C#
Optis-World/ATF
/Framework/Atf.Gui.WinForms/Controls/Adaptable/Graphs/KeyboardIOGraphNavigator.cs
2.5625
3
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Linq; using Sce.Atf.Applications; namespace Sce.Atf.Controls.Adaptable.Graphs { /// <summary> /// Allows for navigating an "input-output" graph using the arrow keys. This kind of /// graph has inputs on only one side of a node and outputs on another side.</summary> /// <typeparam name="TNode">Node type, must implement IGraphNode</typeparam> /// <typeparam name="TEdge">Edge type, must implement IGraphEdge</typeparam> /// <typeparam name="TEdgeRoute">Edge route type, must implement IEdgeRoute</typeparam> /// <remarks>Requires that the adaptable control's context be adaptable to ISelectionContext /// and IGraph. Optionally, this context should be adaptable to IViewingContext. /// Requires that the adaptable control can be adapted to IPickingAdapter2. /// See also KeyboardGraphNavigator.</remarks> public class KeyboardIOGraphNavigator<TNode, TEdge, TEdgeRoute> : ControlAdapter where TNode : class, IGraphNode where TEdge : class, IGraphEdge<TNode, TEdgeRoute> where TEdgeRoute : class, IEdgeRoute { /// <summary> /// Returns whether the given key should navigate to input nodes. By default, the input nodes /// are assumed to connect on the left side of the current node, and outputs are assumed to /// connect on the right side.</summary> /// <param name="key">Key press, without any modifiers</param> /// <returns>Whether the given key should navigate to input nodes</returns> protected virtual bool IsInputNavigationKey(Keys key) { return key == Keys.Left; } /// <summary> /// Returns whether the given key should navigate to output nodes. By default, the input nodes /// are assumed to connect on the left side of the current node, and outputs are assumed to /// connect on the right side.</summary> /// <param name="key">Key press, without any modifiers</param> /// <returns>Whether the given key should navigate to output nodes</returns> protected virtual bool IsOutputNavigationKey(Keys key) { return key == Keys.Right; } /// <summary> /// Returns whether the given key should navigate to other nodes</summary> /// <param name="key">Key press, without any modifiers</param> /// <returns>Whether the given key should navigate to other nodes</returns> protected virtual bool IsNavigationKey(Keys key) { return key == Keys.Up || key == Keys.Right || key == Keys.Down || key == Keys.Left; } /// <summary> /// Returns whether or not these two keys represent opposite directions, for purposes of /// knowing if Shift+selection should be undone. The keys do not have modifiers (Shift, /// Control, or Alt).</summary> /// <param name="a">First key</param> /// <param name="b">Second key</param> /// <returns>True iff two keys represent opposite directions</returns> protected virtual bool OppositeNavigationKeys(Keys a, Keys b) { return (IsOutputNavigationKey(a) && IsInputNavigationKey(b)) || (IsInputNavigationKey(a) && IsOutputNavigationKey(b)) || (a == Keys.Up && b == Keys.Down) || (a == Keys.Down && b == Keys.Up); } /// <summary> /// Binds the adapter to the adaptable control; called in the order that the adapters /// were defined on the control</summary> /// <param name="control">Adaptable control</param> protected override void Bind(AdaptableControl control) { base.Bind(control); control.ContextChanged += control_ContextChanged; control.PreviewKeyDown += PreviewKeyDown; m_pickingAdapter = control.Cast<IPickingAdapter2>(); m_transformAdapter = control.As<ITransformAdapter>(); //optional } /// <summary> /// Unbinds the adapter from the adaptable control</summary> /// <param name="control">Adaptable control</param> protected override void Unbind(AdaptableControl control) { control.ContextChanged -= control_ContextChanged; control.PreviewKeyDown -= PreviewKeyDown; m_pickingAdapter = null; m_transformAdapter = null; m_shiftKeySelectionStack.Clear(); m_lastKeyWithShift = Keys.None; base.Unbind(control); } /// <summary> /// Finds the nearest node to a starting node, in the desired direction</summary> /// <param name="startNode">Node to measure distance from</param> /// <param name="key">Key press (e.g., Keys.Up, Keys.Right, Keys.Down, or Keys.Left), /// without modifier keys</param> /// <param name="modifiers">Modifier keys that were pressed</param> /// <returns>The nearest node or null if there is none in that direction</returns> protected virtual TNode FindNearestNode(TNode startNode, Keys key, Keys modifiers) { TNode nearest = null; int bestDist = int.MaxValue; Rectangle startRect = m_pickingAdapter.GetBounds(new[] { startNode }); foreach (TNode node in m_graph.Nodes) { if (node != startNode) { Rectangle targetRect = m_pickingAdapter.GetBounds(new[] { node }); int dist = WinFormsUtil.CalculateDistance(startRect, key, targetRect); if (dist < bestDist) { bestDist = dist; nearest = node; } } } return nearest; } /// <summary> /// Finds the connected nodes to a starting node, given the key press. Only searches for /// nodes connected to starting node via an edge.</summary> /// <param name="startNode">Starting node</param> /// <param name="key">Key press (e.g., Keys.Up, Keys.Right, Keys.Down, or Keys.Left), /// without modifier keys</param> /// <param name="modifiers">Modifier keys that were pressed</param> /// <returns>Connected nodes to starting node</returns> protected virtual IEnumerable<TNode> FindConnectedNodes(TNode startNode, Keys key, Keys modifiers) { if (IsOutputNavigationKey(key)) { foreach (TNode outNode in m_graph.GetOutputNodes(startNode)) yield return outNode; } else if (IsInputNavigationKey(key)) { foreach (TNode inNode in m_graph.GetInputNodes(startNode)) yield return inNode; } } /// <summary> /// Handles the PreviewKeyDown event on AdaptedControl, and changes the selection /// if the user navigates using the keyboard</summary> /// <param name="sender">Sender</param> /// <param name="e">Event args</param> protected virtual void PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { Keys keyData = e.KeyData; Keys modifiers = keyData & Keys.Modifiers; keyData &= ~Keys.Modifiers; if (IsNavigationKey(keyData)) { List<TNode> oldSelection; // If the user is reversing direction of a past shift+selection, and they didn't // overshoot the beginning (i.e., the stack isn't empty), then don't search for // nodes and instead restore a past selection. if (modifiers == Keys.Shift && OppositeNavigationKeys(m_lastKeyWithShift, keyData) && m_shiftKeySelectionStack.Count > 0) { oldSelection = m_shiftKeySelectionStack.Pop(); ChangeSelection(oldSelection); return; } // We need to know the current selection now. oldSelection = new List<TNode>(m_selectionContext.SelectionCount); oldSelection.AddRange(m_selectionContext.GetSelection<TNode>()); // If the user is doing a shift+selection, then push the current selection on to the // stack. But if the user chose a new direction, clear the stack first. bool pushOldSelectionIfSelectionChanges = false; if (modifiers == Keys.Shift) { if (m_lastKeyWithShift != Keys.None && m_lastKeyWithShift != keyData) { m_lastKeyWithShift = Keys.None; m_shiftKeySelectionStack.Clear(); } pushOldSelectionIfSelectionChanges = true; } else { m_lastKeyWithShift = Keys.None; m_shiftKeySelectionStack.Clear(); } // Do a search from the existing selected nodes, looking only along wires. var connectedNodes = new HashSet<TNode>(); foreach (TNode startElement in m_selectionContext.GetSelection<TNode>()) { foreach (TNode connectedNode in FindConnectedNodes(startElement, keyData, modifiers)) connectedNodes.Add(connectedNode); } // If no connected nodes were found, then look for the nearest nodes. if (connectedNodes.Count == 0) { foreach (TNode startElement in m_selectionContext.GetSelection<TNode>()) { TNode nearestNode = FindNearestNode(startElement, keyData, modifiers); if (nearestNode != null) connectedNodes.Add(nearestNode); } } // If we have new connected nodes then change the selection. if (connectedNodes.Count > 0) { // With this keyboard navigation, the Control key doesn't seem to make sense // for toggling nodes in the selection. modifiers &= ~Keys.Control; var newSelection = new HashSet<TNode>(oldSelection); KeysUtil.Select(newSelection, connectedNodes, modifiers); if (!newSelection.SetEquals(oldSelection)) { ChangeSelection(newSelection); if (pushOldSelectionIfSelectionChanges) { m_lastKeyWithShift = keyData; m_shiftKeySelectionStack.Push(new List<TNode>(oldSelection)); } // Attempt to pan, to make sure the newly selected nodes are visible if (m_transformAdapter != null) { Rectangle boundingRect = m_pickingAdapter.GetBounds(newSelection.OfType<object>()); m_transformAdapter.PanToRect(boundingRect); } } } } } private void ChangeSelection(IEnumerable<TNode> selection) { try { m_changingSelection = true; m_selectionContext.Selection = selection.Cast<object>(); } finally { m_changingSelection = false; } } private void control_ContextChanged(object sender, EventArgs e) { if (m_selectionContext != null) m_selectionContext.SelectionChanged -= m_selectionContext_SelectionChanged; // mandatory m_selectionContext = AdaptedControl.ContextCast<ISelectionContext>(); m_selectionContext.SelectionChanged += m_selectionContext_SelectionChanged; m_graph = AdaptedControl.ContextCast<IGraph<TNode, TEdge, TEdgeRoute>>(); } private void m_selectionContext_SelectionChanged(object sender, EventArgs args) { if (!m_changingSelection) { m_shiftKeySelectionStack.Clear(); m_lastKeyWithShift = Keys.None; } } private ISelectionContext m_selectionContext; //mandatory private IGraph<TNode, TEdge, TEdgeRoute> m_graph; //mandatory private IPickingAdapter2 m_pickingAdapter; //mandatory private ITransformAdapter m_transformAdapter; //optional // To remember how to unwind the selection as the user is holding the shift key // and using the input and output navigation keys (e.g., left and right arrow keys). private Stack<List<TNode>> m_shiftKeySelectionStack = new Stack<List<TNode>>(); private Keys m_lastKeyWithShift = Keys.None; private bool m_changingSelection; } }
7373656f48b93a0f4ae24c0ce655579bb5ace56d
C#
MartinLenaerts/school-ISF-project
/Models/Client.cs
2.75
3
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text.Json.Serialization; namespace Bank.Models { [Table("Client")] public class Client { private int _tries; public Client() { CurrencyClients = new HashSet<CurrencyClient>(); } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key] public int Guid { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public int Pin { get; set; } public bool Blocked { get; set; } public int Tries { get => _tries; set { if (Tries >= 3) Blocked = true; _tries = value; } } [JsonIgnore] public virtual ICollection<CurrencyClient> CurrencyClients { get; set; } public override string ToString() { var currencies = "\n"; foreach (var currencyClient in CurrencyClients) currencies += " - " + currencyClient + " \n"; currencies = currencies == "\n" ? " no currency \n" : currencies; return "Client n°" + Guid + " \n" + " Firstname : " + Firstname + " \n" + " LastName : " + Lastname + " \n" + " isBlocked : " + Blocked + " \n" + " Tries : " + Tries + "\n" + " Currencies : " + currencies; } public void Merge(Client c) { Firstname = c.Firstname == null ? Firstname : c.Firstname; Lastname = c.Lastname == null ? Lastname : c.Lastname; Pin = c.Pin == 0 ? Pin : c.Pin; Blocked = c.Blocked; Tries = c.Tries; CurrencyClients = c.CurrencyClients.Count == 0 ? CurrencyClients : c.CurrencyClients; } public override bool Equals(object obj) { if (obj == null || !(obj is Client)) return false; return Guid == ((Client) obj).Guid; } public override int GetHashCode() { return base.GetHashCode(); } public void unBlockedAndReset() { Blocked = false; Tries = 0; } } }
6211c431f9ff7e01741f419f1c53921f1d8a30dd
C#
sharpshooter1099/SimpliSafeMonitorService
/SimpliSafeMonitorService/Configurer.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpliSafeMonitorService { //this code was written by Alex Wardlaw, the best programmer in the world. copyright 2015. public class Configurer { #region Fields private string fileName; internal bool changes; //internal string[] allLines; internal Dictionary<string, string[]> fields; public Dictionary<string, string[]> activeFields { get { return fields; } } #endregion Fields #region Public public Configurer(string appName) { fields = new Dictionary<string, string[]>(); string[] allLines; if (appName.ToLower().Contains(@".conf")) fileName = appName; else fileName = string.Format(@"{0}.conf", appName); allLines = System.IO.File.ReadAllLines(fileName); char[] lineDelimiters = { '=' }; char[] valueDelimiters = { ',' }; foreach (string line in allLines) { if (line.Length > 0 && line[0] != '#') { string[] split1 = line.Split(lineDelimiters, StringSplitOptions.RemoveEmptyEntries); string key = split1[0]; string[] split2 = split1[1].Split(valueDelimiters, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < split2.Length; i++) split2[i] = split2[i].Trim(); fields.Add(key.Trim(), split2); } } changes = false; } public string[] RequestValues(string field) { if (fields.ContainsKey(field)) return fields[field]; else return null; } public void UpdateValues(string field, string[] values) { if (fields.ContainsKey(field)) fields[field] = values; else fields.Add(field, values); changes = true; } //destructor- if changes were made write file ~Configurer() { if (changes) { string[] fileContents = System.IO.File.ReadAllLines(fileName); List<string> allLines = new List<string>(); char[] lineDelimiters = { '=' }; for (int i = 0; i < fileContents.Length; i++) { string line = fileContents[i]; if (line.Length > 0 && line[0] != '#') { string tmp = line.Replace(" ", ""); string[] split1 = tmp.Split(lineDelimiters, StringSplitOptions.RemoveEmptyEntries); string key = split1[0]; if (fields.ContainsKey(key)) line = string.Format(@"{0}={1}", key, String.Join(",", fields[key])); } allLines.Add(line); } System.IO.File.WriteAllLines(fileName, allLines); } } #endregion Public #region Private #endregion Private #region Internal #endregion Internal } }
885fe5a0aa9382011a603c66f5319dd5b8ecefe4
C#
SingleAccretion/Accretion.JitDumpVisualizer
/Source/Accretion.JitDumpVisualizer.Parsing/Tokens/Lexing/Lexer.DetalizationState.cs
2.5625
3
using Accretion.JitDumpVisualizer.Parsing.Auxiliaries; using System.Runtime.CompilerServices; namespace Accretion.JitDumpVisualizer.Parsing.Tokens.Lexing { internal static unsafe partial class Lexer { public static DetalizationState ParseStatementDetalizationState(char* start, out int width) { Assert.True(Unsafe.SizeOf<DetalizationState>() is 4); if (start[1] is 'a') { Assert.Equal(start, "(after)"); width = "(after)".Length; return DetalizationState.After; } else { Assert.Equal(start, "(before)"); width = "(before)".Length; return DetalizationState.Before; } } } }
f93dac4c16bbed22637a6fb3ae33afcb8e109519
C#
shendongnian/download4
/code7/1335879-36048030-113410257-2.cs
3.140625
3
using System; using System.Collections.Generic; using System.Net; using System.IO; namespace SExperiment { class MainClass { public static void Main(string[] args) { try{ string webAddr="http://gurujsonrpc.appspot.com/guru"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{ \"method\" : \"guru.test\", \"params\" : [ \"Guru\" ], \"id\" : 123 }"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var responseText = streamReader.ReadToEnd(); Console.WriteLine(responseText); //Now you have your response. //or false depending on information in the response } }catch(WebException ex){ Console.WriteLine(ex.Message); } } } }
59822482959ad45a4006a67d27f8a725687cac1a
C#
danvasem/bitacoraRP3
/Rp3.Test.Data/DAL/Repositories/TransactionRepository.cs
2.671875
3
using Rp3.Test.Data.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rp3.Test.Data.Repositories { public class TransactionRepository : Repository<Transaction> { public TransactionRepository(DbContext context) : base(context) { } /* Ejemplo consultar datos a partir de un procedimiento almacenado public List<> GetBalance(int accountId, DateTime dateStart, DateTime dateEnd) { return this.DataBase.SqlQuery< > ("EXEC dbo.spGetBalance @AccountId = {0}, @DateStart = {1}, @DateEnd = {2}", accountId, dateStart, dateEnd).ToList(); } */ } }
b2e634e26441ed36ae909c54c98a09a2d3d169cc
C#
viper3400/MovieSearchEngine
/OfdbParser/XPathRequest.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HtmlAgilityPack; using System.IO; using System.Xml; //using System.Xml.XPath; namespace OfdbParser { public class XPathRequest { XmlDocument xDoc; public List<string> GetXPathValues(string XPath) { var result = XPathHelper.GetXPathValue(xDoc, XPath); return result; } public XPathRequest(string url) { HtmlWeb htmlWeb = new HtmlWeb(); MemoryStream memoryStream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, null); htmlWeb.LoadHtmlAsXml(url, xmlTextWriter); // rewind the memory stream memoryStream.Position = 0; // create, fill, and return the xml document XmlDocument xmlDoc = new XmlDocument(); string xmlDocContent = (new StreamReader(memoryStream)).ReadToEnd(); xmlDoc.LoadXml(xmlDocContent); xDoc = xmlDoc; } } }
695605faf9e2eaffd96bfcda6a0201858f02af07
C#
dreipoe/hse-cs
/HelloWorld/Lab3.cs
3.546875
4
using static System.Console; using static System.Math; namespace HelloWorld { class Lab3 { // TODO: Что-то здесь не так public static void Run() { WriteLine("Циклическое вычисление:"); double a = PI / 5; double b = 9 * a; double step = (b - a) / 10; for (double x = a; x <= b; x += step) { //инициализируем переменные сразу первым членом double sn = Cos(x), se = sn, pre = se; int n; for (n = 2; n <= 40; n++) sn += Cos(n * x) / n; n = 2; double r; do { se += Cos(n * x) / n; r = Abs(se - pre); pre = se; n++; } while (r > 0.0001); double y = -Log( Abs( 2 * Sin(x / 2) ) ); WriteLine($"X = {x:f7} \t SN = {sn:f7} \t SE = {se:f7} \t Y = {y:f7}"); } } } }
521c971c42ec1eb4057f51746505afd439a29bf3
C#
JerryAllMighty/ConsoleApp0916
/ConsoleApp0916/ForInheritance.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp0916 { class ForInheritance //형 변환을 담당하는 클래스 { public virtual int CheckErr(string str) { int number; bool bFlag = int.TryParse(str, out number); if (bFlag) { return number; } else { Console.WriteLine("Error! 숫자로 입력해달라능!!"); return 0; } } } }
67e1940394f7411c0a7be6991857e29fa21c6faa
C#
PlumpMath/DesignPatterns-257
/DesignPatterns/BridgePattern/StandardFormatter.cs
2.875
3
namespace DesignPatterns.BridgePattern { class StandardFormatter : ICustomFormatter { public string Format(string key, string value) { return $"{key} : {value}"; } } }
988d2223eb43acc3c2873e3cc0f342668a481e6a
C#
FireBall1725/Razor.Framework
/Backup/Razor/Networking/Http/HttpContentEncodings.cs
2.53125
3
using System; namespace Razor.Networking.Http { /// <summary> /// Summary description for HttpContentEncodings. /// </summary> public class HttpContentEncodings { /// <summary> /// An encoding format produced by the file compression program gzip (GNU zip) as described in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC. /// </summary> public const string GZip = @"gzip"; /// <summary> /// The encoding format produced by the common UNIX file compression program compress. This format is an adaptive Lempel-Ziv-Welch coding (LZW). Use of program names for the identification of encoding formats is not desirable and is discouraged for future encodings. Their use here is representative of historical practice, not good design. For compatibility with previous implementations of HTTP, applications SHOULD consider x-gzip and x-compress to be equivalent to gzip and compress respectively. /// </summary> public const string Compress = @"compress"; /// <summary> /// The zlib format defined in RFC 1950 [31] in combination with the deflate compression mechanism described in RFC 1951 [29]. /// </summary> public const string Deflate = @"deflate"; /// <summary> /// The default (identity) encoding; the use of no transformation whatsoever. This content-coding is used only in the Accept-Encoding header, and SHOULD NOT be used in the Content-Encoding header. /// </summary> public const string Identity = @"identity"; } }
d93e4ce2e2e2620f587cbb22244bebb2a69f5220
C#
nelson9/repositorypattern
/ConsoleApplication/Program.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Data; using Data.SchoolDb; using Model; using Ninject; namespace ConsoleApplication { class Program { public static void Main(string[] args) { // Add student and a new Classroom using (var unitOfWork = new UnitOfWork(new SchoolContext())) { Student student = new Student { Classroom = new Classroom { Name = "1A" }, DateOfBirth = DateTime.Now, Name = "Dave" }; unitOfWork.Students.Add(student); unitOfWork.SaveChanges(); } // ADD 3 Teachers using (var unitOfWork = new UnitOfWork(new SchoolContext())) { List<Teacher> teachers = new List<Teacher>(); teachers.Add(new Teacher() { Name = "Teacher1" }); teachers.Add(new Teacher() { Name = "Teacher2" }); teachers.Add(new Teacher() { Name = "Teacher3" }); unitOfWork.Teachers.AddRange(teachers); unitOfWork.SaveChanges(); } //// UPDATE Classroom adding Teachers /// THIS METHOD NEEDS TO BE IMPLEMENTED SPECIFICALLY IN THE CLASSROOM REPOSITORY //using (var unitOfWork = new UnitOfWork(new SchoolContext())) //{ // Classroom updatedClassroom = new Classroom // { // Id = 1, // Teachers = new List<Teacher> // { // new Teacher {Id = 3}, // new Teacher {Id = 1} // } // }; //} // Add Classroom with existing teachers. // Check implementation of ClassroomsRepository.AddWithExistingTeachers using (var unitOfWork = new UnitOfWork(new SchoolContext())) { unitOfWork.Classrooms.AddWithExistingTeachers(new Classroom { Name = "Classroom with existing teachers3", Teachers = new List<Teacher> { new Teacher { Id = 2 }, new Teacher { Id = 3 } } }); unitOfWork.SaveChanges(); } // Add Student with existing classroom using (var unitOfWork = new UnitOfWork(new SchoolContext())) { unitOfWork.Students.AddWithExistingClassroom(new Student { Name = "Fab", ClassId = 1}); unitOfWork.SaveChanges(); } } } }
3a064cd8dc9a377258bfe03ac29dd065c7c4be9f
C#
fullphat/TheSauceStation
/0.8/app/IngredientSetter.cs
2.6875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Diagnostics; using System.Windows.Forms; using SauceStation; namespace TheSauceStation { // lookup - search field // dynamic_list - similar to lookup but needs no input public partial class IngredientSetter : Form { private RecipeIngredient _theIngredient; private Recipe _theRecipe; public delegate void IngredientChangedHandler(RecipeIngredient ingredient); public event IngredientChangedHandler OnIngredientChanged; public IngredientSetter(RecipeIngredient ingredient, Recipe recipe) { InitializeComponent(); _theIngredient = ingredient; _theRecipe = recipe; } private void IngredientSetter_Load(object sender, EventArgs e) { this.Text = "Set Ingredient Value..."; lblHint.Text = "Enter the value for ingredient {" + _theIngredient.Ingredient.Name + "}"; label1.Text = (_theIngredient.Ingredient.Hint != "" ? "" + _theIngredient.Ingredient.Hint.TrimEnd('.') + "." : ""); //(_theIngredient.Ingredient.IsRequired ? "Required" : "Optional") + //tbHint.ForeColor = (_theIngredient.Ingredient.IsRequired ? Color.OrangeRed : Color.SteelBlue); tbRIValue.Text = _theIngredient.Value; cbLookup.Items.Clear(); // set controls bnLookup.Visible = false; cbLookup.Visible = false; cbLookup.Width = 310; cbValue.Visible = false; switch (_theIngredient.Ingredient.Type) { case Ingredient.IngredientType.SwitchIngredient: cbValue.Text = _theIngredient.Ingredient.Name; cbValue.Visible = true; break; case Ingredient.IngredientType.LookupIngredient: bnLookup.Visible = true; cbLookup.Visible = true; break; case Ingredient.IngredientType.ListIngredient: cbLookup.Width = tbRIValue.Width; cbLookup.Visible = true; foreach (KeyValuePair<string, string> kvp in _theIngredient.Ingredient.Contents) { cbLookup.Items.Add(new SimpleItem(kvp.Key, kvp.Value)); } break; case Ingredient.IngredientType.DynamicListIngredient: cbLookup.Width = tbRIValue.Width; cbLookup.Visible = true; bnLookup_Click(this, new EventArgs()); break; } } private void bnSetValue_Click(object sender, EventArgs e) { switch (_theIngredient.Ingredient.Type) { case Ingredient.IngredientType.SwitchIngredient: _theIngredient.Value = (cbValue.Checked ? "1" : "0"); break; case Ingredient.IngredientType.DynamicListIngredient: case Ingredient.IngredientType.ListIngredient: case Ingredient.IngredientType.LookupIngredient: SimpleItem si = (SimpleItem)cbLookup.SelectedItem; if (si != null) { _theIngredient.Value = si.Key; _theIngredient.Friendly = si.Text; } else { MessageBox.Show("This ingredient requires you to pick a value from the list of results displayed.", "Ingredient Mismatch Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } break; case Ingredient.IngredientType.StringArrayIngredient: case Ingredient.IngredientType.StringIngredient: _theIngredient.Value = tbRIValue.Text; break; } OnIngredientChanged(_theIngredient); this.Close(); } private void bnLookup_Click(object sender, EventArgs e) { //lastLookupText = cbLookup.Text; cbLookup.Items.Clear(); Results results = _theRecipe.Sauce.Translate((Sauce)_theRecipe.Trigger, _theIngredient.Ingredient, cbLookup.Text); if (results.Items.Count > 0) { foreach (SimpleItem item in results.Items) { cbLookup.Items.Add(item); } cbLookup.Text = "[" + results.Items.Count + " found]"; } else { cbLookup.Text = "[No results]"; } } } }
33a6ba14eee78bbd5dd5a22ecad3cfc2919df600
C#
tanneryea/cs
/Program-6.cs
3.34375
3
using System; using static System.Console; namespace CH8HW { class Program { static void Main(string[] args) { double[,] waterDepth = new double[6, 5]; //Initialized as 6/5 to have extra space for averages string[] location = {"Surf City", "Solomons", "Hilton Head", "Miami", "Savannah"}; string[] recordingTime = { "0700 (7am)", "1200 (noon)", "1700 (5pm)", "2100 (9pm)" }; InitializeArray(waterDepth); GetWaterDepths(waterDepth, location, recordingTime); FindAvgDepthByLocation(waterDepth); FindAvgDepthByTime(waterDepth); DisplayTable(waterDepth, location, recordingTime); ReadKey(); } public static void InitializeArray(double[,] depth) //Initializes empty array { Array.Clear(depth, 0, depth.Length); } public static void GetWaterDepths(double[,] waterDepth, string[] location, string[] recording) { int locationNum, recordingTime; string inputValue; bool moreData = true; while (moreData) { locationNum = GetLocationNumber(location); recordingTime = GetRecTimeNum(recording); waterDepth[locationNum, recordingTime] = GetWaterDepths(); Write("\n\nIs there more depths to record? (y/n)"); inputValue = ReadLine(); switch (inputValue) //Loop to enter more data if needed { case "n": case "N": moreData = false; break; default: moreData = true; break; } } } public static int GetLocationNumber(string[] location) //Displays locations and allows selection of one { int locationNum = -1; Console.WriteLine("Available Locations:"); for (int i=0; i < location.Length; i++) { Console.WriteLine((i + 1) + ". " + location[i]); } Console.Write("Enter Location Number:"); locationNum = Convert.ToInt32(Console.ReadLine()); return locationNum; } public static int GetRecTimeNum(string[] recording) //Display recording times and allows selection of one { int recordingTime = -1; Console.WriteLine("Applicable Recording Times:"); for (int i = 0; i < recording.Length; i++) { Console.WriteLine((i + 1) + ". " + recording[i]); } Console.Write("Enter Recording Time:"); recordingTime = Convert.ToInt32(Console.ReadLine()); return recordingTime; } public static double GetWaterDepths() //Sets water depth and returns to array { double depth = 0.0; Console.Write("Enter depth of water:"); depth = Convert.ToDouble(Console.ReadLine()); return depth; } public static void DisplayTable(double[,] waterDepth, string[] location, string[] recording) //Displays table with total data { Console.WriteLine("Location\tAverage Depth"); for (int i = 1; i < waterDepth.GetLength(0); i++) { Console.WriteLine(i + ". " + location[i - 1] + "\t" + waterDepth[i, 0]); } Console.WriteLine("Recording Time\tAverage Depth"); for (int i = 1; i < waterDepth.GetLength(1); i++) { Console.WriteLine(i + ". " + recording[i - 1] + "\t" + waterDepth[0, i]); } } public static void FindAvgDepthByLocation(double[,] waterDepth) //Averages depth by location { int countOfActualData = 0; double total = 0; for (int row = 1; row < waterDepth.GetLength(0); row++) { for (int col = 1; col < waterDepth.GetLength(1); col++) { if (waterDepth[row, col] > 0) { total += waterDepth[row, col]; countOfActualData++; } } if (countOfActualData != 0) //Assigns average to 0 index of column { waterDepth[row, 0] = total / countOfActualData; total = 0; countOfActualData = 0; } else waterDepth[row, 0] = 0; } } public static void FindAvgDepthByTime(double[,] waterDepth) //Averages depth by time { int countOfActualData = 0; double total = 0; for (int col = 1; col < waterDepth.GetLength(1); col++) { for (int row = 1; row < waterDepth.GetLength(0); row++) { if (waterDepth[row, col] > 0) { total += waterDepth[row, col]; countOfActualData++; } } if (countOfActualData != 0) { waterDepth[0, col] = total / countOfActualData; total = 0; countOfActualData = 0; } else waterDepth[0, col] = 0; } } } }
9ec9563d1a9087d9a181c2e61ebfeab6e93a5fdc
C#
Whiteknight/CSPath
/CSPath/Predicates/AllAtLeastOneArityComparer.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; namespace CSPath.Predicates { public class AllAtLeastOneArityComparer : IArityComparer { public bool IsMatch(IReadOnlyList<object> values, Func<object, bool> predicate) => values.Count >= 1 && values.All(predicate); } }
201bf9329de192cb73f151ad49ab490022801b2b
C#
AJEETX/Smart.Chat.Bot
/Dialogs/MainDialog.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Dialogs.Adaptive.Recognizers; using Microsoft.Bot.Schema; using Microsoft.Extensions.Logging; using Microsoft.Recognizers.Text.DataTypes.TimexExpression; namespace Microsoft.BotBuilderSamples.Dialogs { public class MainDialog : ComponentDialog { protected readonly ILogger Logger; public MainDialog(BookingDialog bookingDialog, ILogger<MainDialog> logger) : base(nameof(MainDialog)) { Logger = logger; AddDialog(new TextPrompt(nameof(TextPrompt))); AddDialog(bookingDialog); AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[] { IntroStepAsync, ActStepAsync, FinalStepAsync, })); InitialDialogId = nameof(WaterfallDialog); } private async Task<DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Use the text provided in FinalStepAsync or the default if it is the first time. var weekLaterDate = DateTime.Now.AddDays(7).ToString("MMMM d, yyyy"); var messageText = stepContext.Options?.ToString() ?? $"What can I help you with today?\nSay something like \"Book a flight from Paris to Berlin on {weekLaterDate}\""; var promptMessage = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput); return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = promptMessage }, cancellationToken); } private async Task<DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var activity = stepContext.Context.Activity; var recognizer = new RegexRecognizer { Intents = new List<IntentPattern> { new IntentPattern("BookFlight","(?i)book"), new IntentPattern("GetWeather","(?i)weather"), new IntentPattern("help","(?i)help") } }; // Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.) var recognizerResult = await recognizer.RecognizeAsync(stepContext, activity, cancellationToken); var intent = recognizerResult.Intents.FirstOrDefault(i => i.Key.ToLowerInvariant().Contains(activity.Text.Trim().ToLowerInvariant())); switch (intent.Key) { case "BookFlight": // Run the BookingDialog giving it whatever details we have from the LUIS call, it will fill out the remainder. return await stepContext.BeginDialogAsync(nameof(BookingDialog), new BookingDetails(), cancellationToken); case "GetWeather": return await stepContext.BeginDialogAsync(nameof(WeatherDialog), new BookingDetails(), cancellationToken); default: // Catch all for unhandled intents var didntUnderstandMessageText = $"Sorry, I didn't get that. Please try asking in a different way (intent was {intent.Key})"; var didntUnderstandMessage = MessageFactory.Text(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput); await stepContext.Context.SendActivityAsync(didntUnderstandMessage, cancellationToken); break; } return await stepContext.NextAsync(null, cancellationToken); } private async Task<DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // If the child dialog ("BookingDialog") was cancelled, the user failed to confirm or if the intent wasn't BookFlight // the Result here will be null. if (stepContext.Result is BookingDetails result) { // Now we have all the booking details call the booking service. // If the call to the booking service was successful tell the user. var timeProperty = new TimexProperty(result.TravelDate); var travelDateMsg = timeProperty.ToNaturalLanguage(DateTime.Now); var messageText = $"I have you booked to {result.Destination} from {result.Origin} on {travelDateMsg}"; var message = MessageFactory.Text(messageText, messageText, InputHints.IgnoringInput); await stepContext.Context.SendActivityAsync(message, cancellationToken); } // Restart the main dialog with a different message the second time around var promptMessage = "What else can I do for you?"; return await stepContext.ReplaceDialogAsync(InitialDialogId, promptMessage, cancellationToken); } } }
3426b6a9226e6d5695436532282890b0d60d7fc2
C#
hj0807/HJ-Project
/Unity_Pattern/Assets/Scripts/Visitor_Pattern/Ex1/Wheel.cs
3.015625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VisitorPattern.ex1 { /// <summary> /// 데이터 클래스 /// Visit에게 자신을 전달. /// </summary> public class Wheel : ICarElement { private string name; public Wheel(string name) { this.name = name; } public string GetName() { return name; } public void Accept(ICarElementVisitor visitor) { visitor.visit(this); } } }
c7fba584e77eacba2c47d5ff5c9f5e4c3b2db40b
C#
Shawdown/MorningPagesApp
/src/DropboxManager.cs
2.65625
3
using System; using System.IO; using System.Net; using System.Net.Http; using System.Runtime.InteropServices; using System.Threading.Tasks; using Dropbox.Api; using Dropbox.Api.Files; namespace MorningPagesApp { public class DropboxManager { private static readonly string API_KEY = "9f7kpp1386tvyuf"; // This loopback host is for demo purpose. If this port is not // available on your machine you need to update this URL with an unused port. private static readonly string LoopbackHost = "http://127.0.0.1:52475/"; // URL to receive OAuth 2 redirect from Dropbox server. // You also need to register this redirect URL on https://www.dropbox.com/developers/apps. private static readonly Uri RedirectUri = new Uri(LoopbackHost + "authorize"); // URL to receive access token from JS. private static readonly Uri JSRedirectUri = new Uri(LoopbackHost + "token"); [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetForegroundWindow(IntPtr hWnd); private bool initialized; private DropboxClient client; private HttpClient httpClient; public async Task<bool> Init() { DropboxCertHelper.InitializeCertPinning(); var accessToken = await GetAccessToken(); if (string.IsNullOrEmpty(accessToken)) { return false; } // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; try { var config = new DropboxClientConfig("MorningPager app") { HttpClient = httpClient }; client = new DropboxClient(accessToken, config); initialized = true; } catch (HttpException e) { Program.log.Info("Exception reported from RPC layer"); Program.log.Info($" Status code: {e.StatusCode}"); Program.log.Info($" Message : {e.Message}"); if (e.RequestUri != null) { Program.log.Info($" Request uri: {e.RequestUri}"); } } return initialized; } /// <summary> /// Uploads given content to a file in Dropbox. /// </summary> /// <param name="client">The Dropbox client.</param> /// <param name="folder">The folder to upload the file.</param> /// <param name="fileName">The name of the file.</param> /// <param name="fileContent">The file content.</param> /// <returns></returns> public async Task Upload(string fileName, string fileContent) { if (!initialized) { return; } using (var stream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(fileContent))) { var response = await client.Files.UploadAsync("/MorningPager/" + fileName, WriteMode.Overwrite.Instance, body: stream); } } /// <summary> /// Downloads a file. /// </summary> /// <remarks>This demonstrates calling a download style api in the Files namespace.</remarks> /// <param name="client">The Dropbox client.</param> /// <param name="folder">The folder path in which the file should be found.</param> /// <param name="file">The file to download within <paramref name="folder"/>.</param> /// <returns></returns> public async Task<string> Download (string fileName) { Console.WriteLine("Download file..."); using (var response = await client.Files.DownloadAsync("/MorningPager/" + fileName)) { Console.WriteLine("Downloaded {0} Rev {1}", response.Response.Name, response.Response.Rev); Console.WriteLine("------------------------------"); Console.WriteLine(await response.GetContentAsStringAsync()); Console.WriteLine("------------------------------"); return await response.GetContentAsStringAsync(); } } /// <summary> /// Gets the dropbox access token. /// <para> /// This fetches the access token from the applications settings, if it is not found there /// (or if the user chooses to reset the settings) then the UI in <see cref="LoginForm"/> is /// displayed to authorize the user. /// </para> /// </summary> /// <returns>A valid access token or null.</returns> private async Task<string> GetAccessToken() { var accessToken = ConfigManager.ReadSetting(ConfigKeys.DROPBOX_ACCESS_TOKEN); if (string.IsNullOrEmpty(accessToken)) { try { var state = Guid.NewGuid().ToString("N"); var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, API_KEY, RedirectUri, state: state); var http = new HttpListener(); http.Prefixes.Add(LoopbackHost); http.Start(); System.Diagnostics.Process.Start(authorizeUri.ToString()); // Handle OAuth redirect and send URL fragment to local server using JS. await HandleOAuth2Redirect(http); // Handle redirect from JS and process OAuth response. var result = await HandleJSRedirect(http); if (result.State != state) { // The state in the response doesn't match the state in the request. return null; } // Bring console window to the front. //SetForegroundWindow(GetConsoleWindow()); accessToken = result.AccessToken; var uid = result.Uid; Program.log.Info($"Uid: {uid}"); ConfigManager.UpdateSetting(ConfigKeys.DROPBOX_ACCESS_TOKEN, accessToken); ConfigManager.UpdateSetting(ConfigKeys.DROPBOX_UID, uid); } catch (Exception e) { Program.log.Info($"Error: {e.Message}"); return null; } } return accessToken; } /// <summary> /// Handles the redirect from Dropbox server. Because we are using token flow, the local /// http server cannot directly receive the URL fragment. We need to return a HTML page with /// inline JS which can send URL fragment to local server as URL parameter. /// </summary> /// <param name="http">The http listener.</param> /// <returns>The <see cref="Task"/></returns> private async Task HandleOAuth2Redirect(HttpListener http) { var context = await http.GetContextAsync(); // We only care about request to RedirectUri endpoint. while (context.Request.Url.AbsolutePath != RedirectUri.AbsolutePath) { context = await http.GetContextAsync(); } context.Response.ContentType = "text/html"; // Respond with a page which runs JS and sends URL fragment as query string // to TokenRedirectUri. using (var file = File.OpenRead("index.html")) { file.CopyTo(context.Response.OutputStream); } context.Response.OutputStream.Close(); } /// <summary> /// Handle the redirect from JS and process raw redirect URI with fragment to /// complete the authorization flow. /// </summary> /// <param name="http">The http listener.</param> /// <returns>The <see cref="OAuth2Response"/></returns> private async Task<OAuth2Response> HandleJSRedirect(HttpListener http) { var context = await http.GetContextAsync(); // We only care about request to TokenRedirectUri endpoint. while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath) { context = await http.GetContextAsync(); } var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]); var result = DropboxOAuth2Helper.ParseTokenFragment(redirectUri); return result; } } }
005a36d926c9628d42fb2f0f76d92daefae54f94
C#
tezjarl/FixedThreadPool
/FixedThreadPool/FixedThreadPool.cs
3.0625
3
using System; using System.Collections.Concurrent; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace FixedThreadPool { public class FixedThreadPool { private bool _isStopped; private readonly int _workCount; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly ConcurrentDictionary<ITask, Task> _executingTasks = new ConcurrentDictionary<ITask, Task>(); private readonly ConcurrentQueue<ITask> _highPriorityTasks = new ConcurrentQueue<ITask>(); private readonly ConcurrentQueue<ITask> _normalPriorityTasks = new ConcurrentQueue<ITask>(); private readonly ConcurrentQueue<ITask> _lowPriorityTasks = new ConcurrentQueue<ITask>(); private readonly TimeSpan _spinTimeout = TimeSpan.FromMilliseconds(5); private readonly TimeSpan _finishTasksTimeout = TimeSpan.FromSeconds(20); private const int HighTaskRatio = 3; private const int NormalTaskRatio = 1; /// <summary> /// Конструктор /// </summary> /// <param name="workCount"> Количество потоков для обработки задач</param> /// <exception cref="ArgumentOutOfRangeException"></exception> public FixedThreadPool(int workCount) { if (workCount <= 0) { throw new ArgumentOutOfRangeException(nameof(workCount)); } _workCount = workCount; var cancellationToken = _cancellationTokenSource.Token; Task.Run(async () => await ScheduleTaskAsync(cancellationToken), cancellationToken); } /// <summary> /// Ставит задачу на выполнение с указанным приоритетом /// </summary> /// <param name="task">Задача</param> /// <param name="priority">Приоритет</param> /// <returns>Флаг, показывающий была ли задача поставлена в очередь на выполнение</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidEnumArgumentException"></exception> public bool Execute(ITask task, Priority priority) { if (task == null) { throw new ArgumentNullException(nameof(task)); } if (_isStopped) { return false; } switch (priority) { case Priority.HIGH: _highPriorityTasks.Enqueue(task); break; case Priority.NORMAL: _normalPriorityTasks.Enqueue(task); break; case Priority.LOW: _lowPriorityTasks.Enqueue(task); break; default: throw new ArgumentException("Указаное значение приоритета не поддерживается", nameof(priority)); } return true; } public void Stop() { _isStopped = true; Task.WaitAll(_executingTasks.Values.ToArray(), _finishTasksTimeout); _cancellationTokenSource.Cancel(); } private async Task ScheduleTaskAsync(CancellationToken cancellationToken) { var executedHighPriorityTaskCount = 0; var normalPriorityTasksToExecute = 0; while (!cancellationToken.IsCancellationRequested) { if (AreThereScheduledTasks() && !IsWorkCapacityReached()) { var isExecutionOfNormalPriorityTaskAllowed = executedHighPriorityTaskCount >= HighTaskRatio && normalPriorityTasksToExecute < NormalTaskRatio; if (_highPriorityTasks.Any()) { var couldHighPriorityTaskBeExecuted = !_normalPriorityTasks.Any() || !isExecutionOfNormalPriorityTaskAllowed; if (couldHighPriorityTaskBeExecuted && TryExecuteTaskFromQueue(_highPriorityTasks)) { executedHighPriorityTaskCount++; continue; } } if (_normalPriorityTasks.Any()) { var couldNormalPriorityTaskBeExecuted = !_highPriorityTasks.Any() || isExecutionOfNormalPriorityTaskAllowed; if (couldNormalPriorityTaskBeExecuted && TryExecuteTaskFromQueue(_normalPriorityTasks)) { normalPriorityTasksToExecute++; } if (normalPriorityTasksToExecute >= NormalTaskRatio) { executedHighPriorityTaskCount = 0; } continue; } if (_lowPriorityTasks.Any()) { var couldLowPriorityTaskBeExecuted = !_highPriorityTasks.Any() && !_normalPriorityTasks.Any(); if (couldLowPriorityTaskBeExecuted) { TryExecuteTaskFromQueue(_lowPriorityTasks); } } } else { await Task.Delay(_spinTimeout, cancellationToken); } } } private bool IsWorkCapacityReached() => _executingTasks.Count > _workCount; private bool AreThereScheduledTasks() => _highPriorityTasks.Any() || _normalPriorityTasks.Any() || _lowPriorityTasks.Any(); private bool TryExecuteTaskFromQueue(ConcurrentQueue<ITask> queue) { if (queue.TryDequeue(out var task)) { ExecuteTask(task); return true; } return false; } private void ExecuteTask(ITask task) { if (_executingTasks.TryAdd(task, new Task(task.Execute))) { Task.Run(() => task.Execute()); _executingTasks.TryRemove(task, out _); } } } }
ac7ca3ced2ac5cf7d543f2993d72c0b8dbfd33f7
C#
t-ashula/bl4n
/bl4n/Data/ResultPagingOptions.cs
2.84375
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ResultPagingOptions.cs"> // bl4n - Backlog.jp API Client library // this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace BL4N.Data { /// <summary> 結果の範囲や個数,順序を指定するオプションを表します </summary> public class ResultPagingOptions : OptionalParams { private const string MinIdProperty = "minId"; private const string MaxIdProperty = "maxId"; private const string CountProperty = "count"; private const string OrderProperty = "order"; private long _minId; private long _maxId; private int _count; private bool _ascending; /// <summary> <see cref="RecentUpdateFilterOptions"/> のインスタンスを初期化します </summary> public ResultPagingOptions() : base(MinIdProperty, MaxIdProperty, CountProperty, OrderProperty) { } /// <summary> 最小のID を取得または設定します. </summary> public long MinId { get { return _minId; } set { _minId = value; PropertyChanged(MinIdProperty); } } /// <summary> 最大のID を取得または設定します. </summary> public long MaxId { get { return _maxId; } set { _maxId = value; PropertyChanged(MaxIdProperty); } } /// <summary> 取得個数を取得または設定します. </summary> /// <remarks> 1から100 まで(指定無しの場合 20)</remarks> public int Count { get { return _count; } set { _count = value; if (_count > 100) { _count = 100; } if (_count < 1) { _count = 1; } PropertyChanged(CountProperty); } } /// <summary> 昇順で取得するかどうかを取得または設定します </summary> /// <remarks> 指定無しの場合 降順</remarks> public bool Ascending { get { return _ascending; } set { _ascending = value; PropertyChanged(OrderProperty); } } /// <summary> HTTP Request 用の Key-value ペアの一覧を取得します </summary> /// <returns> key-value ペアの一覧 </returns> public IEnumerable<KeyValuePair<string, string>> ToKeyValuePairs() { var pairs = new List<KeyValuePair<string, string>>(); if (IsPropertyChanged(MinIdProperty)) { pairs.Add(new KeyValuePair<string, string>(MinIdProperty, string.Format("{0}", MinId))); } if (IsPropertyChanged(MaxIdProperty)) { pairs.Add(new KeyValuePair<string, string>(MaxIdProperty, string.Format("{0}", MaxId))); } if (IsPropertyChanged(CountProperty)) { pairs.Add(new KeyValuePair<string, string>(CountProperty, string.Format("{0}", Count))); } if (IsPropertyChanged(OrderProperty)) { pairs.Add(new KeyValuePair<string, string>(OrderProperty, Ascending ? "asc" : "desc")); } return pairs; } } }
b976751fa58b6b9cfc26cf351e52a939f9d8b8a4
C#
yifrach/ImageService
/ImageServiceGui/VM/VM_MainWindow.cs
2.609375
3
using ImageServiceGui.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ImageServiceGui.VM { class VM_MainWindow { private IMainWindowModel model; /// <summary> /// C'tor. /// </summary> public VM_MainWindow() { model = new MainWindowModel(); } /// <summary> /// Checks if the GUI is connected to the server /// and change the color of the title. /// </summary> public string IsConnected { get { return model.Color(); } } } }
4c10c992bcdbdbb724daa6c57a50a8b424b08513
C#
jacobwillinger/NoteService
/NoteService/Startup.cs
2.640625
3
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MongoDB.Bson; using Newtonsoft.Json; using Newtonsoft.Json.Bson.Converters; using System; namespace NoteService { public class ObjectIdConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(ObjectId); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) throw new Exception($"Unexpected token parsing ObjectId. Expected String, got {reader.TokenType}."); var value = (string)reader.Value; return string.IsNullOrEmpty(value) ? ObjectId.Empty : new ObjectId(value); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is ObjectId) { var objectId = (ObjectId)value; writer.WriteValue(objectId != ObjectId.Empty ? objectId.ToString() : string.Empty); } else { throw new Exception("Expected ObjectId value."); } } } public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(MongoDB.Bson.Serialization.Serializers.ObjectIdSerializer); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
fa1a3b7840f748b7f9de293f58ff7f86c9918503
C#
Feroks/DailyCodingProblem
/DailyCodingProblem/8/Problem8Linq.cs
3.28125
3
using System.Linq; namespace DailyCodingProblem._8 { public class Problem8Linq : IProblem8 { public int Run(Node node) { return RunInternal(node); } private static int RunInternal(Node node) { var (value, children) = node; var count = AllChildrenEqual(node, value) ? 1 : 0; return count + children.Sum(RunInternal); } private static bool AllChildrenEqual(Node node, int value) { var (nodeValue, children) = node; return nodeValue == value && children.All(x => AllChildrenEqual(x, nodeValue)); } } }
f2fc15f9a6d47d30d7397bd3c573f45b14d27b86
C#
brandon-irl/Bridge
/Tests/Batch1/BasicCSharp/TestValueTypes.cs
2.96875
3
using Bridge.Test.NUnit; namespace Bridge.ClientTest.BasicCSharp { public struct Point { // TODO Add more types public static int StatitIntNotInitialized; public static string StatitStringNotInitialized; public static int StaticInt; public static string StaticString; public const char CONST_CHAR = 'W'; public int x, y; static Point() { Point.StaticInt = 500; Point.StaticString = "Initialized"; } public int Test1() { return Point.StaticInt + this.x; } public Point Test2(Point p) { return new Point() { x = this.x + p.x, y = this.y + p.y }; } public static int Test3() { return Point.StatitIntNotInitialized + Point.StaticInt; } } public struct Rectangle { public Point l; public Point t; public Rectangle(int x, int y) { // [#69] this = new Rectangle(); this.l.x = x; this.l.y = y; } // [#66] public Rectangle(int x1, int y1, int x2, int y2) { this.l.x = x1; this.l.y = y1; this.t.x = x2; this.t.y = y2; } } // Tests: // Check value types [Category(Constants.MODULE_BASIC_CSHARP)] [TestFixture(TestNameFormat = "Value types - {0}")] public class TestValueTypes { // Check instance methods and constructors [Test(ExpectedCount = 18)] public static void TestInstanceConstructorsAndMethods() { // Check parameterless constructor var a = new Point(); Assert.AreEqual(0, a.x, "x 0"); Assert.AreEqual(0, a.y, "y 0"); var r = new Rectangle(); Assert.AreEqual(0, r.l.x, "r.l.x 0"); Assert.AreEqual(0, r.l.y, "r.l.y 0"); Assert.AreEqual(0, r.t.x, "r.t.x 0"); Assert.AreEqual(0, r.t.y, "r.t.y 0"); r = new Rectangle(10, 20); Assert.AreEqual(10, r.l.x, "r.l.x 10"); Assert.AreEqual(20, r.l.y, "r.l.y 20"); Assert.AreEqual(0, r.t.x, "r.t.x 0"); Assert.AreEqual(0, r.t.y, "r.t.y 0"); r = new Rectangle(30, 40, 50, 60); Assert.AreEqual(30, r.l.x, "r.l.x 30"); Assert.AreEqual(40, r.l.y, "r.l.y 40"); Assert.AreEqual(50, r.t.x, "r.t.x 50"); Assert.AreEqual(60, r.t.y, "r.t.y 60"); var i = a.Test1(); Assert.AreEqual(500, i, "i 500"); a.x = 300; i = a.Test1(); Assert.AreEqual(800, i, "i 800"); a.y = 400; var b = new Point() { x = 5, y = 7 }; var c = b.Test2(a); Assert.AreEqual(305, c.x, "c.x 305"); Assert.AreEqual(407, c.y, "c.y 407"); } // Check static methods and constructor [Test(ExpectedCount = 7)] public static void TestStaticConstructorsAndMethods() { Assert.AreEqual(500, Point.StaticInt, "Point.StaticInt 500"); Assert.AreEqual("Initialized", Point.StaticString, "Point.StaticString Initialized"); Assert.AreEqual(0, Point.StatitIntNotInitialized, "Point.StatitIntNotInitialized 0"); Assert.AreEqual(null, Point.StatitStringNotInitialized, "Point.StatitStringNotInitialized null"); Assert.AreEqual((int)'W', Point.CONST_CHAR, "Point.CONST_CHAR W"); Point.StatitIntNotInitialized = -1; Assert.AreEqual(-1, Point.StatitIntNotInitialized, "Point.StatitIntNotInitialized -1"); var i = Point.Test3(); Assert.AreEqual(499, i, "i 499"); } } }
4944ec7c70a6a052363d64a8bf6cf55d6dbeba2d
C#
TAnisha28/FairManagementSystem
/FairManagementApp/BLL/VisitorEntryManager.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FairManagementApp.DAL; using FairManagementApp.Model; namespace FairManagementApp.BLL { class VisitorEntryManager { VisitorEntryGateway aVisitorEntryGateway=new VisitorEntryGateway(); public string SaveVisitor(Visitor aVisitor) { bool IsEmailExist = aVisitorEntryGateway.IsEmailExist(aVisitor.email); if (!IsEmailExist) { if (aVisitorEntryGateway.SaveVisitor(aVisitor) > 0) { return "Saved successfully"; } else { return "Save failed"; } } else { return "Email Exist"; } } public int GetVisitorIdByEmail(string email) { return aVisitorEntryGateway.GetVisitorIdByEmail(email); } } }
3df2837196b943329a91cbfaa5453737ee0140a9
C#
mibrahim2018/xperience-module-bynder
/src/DancingGoatCore/Models/Grinders/GrinderFilterWhereCondition.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using CMS.DataEngine; using CMS.DocumentEngine.Types.DancingGoatCore; namespace DancingGoat.Models { public class GrinderFilterWhereCondition { private readonly GrinderFilterViewModel grinderFilter; public GrinderFilterWhereCondition(GrinderFilterViewModel grinderFilter) { this.grinderFilter = grinderFilter; } public WhereCondition GetWhereCondition() { var where = new WhereCondition() .And(GetManufacturerWhereCondition()) .And(GetPriceWhereCondition()); if (grinderFilter.DisplayElectricGrinders() && !grinderFilter.DisplayManualGrinders()) { where = where.WhereEquals("ClassName", ElectricGrinder.CLASS_NAME); } if (!grinderFilter.DisplayElectricGrinders() && grinderFilter.DisplayManualGrinders()) { where = where.WhereEquals("ClassName", ManualGrinder.CLASS_NAME); } return where; } private WhereCondition GetManufacturerWhereCondition() { var where = new WhereCondition(); var selectedManufacturerIds = GetSelectedManufacturerIds(); if (selectedManufacturerIds.Any()) { where.WhereIn("SKUManufacturerID", selectedManufacturerIds); } return where; } private WhereCondition GetPriceWhereCondition() { var where = new WhereCondition(); foreach (var range in GetSelectedRanges()) { where.Or(GetWhereConditionForPriceRange(range)); } return where; } private IEnumerable<GrinderPriceRangeEnum> GetSelectedRanges() { return grinderFilter.Prices .Where(price => price.IsChecked) .Select(GetRangeFromSelectedValue); } private static GrinderPriceRangeEnum GetRangeFromSelectedValue(GrindersProductFilterCheckboxViewModel price) { return (GrinderPriceRangeEnum)price.Value; } private static WhereCondition GetWhereConditionForPriceRange(GrinderPriceRangeEnum range) { switch (range) { case GrinderPriceRangeEnum.ToFifty: return GetPriceRangeWhereCondition(0, 50); case GrinderPriceRangeEnum.FromFiftyToFiveHundred: return GetPriceRangeWhereCondition(50, 500); case GrinderPriceRangeEnum.FromFiveHundredToFiveThousand: return GetPriceRangeWhereCondition(500, 5000); default: throw new ArgumentOutOfRangeException(nameof(range)); } } private static WhereCondition GetPriceRangeWhereCondition(int from, int to) { return new WhereCondition() .WhereGreaterOrEquals("SKUPrice", from) .And().WhereLessThan("SKUPrice", to); } private List<int> GetSelectedManufacturerIds() { return grinderFilter.Manufacturers .Where(x => x.IsChecked) .Select(x => x.Value) .ToList(); } } }
28e5ffb80ad155865a52c94e2219a910ef5d8544
C#
sindamnataraj/Algorithms-and-Data-Structures
/Program.cs
2.8125
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace prepPhase3 { class Program { static void Main(string[] args) { #region Bit Problems #endregion #region Sorting //int[] A = { 98, 91, 1, 2,16,19,4,0}; //Sorting.SelectionSort(ref A); //Sorting.InsertionSort(ref A, 0, A.Length - 1); //Sorting.QuickSort(ref A, 0, A.Length - 1); //Sorting.MergeSort(ref A, 0, A.Length - 1); //PrintArray(A); //int[] A = { 8, 9, 1, 2, 1, 9, 4, 0 }; //Sorting.ShellSort(ref A); //MyHeap h = new MyHeap(); //h.HeapSort(ref A); //PrintArray(A); //int[] A = { 1, 2, 3, 1, 3, 6, 6 }; //Console.WriteLine("{0}",Sorting.IsAnyNumberRepeated(A,0,A.Length-1)); //Console.WriteLine("{0}", Sorting.IsAnyNumberRepeated1(A, 0, A.Length - 1)); #endregion #region Searching //Console.WriteLine("** Searching Section **"); //int[] A1 = { 1, 60, -10, 70, -80, 85 }; //int[] A3 = { 0, 1, 0, 1, 0, 1 }; //int[] Z = {-1, 0, 1, 2, -1, -4}; //int[] I = {1,1,1,1,1,0,0,0,0,0,0,0,0 }; //int[] O = { 12, 11, 15, 10, 20 }; //int[] T = { 10, 11,11,11,12, 12, 15, 20 }; //int[] Triple = { 0,1,2,0,0,1,1,1,2,0,1,2,0,0}; ////Console.WriteLine(Searching.FindMissingNum2(A1)); //Searching.FindTheRepeatingTwo(A1); //Searching.FindTwoWhoseSumIsK2(A1,16); //Searching.SumClosestToZero(A1); //Searching.FindThreeSumIsK(A3, 24); //Searching.SumThreeClosestToZero(Z); //Console.WriteLine(Searching.FirstOccuerence(T,0,T.Length-1,12)); //Searching.FindMedian(O, 0, O.Length - 1, T, 0, T.Length - 1); //Searching.NUmberOfRepeatitions(T, 13); //Searching.SeparateTriple(ref Triple, 0, Triple.Length - 1); //PrintArray(Triple); #endregion #region selection //Console.WriteLine("** Selection **"); //int[] A = { 9, 8, 7, 6, 5 }; //Console.WriteLine(Selection.KthElement(A,0,A.Length-1,1)); #endregion #region strings //Console.WriteLine("** strings **"); //Console.WriteLine (StringProblems.IsValidParenthesis("(((())()))")); //Console.WriteLine(sb.ToString()); //string pattern = "abba"; //string str = "dog cat cat dog";// should return true. //Console.WriteLine(StringProblems.WordPattern(pattern,str)); //Console.WriteLine(); //Console.WriteLine(StringProblems.ReverseVowels("leetcode")); #endregion #region MyLinkedList MyLinkedList L = new MyLinkedList(); //L.Insert(7); //L.Insert(7); //L.Insert(7); //L.Insert(4); //L.Insert(4); //L.Insert(2); //L.Insert(1); L.DeleteDups(); L.PrintMyList(); //L.ReorderList(); #endregion #region MyStack //MyStack s = new MyStack(5); //s.Push(1); //s.Push(2); //s.Push(3); //s.PrintStack(); //int res = s.Pop(); //s.Push(4); //s.PrintStack(); #endregion #region MyBinaryTree //MyBinaryTree bt = new MyBinaryTree(); //bt.Insert(3); //bt.Insert(2); //bt.Insert(1); //bt.Insert(5); //bt.Insert(4); //bt.Insert(7); //bt.PrintColumns(); //Console.WriteLine(); ////bt.ZigZag(); //bt.PreOrder_NonRecursive(); #endregion #region Stacks #endregion #region Dynamic Programming //DynamicProgramming.LCS("ABCDGH","AEDFHR"); //int[] A2 = { -2, -3, 4, -1, -2, 1, 5, -3 }; //DynamicProgramming.Max_Value_Continous_Subsequence(A2); //int[] A3 = { 10, 9, 2, 5, 3, 7, 101, 18 }; //int[] A4 = { 2 , 3, 5, 7, 9,10, 18,101 }; //DynamicProgramming.LCS_Integers(A3, A4); //int[] A2 = { 5,5,10,40,50,35}; //DynamicProgramming.Max_Value_Contigous_Subsequence_NoTwo_Continous(A2); //int[] W = { 9,6,5,1}; //Console.WriteLine(DynamicProgramming.ChangeCoins(W,11)); //int[] S = { 10, 22, 9, 33, 21, 50, 41, 60, 80 }; //DynamicProgramming.Longest_Increasing_Subsequence(S); //int[] X = { 3, 34, 4, 12, 5, 2 }; //Console.WriteLine(DynamicProgramming.IsThereSubset(X, 9)); //int[] M = { 1, 101, 2, 3, 100, 4, 5 }; //Console.WriteLine(DynamicProgramming.MaxSum_Increasing_sequence(M)); #endregion #region Random Sites //Console.WriteLine("** Random Sites **"); //int[] A = { 9, 9, 3, 4, 2, 2, 3, 6, 7, 6, 8, 9 }; //int[] A = {123,321,432,433,232}; //int[] B = FromRandonSites.CountingSort(A); //PrintArray(B); //Console.WriteLine(FromRandonSites.CountingSort_String("cccbbbaarrrttqqaaa")); //FromRandonSites.RadixSort(ref A); //PrintArray(A); #endregion #region Maths //Console.WriteLine(MathTricks.GetSum(1,4)); //Console.WriteLine(MathTricks.GetSum(-1, 4)); //Console.WriteLine(MathTricks.IsPalindrome(-748847)); //Console.WriteLine(MathTricks.IsMultipleOf3(330)); #endregion //int[] A = new int[10]; //A.ToList() //List<int> l = new List<int>(A); //int[] K = { 100, 180, 260, 310, 40, 535, 695 }; //Console.WriteLine(MaxProfit_1Transaction(K, 0, K.Length - 1)); //ISet<int> n = new HashSet<int>(); //List<int> li = n.ToList<int>(); // //Console.WriteLine(); ////StringProblems.permte(new StringBuilder("abc"), 0, 2); //List<string> li = new List<string>(); //li.Add("one"); //li.Add("two"); //StringProblems.PermuteListOfWords(li, 0, li.Count - 1); //BinrayTree2 bt = new BinrayTree2(); //bt.Insert(1); //bt.Insert(2); //bt.Insert(3); //bt.Insert(4); //bt.Insert(5); //bt.practice_level(); //int[] Ino = { 4,2,5,1,6,3}; //int[] Pre = { 1,2,4,5,3,6}; //bt.BuildTreeFrom_InorderAndPreOrder(Ino, Pre); ////bt.PrintAllPaths(); //bt.Diameter(); //bt.LevelOrder(); //bt.DeepestNode(); //int[] n = { 0, 1, 0, 1, 0, 1, 1, 2, 0, 2, 0 }; //Partition(ref n, 0, n.Length - 1); //PrintArray(n); //Permute("abc", 0, 2); //int[] A = { 1,2,3,4,5,6}; //SeparateEvenOdd(ref A); //PrintArray(A); //MoveZeroesRight(ref A); //Combinations(A, 0, A.Length - 1, 2, new List<int>(), 0); //PowerSet(A); //int[] A = { 1, 2, 3, 4, 5, 6, 7, 9}; //QuickSort(ref A, 0, A.Length - 1); //PrintArray(A); //Console.WriteLine(MaxSumContinousSequence(A)); //int[] A = new int[10]; //EvenOddIndexSeparation(ref A); //PrintArray(A); //SortedSet<int> set = new SortedSet<int>(); // MyTrie t = new MyTrie(); // t.Insert("tea"); // t.Insert("dead"); // t.Insert("te"); // t.PrintAllStrings(); // Console.WriteLine("{0} {1}","tea",t.Search("tea")); // Console.WriteLine("{0} {1}", "te", t.Search("te")); // HashSet<string> dic = new HashSet<string>(); // dic.Add("leet"); // dic.Add("code"); // Console.WriteLine(WordBreak("leetcode",dic)); // Console.WriteLine("{0}", SumOffAllNumbersInString("a12b23b12")); // List<int> l = new List<int>(); // int[] A = l.ToArray(); // int[] AN = {2,4,12,3,3,4,5 }; // Separate_Evn_odd(ref AN); // PrintArray(AN); // Print_All_Posssible("", 1, 2, false); // MyOrderedSet s = new MyOrderedSet(); // s.DuplicateAddedEvent += SubscribeToDuplicateEvent; //PrintAllParenths(3, 0, 0, ""); //BinaryTree3 tree = new BinaryTree3(); //tree.Insert(8); //tree.Insert(10); //tree.Insert(14); //tree.Insert(13); //tree.Insert(3); //tree.Insert(6); //tree.Insert(1); //tree.Insert(7); //tree.Insert(4); //tree.Inorder();d //Console.WriteLine(); //tree.PreOrder(); //Console.WriteLine(); //tree.PostOrder(); //tree.Inorder(); //tree.PreOrder(); //tree.Deepest(); //tree.PrintAllPaths(); //BinaryTree bt = new BinaryTree(); //bt.Insert(8); //bt.Insert(3); //bt.Insert(1); //bt.Insert(6); //bt.Insert(4); //bt.Insert(7); //bt.Insert(10); //bt.Insert(14); //bt.Insert(13); //bt.PritnAllPaths(); //PhoneDirectory myPhone = new PhoneDirectory(); //myPhone.AddNumber("6087703061", "nataraj"); //myPhone.AddNumber("6087703062", "vindesiel"); //Console.WriteLine(myPhone.GetName("6087703061")); //Console.WriteLine(myPhone.GetName("6087703062")); mylist l = new mylist(); l.Add(1); l.Add(2); l.Add(3); l.Add(4); l.Add(5); l.PrintList(); l.Reverse(); l.PrintList(); Console.ReadLine(); } public static void TestEvents1(int n) { Console.WriteLine("Test Events 1 = {0}",n); } public static int FirstMissingPositive(int[] nums) { int positiveXor = 0; int lowestPositive = int.MaxValue; //should be >=1 int positiveCount = 0; bool isPositivePresent = false; for (int i = 0; i < nums.Length; i++) { if (nums[i] > 0) { isPositivePresent = true; positiveXor = positiveXor ^ nums[i]; positiveCount++; if (nums[i] < lowestPositive) { lowestPositive = nums[i]; } } } if (!isPositivePresent) return 1; int n = positiveCount; int xor = lowestPositive; int j = 0; for (j = 1; j <= n; j++) { xor = xor ^ (lowestPositive + j); } return xor ^ positiveXor; } public static void Text(int[] B) { } public static void SubscribeToDuplicateEvent() { Console.WriteLine("Duplicate is added"); } public static void PrintArray(int[] A) { for (int i = 0; i < A.Length; i++) { Console.Write("{0} ", A[i]); } Console.WriteLine(); } //()()()() public static void PrintAllParenths(int n, int openParenth, int closedParenth, string s) { if (closedParenth == n) { Console.WriteLine(s); } else { if (openParenth > closedParenth) { StringBuilder sb = new StringBuilder(s); sb.AppendFormat("{0}", ")"); PrintAllParenths(n, openParenth, closedParenth + 1, sb.ToString()); } if (openParenth < n) { StringBuilder sb = new StringBuilder(s); sb.AppendFormat("{0}", "("); PrintAllParenths(n, openParenth + 1, closedParenth, sb.ToString()); } } } public static void Separate_Evn_odd(ref int[] A) { if (A.Length == 0) return; int i = -1; int j = 0; while (j < A.Length) { if (A[j] % 2 == 0) { swap(ref A, i + 1, j); i++; } j++; } } //remember words can be repeated public static int Shortest_word_Distance_1(string[] words, string word1, string word2) { int min = int.MaxValue; int index1 = -1; //track index where word1 occurs in case of min distance, //-1 indicates we havent found the word yet int index2 = -1; for (int i = 0; i < words.Length; i++) { if (words[i] == word1) { index1 = i; if (index2 != -1) { min = Math.Min(min, Math.Abs(index1 - index2)); } } else if (words[i] == word2) { index2 = i; if (index1 != -1) { min = Math.Min(min, Math.Abs(index1 - index2)); } } } return min; } public static int[] KMPPrefix(string P) { int[] F = new int[P.Length]; if (P.Length == 0) return F; int i = 1; int j = 0; F[0] = 0; while (i < P.Length) { if (P[i] == P[j]) { F[i] = j + 1; i++; j++; } else if (j > 0) { j = F[j - 1]; } else { F[i] = 0; i++; } } return F; } public static int IsSubstring_KMP(string T, string P) { int[] F = KMPPrefix(P); int i = 0; int j = 0; while (i < T.Length) { if (T[i] == P[j]) { if (j == P.Length - 1) { return i - j; } else { i++; j++; } } else if (j > 0) { j = F[j - 1]; } else { i++; } } return -1; } #region stock Problems //if 1 transaction is allowed what is the max profit that can be made ? public static int MaxProfit_1Transaction(int[] A, int p, int q) { if (p == q) return 0; int maxProfit = int.MinValue; int currentMin = A[p]; int j = p + 1; while (j <= q) { int currentProfit = A[j] - currentMin; if (currentProfit > maxProfit) { maxProfit = currentProfit; } if (A[j] < currentMin) { currentMin = A[j]; } j++; } if (maxProfit < 0) return 0; return maxProfit; } public static void Partition(ref int[] nums, int low, int high) { int pivot = 1; int p = low - 1; int q = high + 1; int r = low; while (r < q && r > p && p < q) { if (nums[r] < pivot) { Interchange(ref nums, p + 1, r); p++; r++; ; } else if (nums[r] == pivot) { r++; } else { Interchange(ref nums, q - 1, r); q--; } } } public static void Interchange(ref int[] A, int x, int y) { int temp = A[x]; A[x] = A[y]; A[y] = temp; } #endregion #region LinkedIn Practice public static int NumberOfOccurences(int[] A, int k) { if (A.Length == 0) return 0; int first = FirstOccurrence(A, 0, A.Length - 1, k); if (first == -1) return 0; int last = LastOccurence(A, 0, A.Length - 1, k); return last - first + 1; } public static int FirstOccurrence(int[] A, int p, int q, int k) { if (p <= q) { int mid = p + (q - p) / 2; if (A[mid] == k) { if (mid == p || A[mid - 1] != k) { return mid; } else { return FirstOccurrence(A, p, mid - 1, k); } } else if (k < A[mid]) { return FirstOccurrence(A, p, mid - 1, k); } else { return FirstOccurrence(A, mid + 1, q, k); } } return -1; } public static int LastOccurence(int[] A, int p, int q, int k) { if (p <= q) { int mid = p + (q - p) / 2; if (A[mid] == k) { if (mid == q || A[mid + 1] != k) { return mid; } else { return LastOccurence(A, mid + 1, q, k); } } else if (k > A[mid]) { return LastOccurence(A, mid + 1, q, k); } else { return LastOccurence(A, p, mid - 1, k); } } return -1; } //true exp = “[()]{}{[()()]()}” and false for exp = “[(])” public static bool ParenthesisMatching(string s) { int len = s.Length; //Parenthesis couldnt be balanced if the lenght is odd if (len % 2 != 0) return false; Stack<char> stackForLefts = new Stack<char>(); for (int i = 0; i < s.Length; i++) { char c = s[i]; if (IsLeft(c)) { stackForLefts.Push(c); } else if (IsRight(c)) { if (stackForLefts.Count == 0) return false; char top = stackForLefts.Peek(); if (top != c) return false; stackForLefts.Pop(); } else { //Not a valid input since char is not part of the 6 letterrs return false; } } if (stackForLefts.Count > 0) return false; return true; } public static bool IsLeft(char c) { if (c == '(' || c == '[' || c == '{') return true; return false; } public static bool IsRight(char c) { if (c == ')' || c == ']' || c == '}') return true; return false; } #region Permutations Related //Gray Code //Permutations 1 //Find all combinations of given integers public static void Permute(string s, int p, int q) { if (p == q) { Console.WriteLine(s); } else if (p < q) { StringBuilder sb = new StringBuilder(s); for (int i = p; i <= q; i++) { char c = sb[i]; sb[i] = sb[p]; sb[p] = c; Permute(sb.ToString(), p + 1, q); c = sb[i]; sb[i] = sb[p]; sb[p] = c; } } } //Permutations 2 // Given a collection of numbers that might contain duplicates, return all possible unique permutations. // For example, // [1,1,2] have the following unique permutations: //[ // [1,1,2], // [1,2,1], // [2,1,1] //] public IList<IList<int>> PermuteUnique(int[] nums) { List<IList<int>> final = new List<IList<int>>(); Permute(nums, 0, nums.Length - 1, ref final); return (IList<IList<int>>)final; } public static void Permute(int[] A, int p, int q, ref List<IList<int>> final) { if (p == q) { List<int> li = new List<int>(A); final.Add((IList<int>)li); } else if (p < q) { int prev = p; for (int i = p; i <= q; i++) { if (HasDuplicate(A, p, i) == false) { Interchange(ref A, p, i); Permute(A, p + 1, q, ref final); Interchange(ref A, p, i); } } } } //Checks if element A[q] is present in A[p]...A[q-1] public static bool HasDuplicate(int[] A, int p, int q) { for (int i = p; i < q; i++) { if (A[i] == A[q]) return true; } return false; } //Next Permutation (LeetCode) //Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. //If such arrangement is not possible, it must rearrange it as the lowest possible order(ie, sorted in ascending order). //The replacement must be in-place, do not allocate extra memory. //Here are some examples.Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. //1,2,3 → 1,3,2 //3,2,1 → 1,2,3 //1,1,5 → 1,5,1 //1. From right to left, find the first digit(PartitionNumber) which violate the increase trend. //2. From right to left, find the first digit which larger than PartitionNumber, call it ChangeNumber. //3. Swap the PartitionNumber and ChangeNumber. //4. Reverse all the digit on the right of partition index. public static void NextPermutation(ref int[] nums, int p, int q) { // public void Next(ref int[] nums, int p, int q) int i = q - 1; while (i >= p && nums[i] >= nums[i + 1]) //here increasing sequence is not strictly increasing for ex [5,1,1] { i--; } if (i < p) { Reverse(ref nums, p, q); return; } int partition = i; int j = q; while (j >= p && nums[j] <= nums[partition]) { j--; } if (j < p) return; swap(ref nums, partition, j); Reverse(ref nums, partition + 1, q); } public static void swap(ref int[] N, int p, int q) { int n = N[p]; N[p] = N[q]; N[q] = n; } public static void Reverse(ref int[] nums, int p, int q) { while (p < q) { int n = nums[p]; nums[p] = nums[q]; nums[q] = n; p++; q--; } } //Palindrome Permutation || (LeetCode) //Does the given string have a palindrome permutation public static bool HasPalindromePermutation(string s) { Dictionary<char, int> d = new Dictionary<char, int>(); for (int i = 0; i < s.Length; i++) { char c = s[i]; if (d.ContainsKey(c)) { d[c]++; } else { d.Add(c, 1); } } int countOdds = 0; foreach (char c in d.Keys) { if (d[c] % 2 != 0) { countOdds++; } } //if s is odd length.... abc if (s.Length % 2 != 0) { if (countOdds > 1) return false; return true; } //if s is even then odds should be even if (countOdds % 2 == 0) return true; return false; } //better way than above public static bool HasPalindromePermutation1(string s) { HashSet<char> unpairedChars = new HashSet<char>(); foreach (char c in s) { if (unpairedChars.Contains(c)) { unpairedChars.Remove(c); } else { unpairedChars.Add(c); } } if (s.Length % 2 == 0) { if (unpairedChars.Count == 0) return true; return false; } if (unpairedChars.Count <= 1) return true; return false; } //Palindrome Partitioning II // Given a string s, partition s such that every substring of the partition is a palindrome. //Return the minimum cuts needed for a palindrome partitioning of s. //For example, given s = "aab", //Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. //finding power set of given set public static void PowerSet(int[] A) { List<HashSet<int>> res = new List<HashSet<int>>(); int n = A.Length; int m = (int)Math.Pow(2, n); for (int i = 0; i < m; i++) { res.Add(new HashSet<int>()); for (int j = 1; j <= n; j++) { if (Isset(i, j)) { res[i].Add(A[j - 1]); } } } foreach (HashSet<int> h in res) { Console.Write("{"); foreach (int i in h) { Console.Write(i); Console.Write(" "); } Console.Write("}"); Console.WriteLine(); } } //is kth bit set in n public static bool Isset(int n, int k) { int m = 1; while (k > 1) { m = m << 1; k--; } return (n & m) != 0; } //http://www.martinbroadhurst.com/combinatorial-algorithms.html //combinations = ncr //selecting r elements from given n elements public static void Combinations(int[] A, int low, int high, int r, List<int> l, int index) { if (index == r) { PrintArray(l.ToArray()); return; } else { for (int i = low; (i <= high) && ((high - i + 1) >= (r - index)); i++) { if (index >= l.Count) l.Add(new int()); l[index] = A[i]; Combinations(A, i + 1, high, r, l, index + 1); } } } #endregion //the sum of any two sides must be greater than the value of third side). //given list of numbers whihc represent sides of triangle , how many valid traingles can be formed //This is of O(n2) while brute force is O(n3) public static int NumberOfTriangles(int[] A) { if (A.Length < 3) return 0; Array.Sort(A); return NumberOfTriangles(A, 0, A.Length - 1); } public static int NumberOfTriangles(int[] A, int p, int q) { int count = 0; for (int i = p; i < q - 1; i++) { for (int j = i + 1; j < q; j++) { int k = j + 1; while (k <= q && A[i] + A[j] > A[k]) k++; count += k - j - 1; } } return count; } //Evalutate post fix expression public static int EvaluatePostFix(string s) { Stack<int> stackOfOperands = new Stack<int>(); for (int i = 0; i < s.Length; i++) { if (IsNumber(s[i])) { stackOfOperands.Push((int)s[i]); } else { //we have an operator if (stackOfOperands.Count > 1) { int n1 = stackOfOperands.Pop(); int n2 = stackOfOperands.Pop(); stackOfOperands.Push(Operate(s[i], n1, n2)); } else { //invalid expression return -999; } } } if (stackOfOperands.Count != 1) return -999; return stackOfOperands.Pop(); } public static bool IsNumber(char c) { int asci = (int)c; if (asci >= 48 && asci <= 57) return true; return false; } public static int Operate(int c, int n1, int n2) { switch (c) { case '*': return n1 * n2; case '/': return n2 / n1; case '+': return n1 + n2; case '-': return n2 - n1; default: return -999; } } //Given an array of numbers , replace each number with the product of //all the numbers divided by the number at that index without using the division operator public static void SetProductOfAll(ref int[] A) { if (A.Length == 1) { A[0] = 1; return; } int[] left = new int[A.Length]; for (int i = 0; i < left.Length; i++) { if (i == 0) { left[i] = A[i]; } else { left[i] = left[i - 1] * A[i]; } } int[] right = new int[A.Length]; for (int i = right.Length - 1; i >= 0; i--) { if (i == right.Length - 1) { right[i] = A[i]; } else { right[i] = right[i + 1] * A[i]; } } for (int i = 0; i < A.Length; i++) { if (i == 0 && i + 1 < A.Length) { A[i] = right[i + 1]; } else if (i == A.Length) { A[i] = left[i - 1]; } else { A[i] = left[i - 1] * right[i + 1]; } } } //Minumim window string ******** //see https://leetcode.com/problems/minimum-window-substring/ public static string MinWindow(string s, string t) { //if (t.Length > s.Length) return ""; ////HashSet<char> set = new HashSet<char>(); ////HashSet<char> set1 = new HashSet<char>(); //Dictionary<char, int> d = new Dictionary<char, int>(); //Dictionary<char, int> d1 = new Dictionary<char, int>(); //for (int b = 0; b < t.Length; b++) //{ // //set.Add(t[b]); // if (d.ContainsKey(t[i])) // { // d[t[i]]++; // } // { // d.Add(t[i], 1); // } // //set1.Add(t[b]); // d1.Add(t[i], 1); //} //int i = 0; //while (!set.Contains(s[i]) && i < s.Length) //{ // i++; //} //if (i == s.Length) return ""; //set.Remove(s[i]); //int j = i + 1; //while (j < s.Length && set.Count > 0) //{ // if (set.Contains(s[i])) // { // set.Remove(s[i]); // } // j++; //} //if (set.Count > 0) return ""; //if (j >= s.Length) return s; //int minLen = j - i + 1; //j++; //while (j < s.Length) //{ // if (s[j] == s[i]) // { // i++; // while (!set1.Contains(s[i])) // { // i++; // } // int newLen = j - i + 1; // if (newLen < minLen) // { // minLen = newLen; // } // } // j++; //} //return s.Substring(i, minLen); ////return minLen; return ""; } //Move zeroes to right //input [0, 1, 0, 3, 12] //output [1, 3, 12, 0, 0] public static void MoveZeroesRight(ref int[] A) { if (A.Length <= 1) return; int i = -1; int j = 0; while (j < A.Length) { if (A[j] != 0) { Interchange(ref A, i + 1, j); i++; if (i == j) j++; } else { j++; } } PrintArray(A); } //Atoi - string to number //returns zero if input has anything other than numbers public static int MyAtoi(string s) { int res = 0; for (int i = 0; i < s.Length; i++) { int asci = (int)s[i]; if (asci < 48 || asci > 57) return 0; res = (res * 10) + asci; } return res; } //Separte Even odd public static void SeparateEvenOdd(ref int[] A) { if (A.Length <= 1) return; int i = -1; int j = 0; while (j < A.Length) { if (A[j] % 2 == 0) { Interchange(ref A, i + 1, j); i++; if (i == j) j++; } else { j++; } } } public static int depthSum(List<NestedInteger> input) { // ur implementation here return sumCal(input, 1); } public static int sumCal(List<NestedInteger> input, int depth) { if (input == null || input.Count == 0) return 0; int sum = 0; for (int i = 0; i < input.Count; i++) { NestedInteger nestInt = input[i]; if (nestInt.isInteger()) { sum = sum + depth * nestInt.getInteger(); } else { sum = sum + sumCal(nestInt.getList(), depth + 1); } } return sum; } //This is the interface that represents nested lists. //You should not implement it, or speculate about its implementation. public interface NestedInteger { // @return true if this NestedInteger holds a single integer, rather than a nested list */ bool isInteger(); // @return the single integer that this NestedInteger holds, if it holds a single integer // Return null if this NestedInteger holds a nested list */ int getInteger(); // @return the nested list that this NestedInteger holds, if it holds a nested list // Return null if this NestedInteger holds a single integer */ List<NestedInteger> getList(); } //Given a target and a sorted array, find the element that is strictly //larger than the target.i.e. {a,c,d,e} b output: c public static int StrictlyGreater(int[] A, int p, int q, int k) { if (p == q) { if (A[p] > k) return p; return -1; } else if (p < q) { int mid = p + (q - p) / 2; if (A[mid] > k) { if (A[mid - 1] <= k) { return mid; } else { return StrictlyGreater(A, p, mid - 1, k); } } else { return StrictlyGreater(A, mid + 1, q, k); } } return -1; } //find the max sum of continuous sequence in the array. {2,-1,3,-5,3} output: 4 public static int MaxSumContinousSequence(int[] A) { if (A.Length == 0) return 0; int[] M = new int[A.Length]; M[0] = A[0]; for (int i = 1; i < M.Length; i++) { M[i] = Math.Max(M[i - 1] + A[i], A[i]); } return M.Max(); } #region Interval Problems //{1,3}, {2,4}, {5,7}, {6,8} }. merge overlapping intervals public static List<Range> MergeRanges(List<Range> L) { if (L.Count == 0) return null; MergeSortRanges(ref L, 0, L.Count - 1); List<Range> result = new List<Range>(); Range prev = L[0]; for (int i = 1; i < L.Count; i++) { if (L[i].left <= prev.right) { prev.right = L[i].right; } else { result.Add(prev); prev = L[i]; } } return result; } //sort the list of ranges based on first elements public static void MergeSortRanges(ref List<Range> l, int p, int q) { if (p < q) { int mid = p + (q - p) / 2; MergeSortRanges(ref l, p, mid); MergeSortRanges(ref l, mid + 1, q); MergeSortedRanges(ref l, p, mid, q); } } public static void MergeSortedRanges(ref List<Range> l, int p, int r, int q) { int l1 = r - p + 1; int l2 = q - r; List<Range> left = new List<Range>(); for (int i = 0; i < l1; i++) { left.Add(l[p + i]); } List<Range> right = new List<Range>(); for (int j = 0; j < l2; j++) { right.Add(l[r + 1 + j]); } int i1 = 0; int j1 = 0; int k1 = 0; while (i1 < left.Count && j1 < right.Count) { if (left[i1].left <= right[j1].left) { l[k1] = left[i1]; i1++; } else { l[k1] = right[j1]; j1++; } k1++; } while (i1 < left.Count) { l[k1] = left[i1]; i1++; k1++; } while (j1 < right.Count) { l[k1] = right[j1]; j1++; k1++; } } //InsertInterval //Meeting Room 1 // Given an array of meeting time intervals consisting of start and end times[[s1, e1],[s2, e2],...] (si<ei), determine if a person could attend all meetings. //For example, //Given[[0, 30],[5, 10],[15, 20]], //return false. //the idea is: first sort the intervals according to the start times, then check if there is any overlap. //Meeting Room 2 //Given an array of meeting time intervals consisting of start and end times[[s1, e1],[s2, e2],...] (si<ei), //find the minimum number of conference rooms required. //For example, //Given[[0, 30],[5, 10],[15, 20]], //return 2. //http://buttercola.blogspot.com/2014/11/facebook-maximum-number-of-overlapping.html //Hint: Keep start times end times in two arrays sort them #endregion //Are two strings isomorphic ?? public static bool AreIsomorphic(string s, string t) { if (s.Length == 0 && t.Length == 0) return true; if (s.Length != t.Length) return false; Dictionary<char, char> Map = new Dictionary<char, char>(); Dictionary<char, char> Map1 = new Dictionary<char, char>(); for (int i = 0; i < s.Length; i++) { char key = s[i]; char val = t[i]; if (Map.ContainsKey(key)) { if (val != Map[key]) return false; } else { if (Map1.ContainsKey(val)) { char c1 = Map1[val]; if (c1 != key) return false; } Map.Add(key, val); Map1.Add(val, key); } } return true; } //flood fill algo public static void FloodFill(ref int[,] Screen, int x, int y, int newColor) { int m = Screen.GetLength(0) - 1; int n = Screen.GetLength(1) - 1; if (AreValidInputs(x, y, m, n) == false) return; int oldColor = Screen[x, y]; if (oldColor == newColor) return; FloodFill(ref Screen, m, n, oldColor, x, y, newColor); } public static void FloodFill(ref int[,] Screen, int m, int n, int oldCOlor, int x, int y, int newColor) { if (AreValidInputs(x, y, m, n) && Screen[x, y] == oldCOlor) { Screen[x, y] = newColor; FloodFill(ref Screen, m, n, oldCOlor, x - 1, y, newColor); FloodFill(ref Screen, m, n, oldCOlor, x - 1, y, newColor); FloodFill(ref Screen, m, n, oldCOlor, x - 1, y, newColor); FloodFill(ref Screen, m, n, oldCOlor, x - 1, y, newColor); } } public static bool AreValidInputs(int x, int y, int m, int n) { if (x < 0 || x > m) return false; if (y < 0 || y > n) return false; return true; } //Islands public static int NumIslands(char[,] grid) { int m = grid.GetLength(0); int n = grid.GetLength(1); if (m == 0 && n == 0) return 0; bool[,] IsVisited = new bool[m, n]; for (int a = 0; a < m; a++) { for (int b = 0; b < n; b++) { IsVisited[a, b] = false; } } m--; n--; int num = 0; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (IsVisited[i, j] == false) { if (grid[i, j] == 0) { IsVisited[i, j] = true; } else { num++; DFSVisit(grid, i, j, ref IsVisited, m, n); } } } } return num; } public static void DFSVisit(char[,] grid, int x, int y, ref bool[,] IsVisited, int m, int n) { IsVisited[x, y] = true; if (IsValid(x - 1, y, m, n) == true && IsVisited[x - 1, y] == false && grid[x - 1, y] == 1) DFSVisit(grid, x - 1, y, ref IsVisited, m, n); if (IsValid(x, y - 1, m, n) == true && IsVisited[x, y - 1] == false && grid[x, y - 1] == 1) DFSVisit(grid, x, y - 1, ref IsVisited, m, n); if (IsValid(x, y + 1, m, n) == true && IsVisited[x, y + 1] == false && grid[x, y + 1] == 1) DFSVisit(grid, x, y + 1, ref IsVisited, m, n); if (IsValid(x + 1, y, m, n) == true && IsVisited[x + 1, y] == false && grid[x + 1, y] == 1) DFSVisit(grid, x + 1, y, ref IsVisited, m, n); } public static bool IsValid(int x, int y, int m, int n) { if (x < 0 || x > m) return false; if (y < 0 || y > n) return false; return true; } #region N Queen //N Queen Problem //https://www.youtube.com/watch?v=JkP-xats3no //called as follows: // if(solveQueen(Board,0,4)) { PrintBoard(Board); } public static bool SolveQueen(int[,] Board, int col, int N) { if (col >= N) { return true; } for (int i = 0; i < Board.GetLength(0); i++) { if (canPutQueenAt(Board, i, col)) { Board[i, col] = 1; if (SolveQueen(Board, col + 1, N)) { return true; } Board[i, col] = 0; } } return false; } public static bool canPutQueenAt(int[,] Board, int row, int col) { int i = 0; for (i = 0; i < col; i++) { if (Board[row, i] == 1) return false; } int j = 0; j = col; i = row; for (; j >= 0 && i >= 0; j--, i--) { if (Board[i, j] == 1) return false; } j = col; i = row; for (; j >= 0 && i < col; j--, i++) { if (Board[i, j] == 1) return false; } return true; } public static void PrintBoard(int[,] Board) { int m = Board.GetLength(0); int n = Board.GetLength(1); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (Board[i, j] == 1) { Console.Write(" Q"); } else { Console.Write(" -"); } } Console.WriteLine(); } } #endregion //travelling salesman //http://www.geeksforgeeks.org/travelling-salesman-problem-set-2-approximate-using-mst/ //http://www.csd.uoc.gr/~hy583/papers/ch11.pdf // 1.select a “root” vertex r ∈ V[G]. //2.use MST-Prim(G, c, r) to compute a minimum spanning tree from r. //3.assume L to be the sequence of vertices visited in a preorder tree walk of T. //4.return the Hamiltonian cycle H that visits the vertices in the order L. public static void TravellingSalesman() { } //Producer-Consumer Problem - Important in multi threading - Also called as Bounded-Buffer problem //http://www.dcs.ed.ac.uk/home/adamd/essays/ex1.html single vs mutiple producer-consumer problem //https://www.cs.mtu.edu/~shene/NSF-3/e-Book/SEMA/VISUAL/VISUAL-sema-buffer.html //Related KeyWords = semaphore, threads, concurrent system, operating systems public static void ProducerConsumer() { } //Max flow and min cost flow //Vehicle Routing Problem //Job Shop problem //Given a collection of candidate numbers(C) and a target number(T), find all unique combinations in C where the candidate numbers sums to T. //Each number in C may only be used once in the combination. //Note: //All numbers (including target) will be positive integers. //The solution set must not contain duplicate combinations. //For example, given candidate set[10, 1, 2, 7, 6, 1, 5] and target 8, //A solution set is: //[ // [1, 7], // [1, 2, 5], // [2, 6], // [1, 1, 6] //] public static IList<IList<int>> CombinationSum2(int[] candidates, int target) { //Array.Sort(candidates); return null; } public static void Helper(int[] Candidates, int index, int target, ref List<List<int>> res, List<int> curSet) { if (target == 0) { res.Add(curSet); return; } if (target < 0) { return; } int prev = -1; for (int i = index; i < Candidates.Length; i++) { if (Candidates[i] != prev) { curSet.Add(Candidates[i]); Helper(Candidates, index + 1, target - Candidates[i], ref res, curSet); prev = Candidates[i]; } } } //put even numbers in even indexes and odd numbers in odd indexes //http://thenoisychannel.com/2011/08/08/retiring-a-great-interview-problem #region WordBreak 1 //word break //this returns true if you can split the given string in to two words given in a dicctionalry public static bool CanBreakWord(string s, HashSet<string> Dict) { for (int i = 1; i < s.Length; i++) { string prefix = s.Substring(0, i + 1); if (Dict.Contains(prefix)) { string suffix = s.Substring(i + 1, s.Length - i - 1); if (Dict.Contains(suffix)) { return true; } } } return false; } //this returns true if you can split the given string in more than one word with the given dictionary //complexity O(2^n) public static bool CanBreakIntoMultipleWords(string s, HashSet<string> Dict) { if (Dict.Contains(s)) return true; for (int i = 1; i < s.Length; i++) { string prefix = s.Substring(0, i); if (Dict.Contains(prefix)) { string suffix = s.Substring(i, s.Length - 1 - i); if (CanBreakIntoMultipleWords(suffix, Dict)) return true; } } return false; } //better way of above problem using dynamic programming O(n^2) public static bool WordBreak(string s, ISet<string> wordDict) { return Break(s, wordDict, new HashSet<string>()); } private static bool Break(string s, ISet<string> dict, HashSet<string> dp) { if (dict.Contains(s) || dp.Contains(s)) { return true; } for (int i = 1; i < s.Length; i++) { string prefix = s.Substring(0, i); if (dict.Contains(prefix)) { string suffix = s.Substring(i, s.Length - i); if (Break(suffix, dict, dp)) { dp.Add(suffix); return true; } } } return false; } #endregion public static void test() { bool[,] isvis = new bool[2, 3]; HashSet<string> s = new HashSet<string>(); List<string> l = s.ToList<string>(); Console.WriteLine("{0} {1}", isvis.GetLength(0), isvis.GetLength(1)); } #region Word Ladder 2 // Given two words(beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: //Only one letter can be changed at a time //Each intermediate word must exist in the word list //For example, //Given: //beginWord = "hit" //endWord = "cog" //wordList = ["hot","dot","dog","lot","log"] #endregion //Word Search 2 //Given a 2D board and a list of words from the dictionary, find all words in the board. //Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring.The same letter cell may not be used more than once in a word. //For example, //Given words = ["oath", "pea", "eat", "rain"] and board = //[ // ['o', 'a', 'a', 'n'], // ['e','t','a','e'], // ['i','h','k','r'], // ['i','f','l','v'] //] //Return["eat", "oath"]. public IList<string> FindWords(char[,] board, string[] words) { //see leetcode return null; } //http://www.allenlipeng47.com/blog/index.php/2016/03/15/palindrome-pairs/ //print all factors // private static void PrintFactors(int n, string curString) { } private static void PrintFactorsHelper(string currenExpression, int dividend, int prevFactor) { for (int factor = dividend - 1; factor >= 2; factor--) { if (dividend % factor == 0 && factor <= prevFactor) { } } } //1-D closest pair distance //given n points on one horizontal line ,find the closest pair points (1-D 1 dimensional) //since all points have same y we consider single dimension array whihc will represent the //x coordinated of n points //see https://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf private static int ClosesPairDistance(int[] N) { Array.Sort(N); return ClosesPair_Distance_Aux(N, 0, N.Length - 1); } private static int ClosesPair_Distance_Aux(int[] N, int p, int q) { if (p == q) return int.MaxValue; //return infinity if (p == q - 1) { return Math.Abs(N[p] - N[q]); } int mid = p + (q - p) / 2; int leftd = ClosesPair_Distance_Aux(N, p, mid); int rightd = ClosesPair_Distance_Aux(N, mid + 1, q); int mind = Math.Min(leftd, rightd); int x = Math.Min(Math.Abs(N[mid] - N[mid + 1]), Math.Abs(N[mid] - N[mid - 1])); return Math.Min(x, mind); } //closes pair given n pairs on a plane (2-D) //see https://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf public static bool CompareX(Point a, Point b) { if (a.x < b.x) return true; return false; } public static bool CompareY(Point a, Point b) { if (a.y < b.y) return true; return false; } public static double Distance(Point a, Point b) { return Math.Sqrt(Math.Pow(a.x - b.x, 2) + Math.Pow(a.y - b.y, 2)); } public static double ClosestPairIn2D(Point[] P) { if (P.Length == 1) return int.MaxValue; if (P.Length == 2) return Distance(P[0], P[1]); Point[] Px = new Point[P.Length]; Array.Copy(P, Px, P.Length); Point[] Py = new Point[P.Length]; Array.Copy(P, Py, P.Length); return 1.0; } public static double ClosesPair2D_Aux(Point[] Px, int xp, int xq, Point[] Py) { if (xq - xp + 1 <= 3) { return BruteForceClosestPair(Px, xp, xq); } int mid = xp + (xq - xp) / 2; double leftMin = ClosesPair2D_Aux(Px, xp, mid, Py); double rightMin = ClosesPair2D_Aux(Px, mid + 1, xq, Py); double delta = Math.Min(leftMin, rightMin); return 1.0; } public static double BruteForceClosestPair(Point[] A, int p, int q) { double totatMin = int.MaxValue; for (int i = p; i <= q; i++) { double curMin = int.MaxValue; for (int j = p; j <= q; j++) { if (j != i) { double curDist = Distance(A[i], A[j]); if (curDist < curMin) { curMin = curDist; } } } if (curMin < totatMin) { totatMin = curMin; } } return totatMin; } public static void EvenOddIndexSeparation(ref int[] A) { int len = A.Length; if (len < 2) return; int evenIndex = 0; int oddIndex = 1; while (evenIndex < len && oddIndex < len) { while (evenIndex < len && A[evenIndex] % 2 == 0) { evenIndex += 2; } while (oddIndex < len && A[oddIndex] % 2 != 0) { oddIndex += 2; } if (evenIndex >= len || oddIndex >= len) { return; } else { int t = A[evenIndex]; A[evenIndex] = A[oddIndex]; A[oddIndex] = t; } } } public static void ReverseWords(StringBuilder sb, int p, int q) { int i = p - 1; int j = p; while (j < sb.Length && i < sb.Length) { while (j < sb.Length && sb[j] != ' ') { j++; } if (j == sb.Length) break; ReverseString(ref sb, i + 1, j - i - 1); i = j; j++; } ReverseString(ref sb, i + 1, j - i - 1); ReverseString(ref sb, 0, sb.Length - 1); } public static void ReverseString(ref StringBuilder s, int p, int q) { while (p < q) { char c = s[p]; s[p] = s[q]; s[q] = c; p++; q--; } } //Iterate through K dimensional array //search for pattern - Brute force //O(mn) public static bool SearchPattern(string s, string p) { if (p.Length > s.Length) return false; for (int i = 0; i < s.Length - p.Length - 2; i++) { //compare s[i...i+s.Length-1] with p[0....p.Length-1] if (AreStringsSame(s, i, i + s.Length - 1, p, 0, p.Length - 1)) return true; } return false; } public static bool AreStringsSame(string s, int slow, int shigh, string p, int plow, int phigh) { int len1 = shigh - slow + 1; int len2 = phigh - plow + 1; if (len1 != len2) return false; while (slow <= shigh && plow <= phigh) { if (s[slow] != p[plow]) return false; slow++; plow++; } return true; } //Given two sorted arrays find the UNION and intersections of elements in them //Hint : Merge from MergeSort //find the element whihc occures more than n/2 times //hint bst //struct bst //{ int n; int count; bst left; bst right; } //Longest increasing path in a matrix //Count primes less than n // #endregion #region Facebook Practice public static void Separate012(ref int[] A) { int i = -1; int j = 0; int k = A.Length; while (j < k) { if (A[j] == 0) { swap1(ref A, i + 1, j); i++; j++; } else if (A[j] == 1) { j++; } else { swap1(ref A, j, k - 1); k--; } } } public static void swap1(ref int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } #endregion #region Amazon Practice public static void Separate_012(ref int[] A) { int i = -1; int j = 0; int k = A.Length; while (j < k) { if (A[j] == 0) { Swap_1(ref A, i + 1, j); i++; j++; } else if (A[i] == 2) { Swap_1(ref A, k - 1, j); k--; } else { j++; } } } public static void Swap_1(ref int[] A, int i, int j) { int t = A[i]; A[i] = A[j]; A[j] = t; } //course schedule //is it possible to come up with a schedule //[0,1] => 0 needs 1 public static bool IsSchedulePossible(int n, int[,] prereq) { if (n == 0) return true; Dictionary<int, List<int>> Map = new Dictionary<int, List<int>>(); BuildGraph(ref Map, prereq); int[] color = new int[n]; //0 - white 1-grey 2 - black for (int i = 0; i < n; i++) { if (color[i] == 0) { bool hasCycle = Visit(i, Map, ref color); if (hasCycle) return false; } } return true; } public static bool Visit(int i,Dictionary<int,List<int>> Map,ref int[] color) { color[i] = 1; List<int> adj = null; if (Map.ContainsKey(i)) { adj = Map[i]; } if (adj == null) { color[i] = 2; return false; } foreach (int adjacent in adj) { if(color[adjacent]==0) { Visit(adjacent, Map, ref color); } if (color[adjacent] == 1) { return true; } } color[i] = 2; return false; } public static void BuildGraph(ref Dictionary<int, List<int>> Map, int[,] prereq) { int m = prereq.GetLength(0); for (int i = 0; i < m; i++) { int b = prereq[i, 0]; int a = prereq[i, 1]; //a->b if(Map.ContainsKey(a)) { Map[a].Add(b); } else { Map.Add(a, new List<int>()); Map[a].Add(b); } } } #endregion } public struct Point { public int x; public int y; } public struct Range { public int left; public int right; } public static class Sorting { //SIBQMBRH /// <summary> /// Complexity is O(n^2) /// </summary> /// <param name="A"></param> public static void SelectionSort(ref int[] A) { for (int i = 0; i < A.Length - 1; i++) { int smallest = i; for (int j = i + 1; j < A.Length; j++) { if (A[j] < A[smallest]) { smallest = j; } } InterchangeInArray(ref A, smallest, i); } } public static void InterchangeInArray(ref int[] A, int first, int second) { int temp = A[first]; A[first] = A[second]; A[second] = temp; } /// <summary> /// Best case: Already Sorted in right order - O(n) /// Avg Case: O(n^2) /// Worst Case: O(n^2) Reveresly sorted /// </summary> /// <param name="A"></param> /// <param name="p"></param> /// <param name="q"></param> public static void InsertionSort(ref int[] A, int p, int q) { for (int i = p + 1; i <= q; i++) { int j = i - 1; int k = A[i]; while (j >= 0 && A[j] > k) { A[j + 1] = A[j]; j--; } A[j + 1] = k; } } /// <summary> /// https://www.khanacademy.org/computing/computer-science/algorithms/quick-sort/a/analysis-of-quicksort /// Best Case: O(nlogn) /// Avg Case: O(nlogn) /// Worst Case: O(n^2) /// </summary> /// <param name="A"></param> /// <param name="p"></param> /// <param name="q"></param> public static void QuickSort(ref int[] A, int p, int q) { if (p < q) { int r = Partition(ref A, p, q); QuickSort(ref A, p, r - 1); QuickSort(ref A, r + 1, q); } } public static int Partition(ref int[] A, int p, int q) { int pivot = A[q]; int i = p; int j = i - 1; while (i < q) { if (A[i] <= pivot) { InterchangeInArray(ref A, j + 1, i); j++; } i++; } A[q] = A[j + 1]; A[j + 1] = pivot; return j + 1; } public static void MergeSort(ref int[] A, int p, int q) { if (p < q) { int r = p + (q - p) / 2; MergeSort(ref A, p, r); MergeSort(ref A, r + 1, q); Merge(ref A, p, r, q); } } public static void Merge(ref int[] A, int p, int r, int q) { int l1 = r - p + 1; int l2 = q - r; int[] left = new int[l1]; int[] right = new int[l2]; for (int i1 = 0; i1 < l1; i1++) { left[i1] = A[p + i1]; } for (int j1 = 0; j1 < l2; j1++) { right[j1] = A[r + 1 + j1]; } int i = 0; int j = 0; int k = p; while (i < l1 && j < l2) { if (left[i] <= right[j]) { A[k] = left[i]; i++; } else { A[k] = right[j]; j++; } k++; } while (i < l1) { A[k] = left[i]; i++; k++; } while (j < l2) { A[k] = right[j]; j++; k++; } } public static void CountingSort(ref int[] A) { int[] c = new int[10]; for (int i = 0; i < A.Length; i++) { c[A[i]]++; } for (int i = 1; i < c.Length; i++) { c[i] = c[i - 1] + c[i]; } for (int i = c.Length - 1; i >= 0; i--) { while (c[i] > 0) { A[c[i] - 1] = i; c[i]--; } } } public static void ShellSort(ref int[] A) { int k = A.Length / 2; while (k > 0) { for (int i = 0; (i + k) < A.Length; i++) { if (A[i] > A[i + k]) { int n = A[i]; A[i] = A[i + k]; A[i + k] = n; } } k--; } } //HeapSort See Heap. //IsAnyNumberRepeated //FOur methods //1 - O(n^2) brute force search //2 - O(nlogn) sorting //3 - O(n) Hash O(n) Memory too //4 - O(n) - Only if numbers in array are in range of (0,n) /// <summary> /// O(n^2) in all cases /// </summary> /// <param name="A"></param> /// <param name="lowIndex"></param> /// <param name="highIndex"></param> /// <returns></returns> public static bool? IsAnyNumberRepeated(int[] A, int lowIndex, int highIndex) { if (lowIndex > highIndex) return null; if (lowIndex < 0 || highIndex >= A.Length) return null; for (int i = lowIndex; i < highIndex; i++) { for (int j = i + 1; j <= highIndex; j++) { if (A[i] == A[j]) return true; } } return false; } /// <summary> /// O(nLogn) /// </summary> /// <param name="A"></param> /// <param name="lowIndex"></param> /// <param name="highIndex"></param> /// <returns></returns> public static bool? IsAnyNumberRepeated1(int[] A, int lowIndex, int highIndex) { if (highIndex < lowIndex) return null; if (lowIndex < 0 || highIndex >= A.Length) return null; QuickSort(ref A, lowIndex, highIndex); for (int i = lowIndex; i < highIndex; i++) { if (A[i] == A[i + 1]) return true; } return false; } public static bool? IsAnyNumberRepeated2(int[] A, int lowIndex, int highIndex) { if (highIndex < lowIndex) return null; if (lowIndex < 0 || highIndex >= A.Length) return null; Dictionary<int, bool> d = new Dictionary<int, bool>(); for (int i = lowIndex; i <= highIndex; i++) { if (d.ContainsKey(A[i])) return true; d.Add(A[i], true); } return false; } public static bool? IsAnyNumberRepeated3(int[] A) { int n = A.Length; for (int i = 0; i < n; i++) { int temp = Math.Abs(A[i]); if (temp <= 0 || temp >= n) return null; //Meaning invalid input for this algorithm. if (A[temp] < 0) return true; A[temp] = A[temp] * (-1); } return false; } //A[0----n-1] represent votes of n people , tell who won //which number repeated maximum number of times is another way to put this question //O(n^2) public static int MaxRepeatedNumber1(int[] A) { int maxCount = 0; int maxCountNumber = -1; for (int i = 0; i < A.Length - 1; i++) { int currentNum = A[i]; int currentCount = 1; for (int j = i + 1; j <= A.Length - 1; j++) { if (A[j] == currentNum) currentCount++; } if (currentCount > maxCount) { maxCount = currentCount; maxCountNumber = i; } } if (maxCountNumber != -1) return A[maxCountNumber]; return maxCountNumber; } //O(nlogn) public static int? MaxRepeatedNumber2(int[] A) { return null; } public static int? MaxRepeatedNumber3(int[] A) { if (A.Length == 0) return null; Dictionary<int, int> d = new Dictionary<int, int>(); for (int i = 0; i < A.Length; i++) { if (d.ContainsKey(A[i])) { d[A[i]]++; } else { d.Add(A[i], 1); } } //find the key with max value. int maxKey = d.FirstOrDefault(x => x.Value == d.Values.Max()).Key; return maxKey; } //all numbers in array should be in rage [0,n) public static int? MaxRepeatedNumber4(int[] A) { if (A.Length == 0) return null; int len = A.Length; for (int i = 0; i < A.Length; i++) { int n = A[i] % len; A[n] = A[n] + len; } int maxTimes = 0; int maxNum = -1; for (int i = 0; i < A.Length; i++) { int q = A[i] / len; int r = A[i] % len; if (q > maxTimes) { maxTimes = q; maxNum = r; } } return maxNum; } //a+b=k a,b belong to arrays A and B respectively //O(nLog n) public static bool IsThereAplusBequalsK(int[] A, int[] B, int k) { QuickSort(ref A, 0, A.Length - 1); foreach (int b in B) { if (BinarySearch(A, 0, A.Length - 1, (k - b))) { return true; } } return false; } //test cases for binary search public static void TestBinarySearch() { //Console.WriteLine("Expected - Actual"); //Console.WriteLine("{0} - {1}",false, bt(new int[] { 1,2,3,4,5},0)); //Console.WriteLine("{0} - {1}", false, bt(new int[] { 1, 2, 3, 4, 5 }, 6)); //Console.WriteLine("{0} - {1}", false, bt(new int[] { 1, 2, 3, 4, 5 }, 3)); //Console.WriteLine("{0} - {1}", false, bt(new int[] { 1, 2, 3, 4, 5 }, 2)); } public static bool bt(int[] A, int k) { return BinarySearch(A, 0, A.Length - 1, k); } //O(log n) public static bool BinarySearch(int[] A, int p, int q, int k) { if (p <= q) { int mid = p + (q - p) / 2; if (A[mid] == k) return true; if (A[mid] < k) return BinarySearch(A, p, mid - 1, k); return BinarySearch(A, mid + 1, q, k); } return false; } //a+b+c=k //(n^2 Log n) public static bool IsThereAplusBplusCequalsK(int[] A, int[] B, int[] C, int k) { foreach (int a in A) { if (IsThereAplusBequalsK(B, C, (k - a))) { return true; } } return false; } //Merge K sorted lists //O(nk) // where n is total number while k is size of each list. public static List<int> MergeKLists(List<List<int>> l) { if (l.Count == 0) return null; if (l.Count == 1) return l[0]; int n = l.Count; List<int> first = l[n - 1]; List<int> second = l[n - 2]; l.RemoveAt(n - 1); l[n - 2] = Merge2Lists(first, second); return MergeKLists(l); } public static List<int> Merge2Lists(List<int> first, List<int> second) { if (first == null && second == null) return null; if (first == null) return second; if (second == null) return first; List<int> result = new List<int>(); int i = 0; //first int j = 0; //second //int k = 0; //result while (i < first.Count && j < second.Count) { if (first[i] <= second[j]) { result.Add(first[i]); i++; } else { result.Add(second[j]); j++; } } while (i < first.Count) { result.Add(first[i]); i++; } while (j < second.Count) { result.Add(second[j]); j++; } return result; } //MErge K lists (linked lists) which are already sorted //Solved in leetcode //public MyLinkedListNode MergeKLists(ListNode[] lists) //{ // if (lists == null) return null; // if (lists.Length == 0) return null; // if (lists.Length == 1) return lists[0]; // return MergeKLists1(lists, lists.Length); //} //public ListNode MergeKLists1(ListNode[] lists, int n) //{ // if (lists == null) return null; // if (n == 0) return null; // if (n == 1) return lists[0]; // ListNode result = Merge2Lists(lists[n - 1], lists[n - 2]); // lists[n - 1] = null; // lists[n - 2] = result; // return MergeKLists1(lists, n - 1); //} //public ListNode Merge2Lists(ListNode first, ListNode second) //{ // if (first == null) return second; // if (second == null) return first; // ListNode result = null; // ListNode resultTail = null; // ListNode temp = null; // while (first != null && second != null) // { // if (first.val <= second.val) // { // temp = first; // first = first.next; // temp.next = null; // } // else // { // temp = second; // second = second.next; // temp.next = null; // } // Insert(ref result, ref resultTail, ref temp); // } // while (first != null) // { // temp = first; // first = first.next; // temp.next = null; // Insert(ref result, ref resultTail, ref temp); // } // while (second != null) // { // temp = second; // second = second.next; // temp.next = null; // Insert(ref result, ref resultTail, ref temp); // } // return result; //} //public void Insert(ref ListNode result, ref ListNode resultTail, ref ListNode temp) //{ // if (result == null && resultTail == null) // { // result = temp; // resultTail = temp; // } // else // { // resultTail.next = temp; // resultTail = resultTail.next; // } //} } public static class Searching { /// <summary> /// Brute force O(n^2) /// </summary> public static bool IsDUplicatePresent1(int[] A) { for (int i = 0; i < A.Length - 1; i++) { int n = A[i]; for (int j = i + 1; j < A.Length; j++) { if (n == A[j]) return true; } } return false; } /// <summary> /// Using sort - O(n^2) /// </summary> public static bool IsDuplicatePresent2(int[] A) { Sorting.QuickSort(ref A, 0, A.Length - 1); for (int i = 1; i < A.Length; i++) { if (A[i - 1] == A[i]) return true; } return false; } /// <summary> /// /// </summary> public static bool IsDuplicatePresent3(int[] A) { Dictionary<int, bool> d = new Dictionary<int, bool>(); for (int i = 0; i < A.Length; i++) { if (d.ContainsKey(A[i])) { return true; } else { d.Add(A[i], true); } } return false; } /// <summary> /// negation technique /// n >0 && n <=A.length-1 /// </summary> public static bool IsDupllicatePresent4(int[] A) { foreach (int n in A) { if (A[Math.Abs(n)] < 0) return false; else { A[Math.Abs(n)] = A[Math.Abs(n)] * (-1); } } return false; } /// <summary> /// Brute force - O(n^2) /// </summary> public static int MostRepeatedNum1(int[] A) { int MaxCount = 0; int MaxNum = -1; for (int i = 0; i < A.Length - 1; i++) { int count = 1; int n = A[i]; for (int j = i + 1; j < A.Length; j++) { if (A[j] == n) count++; } if (count > MaxCount) { MaxCount = count; MaxNum = n; } } return MaxNum; } /// <summary> /// O(n) /// mem - O(k) where k is the number values that can occur in a given place of array /// </summary> public static int MostRepeatedNum2(int[] A) { Dictionary<int, int> d = new Dictionary<int, int>(); foreach (int n in A) { if (d.ContainsKey(n)) { d[n]++; } else { d.Add(n, 1); } } int keywithmaxval = d.FirstOrDefault(x => x.Value == d.Values.Max()).Key; return keywithmaxval; } /// <summary> /// using sorting O(n logn) /// </summary> /// <param name="A"></param> /// <returns></returns> public static int MostRepeatedNum3(int[] A) { Sorting.QuickSort(ref A, 0, A.Length - 1); int maxCount = 0; int maxNum = -1; int i = 0; int n = A[i]; int currCount = 1; while (i < A.Length - 1) { if (A[i + 1] == n) { currCount++; i++; } else { if (currCount > maxCount) { maxCount = currCount; maxNum = n; } i++; n = A[i]; } } return maxNum; } /// <summary> /// negation thnique /// valid incase if n E [0,A.length-1] /// </summary> /// <param name="A"></param> /// <returns></returns> public static int? MostRepeatedNum4(int[] A) { int len = A.Length; if (len == 0) return null; for (int i = 0; i < A.Length; i++) { int n = (A[i]) % len; if (n < 0 || n >= A.Length) return null; //Implies invalid data A[n] = A[n] + len; } int max = 0; int maxnum = -1; for (int i = 0; i < A.Length; i++) { int cur = (A[i] / len); if (cur > max) { max = cur; maxnum = i; } } return maxnum; } /// <summary> /// First Repeating number - brute force /// </summary> public static int FirstRepeatingNum1(int[] A) { return 0; } /// <summary> /// Run - O(n + k) /// Mem - O(k) /// </summary> /// <param name="A"></param> /// <returns></returns> public static int FirstRepeatingNum2(int[] A) { Dictionary<int, int> d = new Dictionary<int, int>(); for (int i = 0; i < A.Length; i++) { if (d.ContainsKey(A[i])) { if (d[A[i]] > 0) { d[A[i]] = d[A[i]] * (-1); } } else { d.Add(A[i], (i + 1)); } } int val = -999; foreach (int key in d.Keys) { if (d[key] < 0 && d[key] > val) { val = d[key]; } } return A[Math.Abs(val) - 1]; } /// <summary> /// O(n) - based on formula /// </summary> /// <param name="A"></param> /// <returns></returns> public static int FindMissingNum1(int[] A) { int n = A.Length + 1; int sum = 0; foreach (int i in A) { sum += i; } int actualSum = n * (n + 1) / 2; return actualSum - sum; } /// <summary> /// O(n) XOR technique /// </summary> /// <param name="A"></param> /// <returns></returns> public static int FindMissingNum2(int[] A) { int n = A.Length + 1; int allXor = 0; int currentXor = 0; foreach (int i in A) { allXor ^= i; } for (int i = 1; i <= n; i++) { currentXor ^= i; } return currentXor ^ allXor; } //n+2 two are repeated twice find them public static void FindTheRepeatingTwo(int[] A) { int n = A.Length - 2; if (n <= 0) return; int XorY = 0; for (int i = 1; i <= n; i++) { XorY = XorY ^ i; } foreach (int k in A) { XorY ^= k; } int rightOne = (~(XorY - 1)) & XorY; int withOnes = 0; foreach (int k in A) { if ((rightOne & k) != 0) withOnes ^= k; } int x = withOnes; int y = withOnes ^ XorY; Console.WriteLine("{0} {1}", x, y); } //in an array all elements come thrice except for one whihc comes only once, find //that number public static int FindOnceInThriceArray(int[] A) { int first = 0; int second = 0; for (int i = 0; i < A.Length; i++) { second = second | (first & A[i]); first = first ^ A[i]; int mask = first & second; mask = ~mask; first = first & (mask); second = second & (mask); } return first; } //a+b ~ 0 //input is sorted array public static int SumClosesToZero(int[] A, int p, int q, int prevsum) { if (p < q) { int sum = A[p] + A[q]; if (sum == 0) return 0; else { int prevdiff = Math.Abs(prevsum - 0); int currdiff = Math.Abs(sum - 0); if (currdiff < prevdiff) { prevsum = sum; } if (sum < 0) { return SumClosesToZero(A, p + 1, q, prevsum); } else { return SumClosesToZero(A, p, q - 1, prevsum); } } } return prevsum; } //a+b+c ~ 0 //input is sorted array public static int ThreeSumClosesToZero(int[] A, int p, int q) { int prevSum = int.MaxValue; for (int i = 0; i < q - 1; i++) { int sum = SumClosesToZero(A, i + 1, q, int.MaxValue); sum = sum + A[i]; if (sum == 0) return 0; if (Math.Abs(sum) < Math.Abs(prevSum)) prevSum = sum; } return prevSum; } //a +b ~ k //sum of two numbers closest to K //input is sorted array public static int TwoSumClosestToK(int[] A, int p, int q, int k, int prevSum) { if (p < q) { int sum = A[p] + A[q]; if (sum == k) { return k; } else { int currDiff = Math.Abs(sum - k); int prevDiff = Math.Abs(prevSum - k); if (currDiff < prevDiff) { prevSum = sum; } if (sum < k) { return TwoSumClosestToK(A, p + 1, q, k, prevSum); } else { return TwoSumClosestToK(A, p, q - 1, k, prevSum); } } } return prevSum; } //a + b + c ~ k //sum of three numbers closest to k public static int ThreeSumClosestToK(int[] A, int p, int q, int k) { int prevSum = int.MaxValue; for (int i = p; i < q - 1; i++) { int sum = TwoSumClosestToK(A, i + 1, q, k - A[i], int.MaxValue); sum = sum + A[i]; if (sum == k) { return k; } int curDiff = Math.Abs(sum - k); int prevDiff = Math.Abs(prevSum - k); if (curDiff < prevDiff) { prevSum = sum; } } return prevSum; } /// <summary> /// A[i] + A[j] = k --> Sorting method /// </summary> public static void FindTwoWhoseSumIsK(int[] A, int p, int q, int k) { Sorting.QuickSort(ref A, 0, A.Length - 1); int x = -99; int y = -99; bool res = __FindTwoWhoseSumIsK(A, 0, A.Length - 1, k, out x, out y); } public static bool __FindTwoWhoseSumIsK(int[] A, int p, int q, int k, out int one, out int two) { if (p < q) { int s = A[p] + A[q]; if (s == k) { //Console.WriteLine("{0} {1}",A[p],A[q]); one = A[p]; two = A[q]; return true; } else if (s < k) { return __FindTwoWhoseSumIsK(A, p + 1, q, k, out one, out two); } else { return __FindTwoWhoseSumIsK(A, p, q - 1, k, out one, out two); } } one = -99; two = -99; return false; } /// <summary> /// A[i] + A[j] = k -> hashing method /// </summary> public static void FindTwoWhoseSumIsK2(int[] A, int k) { Dictionary<int, bool> hash = new Dictionary<int, bool>(); foreach (int n in A) { if (hash.ContainsKey(k - n)) { Console.WriteLine("{0} + {1} = {2}", n, (k - n), k); return; } else { if (!hash.ContainsKey(n)) { hash.Add(n, true); } } } } /// <summary>C:\Users\sindamnataraj\Documents\Visual Studio 2013\Projects\2016 Practice\2016 Practice\LinkedList.cs /// A[i]^2 + A[j]^2 = k^2 /// </summary> public static void FindTwoWhoseSquareSumIsK(int[] A, int k) { //square each number and use the sorting for (int i = 0; i < A.Length; i++) { A[i] *= A[i]; } FindTwoWhoseSumIsK(A, 0, A.Length - 1, (k * k)); } //given an array find sum closest to zero //array has both negative and positive numbers // O(n Log n) public static void SumClosestToZero(int[] A) { Sorting.QuickSort(ref A, 0, A.Length - 1); int sum = 0; int p = -1; int q = -1; __SumClosestToZero(A, 0, A.Length - 1, out sum, out p, out q); Console.WriteLine("{0} + {1} = {2}", A[p], A[q], sum); } public static void __SumClosestToZero(int[] A, int p, int q, out int finalsum, out int finalp, out int finalq) { int low = p; int high = q; finalsum = int.MaxValue; finalp = -1; finalq = -1; while (low < high) { int sum = A[low] + A[high]; if (sum == 0) { //Console.WriteLine("closest is 0"); finalsum = 0; finalp = low; finalq = high; return; } else { if (Math.Abs(sum) < finalsum) { finalsum = Math.Abs(sum); finalp = low; finalq = high; } if (sum < 0) { low++; } else { high--; } } } //Console.WriteLine("{0} + {1} = {2}", A[finalp], A[finalq], finalsum); } //x +y +z = k //given and array and K find three numbers in array whose sum is k public static void FindThreeSumIsK(int[] A, int k) { Sorting.QuickSort(ref A, 0, A.Length - 1); int x = 0; int y = 0; for (int i = 0; i < A.Length - 2; i++) { if (__FindTwoWhoseSumIsK(A, i + 1, A.Length - 1, (k - A[i]), out x, out y)) { Console.WriteLine("{0} + {1} + {2} = {3}", A[i], x, y, k); } } } //sum of three closest to zero public static void SumThreeClosestToZero(int[] A) { Sorting.QuickSort(ref A, 0, A.Length - 1); int superFinal = int.MaxValue; int finalsum = -999; int x = 0; int y = 0; for (int i = 0; i < A.Length - 2; i++) { __SumClosestToZero(A, i + 1, A.Length - 1, out finalsum, out x, out y); if (finalsum + A[i] == 0) { Console.WriteLine("{0} + {1} + {2} = {3}", A[i], A[x], A[y], finalsum + A[i]); return; } else { if (Math.Abs(finalsum + A[i]) < superFinal) { superFinal = finalsum; } } } Console.WriteLine(superFinal); } //find K such that A[0]..A[k] is increasing sequence and A[k]...A[n] is decreasing sequence public static int? FindPivotK(int[] A, int p, int q) { if (p <= q) { if (p == q) { return p; } else if (p == (q - 1)) { if (A[p] > A[q]) { return p; } else { return q; } } else { int mid = p + (q - p) / 2; if (A[mid] > A[mid + 1] && A[mid] > A[mid - 1]) { return mid; } else if (A[mid] < A[mid + 1] && A[mid] > A[mid - 1]) { return FindPivotK(A, mid + 1, q); } else { return FindPivotK(A, p, mid - 1); } } } return null; } //find right most 1 in 111111111111111111000000000000000000 public static int FindRightMost1(int[] A, int p, int q) { if (p == q) { if (A[p] == 1) return p; return -1; } if (p == q - 1) { if (A[p] == 0) return -1; if (A[q] == 1) return q; return p; } if (p < q) { int r = p + (q - p) / 2; if (A[r] == 1 && A[r + 1] == 0) { return r; } else if (A[r] == 1 && A[r + 1] == 1) { return FindRightMost1(A, r + 1, q); } else { return FindRightMost1(A, p, r - 1); } } return -1; } //BInary Search on sorted array = O(log n) public static bool BinarySearch(int[] A, int p, int q, int k) { if (p == q) { if (A[p] == k) return true; } if (p < q) { int r = p + (q - p) / 2; if (A[r] == k) return true; else if (k < A[r]) { return BinarySearch(A, p, r - 1, k); } else { return BinarySearch(A, r + 1, q, k); } } return false; } //given an array sorted unknown times find a given number k public static int PivotInRotated(int[] A, int p, int q) { if (p == q) { return p; } if (p == q - 1) { if (A[p] > A[q]) return p; return q; } if (p < q) { int mid = p + (q - p) / 2; if (A[mid + 1] < A[mid] && A[mid - 1] < A[mid]) { return mid; } else if (A[mid + 1] > A[mid] && A[mid - 1] > A[mid]) { return mid - 1; } else if (A[p] > A[mid] && A[mid] < A[q]) { return PivotInRotated(A, p, mid - 1); } else { return PivotInRotated(A, mid + 1, q); } } return -1; } //search in rotated array //O(log n) //first find the highest numbers index and then do binary search public static bool SearchInRotated(int[] A, int p, int q, int k) { int pivotIndex = PivotInRotated(A, p, q); if (pivotIndex != -1) { if (k <= A[pivotIndex] && k >= A[p]) { return BinarySearch(A, p, pivotIndex, k); } else { return BinarySearch(A, pivotIndex, q, k); } } return false; } //find median of two sorted arrays. public static void FindMedian(int[] A, int alow, int ahigh, int[] B, int blow, int bhigh) { if (ahigh - alow + 1 + bhigh - blow + 1 <= 3) { int l = ahigh - alow + 1 + bhigh - blow + 1; int[] C = new int[l]; int i = 0; int j = alow; int k = blow; while (i < C.Length) { while (j <= ahigh) { C[i] = A[j]; i++; j++; } while (k <= bhigh) { C[i] = B[k]; i++; k++; } } Sorting.QuickSort(ref C, 0, C.Length - 1); Console.WriteLine(C[C.Length / 2]); } else { int med1 = alow + (ahigh - alow) / 2; int med2 = blow + (bhigh - blow) / 2; if (A[med1] <= B[med2]) { FindMedian(A, med1, ahigh, B, blow, med2); } else { FindMedian(A, alow, med1, B, med2, bhigh); } } } //given sorted array with duplicates search for first occurence of a number public static int FirstOccuerence(int[] A, int p, int q, int k) { if (p == q) { if (A[p] == k) return p; return -1; } if (p < q) { int mid = p + (q - p) / 2; if (A[mid] == k) { if (A[mid - 1] != k) return mid; return FirstOccuerence(A, p, mid - 1, k); } else if (k < A[mid]) { return FirstOccuerence(A, p, mid - 1, k); } else { return FirstOccuerence(A, mid + 1, q, k); } } return -1; } //given sorted array with duplicates search for last occurencee of a number public static int LastOccurence(int[] A, int p, int q, int k) { if (p == q) { if (A[p] == k) return p; return -1; } if (p < q) { int mid = p + (q - p) / 2; if (A[mid] == k) { if (A[mid + 1] != k) return mid; return LastOccurence(A, mid + 1, q, k); } else if (k < A[mid]) { return LastOccurence(A, mid + 1, q, k); } else { return LastOccurence(A, p, mid - 1, k); } } return -1; } //given an array of sorted numbers with possbile duplicates find the number of times a number is repaeadted public static void NUmberOfRepeatitions(int[] A, int k) { int first = FirstOccuerence(A, 0, A.Length - 1, k); int last = LastOccurence(A, 0, A.Length - 1, k); if (first == -1 || last == -1) { Console.WriteLine("{0} is not present", k); } else { int c = last - first + 1; Console.WriteLine("{0} is repeated {1} times.", k, c); } } //separate odd and even numbers //input : 1234567 //output: 2461357 public static void SeparateEvenOdd(ref int[] A, int p, int q) { int i = p - 1; int j = p; while (j <= q) { if (IsEven(A[j])) { Interchange(ref A, j, i + 1); i++; } j++; } } public static void Interchange(ref int[] A, int p, int q) { int t = A[p]; A[p] = A[q]; A[q] = t; } public static bool IsEven(int n) { if (n % 2 == 0) return true; return false; } //given array of 0s and 1s separate them public static void SeprateOs1s(ref int[] A, int p, int q) { int i = p - 1; int j = p; while (j < A.Length) { if (A[j] == 0) { Interchange(ref A, i + 1, j); i++; } j++; } } //input:01200011221210 //output: 0000111122222 public static void SeparateTriple(ref int[] A, int p, int q) { int i = p - 1; int j = p; int k = q + 1; while (j < k) { if (A[j] == 0) { Interchange(ref A, i + 1, j); i++; j++; } else if (A[j] == 2) { Interchange(ref A, k - 1, j); k--; } else { j++; } } } //Given a sequence of nonnegative integers A and an integer T, return whether there is a* continuous sequence* of A that sums up to exactly T //[23, 5, 4, 7, 2, 11], 20. Return True because 7 + 2 + 11 = 20 public static bool IsThere_Sequence_With_Given_Sum(int[] A, int T) { if (A.Length == 0) return false; if (T == 0) return true; int i = 0; int j = 0; int sum = A[0]; while (i <= j && i < A.Length && j < A.Length) { if (sum == T) { return true; } else if (sum < T) { j++; sum = sum + A[j]; } else { sum = sum - A[i]; i++; sum = sum + A[i]; if (j < i) { j = i; } } } if (sum == T) return true; return false; } } public static class Selection { //O(n) public static int FindLargest1(int[] A, int p, int q) { int max = A[p]; int j = p + 1; while (j <= q) { if (A[j] > max) { max = A[j]; } } return max; } //O(n) public static int FindSmallest1(int[] A, int p, int q) { int min = A[p]; int j = p + 1; while (j <= q) { if (A[j] < min) { min = A[j]; } } return min; } public static int KthElement(int[] A, int p, int q, int k) { if (p < q) { int r = Partition(ref A, p, q); if (r == k) { return A[r]; } else if (k < r) { return KthElement(A, p, r - 1, k); } else { return KthElement(A, r + 1, q, k); } } return -9999; } public static int Partition(ref int[] A, int p, int q) { int n = A[q]; int i = p; int j = i - 1; while (i < q) { if (A[i] <= n) { Searching.Interchange(ref A, i, j + 1); j++; } i++; } A[q] = A[j + 1]; A[j + 1] = n; return j + 1; } public static int RandomizedPartition(ref int[] A, int p, int q) { //Debug.Assert(p >= 0 && q < A.Length && p <= q); //Random r = new Random(); //int index = r.Next(p, q); ////A[q] A[index] //int t = A[index]; //A[index] = A[q]; //A[q] = t; //return Partition(ref A, p, q); return -1; } } public static class StringProblems { public static string ReverseString(string s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < (sb.Length) / 2; i++) { InterchangeChars(ref sb, i, sb.Length - 1 - i); } return sb.ToString(); } //complexity: public static void Permute(StringBuilder sb, int p, int q) { if (p == q) { Console.WriteLine(sb.ToString()); return; } if (p < q) { for (int i = p; i <= q; i++) { InterchangeChars(ref sb, p, i); Permute(sb, p + 1, q); InterchangeChars(ref sb, i, p); } } } public static void permuteString(StringBuilder sb, int p, int q) { if (p == q) { Console.WriteLine(sb.ToString()); } else if (p < q) { for (int i = p; i <= q; i++) { InterchangeInSB(ref sb, p, i); permuteString(sb, p + 1, q); InterchangeInSB(ref sb, p, i); } } } public static void PermuteListOfWords(List<string> li, int p, int q) { if (p == q) { StringBuilder sb = new StringBuilder(); foreach (string s in li) { sb.Append(s); } Console.WriteLine(sb.ToString()); } else if (p < q) { for (int i = p; i <= q; i++) { //interchange list(i,p) InterchangeInList(ref li, p, i); PermuteListOfWords(li, p + 1, q); InterchangeInList(ref li, p, i); } } } //find permutations which are palindromes too public static void InterchangeChars(ref StringBuilder sb, int i, int j) { char c = sb[i]; sb[i] = sb[j]; sb[j] = c; } public static void InterchangeInList(ref List<string> li, int p, int q) { string temp = li[p]; li[p] = li[q]; li[q] = temp; } public static void InterchangeInSB(ref StringBuilder sb, int p, int q) { char temp = sb[p]; sb[p] = sb[q]; sb[q] = temp; } public static bool IsNumberPalindrome(int x) { long y = 0; long originalx = (long)x; originalx = Math.Abs(originalx); long xtemp = originalx; while (xtemp > 0) { int rem = (int)(xtemp % 10); xtemp = xtemp - rem; xtemp = xtemp / 10; y = (y * 10) + rem; } if (y == originalx) return true; return false; } //is a given sentence palindrome iff spaces are not considered public static bool IsSentencePalindrome(string s) { if (s.Length == 0 || s.Length == 1) return true; int low = 0; int high = s.Length - 1; while (low < high) { if (s[low] == ' ' || s[high] == ' ') { if (s[low] == ' ') { low++; } else { high--; } } else { if (s[low] != s[high]) { return false; } else { low++; high--; } } } return true; } //counting sort of string //written for lower case public static string CountingSort(string s) { StringBuilder ret = new StringBuilder(s); int[] c = new int[26]; foreach (char letter in s) { int asci = (int)letter; asci = asci - 97; c[asci]++; } for (int i = 1; i < c.Length; i++) { c[i] = c[i - 1] + c[i]; } for (int i = s.Length - 1; i >= 0; i--) { int asci = (int)s[i]; asci = asci - 97; ret[c[asci] - 1] = s[i]; c[asci]--; } return ret.ToString(); } //if given tow strings are anagrams //O(len1 + len2) public static bool AreAnagrams(string s1, string s2) { string s1Sorted = CountingSort(s1); string s2Sorted = CountingSort(s2); if (string.Equals(s1Sorted, s2Sorted)) return true; return false; } //are two strings isomorphic //"egg" & "add" public static bool AreIsomorphic(string s1, string s2) { Dictionary<char, char> d = new Dictionary<char, char>(); if (s1.Length != s2.Length) return true; if (s1.Length == 0 && s2.Length == 0) return true; int i = 0; while (i < s1.Length) { if (d.ContainsKey(s1[i])) { if (d[s1[i]] != s2[i]) { return false; } } else { if (d.ContainsValue(s2[i])) { char x1 = d.FirstOrDefault(x => x.Value == s2[i]).Key; if (x1 != s1[i]) { return false; } } else { d.Add(s1[i], s2[i]); } } i++; } return true; } //one string is reverse of the other public static bool ArePalindromes(string s1, string s2) { if (s1.Length != s2.Length) return false; if (s1.Length == 0 && s2.Length == 0) return true; string reverses1 = ReverseString(s1); if (string.Equals(reverses1, s2)) return true; return false; } //reverse words in a string public static void ReverseWords(ref StringBuilder sb, int p, int q) { Debug.Assert(p <= q && q < sb.Length && p >= 0); ReverseStringBuilder(ref sb, p, q); int i = p; while (i <= q && sb[i] == ' ') { i++; } int j = i; while (j <= q) { while (j <= q && sb[j] != ' ') { j++; } ReverseStringBuilder(ref sb, i, j - 1); while (j <= q && sb[j] == ' ') { j++; } i = j; } } //reverese auxiliary for stringbuilder public static void ReverseStringBuilder(ref StringBuilder sb, int p, int q) { Debug.Assert(p <= q && q < sb.Length && p >= 0); int mid = (q - p) / 2; for (int i = 0; i <= mid; i++) { InterchangeChars(ref sb, p + i, q - i); } } //reverse vowels of a string //aeiou //string to integer = atoi //valid parenthesis //() ((() //Complexity - O(s.length) public static bool IsValidParenthesis(string s) { Stack<char> stk = new Stack<char>(); foreach (char c in s) { if (c == '(') { stk.Push(c); } else { if (stk.Count == 0) return false; stk.Pop(); } } if (stk.Count == 0) return true; return false; } //Given a pattern and a string str, find if str follows the same pattern. //pattern = "abba", str = "dog cat cat dog" should return true. //pattern = "abba", str = "dog cat cat fish" should return false. //https://leetcode.com/problems/word-pattern/ public static bool WordPattern(string pattern, string str) { Dictionary<char, string> d = new Dictionary<char, string>(); int i = 0; //track pattern letters int j = 0; //track word start in str int k = j + 1; while (i < pattern.Length) { while (k < str.Length && str[k] != ' ') { k++; } string word = str.Substring(j, k - j); if (d.ContainsKey(pattern[i])) { if (d[pattern[i]] != word) { return false; } } else { char skey = d.FirstOrDefault(x => x.Value == word).Key; if (skey != '\0' && skey != pattern[i]) { return false; } d.Add(pattern[i], word); } j = k + 1; k++; i++; } return true; } //Given s = "leetcode", return "leotcede". public static string ReverseVowels(string s) { StringBuilder sb = new StringBuilder(s); int i = 0; int j = s.Length - 1; while (i <= j) { if (IsVowel(sb[i]) && IsVowel(sb[j])) { InterchangeChars(ref sb, i, j); i++; j--; } else { if (!IsVowel(s[i])) { i++; } if (!IsVowel(s[j])) { j--; } } } return sb.ToString(); } public static bool IsVowel(char c) { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return true; return false; } //given a string and a dictionary of words //see if the given string can be //split in to space separated wordsf //wordbreak problem public static void SeprateToWords(string s, HashSet<string> dict) { int i = 0; int j = 0; while (j <= s.Length - 1) { int l1 = j - i + 1; string left = s.Substring(i, l1); int l2 = s.Length - 1 - j; string right = (l2 != 0) ? s.Substring(j + 1, l2) : ""; } } //Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. //For example, //Given 1->2->3->3->4->4->5, return 1->2->5. //Given 1->1->1->2->3, return 2->3. //A message containing letters from A-Z is being encoded to numbers using the following mapping: //'A' -> 1 //'B' -> 2 // ... //'Z' -> 26 //Given an encoded message containing digits, determine the total number of ways to decode it. //For example, //Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). //The number of ways decoding "12" is 2. public static int Decode(string s, int p, int q) { if (p == q) return 1; int total = 0; if (p < q) { int c1 = int.Parse(s[p].ToString()); int c2 = int.Parse(s[p + 1].ToString()); int num = (c1 * 10) + c2; //int twoPossible = 0; if (num >= 1 && num <= 26) { total = total + Decode(s, p + 2, q); } total += Decode(s, p + 1, q); return total; } return 0; } } public static class DynamicProgramming { //Overlapping sub problems //Optimal Substructure // Dynamic Probblem = Recursion + Memory //Fibonnacci - Simple Recursion //Complexity = T(n) = T(n-1) + T(n-2) = public static int Fibonacci_Simple_Recursion(int n) { if (n <= 1) return 1; if (n == 2) return 2; return Fibonacci_Simple_Recursion(n - 1) + Fibonacci_Simple_Recursion(n - 2); } //Fibonacci - Dynamic Programming with Memoization(top down) - Memory table fiilled on demand , incase of //problem not all memory gaps are filled like in case of Fibo case. private static int[] Fibo = new int[100]; public static int Fibonacci_Dp_Memoization(int n) { if (Fibo[n] != 0) return Fibo[n]; if (n == 1) { Fibo[n] = 1; } else if (n == 2) { Fibo[n] = 2; } else { Fibo[n] = Fibonacci_Dp_Memoization(n - 1) + Fibonacci_Dp_Memoization(n - 2); } return Fibo[n]; } //Fibonacci - Dynamic Programming with Tabularization public static int Fibonacci_Dp_tabulation(int n) { if (n == 1 || n == 2) return n; int[] fib = new int[100]; fib[0] = 1; fib[1] = 2; for (int i = 2; i <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } return fib[n]; } //Factorial Recursion //complaxity: T(n) = T(n-1) + O(1) => O(n) public static int Factorial_Recursion(int n) { if (n <= 1) return 1; return Factorial_Recursion(n - 1) * n; } //Factorial Memoization //O(n) private static int[] Fact = new int[100]; public static int Factorial(int n) { if (Fact[n] != 0) return Fact[n]; if (n == 0) { Fact[n] = 1; return Fact[n]; } else { Fact[n] = Factorial(n - 1) * n; return Fact[n]; } } //Factorial Tabulization //O(n) public static int Factorial_Dp_Tabulation(int n) { int[] F = new int[100]; F[0] = 1; for (int i = 1; i <= n; i++) { F[i] = F[i - 1] * i; } return F[n]; } //Binomial coeffecient //C(n,k) = C(n-1,k-1) + C(n-1,k) //C(n,0) = C(n,n) = 1 // public static int BinomialCoeffecient(int n, int k) { return 0; } //longest common subsequence for two strings //X Y //O(mn) public static void LCS_String(string X, string Y) { int[,] LCS = new int[X.Length + 1, Y.Length + 1]; int[,] D = new int[X.Length, Y.Length]; //0 - cross //1 - up //2 -down for (int i = 0; i <= X.Length; i++) { LCS[i, 0] = 0; } for (int j = 0; j <= Y.Length; j++) { LCS[0, j] = 0; } for (int i = 1; i <= X.Length; i++) { for (int j = 1; j <= Y.Length; j++) { if (X[i - 1] == Y[j - 1]) { LCS[i, j] = LCS[i - 1, j - 1] + 1; D[i - 1, j - 1] = 3; } else if (LCS[i - 1, j] >= LCS[i, j - 1]) { LCS[i, j] = LCS[i - 1, j]; D[i - 1, j - 1] = 1; //up } else { LCS[i, j] = LCS[i, j - 1]; D[i - 1, j - 1] = 2; //left } } } StringBuilder sb = new StringBuilder(); int i1 = X.Length; int j1 = Y.Length; while (i1 > 0 && j1 > 0) { if (D[i1 - 1, j1 - 1] == 3) { sb.Append(X[i1 - 1]); i1--; j1--; } else if (D[i1 - 1, j1 - 1] == 2) { j1--; } else { i1--; } } string res = sb.ToString(); Console.WriteLine("LCS = {0} Length = {1}", StringProblems.ReverseString(res), LCS[X.Length, Y.Length]); string[] words = new string[10]; foreach (string word in words) { } } //longest common subsequence - for two arrays of integers public static void LCS_Integers(int[] A, int[] B) { int[,] C = new int[A.Length + 1, B.Length + 1]; int[,] S = new int[A.Length, B.Length]; for (int i = 0; i <= A.Length; i++) { C[i, 0] = 0; } for (int j = 0; j <= B.Length; j++) { C[0, j] = 0; } for (int i = 1; i <= A.Length; i++) { for (int j = 1; j <= B.Length; j++) { if (A[i - 1] == B[j - 1]) { C[i, j] = C[i - 1, j - 1] + 1; S[i - 1, j - 1] = 1; //across } else if (C[i - 1, j] >= C[i, j - 1]) { C[i, j] = C[i - 1, j]; S[i - 1, j - 1] = 2; //up } else { C[i, j] = C[i, j - 1]; S[i - 1, j - 1] = 3; //left } } } List<int> LCS = new List<int>(); int i1 = A.Length - 1; int j1 = B.Length - 1; while (i1 >= 0 && j1 >= 0) { if (S[i1, j1] == 1) { LCS.Add(A[i1]); i1--; j1--; } else if (S[i1, j1] == 2) { i1--; } else { j1--; } } LCS.Reverse(); foreach (int n in LCS) { Console.Write("{0} ", n); } Console.WriteLine(); Console.WriteLine("LCS Length = {0}", C[A.Length, B.Length]); } //maximum vlue continous subsequence public static void Max_Value_Continous_Subsequence(int[] A) { int[] M = new int[A.Length]; for (int i = 0; i < M.Length; i++) { if (i == 0) { M[i] = A[i]; } else { M[i] = Math.Max(M[i - 1] + A[i], A[i]); } } Console.WriteLine(M.Max()); } //maximum value no two contious subsequence // M[i] = Max(M[i-1],M[i-2]+A[i]) // // public static void Max_Value_Contigous_Subsequence_NoTwo_Continous(int[] A) { int[] M = new int[A.Length]; for (int i = 0; i < M.Length; i++) { if (i == 0) { M[i] = A[i]; } else if (i == 1) { M[i] = Math.Max(A[i], A[i - 1]); } else { M[i] = Math.Max(M[i - 2] + A[i], M[i - 1]); } } Console.WriteLine(M.Max()); } //Max sum no three continous public static void Max_Sum_NoThree_Continous(int[] A) { int[] M = new int[A.Length]; for (int i = 0; i < M.Length; i++) { if (i == 0) { M[i] = A[i]; } else if (i == 1) { M[i] = Math.Max(M[i - 1] + A[i], A[i]); } else if (i == 2) { M[i] = Math.Max(M[i - 1], M[i - 2] + A[i]); } else { M[i] = Math.Max(M[i - 1], Math.Max(M[i - 2] + A[i], M[i - 3] + A[i] + A[i - 1])); } } } public static int Knapsack_0_1(int[] W, int[] V, int sackWeight) { if (sackWeight <= 0) return 0; int N = W.Length; int[,] B = new int[N + 1, sackWeight + 1]; for (int i = 0; i <= N; i++) { for (int j = 0; j <= sackWeight; j++) { if (i == 0 || j == 0) { B[i, j] = 0; } else { if (W[i - 1] > j) { B[i, j] = B[i - 1, j]; } else { B[i, j] = Math.Max(B[i - 1, j - W[i - 1]] + V[i - 1], B[i - 1, j]); } } } } return B[N, sackWeight]; } //given unlimited number or dertain denominations //find the min number of coins required for changing a given value public static int ChangeCoins(int[] V, int Value) { int[] M = new int[Value + 1]; for (int i = 0; i < M.Length; i++) { if (i == 0) { M[i] = 0; } else { M[i] = int.MaxValue; } } for (int i = 1; i < M.Length; i++) { int min = int.MaxValue; foreach (int vj in V) { if (i - vj >= 0 && M[i - vj] < min) { min = M[i - vj]; } } if (min + 1 < int.MaxValue) { M[i] = min + 1; } } return M[M.Length - 1]; } //Longest increasing subsequence public static void Longest_Increasing_Subsequence(int[] Input) { int[] L = new int[Input.Length]; int[] Path = new int[Input.Length]; //Keep track of predecessors for (int i = 0; i < L.Length; i++) { L[i] = 1; Path[i] = -1; } for (int i = 1; i < L.Length; i++) { int max = 0; int maxIndex = -1; for (int j = 0; j < i; j++) { if (Input[j] <= Input[i] && L[j] > max) { max = L[j]; maxIndex = j; } } if (max != 0 && maxIndex > -1) { L[i] = max + 1; Path[i] = maxIndex; } } int fmax = int.MinValue; int fmaxindex = -1; for (int i = 0; i < L.Length; i++) { if (L[i] > fmax) { fmax = L[i]; fmaxindex = i; } } int start = fmaxindex; while (start > -1) { Console.Write("{0} ", Input[start]); start = Path[start]; } Console.WriteLine(); Console.WriteLine(fmax); } //Longest Decreasing subsequence public static void Longest_Decreasing_Subsequence(int[] Input) { int[] LD = new int[Input.Length]; for (int i = 0; i < Input.Length; i++) { } } //is there a subset with given sum public static bool IsThereSubset(int[] A, int V) { int N = A.Length; int[,] B = new int[N + 1, V + 1]; //B[0, 0] = 1; for (int i = 0; i <= N; i++) { for (int j = 0; j <= V; j++) { if (i == 0 && j == 0) { B[i, j] = 1; } else { B[i, j] = 0; } } } for (int i = 1; i <= N; i++) { for (int j = 0; j <= V; j++) { if (B[i - 1, j] == 1) { B[i, j] = 1; } else if (j - A[i - 1] > -1) { if (B[i - 1, j - A[i - 1]] == 1) { B[i, j] = 1; } } } } return (B[N, V] == 1); } //maximum sum increasing sequence public static int MaxSum_Increasing_sequence(int[] A) { if (A.Length == 0) return 0; int[] M = new int[A.Length]; for (int i = 0; i < M.Length; i++) { M[i] = A[i]; } //M[0] = A[0]; for (int j = 1; j < M.Length; j++) { int max = int.MinValue; for (int i = 0; i < j; i++) { if (A[i] <= A[j] && M[i] > max) { max = M[i]; } } if (max != int.MinValue) { M[j] = max + A[j]; } } return M.Max(); } //edit distance problem // Given two strings str1 and str2 and below operations that can performed on str1.Find minimum number of edits (operations) required to convert ‘str1′ into ‘str2′. //Insert //Remove //Replace //All of the above operations are of equal cost. //Examples: //Input: str1 = "geek", str2 = "gesek" //Output: 1 //We can convert str1 into str2 by inserting a 's'. public static int MinOperations(string str1, string str2) { int[,] dp = new int[str1.Length + 1, str2.Length + 1]; for (int i = 0; i <= str1.Length; i++) { for (int j = 0; j <= str2.Length; j++) { if (i == 0) dp[i, j] = j; // Min. operations = j // If second string is empty, only option is to // remove all characters of second string else if (j == 0) dp[i, j] = i; // Min. operations = i // If last characters are same, ignore last char // and recur for remaining string else if (str1[i - 1] == str2[j - 1]) dp[i, j] = dp[i - 1, j - 1]; // If last character are different, consider all // possibilities and find minimum else dp[i, j] = 1 + Math.Min(dp[i, j - 1], Math.Min(dp[i-1,j],dp[i-1,j-1])); // Insert // Remove // Replace } } return 0; } public class FromRandonSites { //complexity = O(n) running time //O(k) = memory where k is number of digits that can be possible public static int[] CountingSort(int[] A) { if (A.Length == 0) return null; int[] C = new int[10]; foreach (int i in A) { C[i]++; } for (int i = 1; i < C.Length; i++) { C[i] = C[i] + C[i - 1]; } int[] sortedA = new int[A.Length]; for (int i = A.Length - 1; i >= 0; i--) { int position = C[A[i]] - 1; sortedA[position] = A[i]; C[A[i]]--; } return sortedA; } #region Radix Sort for integer array with all numbers being of same size //Complexisty of radix sort O(d(n+k)) // k is number of possible digits whihc is 10 in case of integers and 26 if only letters // d is the size of integer, like 3 is size of 769 //assume that all the integers are of same nuber of digits public static void RadixSort(ref int[] A) { if (A.Length == 0) return; int digitCount = FindSize(A[0]); for (int i = 1; i <= digitCount; i++) { //do counting sort of A on digit i CountingSort_ForDigitI(ref A, i); } } public static void CountingSort_ForDigitI(ref int[] A, int d) { if (A.Length == 0) return; int[] C = new int[10]; int[] output = new int[A.Length]; for (int i = 0; i < A.Length; i++) { int num = A[i]; int dnum = GetNthPlace(num, d); C[dnum]++; } for (int i = 1; i < C.Length; i++) { C[i] = C[i - 1] + C[i]; } for (int i = A.Length - 1; i >= 0; i--) { int num = A[i]; int dnum = GetNthPlace(num, d); output[C[dnum] - 1] = A[i]; C[dnum]--; } Array.Copy(output, A, output.Length); } public static int FindSize(int n) { n = Math.Abs(n); int size = 1; while (n > 10) { n = n / 10; size++; } return size; } public static int GetNthPlace(int num, int n) { //123 int rem = 0; int q = 0; while (n > 0) { rem = num % 10; num = (num - rem) / 10; n--; } return rem; } #endregion //for small letters (a-z)(97-) public static string CountingSort_String(string s) { if (s.Length == 0) return ""; int[] C = new int[26]; StringBuilder sb = new StringBuilder(s); foreach (char c in s) { int asci = (int)c; asci -= 97; C[asci]++; } for (int i = 1; i < C.Length; i++) { C[i] = C[i - 1] + C[i]; } for (int i = s.Length - 1; i >= 0; i--) { int asci = (int)s[i]; asci = asci - 97; sb[C[asci] - 1] = s[i]; C[asci]--; } return sb.ToString(); } } } public static class MathTricks { public static int GetSum(int a, int b) { if (a < 0) { while (a != 0) { b--; a++; } } else { while (a != 0) { b++; a--; } } return b; } public static int[] Intersection(int[] nums1, int[] nums2) { //Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Dictionary<int, bool> h = new Dictionary<int, bool>(); Array.Sort(nums2); for (int i = 0; i < nums1.Length; i++) { int n = nums1[i]; if (Searching.BinarySearch(nums2, 0, nums2.Length - 1, n)) { if (!h.ContainsKey(n)) { h.Add(n, true); } } } int[] ret = h.Select(x => x.Key).ToArray(); return ret; } public static bool IsMultipleOf3(int n) { if (n == 0 || n == 1) return true; int oddCount = 0; int evenCount = 0; bool isOdd = true; while (n != 0) { if (isOdd) { if (getLastbit(n)) { oddCount++; } } else { if (getLastbit(n)) { evenCount++; } } n = n >> 1; } return IsMultipleOf3(Math.Abs(oddCount - evenCount)); } public static bool getLastbit(int n) { return ((1 & n) == 1); } } public static class GraphProblems { //BFS - Shortest ddistance from given source to all reachable vertices. // O(E) //DFS - TB{FC} (Tree Edge, Back Edge, Forward Edge, Cross Edge) - WGB (White,Gray,Black) //DFS Application: Detect a cycle in a directed graph public static bool HasCycle_DirectedGraph(bool[,] Adj) { int count = Adj.GetUpperBound(0); List<Vertex> v = new List<Vertex>(); for (int i = 0; i < count; i++) { v.Add(new Vertex()); v[i].Color = 0; v[i].Parent = -1; } int time = 0; bool foundbackedge = new bool(); for (int i = 0; i < count; i++) { if (v[i].Color == 0) { //dfs visit DFSVisit(ref v, Adj, ref time, i, count, ref foundbackedge); if (foundbackedge) return true; } } if (foundbackedge) return true; return false; } public static void DFSVisit(ref List<Vertex> v, bool[,] Adj, ref int time, int i, int count, ref bool foundBackEdge) { time++; v[i].StartTime = time; v[i].Color = 1; //gray for (int j = 0; j < count; j++) { if (Adj[i, j]) { if (v[j].Color == 0) { DFSVisit(ref v, Adj, ref time, i, count, ref foundBackEdge); } else if (v[j].Color == 1) { foundBackEdge = true; } } } v[i].Color = 2; v[i].EndTime = ++time; } public class Vertex { //0 - white //1 - gray //2 - black public int Color { get; set; } public int Parent { get; set; } public int StartTime { get; set; } public int EndTime { get; set; } } public static void Test() { } } public static class StackProblems { private static Dictionary<char, int> Priority; static StackProblems() { Priority = new Dictionary<char, int>(); Priority.Add('+', 1); Priority.Add('-', 1); Priority.Add('*', 2); Priority.Add('/', 2); Priority.Add('(', 3); Priority.Add(')', 3); } public static string InFix2PostFix(string s) { StringBuilder sb = new StringBuilder(); Stack<char> stk = new Stack<char>(); for (int i = 0; i < s.Length; i++) { char c = s[i]; if (IsCapital(c)) { sb.AppendFormat("{0}", c); } else if (c == ')') { while (stk.Count > 0 && stk.Peek() != '(') { sb.AppendFormat("{0}", stk.Pop()); } stk.Pop(); } else { if (c == '(') { stk.Push(c); } else { while (stk.Count > 0 && (stk.Peek()!='(') && (Priority[stk.Peek()] >= Priority[c])) { sb.AppendFormat("{0}", stk.Pop()); } stk.Push(c); } } } while (stk.Count > 0) { sb.AppendFormat("{0}", stk.Pop()); } return sb.ToString(); } //infix to prefix public static void ReverseStack(ref Stack<int> s) { if (s.Count == 0) return; int n = s.Pop(); ReverseStack(ref s); InsertAtBottom(ref s, n); } public static void InsertAtBottom(ref Stack<int> s,int n) { if (s.Count == 0) { s.Push(n); return; } int temp = s.Pop(); InsertAtBottom(ref s, n); s.Push(temp); } //Remove duplicate letters //Evaluate Reverrse Polish Notation //Solved in LeetCode //basically same as evaluating post order //ex: ["2","1","+","3","*"] => 9 public static int EvaluatePolishNotation(string[] tokens) { return -1; } public static bool IsCapital(char c) { int n = (int)c; if (n <= 90 && n >= 65) return true; return false; } //{6, 2, 5, 4, 5, 2, 6} //stack problem: largest rectangle area in histogram public static int LargestRectangleArea(int[] heights) { if (heights.Length == 0) return 0; //store indexes not actual heights Stack<int> s = new Stack<int>(); int maxarea = -1; int i = 0; while (i < heights.Length) { if (s.Count == 0 || heights[i] > heights[s.Peek()]) { s.Push(i); i++; } else { //heights[i] <= heights[s.Pop] int top = s.Pop(); int curarea = heights[top] * (s.Count == 0 ? i : (i - s.Peek() - 1)); if (curarea > maxarea) maxarea = curarea; } } while (s.Count > 0) { int top = s.Pop(); int curarea = heights[top] * (s.Count == 0 ? i : (i - s.Peek() - 1)); if (curarea > maxarea) maxarea = curarea; } return maxarea; } //Maximal Rectangle QuestionEditorial Solution My Submissions //Total Accepted: 46427 //Total Submissions: 191926 //Difficulty: Hard //Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. //For example, given the following matrix: //1 0 1 0 0 //1 0 1 1 1 //1 1 1 1 1 //1 0 0 1 0 //Return 6. //public static int MaxArea(char[,] Matrix) //{ // int maxarea = 0; // int m = Matrix.GetLength(0); // int n = Matrix.GetLength(1); // bool[,] IsVisited = new bool[m, n]; // for (int i = 0; i < m; i++) // { // for (int j = 0; j < n; j++) // { // if (IsVisited[i, j] == false) // { // if (Matrix[i, j] == '0') // { // IsVisited[i, j] = true; // } // else // { // MaxArea_Aux(Matrix, i, j, 1, 1, ref maxarea); // } // } // } // } //} //public static void MaxArea_Aux(char[,] Matrix,int i,int j, int curwid, int curheight, ref int maxarea) //{ //} } public static class Random { #region Named && Matrix Algorithms //Flood Fill algorithms public static void FillPaint(ref int[,] Screen, int x, int y, int NewColor) { int m = Screen.GetLength(0); int n = Screen.GetLength(1); if (!AreValidInputs(x, y, m, n)) return; int OldColor = Screen[x, y]; if (OldColor == NewColor) return; FillPaintAux(ref Screen, m, n, x, y, OldColor, NewColor); } public static void FillPaintAux(ref int[,] Screen, int m,int n,int x, int y, int oldColor, int newColor) { if (!AreValidInputs(x, y, m, n)) return; if (Screen[x,y]!=oldColor) return; Screen[x, y] = newColor; FillPaintAux(ref Screen,m,n, x - 1, y, oldColor, newColor); FillPaintAux(ref Screen,m,n, x, y-1, oldColor, newColor); FillPaintAux(ref Screen,m,n, x+1, y, oldColor, newColor); FillPaintAux(ref Screen,m,n, x, y+1, oldColor, newColor); } public static bool AreValidInputs(int x, int y, int m, int n) { if (x < 0 || y < 0) return false; if (x >= m || y >= n) return false; return true; } //Islands //complexity - O(m*n) public static int NumIslands(char[,] grid) { int m = grid.GetLength(0); int n = grid.GetLength(1); if (m == 0 && n == 0) return 0; bool[,] IsVisited = new bool[m, n]; for (int a = 0; a < m; a++) { for (int b = 0; b < n; b++) { IsVisited[a, b] = false; } } m--; n--; int num = 0; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (IsVisited[i, j] == false) { if (grid[i, j] == 0) { IsVisited[i, j] = true; } else { num++; DFSVisit(grid, i, j, ref IsVisited, m, n); } } } } return num; } public static void DFSVisit(char[,] grid, int x, int y, ref bool[,] IsVisited, int m, int n) { IsVisited[x, y] = true; if (IsValid(x - 1, y, m, n) == true && IsVisited[x - 1, y] == false && grid[x - 1, y] == 1) DFSVisit(grid, x - 1, y, ref IsVisited, m, n); if (IsValid(x, y - 1, m, n) == true && IsVisited[x, y - 1] == false && grid[x, y - 1] == 1) DFSVisit(grid, x, y - 1, ref IsVisited, m, n); if (IsValid(x, y + 1, m, n) == true && IsVisited[x, y + 1] == false && grid[x, y + 1] == 1) DFSVisit(grid, x, y + 1, ref IsVisited, m, n); if (IsValid(x + 1, y, m, n) == true && IsVisited[x + 1, y] == false && grid[x + 1, y] == 1) DFSVisit(grid, x + 1, y, ref IsVisited, m, n); } public static bool IsValid(int x, int y, int m, int n) { if (x < 0 || x > m) return false; if (y < 0 || y > n) return false; return true; } //word brak proble //given a string and a dictionary of words //see if the given string can be //split in to space separated wordsf //wordbreak problem public static void SeprateToWords(string s, HashSet<string> dict) { int i = 0; int j = 0; while (j <= s.Length - 1) { int l1 = j - i + 1; string left = s.Substring(i, l1); int l2 = s.Length - 1 - j; string right = (l2 != 0) ? s.Substring(j + 1, l2) : ""; } } // Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). //For example, //S = "ADOBECODEBANC" //T = "ABC" //Minimum window is "BANC". public static void MinimumWindow(string S,string T) { } //word distance problem or also called as edit distance //given you can replace remove //edit distance problem // Given two strings str1 and str2 and below operations that can performed on str1.Find minimum number of edits (operations) required to convert ‘str1′ into ‘str2′. //Insert //Remove //Replace //All of the above operations are of equal cost. //Examples: //Input: str1 = "geek", str2 = "gesek" //Output: 1 //We can convert str1 into str2 by inserting a 's'. public static int MinOperations(string s1, string s2) { int[,] Dp = new int[s1.Length + 1, s2.Length + 1]; for (int i = 0; i <= s1.Length; i++) { for (int j = 0; j <= s2.Length; j++) { } } return 0; } //word Ladder problem //given a dictionary of words , see if given given two words can be transformed from one to another by changing 1 leteer at a time. //Each intermediate word must exist in the word list // For example, // Given: //beginWord = "hit" //endWord = "cog" //wordList = ["hot","dot","dog","lot","log"] // As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", public static int LadderLength(string beginWord, string endWord, ISet<string> wordList) { return 0; } #endregion #region Matrix Problem //LeetCode - Longest Increasing path in a Matrix // nums = [ //[9,9,4], //[6,6,8], //[2,1,1] //] output is length 4 corresponding to path [1,2,6,9] //from any point you can move in four directions public static int LongestIncreasingPath(int[] Matrix) { return 0; } public static int[] KMPPrefix(string P) { int[] F = new int[P.Length]; if (P.Length == 0) return F; F[0] = 0; int i = 1; int j = 0; while (i < P.Length) { if (P[i] == P[j]) { F[i] = j + 1; i++; j++; } else if (j > 0) { j = F[j - 1]; } else { F[i] = 0; i++; } } return F; } public static int FindPattern_KMP(string s, string p) { return 0; } #endregion } }
c9c248c10791974b41f1e2d2f93fe38b8b92677c
C#
lushijun8/teamtool
/Entity/TEAMTOOL/DATABASE_TABLE_UPDATELOG.cs
2.75
3
 using System; namespace Entity.TEAMTOOL { /// <summary> /// 本类中的(系统代码部分)由代码生成器自动生成,如果数据库表结构有所改动请及时更新 /// DataBase="TEAMTOOL" /// Table="DATABASE_TABLE_UPDATELOG" /// Columns="ID,WEBMANAGER_NAME,DATABASE_IP_ROMOTE,DATABASE_NAME,TABLE_NAME,COLUMN_NAME,DESCRIPTION,CREATETIME" /// PrimaryKeys="ID" /// </summary> public sealed class DATABASE_TABLE_UPDATELOG : Entity.TEAMTOOL.EntityBase { #region 系统代码,请不要动 生成日期:2016/2/5 15:55:30 #region 属性 /// <summary> /// BIGINT(8) 自增列 NOT NULL /// 只写属性,如果非要读取该字段的字符串,建议使用 ID_ToString 更加准确 /// 唯一主键 /// </summary> public long ID { set { ColumnValues[0] = value.ToString(); UpdateStatus[0] = 1; } } /// <summary> /// BIGINT(8) 自增列 NOT NULL /// 只读属性,如果非要写入该字段,请使用 ID /// 唯一主键 /// </summary> public string ID_ToString { get { return ColumnValues[0]; } } /// <summary> /// VARCHAR(50) NULL /// </summary> public string WEBMANAGER_NAME { get { return ColumnValues[1]; } set { ColumnValues[1] = value; UpdateStatus[1] = 1; } } /// <summary> /// VARCHAR(50) NULL /// </summary> public string DATABASE_IP_ROMOTE { get { return ColumnValues[2]; } set { ColumnValues[2] = value; UpdateStatus[2] = 1; } } /// <summary> /// VARCHAR(50) NULL /// </summary> public string DATABASE_NAME { get { return ColumnValues[3]; } set { ColumnValues[3] = value; UpdateStatus[3] = 1; } } /// <summary> /// VARCHAR(50) NULL /// </summary> public string TABLE_NAME { get { return ColumnValues[4]; } set { ColumnValues[4] = value; UpdateStatus[4] = 1; } } /// <summary> /// VARCHAR(50) NULL /// </summary> public string COLUMN_NAME { get { return ColumnValues[5]; } set { ColumnValues[5] = value; UpdateStatus[5] = 1; } } /// <summary> /// NVARCHAR(8000) NULL /// </summary> public string DESCRIPTION { get { return ColumnValues[6]; } set { ColumnValues[6] = value; UpdateStatus[6] = 1; } } /// <summary> /// DATETIME(8) NULL /// 只写属性,如果非要读取该字段的字符串,建议使用 CREATETIME_ToString 更加准确 /// </summary> public DateTime CREATETIME { set { ColumnValues[7] = value.ToString("yyyy-MM-dd HH:mm:ss.fff"); UpdateStatus[7] = 1; } } /// <summary> /// DATETIME(8) NULL /// 只读属性,如果非要写入该字段,请使用 CREATETIME /// </summary> public string CREATETIME_ToString { get { return ColumnValues[7]; } } #endregion #region 同名列变量 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用以下同名列变量 /// <summary> /// 返回 "ID", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _ID = "ID"; /// <summary> /// 返回 "WEBMANAGER_NAME", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _WEBMANAGER_NAME = "WEBMANAGER_NAME"; /// <summary> /// 返回 "DATABASE_IP_ROMOTE", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _DATABASE_IP_ROMOTE = "DATABASE_IP_ROMOTE"; /// <summary> /// 返回 "DATABASE_NAME", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _DATABASE_NAME = "DATABASE_NAME"; /// <summary> /// 返回 "TABLE_NAME", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _TABLE_NAME = "TABLE_NAME"; /// <summary> /// 返回 "COLUMN_NAME", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _COLUMN_NAME = "COLUMN_NAME"; /// <summary> /// 返回 "DESCRIPTION", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _DESCRIPTION = "DESCRIPTION"; /// <summary> /// 返回 "CREATETIME", 为了与数据库同步,避免列名写错,如果用到表的列名,请尽量使用同名列变量 /// </summary> public readonly string _CREATETIME = "CREATETIME"; #endregion #region 函数 /// <summary> /// DATABASE_TABLE_UPDATELOG的构造函数 /// </summary> public DATABASE_TABLE_UPDATELOG() { this.TableName = "DATABASE_TABLE_UPDATELOG"; this.PrimaryKey = new string[] { _ID }; this.IdentityColumn = this._ID; this.columns = new string[] { _ID, _WEBMANAGER_NAME, _DATABASE_IP_ROMOTE, _DATABASE_NAME, _TABLE_NAME, _COLUMN_NAME, _DESCRIPTION, _CREATETIME }; this.SelectColumns = this.Columns; this.ColumnValues = new string[this.Columns.Length]; this.UpdateStatus = new int[this.Columns.Length]; for (int i = 0; i < this.Columns.Length; i++) { this.UpdateStatus[i] = 0; this.ColumnValues[i] = ""; }; } /// <summary> /// 初始化表DATABASE_TABLE_UPDATELOG的各种相关值 /// </summary> protected override void SetValuesOnInit() { if (this.DataTypes == null || this.DataTypes.Length == 0) { this.IsPrimaryKeys = new int[] { 1, 0, 0, 0, 0, 0, 0, 0 }; this.DataTypes = new string[] { BIGINT, VARCHAR, VARCHAR, VARCHAR, VARCHAR, VARCHAR, NVARCHAR, DATETIME }; this.Lengths = new int[] { 8, 50, 50, 50, 50, 50, 8000, 8 }; this.IsNullables = new int[] { 0, 1, 1, 1, 1, 1, 1, 1 }; this.DefaultValues = new string[] { " ", " ", " ", " ", " ", " ", " ", " " }; this.Descriptions = new string[] { " ", " ", " ", " ", " ", " ", " ", " " }; } } /* /// <summary> /// 根据设置的主键,获得实体的表入口,并且给各个属性赋值,注意:WhereSql,JoinSql对该方法无用 /// </summary> /// <param name="ID"></param> /// <returns>bool</returns> public bool Find(long P_ID) { bool Value=false; this.ColumnValues[0]=P_ID.ToString(); if(this.SelectTop1()!=null) Value=true; return Value; } */ /* /// <summary> /// 深度拷贝DATABASE_TABLE_UPDATELOG(新开辟了内存空间) /// </summary> /// <returns></returns> public DATABASE_TABLE_UPDATELOG Copy() { DATABASE_TABLE_UPDATELOG new_obj=new DATABASE_TABLE_UPDATELOG(); base.CopyObj(new_obj); int columnindex=0; foreach (string column in this.Columns) { new_obj.SetColumnValue(column, this[column],columnindex); columnindex++; } return new_obj; } */ #endregion #region 实现关联Join方法和属性 #endregion #endregion 系统代码,请不要动 #region 在此处添加用户自己的业务逻辑代码 //在此处添加用户自己的业务逻辑代码 #endregion } }
8322927fb53876c4d02f4706ad85fc3b14a1afeb
C#
bharatmangal04/ms-idm-net
/IdmNet/IdmNet/Models/Resource.cs
2.890625
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; // ReSharper disable InconsistentNaming namespace IdmNet.Models { /// <summary> /// Resource - This is the base resource type. The attributes bound to this resource type appears in all resources. /// </summary> public class Resource : IdmResource { /// <summary> /// Parameterless CTOR /// </summary> public Resource() { ObjectType = ForcedObjType = "Resource"; } /// <summary> /// Build a Resource object from a IdmResource object /// </summary> /// <param name="resource">base class</param> public Resource(IdmResource resource) { Attributes = resource.Attributes; ObjectType = ForcedObjType = "Resource"; if (resource.Creator == null) return; Creator = resource.Creator; } readonly string ForcedObjType; /// <summary> /// Object Type (can only be Resource) /// </summary> [Required] public override sealed string ObjectType { get { return GetAttrValue("ObjectType"); } set { if (value != ForcedObjType) throw new InvalidOperationException("Object Type of Resource can only be 'Resource'"); SetAttrValue("ObjectType", value); } } } }
f0d5dc6e81449020f232a86442c01dedaaf219b7
C#
Didnelpsun/HotelManagementSystem
/HotelManagementBLL/Roomer.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Windows.Forms; namespace HotelManagementBLL { public class Roomer { private DataGridView _dgv; public Roomer(DataGridView dgr) { _dgv = dgr; } public Roomer() { } //查询用户信息记录 public void UpdateDataGrid() { DataSet objDataSet = HotelManagementDAL.Roomer.FillByAllRoom(); this._dgv.DataSource = objDataSet.Tables[0]; } //添加住客 public void Add(string ID, string name, Int64 phone, string address, string state, string remark) { HotelManagementDAL.Roomer obj = new HotelManagementDAL.Roomer(); if (obj.GetDataReaderByID(ID)) { MessageBox.Show("该身份证号名已经存在" + ID + ",请重新输入!", "身份证号名已存在", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { if (HotelManagementDAL.Roomer.Add(ID, name, phone, address, state,remark) > 0) { UpdateDataGrid(); MessageBox.Show("成功添加住客信息!", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("添加住客信息失败!", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } //修改住客信息 public void Update(string ID, string name, string phone, string address, string remark) { HotelManagementDAL.Roomer obj = new HotelManagementDAL.Roomer(ID); obj.IDCard = ID;/// 登记 信息 obj.Name = name; obj.Phone = phone; obj.Address = address; obj.Remark = remark; if (obj.Update() > 0) { UpdateDataGrid(); MessageBox.Show("修改住客信息成功!", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("更新操作失败!", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void Delete() { string IDCard = this._dgv.CurrentRow.Cells["ID_Card"].Value.ToString(); string name = this._dgv.CurrentRow.Cells["Name_"].Value.ToString(); if (DialogResult.Yes == MessageBox.Show("确认删除住客信息:' " + name + " '吗?\n删除住客,将同时删除与该住客有相关的所有入住信息,要继续吗?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { HotelManagementDAL.Roomer objRoom = new HotelManagementDAL.Roomer(IDCard); if (objRoom.Delete() > 0) { UpdateDataGrid(); MessageBox.Show("成功删除住客" + name + " '!", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("删除操作失败 " + name + " '!", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public void Search(string ID, string name, string phone, string address, string state, string remark) { DataSet objDataSet = HotelManagementDAL.Roomer.FillByAllRoom(); objDataSet = HotelManagementDAL.Roomer.SearchByFuzzy(ID, name, phone, address, state, remark); _dgv.DataSource = objDataSet.Tables[0]; if(objDataSet.Tables[0].Rows.Count == 0) MessageBox.Show("没有符合的记录!", "结果", MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show("搜索完毕", "结果", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
d055f411d1488e6548004766aed17a9e3cd52910
C#
oakop01/CPMPlatform
/Common/EIS.Common.Pipe/NamedPipeServer.cs
2.53125
3
using System; using System.Collections.Generic; using System.IO.Pipes; using System.Reflection; using System.Reflection.Emit; using System.IO; using System.Threading; namespace EIS.Common.Pipe { public class NamedPipeServer { private NamedPipeServer.DelegateProcessMessage msgHandler; private List<NamedPipeServerStream> _serverPool; private string _pipName; public NamedPipeServer(string pipName, NamedPipeServer.DelegateProcessMessage handler) { this._pipName = pipName; this.msgHandler = handler; } protected NamedPipeServerStream CreateNamedPipeServerStream() { NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream(this._pipName, PipeDirection.InOut, 10); this._serverPool.Add(namedPipeServerStream); int count = this._serverPool.Count; Console.WriteLine(string.Concat("Pool=", count.ToString())); return namedPipeServerStream; } protected void DistroyObject(NamedPipeServerStream npss) { npss.Close(); if (this._serverPool.Contains(npss)) { this._serverPool.Remove(npss); } } protected virtual void ProcessMessage(string str, NamedPipeServerStream pipeServer) { StreamWriter streamWriter = new StreamWriter(pipeServer); try { streamWriter.AutoFlush = true; streamWriter.WriteLine("1="); } finally { if (streamWriter != null) { ((IDisposable)streamWriter).Dispose(); } } } public void Run() { NamedPipeServerStream namedPipeServerStream = this.CreateNamedPipeServerStream(); try { namedPipeServerStream.WaitForConnection(); Action action = new Action(this.Run); action.BeginInvoke(null, null); try { try { bool flag = true; while (true) { if (flag) { string str = (new StreamString(namedPipeServerStream)).ReadString(); string delegateProcessMessage0 = this.msgHandler(str); StreamWriter streamWriter = new StreamWriter(namedPipeServerStream); try { streamWriter.AutoFlush = true; streamWriter.WriteLine(delegateProcessMessage0); } finally { if (streamWriter != null) { ((IDisposable)streamWriter).Dispose(); } } if (!namedPipeServerStream.IsConnected) { flag = false; break; } else { Thread.Sleep(50); } } else { break; } } } catch (IOException oException) { Console.WriteLine("ERROR: {0}", oException.Message); } } finally { this.DistroyObject(namedPipeServerStream); } } finally { if (namedPipeServerStream != null) { ((IDisposable)namedPipeServerStream).Dispose(); } } } public void Stop() { for (int i = 0; i < this._serverPool.Count; i++) { this.DistroyObject(this._serverPool[i]); } } public delegate string DelegateProcessMessage(string msg); } }
bf7307fdafa3bc1cba9b610ab0ff6641acf23cc4
C#
mertgogersin/Blog_Website_Project
/Blog-Website-Project/Models/Repositories/ConvertToDTORepository.cs
2.515625
3
using Blog_Website_Project.Models.DTOs; using Core.Entities; using Core.Services; using System.Collections.Generic; namespace Blog_Website_Project.Models.Repositories { public class ConvertToDTORepository { IUserService userService; public ConvertToDTORepository(IUserService userService) { this.userService = userService; } public ConvertToDTORepository() { } public List<ArticleDTO> GetArticleDTOList(List<Article> articleList) { List<ArticleDTO> articleDTOList = new List<ArticleDTO>(); foreach (Article item in articleList) { ArticleDTO articleDTO = new ArticleDTO() { UserID = item.UserID, FullName = userService.GetUserByUserId(item.UserID.ToString()).FullName, Url = userService.GetUserByUserId(item.UserID.ToString()).Url, ArticleID = item.ArticleID, Title = item.Title, Subtitle = item.Subtitle, Content = item.Content, ReadTime = item.ReadTime, PhotoPath = userService.GetUserByUserId(item.UserID.ToString()).Picture, CreatedDate = item.CreatedDate }; articleDTOList.Add(articleDTO); } return articleDTOList; } public ArticleDTO GetArticleDTO(Article article) { ArticleDTO articleDTO = new ArticleDTO() { UserID = article.UserID, FullName = userService.GetUserByUserId(article.UserID.ToString()).FullName, Url = userService.GetUserByUserId(article.UserID.ToString()).Url, ArticleID = article.ArticleID, Title = article.Title, Subtitle = article.Subtitle, Content = article.Content, ReadTime = article.ReadTime, PhotoPath = userService.GetUserByUserId(article.UserID.ToString()).Picture, CreatedDate = article.CreatedDate }; return articleDTO; } public List<TopicDTO> GetTopicDTOList(List<Topic> topicList) { List<TopicDTO> topicDTOList = new List<TopicDTO>(); TopicDTO topicDTO; foreach (Topic item in topicList) { topicDTO = new TopicDTO() { TopicID = item.TopicID, TopicName = item.TopicName, Description = item.Description }; topicDTOList.Add(topicDTO); } return topicDTOList; } public UserDTO GetUserDTO(User user) { UserDTO userDTO = new UserDTO() { UserID = user.UserID, UserName = user.UserName, FullName = user.FullName, Email = user.Email, Url = user.Url, PhotoPath = user.Picture, Description = user.Description }; return userDTO; } } }
6650c14636030f108509dd33fa94a037a47b3db4
C#
HvaiY/MyCoreStudy
/Day26跨域请求/Startup.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Day26跨域请求 { /// <summary> /// 关于跨域请求问题 /// 需要注册服务 先添加: dotnet add package Microsoft.AspNetCore.Cors /// ASP.NET Core 中使用 CORS 只要在 Startup.ConfigureServices 呼叫 AddCors,就能註冊 CORS 的 Policy 規則 /// </summary> public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //注册服务 跨域请求限制 services.AddCors(options => { options.AddPolicy("MyCorsPolicy", policy => { policy.WithOrigins("http://212.37.89.51:8080", "http://localhost:3000") .AllowAnyHeader() //WithHeaders 做限制 ,允许多个头用‘,’隔开 .AllowAnyMethod()//WithMethods限制请求方法 同上 .AllowCredentials(); }); }); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //全局套用一个跨域限制 app.UseCors("MyCorsPolicy"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } } }
d2b702ea01eb34aedd6508d4948bb9d3e1f3c055
C#
itsMatoosh/logitow-bridge
/src/main/resources/native/LogitowWindowsNative/Scanner.cs
3.09375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.Devices.Bluetooth; using Windows.Devices.Enumeration; using Windows.Devices.Radios; namespace LogitowWindowsNative { /// <summary> /// Used for scanning for active LOGITOW devices. /// </summary> public class Scanner { /// <summary> /// Device watcher. /// </summary> public DeviceWatcher deviceWatcher; /// <summary> /// The default bluetooth adapter. /// </summary> public BluetoothAdapter bleAdapter; /// <summary> /// The currently available radios. /// </summary> public IReadOnlyList<Radio> availableRadios; /// <summary> /// List of unknown discovered devices. /// Will be unknown until the name is not updated. /// </summary> public List<DeviceInformation> unknownDevices = new List<DeviceInformation>(); /// <summary> /// The currently discovered devices. /// </summary> public List<LogitowDevice> discoveredDevices = new List<LogitowDevice>(); /// <summary> /// The currently registered event listener. /// </summary> public DeviceEventReceiver eventListener; /// <summary> /// The instance of the scanner. /// </summary> public static Scanner Instance; /// <summary> /// Default constructor. /// </summary> public Scanner() { if(Instance == null) { Instance = this; Setup(); } } /// <summary> /// Sets up the scanner. /// </summary> public async Task Setup() { Console.WriteLine("Setting up the windows native device manager..."); bleAdapter = await BluetoothAdapter.GetDefaultAsync(); availableRadios = await Radio.GetRadiosAsync(); Console.WriteLine("Set up the windows native device manager"); } #region General /// <summary> /// Sets up the scanner with an event listener. /// </summary> /// <param name="eventListener"></param> public void SetEventListener(DeviceEventReceiver eventListener) { this.eventListener = eventListener; } /// <summary> /// Gets an instance of LogitowDevice based on its uuid. /// </summary> /// <param name="uuid"></param> public LogitowDevice GetConnectedLogitowDevice(string uuid) { foreach(LogitowDevice device in LogitowDevice.connectedDevices) { if(device.deviceInfo.Id.Equals(uuid)) { return device; } } return null; } /// <summary> /// Gets a discovered logitow ble device given uuid. /// </summary> /// <param name="id"></param> /// <returns></returns> public LogitowDevice GetDiscoveredLogitowDevice(string id) { foreach (LogitowDevice logitowDevice in discoveredDevices) { if (logitowDevice.deviceInfo.Id == id) { return logitowDevice; } } return null; } /// <summary> /// Gets an unknown ble device given uuid. /// </summary> /// <param name="id"></param> /// <returns></returns> private DeviceInformation GetUnknownDevice(string id) { foreach (DeviceInformation unknownDevice in unknownDevices) { if (unknownDevice.Id == id) { return unknownDevice; } } return null; } /// <summary> /// Checks whether bluetooth is available on the device. /// </summary> /// <returns></returns> public bool GetBluetoothSupported() { if (bleAdapter == null) return false; if (!bleAdapter.IsCentralRoleSupported) return false; return availableRadios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth) != null; } /// <summary> /// Checks whether bluetooth is enabled on the device. /// </summary> /// <returns></returns> public bool GetBluetoothEnabled() { var bluetoothRadio = availableRadios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth); return bluetoothRadio != null && bluetoothRadio.State == RadioState.On; } #endregion #region DeviceDiscovery /// <summary> /// Starts a device watcher that looks for all nearby Bluetooth devices (paired or unpaired). /// Attaches event handlers to populate the device collection. /// </summary> public void StartBleDeviceWatcher() { Console.WriteLine("Starting Logitow device discovery!"); //Setting up the device watcher. if(deviceWatcher == null) { //Additional properties we would like about the device. //Getting the device address, whether it is currently connected and if the device is a BLE device. string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable", "System.Devices.Aep.IsPaired" }; //Instantiating the device watcher. deviceWatcher = DeviceInformation.CreateWatcher( "", requestedProperties, DeviceInformationKind.AssociationEndpoint); //Registering watcher events. deviceWatcher.Added += DeviceWatcher_Added; deviceWatcher.Updated += DeviceWatcher_Updated; deviceWatcher.Removed += DeviceWatcher_Removed; deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; deviceWatcher.Stopped += DeviceWatcher_Stopped; } //Start over with an empty collection. discoveredDevices.Clear(); unknownDevices.Clear(); //Start the watcher. deviceWatcher.Start(); //Notifying the jvm. Instance.eventListener.OnScanStarted(); } /// <summary> /// Stops watching for all nearby Bluetooth devices. /// </summary> public void StopBleDeviceWatcher() { if (deviceWatcher != null) { //Stopping the watcher. deviceWatcher.Stop(); } } /// <summary> /// Called when a new ble device is discovered. /// </summary> /// <param name="sender"></param> /// <param name="deviceInfo"></param> private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo) { lock (this) { //Making sure that we are processing device from the current device watcher. if (sender == deviceWatcher) { //Making sure device isn't already present in the list. if (GetDiscoveredLogitowDevice(deviceInfo.Id) == null) { //Checking if the device has info or not. bool connectable = false; Boolean.TryParse(deviceInfo.Properties["System.Devices.Aep.Bluetooth.Le.IsConnectable"].ToString(), out connectable); if (System.String.IsNullOrEmpty(deviceInfo.Name)) { unknownDevices.Add(deviceInfo); } else if (deviceInfo.Name == "LOGITOW" && connectable) { Console.WriteLine(System.String.Format("Discovered LOGITOW device: {0}", deviceInfo.Id)); //If device has name LOGITOW, adding it to list. var logitowDevice = new LogitowDevice(deviceInfo); discoveredDevices.Add(logitowDevice); eventListener.OnDeviceDiscovered(logitowDevice.deviceInfo.Id); } } } } } /// <summary> /// Called when a device info is updated. /// </summary> /// <param name="sender"></param> /// <param name="deviceInfoUpdate"></param> private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) { lock(this) { Console.WriteLine(System.String.Format("Updated {0}, {1}", deviceInfoUpdate.Id, "")); //Making sure that we are processing device from the current device watcher. if (sender == deviceWatcher) { LogitowDevice logitowDevice = GetDiscoveredLogitowDevice(deviceInfoUpdate.Id); if (logitowDevice != null) { //Device has already been discovered. Updating the info. logitowDevice.OnBluetoothInfoUpdate(deviceInfoUpdate); return; } else { //Checking in the unknown devices list. DeviceInformation information = GetUnknownDevice(deviceInfoUpdate.Id); //Updating the device info. if(information != null) { information.Update(deviceInfoUpdate); //Checking if the name has been fetched and if it is LOGITOW. if (!System.String.IsNullOrEmpty(information.Name) && information.Name == "LOGITOW" && (bool)information.Properties["System.Devices.Aep.Bluetooth.Le.IsConnectable"] == true) { unknownDevices.Remove(information); LogitowDevice device = new LogitowDevice(information); Console.WriteLine(System.String.Format("Added {0} to the discovered LOGITOW bricks list.", information.Id)); discoveredDevices.Add(logitowDevice); eventListener.OnDeviceDiscovered(device.deviceInfo.Id); } } } } } } /// <summary> /// Called when a BLE device is removed from the system. /// </summary> /// <param name="sender"></param> /// <param name="deviceInfoUpdate"></param> private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) { lock(this) { Console.WriteLine(System.String.Format("Removed {0}, {1}", deviceInfoUpdate.Id, "")); //Making sure that we are processing device from the current device watcher. if (sender == deviceWatcher) { //Find the corresponding DeviceInformation in the collection and remove it. LogitowDevice logitowDevice = GetDiscoveredLogitowDevice(deviceInfoUpdate.Id); if (logitowDevice != null) { discoveredDevices.Remove(logitowDevice); eventListener.OnDeviceLost(logitowDevice.deviceInfo.Id); } DeviceInformation unknownDevice = GetUnknownDevice(deviceInfoUpdate.Id); if (unknownDevice != null) { unknownDevices.Remove(unknownDevice); } } } } /// <summary> /// Called when the device enumeration concludes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object e) { //Making sure that we are processing device from the current device watcher. if (sender == deviceWatcher) { Console.WriteLine($"{discoveredDevices.Count} devices found. Scanning completed!"); eventListener.OnScanStopped(); } } /// <summary> /// Called when the device wathcer is stopped. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeviceWatcher_Stopped(DeviceWatcher sender, object e) { //Making sure that we are processing device from the current device watcher. if (sender == deviceWatcher) { Console.WriteLine("Device discovery stopped."); Instance.eventListener.OnScanStopped(); } } /// <summary> /// Connects or reconnects to a logitow brick. /// </summary> public void Connect(LogitowDevice device) { device.ConnectAsync(); } /// <summary> /// Disconnects the specified device. /// </summary> /// <param name="device"></param> public void Disconnect(LogitowDevice device) { device.DisconnectAsync(); } #endregion } }
edd2f79a28070ff06332ef9a4c9b0f50ecba9840
C#
JackWitek/stickies-sync
/HtmlToRtfX/Html/HtmlTokenDefinition.cs
2.828125
3
using X.HtmlToRtfConverter.Tokenizer; namespace X.HtmlToRtfConverter.Html { public class HtmlTokenDefinition : TokenDefinition<HtmlTokenMatch> { public HtmlTokenType ReturnsToken { get; } public HtmlTokenDefinition(HtmlTokenType returnsToken, string regexPattern) : base(regexPattern) { ReturnsToken = returnsToken; } public override HtmlTokenMatch Match(string inputString) { var result = base.Match(inputString); if (result.IsMatch) { result.TokenType = ReturnsToken; } return result; } } }
5674f498ec8b03dd46917b66c72dd4b781f100c9
C#
AngelHristov/Encapsulation_exercise
/03.ShoppingSpree/Product.cs
3.578125
4
namespace _03.ShoppingSpree { public class Product { private string name; private int cost; public string Name { get => this.name; set { Validator.ValidateName(value); // checks if name is not null or empty string; name = value; } } public int Cost { get => this.cost; set { Validator.ValidateMoney(value); // checks if money < 0; cost = value; } } public Product(string name, int money) { this.Name = name; this.Cost = cost; } public override string ToString() { return this.Name.ToString(); } } }