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
571cc795edee0296ac116b3bc81a8a21c269d776
C#
urosradosavljevic/wpf-hospital-student
/ViewModel/AccountInfoViewModel.cs
2.515625
3
using Bolnica.Model; using System; using System.Linq; using System.Windows; namespace Bolnica.ViewModel { class AccountInfoViewModel : BindableBase { MainWindowViewModel mainWindowDataContext; public string HelpText { get; set; } private readonly App app; private string firstName; private string lastName; private string email; private string username; private string address; private DateTime birthDate; public MyICommand GoHomeCommand { get; set; } private Secretary currentSecretary; public AccountInfoViewModel() { HelpText = "Schedule Apointement Submit Help text"; mainWindowDataContext = Application.Current.MainWindow.DataContext as MainWindowViewModel; app = Application.Current as App; Email = "MA daj"; GoHomeCommand = new MyICommand(OnGoHome); SetUser(); } #region Getters & Setters public Secretary CurrentSecretary { get { return currentSecretary; } set { currentSecretary = value; OnPropertyChanged("CurrentSecretary"); } } public string FirstName { get { return firstName; } set { firstName = value; OnPropertyChanged("FirstName"); OnPropertyChanged("FullName"); } } public string LastName { get { return lastName; } set { lastName = value; OnPropertyChanged("LastName"); OnPropertyChanged("FullName"); } } public string Email { get { return email; } set { email = value; OnPropertyChanged("Email"); } } public string Username { get { return username; } set { username = value; OnPropertyChanged("Username"); } } public string Address { get { return address; } set { address = value; OnPropertyChanged("Address"); } } public DateTime BirthDate { get { return birthDate; } set { birthDate = value; OnPropertyChanged("BirthDate"); } } #endregion #region Data public void SetUser() { Console.WriteLine(app.TempSecretary.Email.Value); CurrentSecretary = app.TempSecretary; } #endregion #region Handlers private void OnGoHome() { mainWindowDataContext.OnNav("home"); } #endregion } }
5fc3b754cd8bf6014c71a73284cffc73beea3bed
C#
abulanadi/Lab8
/GreedySalesman.cs
2.890625
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.IO; using System.Text; using System.Threading.Tasks; namespace Lab8 { public class GreedySalesman { Graph graph = new Graph(); MatrixGen matrixGen = new MatrixGen(); BruteSalesman brute = new BruteSalesman(); static Stopwatch stopwatch = new Stopwatch(); static double leastCost = 9999999999; //static double[,] costMatrix; int nodes; Stack<int> myStack; List<double> bestTour; //int cost; private double minimum = leastCost; public GreedySalesman() { myStack = new Stack<int>(); bestTour = new List<double>(); } public double[] Greedy(double[,] matrix) { nodes = matrix.GetLength(1); int[] visited = new int[nodes]; visited[0] = 1; myStack.Push(1); int el, dst = 0, i; Boolean isMinimum = false; while(myStack.Count() != 0) { el = myStack.Peek(); i = 0; minimum = leastCost; while(i < nodes) { if(matrix[el, i] > 1 && visited[i] == 0) { if(minimum > matrix[el, i]) { minimum = matrix[el, i]; dst = i; isMinimum = true; } } i++; } if (isMinimum) { visited[dst] = 1; myStack.Push(dst); bestTour.Add(dst - 1); isMinimum = false; continue; } myStack.Pop(); } double[] pathArray = new double[bestTour.Count()]; for(int x = 0; x < bestTour.Count(); x++) { if(bestTour[x] != null) { pathArray[x] = bestTour[x]; } } return pathArray; } public double GreedyTravelCost(double[] path, double[,] matrix) { double cost = 0; for(int i = 1; i < path.Length; i++) { double begin = path[i - 1]; double end = path[i]; cost += matrix[(int)begin, (int)end]; } int temp = 0; if(path.Length >= 1) { temp = path.Length - 1; } double last = path[temp]; double first = path[0]; return cost + matrix[(int)last, (int)first]; } public void GreedyCorrectness(double[,] matrix) { var length = matrix.GetLength(0); var expectedCost = matrix[0, 1] * length; graph.PrintMatrix(matrix, length); double[] resultArray = Greedy(matrix); Console.WriteLine("Expected optimal path cost: {0}", expectedCost); var trueCost = GreedyTravelCost(resultArray, matrix); Console.WriteLine("Optimal path:"); foreach (int i in resultArray) { Console.Write("{0} ", i); } Console.Write("0"); Console.WriteLine(); Console.WriteLine("Optimal path cost: {0}", trueCost); } public void GreedyTest(string resultFile) { string resultsFolderPath = "C:\\Users\\Adria\\School Stuff\\CSC482\\Lab8"; int maxInput = Convert.ToInt32(Math.Pow(2, 15)); double numberOfTrials = 10; Stopwatch stopwatch = new Stopwatch(); double nanoSecs = 0; Console.WriteLine("Input Size\tAvg Time (ns)"); for (int i = 50; i <= maxInput; i+=i) { for (int trial = 1; trial <= numberOfTrials; trial++) { double[,] testMatrix = matrixGen.RandomCost(i, 100); stopwatch.Restart(); Greedy(testMatrix); stopwatch.Stop(); nanoSecs += stopwatch.Elapsed.TotalMilliseconds * 1000000; } double averageTrialTime = nanoSecs / numberOfTrials; Console.WriteLine("{0, -10}\t{1, 16}", i, averageTrialTime); using (StreamWriter outputFile = new StreamWriter(Path.Combine(resultsFolderPath, resultFile), true)) { outputFile.WriteLine("{0, -10}\t{1, 16}", i, averageTrialTime); } } } public void HeuristicTest(string resultFile) { string resultsFolderPath = "C:\\Users\\Adria\\School Stuff\\CSC482\\Lab8"; Console.WriteLine("Input Size\tExpected Cost\tAvgGreedCost\tAvg SQR (10 Trials)"); double trialCost = 0; double greedyCostTotal = 0; int numberOfTrials = 10; for(int i = 4; i <= 11; i++) { for(int trial = 1; trial <= numberOfTrials; trial++) { double[,] testMatrix = matrixGen.EuclideanCost(i, 100); double[] greedyArray = Greedy(testMatrix); double currentCost = GreedyTravelCost(greedyArray, testMatrix); brute.BruteForce(testMatrix); trialCost = brute.TravelCost(BruteSalesman.bestTour, testMatrix); //Console.WriteLine(currentCost); greedyCostTotal += currentCost; } double averageGreedyCost = greedyCostTotal / numberOfTrials; double averageSQR = averageGreedyCost / trialCost; Console.WriteLine("{0, -10}\t{1,10}\t{2,10}\t{3,10}", i,trialCost, averageGreedyCost, averageSQR); using (StreamWriter outputFile = new StreamWriter(Path.Combine(resultsFolderPath, resultFile), true)) { outputFile.WriteLine("{0, -10}\t{1,10}\t{2,10}\t{3,10}", i, trialCost, averageGreedyCost, averageSQR); } } } } }
d21d327079f21508072946c29ddf52d633ca091a
C#
56840170/SocketWork
/UDP/UClient/UClient.cs
2.578125
3
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Toys.NetWork { public class UClient : UBasic { /// <summary> /// UDP连接 /// </summary> private UdpClient UdpClient { get; set; } /// <summary> /// 发送队列 /// </summary> private Queue<byte[]> SendLine { get; set; } /// <summary> /// 处理队列 /// </summary> private Queue<byte[]> MessageLine { get; set; } /// <summary> /// 发布消息 /// </summary> public event Action<byte[]> InvokeMessage; /// <summary> /// 准备 /// </summary> private bool SendFlag, ReceiveFlag, ProcessFlag; public UClient(IPEndPoint remote) : base(remote) { SendLine = new Queue<byte[]>(); MessageLine = new Queue<byte[]>(); //绑定端口 Bind(30303); //接收返回的地址 Nat(); } /// <summary> /// 工作线程 /// </summary> public void InitTask() { Task.Factory.StartNew(() => Send(null)); Task.Factory.StartNew(() => Receive()); Task.Factory.StartNew(() => ProcessData(), TaskCreationOptions.LongRunning); while (!SendFlag || !ReceiveFlag || !ProcessFlag) { Thread.Sleep(50); } } /// <summary> /// 绑定端口 /// </summary> /// <param name="port"></param> private void Bind(int port) { try { UdpClient = new UdpClient(); UdpClient.Client.Bind(new IPEndPoint(IPAddress.Any, port)); } catch { UdpClient.Client.Dispose(); UdpClient.Dispose(); Bind(++port); } } /// <summary> /// 循环发送 /// </summary> protected override void Send(byte[] data) { try { lock (SendLine) { if (SendLine.Count > 0) { data = SendLine.Dequeue(); } else { SendFlag = true; Monitor.Wait(SendLine); } } if (data != null) { UdpClient.BeginSend(data, data.Length, Remote, (ar) => { if (UdpClient.EndSend(ar) == data.Length) { ar.AsyncWaitHandle.Dispose(); Send(null); } }, null); } else { Send(null); } } catch (Exception e) { Console.WriteLine(e.Message); Dispose("Send " + e.Message); } } /// <summary> /// 循环接收 /// </summary> protected override void Receive() { try { UdpClient.BeginReceive((ar) => { IPEndPoint iPEnd = null; byte[] data = UdpClient.EndReceive(ar, ref iPEnd); ar.AsyncWaitHandle.Dispose(); if (data.Length > 0) { lock (MessageLine) { MessageLine.Enqueue(data); Monitor.PulseAll(MessageLine); } Receive(); } }, null); ReceiveFlag = true; } catch (Exception e) { Dispose("Receive " + e.Message); } } /// <summary> /// 消息数据处理 /// </summary> private void ProcessData() { while (IsAvailable) { try { byte[] data = null; lock (MessageLine) { if (MessageLine.Count > 0) { data = MessageLine.Dequeue(); } else { ProcessFlag = true; Monitor.Wait(MessageLine); } } if (data != null) { InvokeMessage?.Invoke(data); } } catch (Exception e) { Console.WriteLine(e.Message); Dispose("ProcessData " + e.Message); } } } private void Hole(IPEndPoint iPEndPoint, byte[] buffer) { if (iPEndPoint.CString() == Remote.CString()) { //返回的IP var ip = System.Text.Encoding.UTF8.GetString(buffer); Console.WriteLine(iPEndPoint + " " + ip); var arr = ip.Split(':'); IPEndPoint remote = new IPEndPoint(IPAddress.Parse(arr[0]), Convert.ToInt32(arr[1])); //先接收 UdpClient.BeginReceive((aarr) => { IPEndPoint temp = null; var fialResult = UdpClient.EndReceive(aarr, ref temp); if (fialResult.Length == 113) { IsAvailable = true; Console.WriteLine("打通"); Remote = remote; InitTask(); } }, null); var start = new byte[112]; //顺着通道建立连接 UdpClient.Send(start, start.Length, remote); } else { UdpClient.BeginReceive(WaitForEnd, null); } } private void WaitForEnd(IAsyncResult ar) { IPEndPoint ipend = null; byte[] buffer = UdpClient.EndReceive(ar, ref ipend); Hole(ipend, buffer); } /// <summary> /// MAT穿透 /// </summary> private void Nat() { UdpClient.BeginReceive(WaitForEnd, null); var nat = new byte[111]; int count = UdpClient.Send(nat, nat.Length, Remote); } public override void Dispose(string msg) { Console.WriteLine(msg); try { if (Remote != null) { lock (this) { if (Remote != null) { Remote = null; IsAvailable = false; UdpClient.Close(); UdpClient.Dispose(); SendLine.Clear(); MessageLine.Clear(); } } } } catch (Exception e) { Console.WriteLine("Dispose " + e.Message); } } /// <summary> /// 发送消息 /// </summary> /// <param name="buffer"></param> /// <returns></returns> public override bool PushDataIntoLine(byte[] buffer) { if (IsAvailable) { lock (SendLine) { SendLine.Enqueue(buffer); Monitor.PulseAll(SendLine); } return true; } return false; } } }
74565e7fa1a324b8cdc04621c0d54c43b26df955
C#
tyler-mcwilliam/SPOJ
/Spoj.Library/Heaps/IHeap.cs
2.796875
3
using System.Collections.Generic; namespace Spoj.Library.Heaps { public interface IHeap<TKey, TValue> { int Size { get; } bool IsEmpty { get; } KeyValuePair<TKey, TValue> Top { get; } void Add(TKey key, TValue value); void Add(KeyValuePair<TKey, TValue> keyValuePair); KeyValuePair<TKey, TValue> Extract(); KeyValuePair<TKey, TValue> Replace(TKey key, TValue value); KeyValuePair<TKey, TValue> Replace(KeyValuePair<TKey, TValue> keyValuePair); bool Contains(TKey key); TValue GetValue(TKey key); bool TryGetValue(TKey key, out TValue value); TValue Update(TKey key, TValue value); TValue Update(KeyValuePair<TKey, TValue> keyValuePair); } }
651d293a3512f1eee1df77aa7f9c94eb118cbe93
C#
newmast/Telerik_2015-2016
/CSharp-Two/Methods/SortingArray/SortingArray.cs
4.21875
4
//### Problem 9. Sorting array //* Write a method that return the maximal element in a portion of array of integers starting at given index. //* Using it write another method that sorts an array in ascending / descending order. using System; using System.Linq; class SortingArray { static void Main() { Console.Write("Enter array length: "); int arrLength = int.Parse(Console.ReadLine()); int[] values = new int[arrLength]; for (int i = 0; i < values.GetLength(0); i++) { Console.Write("[{0}]: ", i); values[i] = int.Parse(Console.ReadLine()); } SortArrayDescending(values); SortArrayAscending(values); } static int GetMaxStartingFrom( int begin, int[] values) { int max = values[begin]; for (int i = begin + 1; i < values.GetLength(0); i++) { if (values[i] >= max) { max = values[i]; } } return max; } static void SortArrayDescending(int[] values) { for (int i = 0; i < values.GetLength(0); i++) { int temp2 = GetMaxStartingFrom(i, values); int temp = Array.IndexOf(values, temp2); values[temp] = values[i]; values[i] = temp2; } Console.Write("Descending order: "); for (int i = 0; i < values.GetLength(0); i++) { Console.Write(values[i] + " "); } Console.WriteLine(); } static void SortArrayAscending(int[] values) { int[] valuesReversed = values.Reverse().ToArray(); Console.Write("Ascending order: "); for (int i = 0; i < valuesReversed.GetLength(0); i++) { Console.Write(valuesReversed[i] + " "); } Console.WriteLine(); } }
3f1241cb1bb501d12fef055a75c2f4c8e23bb1c9
C#
leesq87/myCode
/Unity/----------/13.PlayerPrefs/Script/csGameManager.cs
2.53125
3
using UnityEngine; using System.Collections; using UnityEditor; public class csGameManager : MonoBehaviour { void OnGUI(){ if(GUI.Button(new Rect(30,50,180,30),"Set Value")){ SetData(); } if(GUI.Button(new Rect(30,100,180,30),"Get Value")){ GetData (); } } void SetData(){ //key, value PlayerPrefs.SetInt ("Score", 100); PlayerPrefs.SetString ("Name", "홍길동"); } void GetData(){ //get Value by Key int myScore = PlayerPrefs.GetInt("Score"); string myName = PlayerPrefs.GetString ("Name", "N/A"); if(EditorUtility.DisplayDialog("알림","출력할 내용을 선택하세요.","이름"," 점수")){ Debug.Log("Name : "+myName); } else{ Debug.Log ("Score : " + myScore); } } }
bb7485ac14e3b4a48dfa4103dae31eae88c14a92
C#
dvzghr/CSharpNutshell
/Polymorphism/Program.cs
3.109375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphism { public class Program { static void Main(string[] args) { int x, y; Console.WriteLine("\nbaseClass = new BaseClass()\n-------------"); BaseClass baseClass = new BaseClass(2); baseClass.Read(); baseClass.Write(); baseClass.WritePrivate(); //Private baseClass.WriteVirtual(); x = baseClass.SimpleNumber; y = baseClass.ProtectedNumber; //Protected Console.WriteLine("\nbaseClass = new DerivedClass()\n-------------"); BaseClass baseDerived = new DerivedClass(); baseDerived.Read(); baseDerived.Write(); baseDerived.WritePrivate(); //Private baseDerived.WriteVirtual(); baseDerived.DerivedMethod(); //Compiler error x = baseDerived.SimpleNumber; y = baseDerived.ProtectedNumber; //Protected Console.WriteLine("\nderivedClass = new DerivedClass()\n-------------"); DerivedClass derived = new DerivedClass(); derived.Read(); derived.Write(); derived.WritePrivate(); //Private derived.WriteVirtual(); derived.DerivedMethod(); x = baseDerived.SimpleNumber; y = baseDerived.ProtectedNumber; //Protected Console.WriteLine("\nibaseClass = new BaseClass()\n-------------"); IInterface iBaseClass = new BaseClass(3); iBaseClass.Read(); iBaseClass.Write(); //NoVirtualMethod!!! Console.WriteLine("============="); Console.WriteLine("*************"); Console.WriteLine("\nderivedAbstract = new DerivedFromAbstractClass()\n-------------"); var derivedAbstract = new DerivedFromAbstractClass(); Console.ReadKey(); var baseClass2 = new BaseClass(33); IInterface interfaceClass = baseClass2; var baseClass3 = (BaseClass)interfaceClass; Console.WriteLine(baseClass3.SimpleNumber); } } public class BaseClass : IInterface { public BaseClass(int x) { SimpleNumber = x; ProtectedNumber = x + 1; WritePrivate(); } public int SimpleNumber { get; set; } protected int ProtectedNumber { get; set; } public void Write() { Console.WriteLine("Write BaseClass"); } public void Read() { } private void WritePrivate() { Console.WriteLine("WritePrivate BaseClass"); } public virtual void WriteVirtual() { Console.WriteLine("WriteVirtual BaseClass"); } } public class DerivedClass : BaseClass { public DerivedClass() : base(2) { ProtectedNumber = 100; //WritePrivate(); //Base: Private } public void DerivedMethod() { Console.WriteLine(ProtectedNumber); } public int DerivedNumber { get; set; } public void Write() { Console.WriteLine("Write DerivedClass"); } public override void WriteVirtual() { Console.WriteLine("WriteVirtual DerivedClass"); } } interface IInterface { void Write(); void Read(); } public abstract class AbstractClass { private int _broj; public int BrojDrugi { get; set; } protected int BrojProtected { get; set; } } public class DerivedFromAbstractClass : AbstractClass { public DerivedFromAbstractClass() { } } }
e4330d11cfc85987a0d6d9554e1dd1fba2687321
C#
nadita/vj
/Obligatorio 2 PV/Practico/Game.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Practico { public class Game { public Stage actualStage; public int actual_stage; public int actual_lives; public String message; public Boolean end_time; public Boolean bomberman_is_dead; public Boolean level_finished; public int actual_score; public int[][] levels; public int max_stage; public int total_stages; //Time public DateTime time_lag; public int actual_time; private static Game instance = null; public static Game GetInstance() { if (instance == null) { instance = new Game(); } return instance; } private Game() { this.actual_lives = 3; this.actual_stage = 0; this.message = ""; this.end_time = false; this.bomberman_is_dead = false; this.level_finished = false; this.actual_score = 0; this.max_stage = 1; this.total_stages = 3; this.time_lag = DateTime.Now; this.actual_time = 120; } public void InitializeGameObjectValues() { //Initializing bomberman_is_dead = false; level_finished = false; end_time = false; actualStage = new Stage(); Level actualLevel = XmlMngr.GetInstance().levels[actual_stage]; //Loading Blocks Data foreach (string[] block in actualLevel.blocks) { Cell newBlock = new Cell(Cell.BLOCK, Cell.NONE); int x = int.Parse(block[0]); int y = int.Parse(block[1]); actualStage.addItem(newBlock, x, y); } //Loading PowerUps Data foreach (string[] powerUp in actualLevel.powerUps) { Cell newPowerUp = new Cell(Cell.POWERUP, powerUp[0]); int x = int.Parse(powerUp[1]); int y = int.Parse(powerUp[2]); actualStage.addItem(newPowerUp, x, y); } //Loading Enemies Data foreach (string[] enemy in actualLevel.enemies) { int x = int.Parse(enemy[1]); int y = int.Parse(enemy[2]); Enemy newEnemy = new Enemy(enemy[0], x, y); actualStage.addEnemy(newEnemy); } } public void updateTime() { DateTime now = DateTime.Now; if (now.Subtract(this.time_lag).TotalMilliseconds >= 1000 && this.actual_time >= 0) { //Update actual time this.actual_time--; this.time_lag = DateTime.Now; //Update bombs foreach (Bomb b in actualStage.bombs) { b.time--; } } } } }
10e9d0754fdfdefe7c6c40ef09d3639850df9bd0
C#
StefanIvanovIvanov/SoftUni
/Programming Fundamentals-Extended/MoreArraysExercise/17.JumpAround/Program.cs
3.59375
4
using System; using System.Linq; namespace _17.JumpAround { class Program { static void Main(string[] args) { int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray(); int jump = 0; int sum = 0; bool hasMoved = true; while (hasMoved) { hasMoved = false; sum += numbers[jump]; if (numbers[jump] + jump <= numbers.Length) { jump += numbers[jump]; hasMoved = true; }else if (jump-numbers[jump] >= 0) { jump -= numbers[jump]; hasMoved = true; } } Console.WriteLine(sum); } } }
b80ea7de46ce4743fb66d8285f4c1846005fac80
C#
ruthqv/SqLiteEF
/SqLiteEF/AgregateWindow.xaml.cs
2.703125
3
using Data.SqLiteEF; using SqLiteEF.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SqLiteEF { /// <summary> /// Lógica de interacción para AgregateWindow.xaml /// </summary> public partial class AgregateWindow : Window { private Books book; public AgregateWindow(Books book = null) { InitializeComponent(); if(book != null) { this.book = book; FillForm(); } } private void FillForm() { txtTitle.Text = book.title; txtAuthor.Text = book.author; txtPrice.Text = book.price.ToString(); } private void BtnSave_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(txtTitle.Text) || string.IsNullOrEmpty(txtAuthor.Text) || string.IsNullOrEmpty(txtPrice.Text)) { MessageBox.Show("Todos los datos son obligatorios", "Error", MessageBoxButton.OK, MessageBoxImage.Error); txtTitle.Focus(); return; } if (book != null) { book.title = txtTitle.Text; book.author = txtAuthor.Text; book.price = float.Parse(txtPrice.Text); BookManager.UpdateBook(book); } else { var bookNew = new Books() { title = txtTitle.Text, author = txtAuthor.Text, price = float.Parse(txtPrice.Text) }; BookManager.InsertBook(bookNew); } this.Close(); MainWindow main = new MainWindow(); main.RefreshDatas(); } private void BtnCancel_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
c6e2e0b1931180ff9956dd2e34e4f963f15607e0
C#
dcornish84/Student-Exercises
/Program.cs
3.4375
3
using System; using System.Collections.Generic; using System.Linq; namespace StudentExercises { class Program { static void Main(string[] args) { // Exercises var planYourHeist = new Exercise("Plan Your Heist", "C Sharp"); var designClassWebsite = new Exercise("Design Class Website", "UI/UX"); var urbanPlanner = new Exercise("Urban Planner", "C Sharp"); var dictionaryOfWords = new Exercise("Dictionary of Words", "C Sharp"); var jsArrays = new Exercise("Javascript Arrays", "Javascript"); var jsObjects = new Exercise("Javascript Objects", "Javascript"); // Cohorts var cohort35 = new Cohort("Cohort 35"); var cohort36 = new Cohort("Cohort 36"); var cohort37 = new Cohort("Cohort 37"); // Students var nickWessel = new Student("Nick", "Wessel", "Nick Wessel", 35); var philGriswold = new Student("Phil", "Griswold", "Phil Griswold", 35); var heidiSpradlin = new Student("Heidi", "Spradlin", "Heidi Spradlin", 35); var sageKlein = new Student("Sage", "Klein", "Sage Klein", 35); var garyGoober = new Student("Gary", "Goober", "Gary Goober", 36); var donnyDingbat = new Student("Donny", "Dingbat", "Donny Dingbat", 37); // Instructors var madisonPepper = new Instructor("Madi", "Pepper", "Madi Pepper", 35, "Vacations"); var adamSheaffer = new Instructor("Adam", "Sheaffer", "Adam Sheaffer", 35, "Ice Cream"); var brendaLong = new Instructor("Brenda", "Long", "Brenda Long", 35, "Smiling"); // Add Students To Cohort cohort35.Students.Add(nickWessel); cohort35.Students.Add(philGriswold); cohort35.Students.Add(heidiSpradlin); cohort35.Students.Add(sageKlein); cohort36.Students.Add(garyGoober); cohort37.Students.Add(donnyDingbat); // Instructors Assigning Exercises brendaLong.assignExercise(cohort35.Students, designClassWebsite); adamSheaffer.assignExercise(cohort35.Students, planYourHeist); adamSheaffer.assignExercise(cohort35.Students, dictionaryOfWords); madisonPepper.assignExercise(cohort35.Students, urbanPlanner); madisonPepper.assignExercise(cohort36.Students, jsArrays); brendaLong.assignExercise(cohort37.Students, jsObjects); /* Create a list of students. Add all of the student instances to it. */ List<Student> StudentList = new List<Student>() { nickWessel, philGriswold, heidiSpradlin, sageKlein, garyGoober, donnyDingbat }; /* Create a list of exercises. Add all of the exercise instances to it. */ List<Exercise> ExerciseList = new List<Exercise>() { planYourHeist, designClassWebsite, urbanPlanner, dictionaryOfWords, jsArrays, jsObjects }; /* Generate a report that displays which students are working on which exercises. */ foreach (Student student in StudentList) { List<string> currentExercises = new List<string>(); foreach (Exercise exercise in ExerciseList) { currentExercises.Add(exercise.Name); }; Console.WriteLine($"{student.FirstName} {student.LastName} is working on {String.Join(", ", currentExercises)}"); } /* PART 2 */ /* Create 4 new List instances: one to contain students, one to contain exercises, \ one to contain instructors, and one to contain cohorts. */ List<Student> students = new List<Student>() { nickWessel, philGriswold, heidiSpradlin, sageKlein, garyGoober, donnyDingbat }; List<Exercise> exercises = new List<Exercise>() { planYourHeist, designClassWebsite, urbanPlanner, dictionaryOfWords, jsArrays, jsObjects }; List<Instructor> instructors = new List<Instructor>() { adamSheaffer, madisonPepper, brendaLong }; List<Cohort> cohorts = new List<Cohort>() { cohort35, cohort36, cohort37 }; // List exercises for the JavaScript language by using the Where() LINQ method. var jsExercises = (from exercise in exercises where exercise.Language == "Javascript" select exercise).ToList(); Console.WriteLine(""); Console.WriteLine("Javascript Exercises:"); Console.WriteLine("-------"); jsExercises.ForEach(exercise => { Console.WriteLine(exercise.Name); }); // List students in a particular cohort by using the Where() LINQ method. List<Student> cohort35Students = (from student in students where student.Cohort == 35 select student).ToList(); Console.WriteLine(""); Console.WriteLine("Cohort 35 Students:"); Console.WriteLine("-------"); cohort35Students.ForEach(student => { Console.WriteLine($"{student.FirstName} {student.LastName}"); }); // List instructors in a particular cohort by using the Where() LINQ method. List<Instructor> cohort35Instructors = (from instructor in instructors where instructor.Cohort == 35 select instructor).ToList(); Console.WriteLine(""); Console.WriteLine("Cohort 35 Instructors:"); Console.WriteLine("-------"); cohort35Instructors.ForEach(instructor => { Console.WriteLine($"{instructor.FirstName} {instructor.LastName}"); }); // Sort the students by their last name. List<Student> orderedLastNameStudents = students.OrderBy(student => student.LastName).ToList(); Console.WriteLine(""); Console.WriteLine("Students by last name:"); Console.WriteLine("-------"); orderedLastNameStudents.ForEach(student => Console.WriteLine($"{student.FirstName} {student.LastName}")); // Display any students that aren't working on any exercises (Make sure one of your student instances don't have any exercises. Create a new student if you need to.) List<Student> noStudentExercises = (from student in students where student.Exercises.Count == 0 select student).ToList(); Console.WriteLine(""); Console.WriteLine("This student is not working on anything:"); Console.WriteLine("-------"); noStudentExercises.ForEach(student => Console.WriteLine($"{student.FirstName} {student.LastName}")); //Which student is working on the most exercises? Make sure one of your students has more exercises than the others. List<Student> mostStudentExercises = (from student in students orderby student.Exercises.Count descending select student).ToList(); Student mostExercises = mostStudentExercises.First(); Console.WriteLine($"Student working on most exercises: {mostExercises.FirstName} {mostExercises.LastName}"); Console.WriteLine("-------"); // How many students in each cohort? Console.WriteLine(""); Console.WriteLine("Students in each Cohort:"); Console.WriteLine("-------"); cohorts.ForEach(cohort => Console.WriteLine($"{cohort.Name} - {cohort.Students.Count}")); } } }
05b89f327663b27eb65a91ece0c3ce0bd38fd644
C#
szp35/CefSharpDemo
/CefDemo/CefDemo/CefDemo/ThreadQueue.cs
2.8125
3
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace CefDemo { /// <summary> /// 先入先出线程队列 /// </summary> class ThreadQueue { #region 成员字段 //线程锁 private static object _lock = new object(); //在等待中的线程队列 private static ConcurrentQueue<ThreadQueue> _ThreadQuery = new ConcurrentQueue<ThreadQueue>(); //要处理的线程 private Task<Task<CefSharp.JavascriptResponse>> _action = null; //返回值 private Task<CefSharp.JavascriptResponse> _result = null; public Task<CefSharp.JavascriptResponse> Result { get { return _result; } } public GoogleWebBrowser _webBrowser = null; #endregion #region 构造函数 public ThreadQueue(Task<Task<CefSharp.JavascriptResponse>> handle, GoogleWebBrowser webB) { this._action = handle; this._webBrowser = webB; } #endregion #region 将线程加入线程队列等待自动执行 /// <summary> /// 将线程加入线程队列等待处理 /// </summary> /// <param name="isBackground">是否为后台线程</param> public void Start(bool isBackground = true) { _ThreadQuery.Enqueue(this); Thread th = new Thread(() => { bool isEnter = Monitor.TryEnter(_lock); if (isEnter) { while (!_ThreadQuery.IsEmpty) { while (!(_webBrowser.IsChromeLoaded && _webBrowser.IsDocumentLoaded)) { Thread.Sleep(15); } ThreadQueue task; _ThreadQuery.TryDequeue(out task); task._action.Start(); task._action.Wait(); this._result = task._action.Result; } Monitor.Exit(_lock); } }); th.SetApartmentState(ApartmentState.STA); th.IsBackground = isBackground; th.Start(); } #endregion public void Wait() { SpinWait sw = new SpinWait(); while (null == this._result) { sw.SpinOnce(); } } } }
71244237438adf2a3a56e72d0dfd4f0e4a0c7cad
C#
Arctic94/c-sharp-Projects
/Venta pasajes Windows Forms + MySql/Pasajes.Negocio/PasajeMaritimo.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Pasajes.Datos; namespace Pasajes.Negocio { public class PasajeMaritimo:Pasaje { private int _idMaritimo; public int IdMaritimo { get { return _idMaritimo; } set { _idMaritimo = value; } } private string _nombreMuelle; public string NombreMuelle { get { return _nombreMuelle; } set { _nombreMuelle = value; } } public PasajeMaritimo(int id,string nombre, string rut, DateTime fechanacimiento, string sexo, string direccion, string telacc, string telper, string destino, DateTime fechaviaje, string nombremuelle,int idMaritimo):base(id,nombre,rut,fechanacimiento,sexo,direccion,telacc,telper,destino,fechaviaje) { IdMaritimo=idMaritimo; NombreMuelle=nombremuelle; } public PasajeMaritimo( string nombre, string rut, DateTime fechanacimiento, string sexo, string direccion, string telacc, string telper, string destino, DateTime fechaviaje, string nombremuelle, int idMaritimo) : base( nombre, rut, fechanacimiento, sexo, direccion, telacc, telper, destino, fechaviaje) { IdMaritimo = idMaritimo; NombreMuelle = nombremuelle; } public PasajeMaritimo():base() { // TODO: Complete member initialization } public bool CreatePasajeMaritimo() { try { StringBuilder sb = new StringBuilder(); string fecha = _fechaNacimiento.ToString("u"); fecha = fecha.Replace("Z", " "); fecha.Trim(); _fechaNacimiento = Convert.ToDateTime(fecha); string fechav = _fechaViaje.ToString("u"); fechav = fechav.Replace("Z", " "); fechav.Trim(); _fechaViaje = Convert.ToDateTime(fechav); // sb.Append(string.Format("insert into pasaje_base (nombre_pasajero, rut, sexo, fecha_nacimiento,direccion,telefono_emergencia,telefono_contacto,destino,fecha_viaje) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", _nombrePasajero, _rutPasajero, _sexo, fecha, _direccionPasajero, _telefonoAccidente, _telefonoPersonal, _destinoViaje, fechav)); Console.WriteLine(sb.ToString()); Conector con = new Conector(); //con.EjecutarComando(sb.ToString()); sb.Append(string.Format("insert into pasaje_marino (codigo,id_pasaje, nombre_muelle) values ({0},{1},'{2}')", _idMaritimo, _id, _nombreMuelle)); Console.WriteLine(sb.ToString()); con.EjecutarComando(sb.ToString()); return true; } catch { return false; } } } }
ff0615b66a917594ae28555d430faad6fbcebe21
C#
qoollo/bob-client-net
/BobClient/Qoollo.BobClient/IBobApi.cs
2.875
3
using System.Threading; using System.Threading.Tasks; namespace Qoollo.BobClient { /// <summary> /// Bob api /// </summary> public interface IBobApi { /// <summary> /// Writes data to Bob /// </summary> /// <param name="key">Key</param> /// <param name="data">Binary data</param> /// <param name="token">Cancellation token</param> /// <returns>Operation result</returns> void Put(BobKey key, byte[] data, CancellationToken token); /// <summary> /// Writes data to Bob asynchronously /// </summary> /// <param name="key">Key</param> /// <param name="data">binary data</param> /// <param name="token">Cancellation token</param> /// <returns>Operation result</returns> Task PutAsync(BobKey key, byte[] data, CancellationToken token); /// <summary> /// Reads data from Bob /// </summary> /// <param name="key">Key</param> /// <param name="token">Cancellation token</param> /// <returns>Operation result</returns> byte[] Get(BobKey key, CancellationToken token); /// <summary> /// Reads data from Bob asynchronously /// </summary> /// <param name="key">Key</param> /// <param name="token">Cancellation token</param> /// <returns>Operation result with data</returns> Task<byte[]> GetAsync(BobKey key, CancellationToken token); /// <summary> /// Checks data presented in Bob /// </summary> /// <param name="keys">Keys array</param> /// <param name="token">Cancellation token</param> /// <returns>Operation result</returns> bool[] Exists(BobKey[] keys, CancellationToken token); /// <summary> /// Asynchronously checks data presented in Bob /// </summary> /// <param name="keys">Keys array</param> /// <param name="token">Cancellation token</param> /// <returns>Operation result</returns> Task<bool[]> ExistsAsync(BobKey[] keys, CancellationToken token); } }
f7ea4310ac64a6132f4a790e6d51b8ffb7c161c0
C#
zawupf/aoc
/2021/csharp/Aoc2021/Day12.cs
3.09375
3
namespace Aoc2021; public class Day12 : IDay { public override string Day { get; } = nameof(Day12)[3..]; public override string Result1() { return PathCount(InputLines) .ToString(CultureInfo.InvariantCulture); } public override string Result2() { return ExtraPathCount(InputLines) .ToString(CultureInfo.InvariantCulture); } public static int PathCount(IEnumerable<string> lines) { List<(string, string)> ways = Parse(lines); return Pathes(ways).Count(); } public static int ExtraPathCount(IEnumerable<string> lines) { List<(string, string)> ways = Parse(lines); HashSet<string> smallCaves = ways .Aggregate( new HashSet<string>(), (smallCaves, way) => { if (IsSmallInnerCave(way.Item1)) { _ = smallCaves.Add(way.Item1); } else if (IsSmallInnerCave(way.Item2)) { _ = smallCaves.Add(way.Item2); } return smallCaves; } ); return smallCaves .Aggregate( new HashSet<string>(), (pathes, cave) => { pathes.UnionWith(Pathes(ways, cave)); return pathes; } ) .Count; } private static IEnumerable<string> Pathes(List<(string, string)> ways, string specialCave = "") { return Walk("start", new(), ways, specialCave); static IEnumerable<string> Walk(string cave, List<string> path, List<(string, string)> ways, string specialCave) { path = new List<string>(path) { cave }; if (cave == "end") { yield return string.Join(',', path); } List<string> nextCaves = ways .Aggregate( new List<string>(), (caves, way) => { (string cave1, string cave2) = way; if (cave1 == cave) { caves.Add(cave2); } else if (cave2 == cave) { caves.Add(cave1); } return caves; } ); if (IsSmallCave(cave)) { if (cave == specialCave) { specialCave = ""; } else { ways = ways .Where(way => way.Item1 != cave && way.Item2 != cave) .ToList(); } } foreach (string nextCave in nextCaves) { IEnumerable<string> pathes = Walk(nextCave, path, ways, specialCave); foreach (string p in pathes) { yield return p; } } } } private static List<(string, string)> Parse(IEnumerable<string> lines) { return lines .Select(line => { string[] chunks = line.Split('-'); return (chunks[0], chunks[1]); }) .ToList(); } private static readonly HashSet<char> lowerLetters = "abcdefghijklmnopqrstuvwxyz".ToHashSet(); private static bool IsSmallCave(string name) { return lowerLetters.Contains(name[0]); } private static bool IsSmallInnerCave(string name) { return name is not "start" and not "end" && lowerLetters.Contains(name[0]); } }
9fba4530efb0e45c07bdb4be61ab9dc516f95a73
C#
kakaggarwal/Practice
/Practice/ProgProblems/Problem6.cs
3.546875
4
using System; namespace Practice.ProgProblems { // Sum Square Difference class Problem6 { public static void Solution() { Console.WriteLine("Enter N: "); int n = Convert.ToInt32(Console.ReadLine()); long sumOfSquares = 0; long squareOfSum = 0; for (int i = 1; i < (n + 1); i++) { sumOfSquares += i * i; squareOfSum += i; } squareOfSum *= squareOfSum; Console.WriteLine(squareOfSum - sumOfSquares); } } }
c911f83b5ebc4232651bac18367deef1d850cf53
C#
Morzkat/WebApplication
/BuyYourMovie/DataLayer/MovieData.cs
3.375
3
using System; using System.Collections.Generic; using System.Data.SqlClient; using Microsoft.Extensions.Configuration; using BuyYourMovie.Models; using System.Data; namespace BuyYourMovie.DataLayer { //Class for comunicate with the DataBase public class MovieData : IDataLayer<Movie> { //The connection with the db private SqlConnection connection; private String connectionString; public MovieData(IConfiguration configuration) { //The connection string with the direction the of DataBase, locate in the appsettings.json connectionString = configuration.GetConnectionString("localDB"); //Make the connection connection = new SqlConnection(connectionString); } SqlConnection IDataLayer<Movie>.connection { //Getter method for get the connection get => connection = new SqlConnection(connectionString); } //Delete by id public bool DeleteById(int id) { Boolean status = false; if (id != 0) { //Params for the insert / Made a real_escape_string SqlParameter sqlParameter = new SqlParameter("@id", id); //Assign the query var query = "delete from Movie where id = @id"; //Add the parameter to the query using (SqlConnection conne = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand()) { command.Connection = conne; command.CommandType = CommandType.Text; command.CommandText = query; //Parameters added to the command command.Parameters.Add(sqlParameter); try { //Open the connection conne.Open(); command.ExecuteNonQuery(); //Close the connection conne.Close(); status = true; } catch (SqlException e) { Console.WriteLine("Error BD"); return false; } } } } return status; } //Get all the movies in the DataBase public IEnumerable<Movie> GetAll() { connection = new SqlConnection(connectionString); //Open the connection connection.Open(); //A list of movies List<Movie> movies = new List<Movie>(); //A Sql command o Query| SqlCommand command = new SqlCommand("SELECT * FROM Movie ORDER BY id DESC", connection); //Get all the values of the reader all the values came from the DB using (var reader = command.ExecuteReader()) { //While the reader has values while (reader.Read()) { //Create a new movie Movie movie = new Movie ( Convert.ToInt32 ( reader["id"]), reader["movieName"].ToString(), reader["movieSipnosis"].ToString(), reader["movieGender"].ToString(), reader["moviePublished"].ToString(), reader["image"].ToString(), Convert.ToInt32(reader["starts"]) ); //Add the movie to the list of movies movies.Add(movie); } } //Close the connection connection.Close(); //Return all the movies return movies; } public Movie GetById(int id) { Movie movie = null; if (id != 0) { //Open the connection connection.Open(); //Params for the search / Made a real_escape_string SqlParameter sqlParameter = new SqlParameter("@id", id); //A Sql command o Query|Assign the query SqlCommand command = new SqlCommand("SELECT * FROM Movie WHERE id = @id", connection); //Add the parameter to the query command.Parameters.Add(sqlParameter); //Get all the values of the reader all the values came from the DB using (var reader = command.ExecuteReader()) { //While the reader has values while (reader.Read()) { //Create a new movie movie = new Movie ( Convert.ToInt32(reader["id"]), reader["movieName"].ToString(), reader["movieSipnosis"].ToString(), reader["movieGender"].ToString(), reader["moviePublished"].ToString(), reader["image"].ToString(), Convert.ToInt32(reader["starts"]) ); } } } //Close the connection connection.Close(); //Return all the movies return movie; } public IEnumerable<Movie> GetByGender(string movieGender) { List<Movie> movies = new List<Movie>(); if (movieGender != " ") { //Open the connection connection.Open(); //Params for the search / Made a real_escape_string SqlParameter sqlParameter = new SqlParameter("@movieGender", movieGender); //A Sql command o Query|Assign the query SqlCommand command = new SqlCommand("SELECT * FROM Movie WHERE movieGender = @movieGender ORDER BY id DESC", connection); ; // //Add the parameter to the query command.Parameters.Add(sqlParameter); //Get all the values of the reader all the values came from the DB using (var reader = command.ExecuteReader()) { //While the reader has values while (reader.Read()) { //Create a new movie Movie movie = new Movie ( Convert.ToInt32(reader["id"]), reader["movieName"].ToString(), reader["movieSipnosis"].ToString(), reader["movieGender"].ToString(), reader["moviePublished"].ToString(), reader["image"].ToString(), Convert.ToInt32(reader["starts"]) ); movies.Add(movie); } } } //Close the connection connection.Close(); //Return all the movies return movies; } public Boolean Post(Movie newLog) { Boolean status = false; if (newLog != null ) { //Params for the insert / Made a real_escape_string SqlParameter[] sqlParameter = new SqlParameter[6]; //Adding all params sqlParameter[0] = new SqlParameter("@movieName", newLog.movieName); sqlParameter[1] = new SqlParameter("@movieSipnosis", newLog.movieSipnosis); sqlParameter[2] = new SqlParameter("@movieGender", newLog.movieGender); sqlParameter[3] = new SqlParameter("@moviePublished", newLog.moviePublished); sqlParameter[4] = new SqlParameter("@movieImage", newLog.image); sqlParameter[5] = new SqlParameter("@starts", newLog.starts); //Assign the query var query = "insert into Movie (movieName, movieSipnosis, movieGender, " + "moviePublished, image, starts) VALUES (@movieName, @movieSipnosis, @movieGender, " + "@moviePublished, @movieImage, @starts);"; //Add the parameter to the query using (SqlConnection conne = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand()) { command.Connection = conne; command.CommandType = CommandType.Text; command.CommandText = query; //Parameters added to the command command.Parameters.Add(sqlParameter[0]); command.Parameters.Add(sqlParameter[1]); command.Parameters.Add(sqlParameter[2]); command.Parameters.Add(sqlParameter[3]); command.Parameters.Add(sqlParameter[4]); command.Parameters.Add(sqlParameter[5]); try { //Open the connection conne.Open(); command.ExecuteNonQuery(); //Close the connection conne.Close(); status = true; } catch (SqlException e) { Console.WriteLine("Error BD"); return false; } } } } return status; } public bool Put(Movie updateLog, int id) { Boolean status = false; if (updateLog != null) { //Params for the insert / Made a real_escape_string SqlParameter[] sqlParameter = new SqlParameter[7]; //Adding all params sqlParameter[0] = new SqlParameter("@movieName", updateLog.movieName); sqlParameter[1] = new SqlParameter("@movieSipnosis", updateLog.movieSipnosis); sqlParameter[2] = new SqlParameter("@movieGender", updateLog.movieGender); sqlParameter[3] = new SqlParameter("@moviePublished", updateLog.moviePublished); sqlParameter[4] = new SqlParameter("@movieImage", updateLog.image); sqlParameter[5] = new SqlParameter("@starts", updateLog.starts); sqlParameter[6] = new SqlParameter("@id", id); //Assign the query var query = "UPDATE Movie SET movieName = @movieName, MovieSipnosis = @movieSipnosis, movieGender = @movieGender," + "moviePublished = @moviePublished, image = @movieImage, starts = @starts WHERE id = @id; "; //Add the parameter to the query using (SqlConnection conne = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand()) { command.Connection = conne; command.CommandType = CommandType.Text; command.CommandText = query; //Parameters added to the command command.Parameters.Add(sqlParameter[0]); command.Parameters.Add(sqlParameter[1]); command.Parameters.Add(sqlParameter[2]); command.Parameters.Add(sqlParameter[3]); command.Parameters.Add(sqlParameter[4]); command.Parameters.Add(sqlParameter[5]); command.Parameters.Add(sqlParameter[6]); try { //Open the connection conne.Open(); command.ExecuteNonQuery(); //Close the connection conne.Close(); status = true; } catch (SqlException e) { Console.WriteLine("Error BD"); return false; } } } } return status; } } }
156f714108ccf15d0fda22b1b008b7d48c8e86dd
C#
vivaHappyCrab/dnd5
/CharacterBase/Entities/Character.cs
2.515625
3
using System.Collections.Generic; using System.IO.Compression; namespace CharacterBase.Entities { public class Character { public string Name; public Class Class { get; set; } public Race Race { get; set; } public Background Background { get; set; } public Inventory Inventory { get; set; } public int Level { get; set; } public List<Class> MultiClasses { get; set; } public int ProfiencyBonus => this.Level/5 + 2; } }
53f0e4f400d2aa056677f6d4d3dcef857fabd21d
C#
shendongnian/download4
/code10/1749850-50884223-175690744-2.cs
2.984375
3
using System; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; namespace ClassLibrary1 { public class WorkerProducer { public async Task ProduceWorker() { //await ProductTransformer_Transformer.SendAsync(new Worker()) } } public class ProductTransformer { public IObservable<Product> Products { get; private set; } public TransformBlock<Worker, Product> Transformer { get; private set; } private Task<Product> CreateProductAsync(Worker worker) => Task.FromResult(new Product()); public ProductTransformer() { Transformer = new TransformBlock<Worker, Product>(wrk => CreateProductAsync(wrk)); Products = Transformer.AsObservable(); } } public class ProductConsumer { private ThirdParty ThirdParty { get; set; } = new ThirdParty(); private ProductTransformer Transformer { get; set; } public ProductConsumer() { ThirdParty.CheckProducts(Transformer.Products.ToEnumerable()); } public class Worker { } public class Product { } public class ThirdParty { public void CheckProducts(IEnumerable<Product> products) { } } }
d8edb0c846e553ef5654017b0b0b1149ad522e98
C#
duarte25/uriSolution
/Uri1963.cs
3
3
using System; class Uri { static void Main(string[] args) { string[] val = Console.ReadLine().Split(' '); double a = double.Parse(val[0]); double b = double.Parse(val[1]); Console.WriteLine("Eerro "+b); Console.WriteLine((((b - a) / a) * 100.0).ToString("F2")+"%"); } }
042556dd9c84cc69c6bc5a4031fd404ee21cce9f
C#
linksdeity/Lab14
/GrandCircusLab14/Alligatorcs.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GrandCircusLab14 { class Alligator : ICountable { private int Count { get; set; } public string Name { get; set; } public void IncrementCount() { Count++; } public void ResetCount() { Count = 0; } public int GetCount() { return Count; } public string GetCountString() { return Count.ToString(); } } }
9dbc4b2f9a8b9ea114198759711018ee8dfd34c3
C#
jbojacob/jbosolution
/Egenskaber_demo/Program.cs
2.734375
3
using System; namespace Egenskaber_demo { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } class Person { private int alder; public int Alder { get { return Alder; } set { Alder = value; } } private int myVar; public int MyProperty { get { return myVar; } set { myVar = value; } } } } }
38271a5a195b6b770b55c8f4cbf1009a101dee13
C#
Graunarmin/LostStation
/LostStation/Assets/Scripts/Inventory/Manager/ItemContainerManager.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class ItemContainerManager : MonoBehaviour { protected IItemContainer container; protected ItemSlot[] slots; public Transform itemsParent; protected virtual void Start() { container = new Inventory(); slots = itemsParent.GetComponentsInChildren<ItemSlot>(); container.SetSpace(2); } public virtual bool AddItem(Item item) { if (container.AddItem(item)) { UpdateUI(); return true; } return false; } public virtual void RemoveItem(Item item) { container.RemoveItem(item); UpdateUI(); } public virtual void RemoveItem(ItemAsset item) { container.RemoveItem(item); UpdateUI(); } protected virtual void UpdateUI(Item item = null, bool add = false) { for (int i = 0; i < slots.Length; i++) { if(i < container.Size()) { slots[i].AddItemToSlot(container.GetItemAtIndex(i)); } else { slots[i].ClearSlot(); } } } public int GetContainerSize() { return container.Size(); } public bool ContainerContainsItem(Item item) { if (container.ContainsItem(item)) { return true; } return false; } public bool ContainerContainsItem(ItemAsset item) { if (container.ContainsItem(item)) { return true; } return false; } public IItemContainer GetContainer() { return container; } }
0b3e6016815a21bb6bbfe194fd70e4c9ed22cce5
C#
santiagovdk/MyMusic
/MyMusic/BusinessLogic/NewBusinessLogic/clsNewBL.cs
2.546875
3
using DataAccess; using DTO; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Utility; namespace BusinessLogic.NewBusinessLogic { public class clsNewBL { clsFacadeDA FacadeDA = new clsFacadeDA(); clsDeserializeJson DeserializeJson = new clsDeserializeJson(); Serializer serializer = new Serializer(); public string createNew(string pstringRequest,int pintBandId) { clsRequest request = JsonConvert.DeserializeObject<clsRequest>(pstringRequest); clsNew New = DeserializeJson.DeserializeNew(request.Data.ToString()); clsResponse response = new clsResponse(); if (request.Id == pintBandId) { New.Id = FacadeDA.createnew(ref New, ref response, pintBandId); } New.BandName = null; New.Content = null; New.Date = null; New.Title = null; response.Data = serializer.Serialize(New); return serializer.Serialize(response); } public string getNewInfo(int pintNewId) { clsNew New = new clsNew(); clsResponse response = new clsResponse(); FacadeDA.getnew(ref New,ref response,pintNewId); New.Id = pintNewId; response.Data = serializer.Serialize(New); return serializer.Serialize(response); } } }
1c95411e6bf0f294531931a6052562f6906a7ba9
C#
MariaZhikhareva/var
/ConsoleApplication1/ConsoleApplication1/Program.cs
3.3125
3
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Введите второе число для умножения"); //Ввод числа с клавиатуры string s = Console.ReadLine(); int a = Convert.ToInt32(s); //Формула умножения int b = 2 * a; //Вывод ответа на экран Console.WriteLine(b); Console.ReadLine(); } } }
cc64066cc1e977c3f7b796831a34c97b4ecd8cf8
C#
LordBigDuck/BenchCrisis
/BenchCrisis.Core/Models/ValueObjects/PersonName.cs
3.046875
3
using BenchCrisis.Core.Models.Generics; using FluentResults; using System; using System.Collections.Generic; using System.Text; namespace BenchCrisis.Core.Models.ValueObjects { #nullable enable public class PersonName : ValueObject { public string? FirstName { get; } public string? LastName { get; } private PersonName(string? firstName, string? lastName) { FirstName = firstName; LastName = lastName; } public static Result<PersonName> Create(string? firstName = null, string? lastName = null) { if (string.IsNullOrWhiteSpace(firstName) && string.IsNullOrWhiteSpace(lastName)) return Result.Fail("Firstname and Lastname cannot be null"); if (firstName?.Length > 30) return Result.Fail("Firstname should not exceeds 30 characters"); if (lastName?.Length > 30) return Result.Fail("Firstname should not exceeds 30 characters"); return Result.Ok(new PersonName(firstName, lastName)); } protected override IEnumerable<object> GetEqualityComponents() { if (FirstName != null) yield return FirstName; if (LastName != null) yield return LastName; } } }
daa8accc8873e02f7c054ad9d694cd3705689bbb
C#
vilkan32/SoftUniProjects
/IntroAndBasicSyntax/ForeignLanguages/Program.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ForeignLanguages { class Program { static void Main(string[] args) { Dictionary<string, List<string>> Languages = new Dictionary<string, List<string>>(); Languages.Add("English", new List<string>()); Languages["English"].Add("USA"); Languages["English"].Add("England"); Languages.Add("Spanish", new List<string>()); Languages["Spanish"].Add("Argentina"); Languages["Spanish"].Add("Mexico"); Languages["Spanish"].Add("Spain"); string Input = Console.ReadLine(); int counter = 0; foreach (var item in Languages) { foreach (var something in item.Value) { if (something == Input) { Console.WriteLine(item.Key); counter++; } } } if (counter ==0) { Console.WriteLine("unknown"); } } } }
041e9d0589d3499deb75c240e6264c56e5501f1a
C#
Coki32/ElfTaskScheduler
/Zadatak1/SharedResources.cs
3.078125
3
using System; using System.Collections.Generic; using System.Text; using static Zadatak1.ElfTaskData; namespace Zadatak1 { /// <summary> /// Class provides a single method used for consuming resources /// shared between different tasks. It does locking and unlocking /// and notifies who is holding which resource /// </summary> class SharedResources { private static Dictionary<string, dynamic> globals = new Dictionary<string, dynamic>(); private static List<object> locks = new List<object>(); private static List<string> names = new List<string>(); public static void UseResource(string name, ResourceConsumer action, ElfTaskData etd) { try { int lockId = -1; lock (names) lock(locks) //lock both cause I don't want anyone messing with lists while editing { if (!names.Contains(name)) { names.Add(name); locks.Add(new object()); lockId = names.Count - 1; } else lockId = names.IndexOf(name); } lock (locks[lockId])//Guess I can't lock on elements of a Dictionary so this is the "solution" { etd.TakenResource(name);//flag it as taken etd.WantedResources.Remove(name);//now that you have it, you no longer /WANT/ it //Make sure that the name exists before accessing it if (!globals.ContainsKey(name)) globals[name] = new object(); dynamic res = globals[name]; action(ref res); globals[name] = res; } } finally//make sure we flag it as released in case scheduler wants to know { etd.ReleasedResource(name); } } } }
20868df8116732f01c3e8048c81095f712d63c33
C#
ameejac/Sanke_ladder_game
/snake_ladder.cs
3.25
3
using System; namespace snake__and__ladder_project { class Sanke_ladder_uc2 { static void Main(string[] args) { //Constants int NO_OPERATION = 0; int SNAKE_POSITION = 1; int LADDER_POSITION= 2; //variables int position = 0; Random random = new Random(); //computation int Move = random.Next(1,6); int option = random.Next(0, 2); Console.WriteLine("game start position is:" +position); Console.WriteLine("Got the move:" +Move); } } }
c8aa7a0f0fb1f4faca56cdc26175d83fe8776c2e
C#
jalpendesai/Into-the-Space-Unity
/Assets/Scripts/GameController.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameController : MonoBehaviour { public GameObject hazard; // Spawned enemies public Vector2 spawnValue; // Where do enemies spawn? public int hazardCount; // How many enemies? public float startWait; // How long do we wait for the 1st wave public float spawnWait; // How long between each asteroid spawn? public float waveWait; // How long between waves of enemies public SpawnEnemy[] spawnEnemy; public Text scoreText; public Text highScoreText; public Text restartText; public Text gameOverText; public Text livesText; private bool startGame = false; private bool gameOver; private bool restart; private float startTime; //private int score; //private int lives; private bool reloadScene = false; // Use this for initialization void Start () { gameOver = false; restart = false; scoreText.text = ""; restartText.text = ""; gameOverText.text = ""; livesText.text = ""; //score = 0; //lives = 4; UpdateScore (); UpdateLives(); UpdateHighScore(); StartCoroutine(SpawnWaves()); // Starts and calls my coroutine //StartCoroutine(SpawnEnemies()); } // Update is called once per frame void Update () { if (gameOver) { Restart(); } else { if (reloadScene) { StartCoroutine(ReloadScene(3)); reloadScene = false; } } if (restart) { if (Input.GetKeyDown (KeyCode.R)) { // Application.LoadLevel (Application.loadedLevel); -- DECPRICATED PlayerData.score = 0; PlayerData.lives = 4; restart = false; StartCoroutine(ReloadScene(3)); } } if (Input.GetKeyDown (KeyCode.Escape)) { Application.Quit (); } } void FixedUpdate() { //if(!gameOver && startGame) //{ //} if(PlayerData.score > PlayerData.HighScore) { PlayerData.HighScore = PlayerData.score; } } IEnumerator SpawnWaves() { yield return new WaitForSeconds(startWait); while(true) { for(int i = 0; i < hazardCount; i++) { Vector2 spawnPosition = new Vector2(spawnValue.x, Random.Range(-spawnValue.y, spawnValue.y)); Quaternion spawnRotation = Quaternion.identity; Instantiate(hazard, spawnPosition, spawnRotation); yield return new WaitForSeconds(spawnWait); } yield return new WaitForSeconds(waveWait); if(gameOver) { restartText.gameObject.SetActive (true); restartText.text = "Press R for Restart"; restart = true; break; } } } //IEnumerator SpawnEnemies() //{ // yield return new WaitForSeconds(startWait); // for(int i = 0; i < SpawnEnemy.Length, i++) // { // } //} IEnumerator ReloadScene(float waitTime) { yield return new WaitForSeconds(waitTime); startGame = false; SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); startTime = Time.time; } public void Restart() { restart = true; } public void AddScore(int newScoreValue) { PlayerData.score += newScoreValue; // score = score + newScoreValue; UpdateScore(); } public void ReduceLives() { PlayerData.lives --; reloadScene = true; UpdateLives(); //if (lives == 0) //{ // GameOver(); //} } public bool LivesLeft() { return PlayerData.lives > 0; } void UpdateScore() { // Text for the score will go here! scoreText.text = "Score: " + PlayerData.score; } void UpdateHighScore() { highScoreText.text = "HighScore: " + PlayerData.HighScore; } //void AddHighScore(int newHighestScore) //{ // PlayerData.HighScore += newHighestScore(); // UpdateHighScore(); //} void UpdateLives() { livesText.text = "Lives: " + PlayerData.lives; } public void GameOver() { gameOverText.gameObject.SetActive (true); gameOverText.text = "Game Over!"; gameOver = true; } }
34a9006950c53e32eb9195bcc52a5fbde847a93e
C#
Cimpress/FomaSdk.Net
/src/Model/OrderRequestLinks.cs
2.734375
3
using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; namespace Cimpress.Clients.Foma.Model { /// <summary> /// The Links associated with the order request /// </summary> [DataContract] public class OrderRequestLinks { /// <summary> /// The fulfiller to create the order request for. /// </summary> /// <value>The fulfiller to create the order request for.</value> [DataMember(Name="fulfiller", EmitDefaultValue=false)] [JsonProperty(PropertyName = "fulfiller")] public LinkDto Fulfiller { get; set; } /// <summary> /// If the items are sourced elsewhere, this is an optional link to that resource. /// </summary> /// <value>If the items are sourced elsewhere, this is an optional link to that resource.</value> [DataMember(Name="source", EmitDefaultValue=false)] [JsonProperty(PropertyName = "source")] public LinkDto Source { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderRequestLinks {\n"); sb.Append(" Fulfiller: ").Append(Fulfiller).Append("\n"); sb.Append(" Source: ").Append(Source).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
23d948e03e266bcc8ca3ad371c1e313b326b2a03
C#
bramerdaniel/ConsoLovers
/src/Toolkit/ConsoLovers.ConsoleToolkit/Console/FrequencyBasedColorAlternator.cs
3.5625
4
namespace ConsoLovers.ConsoleToolkit.Console { using System; using System.Drawing; using System.Linq; /// <summary> /// Exposes methods and properties used for alternating over a set of colors according to /// frequency of use. /// </summary> public sealed class FrequencyBasedColorAlternator : ColorAlternator, IPrototypable<FrequencyBasedColorAlternator> { private readonly int alternationFrequency; private int writeCount; /// <summary> /// Exposes methods and properties used for alternating over a set of colors according to /// frequency of use. /// </summary> /// <param name="alternationFrequency">The number of times GetNextColor must be called in order for /// the color to alternate.</param> /// <param name="colors">The set of colors over which to alternate.</param> public FrequencyBasedColorAlternator(int alternationFrequency, params Color[] colors) : base(colors) { this.alternationFrequency = alternationFrequency; } public new FrequencyBasedColorAlternator Prototype() { return new FrequencyBasedColorAlternator(alternationFrequency, Colors.DeepCopy().ToArray()); } protected override ColorAlternator PrototypeCore() { return Prototype(); } /// <summary> /// Alternates colors based on the number of times GetNextColor has been called. /// </summary> /// <param name="input">The string to be styled.</param> /// <returns>The current color of the ColorAlternator.</returns> public override Color GetNextColor(string input) { if (Colors.Length == 0) { throw new InvalidOperationException("No colors have been supplied over which to alternate!"); } Color nextColor = Colors[nextColorIndex]; TryIncrementColorIndex(); return nextColor; } protected override void TryIncrementColorIndex() { if (writeCount >= (Colors.Length * alternationFrequency) - 1) { nextColorIndex = 0; writeCount = 0; } else { writeCount++; nextColorIndex = (int)Math.Floor(writeCount / (double)alternationFrequency); } } } }
bc197b009ff793f2761692e715e720ccf6f3d47a
C#
ewkonzo/Projects
/E-Ticket-System-master/ETicketSystem.Web/ETicketSystem.Services/Admin/Implementations/AdminTownService.cs
2.828125
3
namespace ETicketSystem.Services.Admin.Implementations { using AutoMapper.QueryableExtensions; using Contracts; using Data; using Data.Models; using Models; using System.Collections.Generic; using System.Linq; public class AdminTownService : IAdminTownService { private readonly ETicketSystemDbContext db; public AdminTownService(ETicketSystemDbContext db) { this.db = db; } public IEnumerable<AdminTownListingServiceModel> All(int page, string searchTerm, int pageSize = 10) { var towns = this.db.Towns.AsQueryable(); if (!string.IsNullOrEmpty(searchTerm)) { towns = towns.Where(t => t.Name.ToLower().Contains(searchTerm.ToLower())); } return towns .OrderBy(t => t.Name) .Skip((page - 1) * pageSize) .Take(pageSize) .ProjectTo<AdminTownListingServiceModel>() .ToList(); } public void Add(string name) { this.db.Towns.Add(new Town() { Name = name }); this.db.SaveChanges(); } public IEnumerable<AdminTownStationsServiceModel> TownStations(int id) => this.db.Stations .Where(s => s.TownId == id) .ProjectTo<AdminTownStationsServiceModel>() .ToList(); public int TotalTowns(string searchTerm) { if (string.IsNullOrEmpty(searchTerm)) { return this.db.Towns.Count(); } return this.db.Towns.Count(t => t.Name.ToLower().Contains(searchTerm.ToLower())); } public bool TownExists(int id) => this.db.Towns.Any(t => t.Id == id); public bool TownExistsByName(string name) => this.db.Towns .Any(t => t.Name.ToLower() == name.ToLower()); } }
443550bc618c2e5412a08e7c6a4a70c13c3980fc
C#
lkasana/TizenFX
/src/Tizen.NUI.Components/Controls/RadioButtonGroup.cs
2.59375
3
/* * Copyright(c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.ComponentModel; namespace Tizen.NUI.Components { /// <summary> /// The RadioButtonGroup class is used to group together a set of RadioButton control /// It enables the user to select exclusively single radio button of group. /// </summary> /// <code> /// RadioButtonGroup radioGroup = new RadioButtonGroup(); /// RadioButton radio1 = new RadioButton(); /// RadioButton radio2 = new RadioButton(); /// radioGroup.Add(radio1); /// radioGroup.Add(radio2); /// </code> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public class RadioButtonGroup : SelectGroup { /// <summary> /// Construct RadioButtonGroup /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public RadioButtonGroup() : base() { } /// <summary> /// Get the RadioButton object at the specified index. /// </summary> /// <param name="index">item index</param> /// <returns>RadioButton</returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public RadioButton GetItemByIndex(int index) { return itemGroup[index] as RadioButton; } /// <summary> /// Add RadioButton to the end of RadioButtonGroup. /// </summary> /// <param name="radio">The RadioButton to be added to the RadioButtonGroup</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void Add(RadioButton radio) { base.AddSelection(radio); radio.ItemGroup = this; } /// <summary> /// Remove RadioButton from the RadioButtonGroup. /// </summary> /// <param name="radio">The RadioButton to remove from the RadioButtonGroup</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void Remove(RadioButton radio) { base.RemoveSelection(radio); radio.ItemGroup = null; } /// <summary> /// Handle user's select action. Turn on check state of selected RadioButton, /// and turn out check state of other RadioButtons in RadioButtonGroup /// </summary> /// <param name="selection">The selection selected by user</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] protected override void SelectionHandler(SelectButton selection) { RadioButton radio = selection as RadioButton; if (!itemGroup.Contains(radio)) { return; } foreach (RadioButton btn in itemGroup) { if (btn != null && btn != radio && btn.IsEnabled == true) { btn.IsSelected = false; } } } } }
dedd43e0a4684f4f9cccd2062c96923d71a61b2c
C#
oMERIDIANo/HW_917
/GH_HW917_TurnIn/Assets/Assignment.cs
3.53125
4
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Assignment : MonoBehaviour { public string string1 = ""; //Type inside inspector public string[] stringArray; //Type inside inspector // Start is called before the first frame update void Start() { numbersThreeAndSeven(); findCommonLetter(string1); oneLetter(stringArray); } // Update is called once per frame void Update() { } void numbersThreeAndSeven() { for (int x = 0; x < 1000; x++) { string s = x.ToString(); if (s.Contains("3") && s.Contains("7")) { Debug.Log(x); } } } void findCommonLetter(string string1) { Dictionary<char, int> dict = new Dictionary<char, int>(); foreach (char c in string1) { if (dict.ContainsKey(c)) { dict[c]++; } else { dict.Add(c, 1); } } KeyValuePair<char, int> currentLetterWithHighestNumber; foreach (KeyValuePair<char, int> kvp in dict) { if (kvp.Value > currentLetterWithHighestNumber.Value) { currentLetterWithHighestNumber = kvp; } } Debug.Log("The most common letter in your string is " + currentLetterWithHighestNumber.Key); } void oneLetter(string[] s) { string l = " "; Dictionary<char, int> dict = new Dictionary<char, int>(); for (int x = 0; x < s.Length; x++) { foreach (char c in s[x]) { if (dict.ContainsKey(c)) { dict[c]++; } else { dict.Add(c, 1); } } } foreach (KeyValuePair<char, int> kvp in dict) { if (kvp.Value == 1) { l += kvp.Key + " "; } } Debug.Log("One letter: " + l); } }
bcff3aa8c093fffefe71c5de32a094f9ca5f0ba0
C#
NNNIC/project_underdevelop
/excelapp/test2/excelapp/excelapp/ItemBoxElement.cs
2.515625
3
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace excelapp { public class ItemBoxElement { /* box up/down */ public const int knob_button_width = 20; public const int knob_button_height = 20; public const int updown_button_width = 20; public const int updown_button_height = 20; public const int row_box_width = 40; public const int row_box_height = 20; public const int text_box_width = 200; public const int text_box_height = 20; private MainForm m_form; public string m_id { get; private set; } private int __x; private int __y; private List<Control> m_localSaveControls = new List<Control>(); private int m_knobLabel_index; private int m_upButton_index; private int m_dwnButton_index; private int m_rowBox_index; private int m_textBox_index; public Label m_knobLabel{ get { return (Label) m_localSaveControls[m_knobLabel_index];} } public Button m_upButton { get { return (Button) m_localSaveControls[m_upButton_index]; } } public Button m_dwnButton{ get { return (Button) m_localSaveControls[m_dwnButton_index];} } public TextBox m_rowBox { get { return (TextBox)m_localSaveControls[m_rowBox_index]; } } public TextBox m_textBox { get { return (TextBox)m_localSaveControls[m_textBox_index]; } } public void SetLocation(int x, int y) { __x = x; __y = y; _update_location(); } public Point LocalCursor { get { return new Point( Cursor.Position.X - m_form.Location.X - knob_button_width * 2 / 3, Cursor.Position.Y - m_form.Location.Y - SystemInformation.CaptionHeight - knob_button_height / 2 ); } } public void SetText(string text) { m_textBox.Text = text; } public void SetRowText(string text) { m_rowBox.Text = text; } private ItemBoxElement() { } private void _update_location() { m_knobLabel.Location = new Point(__x , __y); m_upButton.Location = new Point(__x + _total_with_in_localSaveControls(0) , __y-3); m_dwnButton.Location = new Point(__x + _total_with_in_localSaveControls(1) , __y-3); m_rowBox.Location = new Point(__x + _total_with_in_localSaveControls(2) , __y-3); m_textBox.Location = new Point(__x + _total_with_in_localSaveControls(3) , __y-3); } public static ItemBoxElement Create(string id, MainForm form,int x, int y) { var ib = new ItemBoxElement(); ib.m_form = form; ib.m_id = id; ib.__x = x; ib.__y = y; ib.create_knob_label(); ib.create_updown_button(true); ib.create_updown_button(false); ib.create_row_box(); ib.create_text_box(); ib._update_location(); return ib; } public void Destroy() { foreach(var c in m_localSaveControls) { m_form.Controls.Remove(c); } } //---- #region knob操作 private void create_knob_label() { var lb = new Label(); lb.Name = m_id + "_knob"; lb.Width = knob_button_width; lb.Height = knob_button_height; lb.Size = new Size(knob_button_width,knob_button_height); lb.Text = "●"; lb.MouseDown += Lb_MouseDown; lb.MouseMove += Lb_MouseMove; m_form.Controls.Add(lb); m_knobLabel_index = m_localSaveControls.Count; m_localSaveControls.Add(lb); } private void Lb_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (m_form.m_draggingItemBox==null) { m_form.m_draggingItemBox = this; System.Diagnostics.Debug.WriteLine("{0},{1}",__x,__y); } } } private void Lb_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if ( m_form.m_draggingItemBox!=null) { SetLocation(LocalCursor.X, LocalCursor.Y); System.Diagnostics.Debug.WriteLine("{0},{1}",__x,__y); } } } #endregion private void create_text_box() { var tb = new TextBox(); tb.Name = m_id + "_textbox"; tb.Width = text_box_width; tb.Height = text_box_height; tb.Multiline = true; tb.Size = new Size(text_box_width,text_box_height); tb.ReadOnly = true; tb.Text = "-"; tb.Click += textbox_Click; m_form.Controls.Add(tb); m_textBox_index = m_localSaveControls.Count; m_localSaveControls.Add(tb); } private void textbox_Click(object sender, EventArgs e) { var row = ParseUtil.IntParse(m_rowBox.Text); if (row!=null) { m_form.Update_EditForm((int)row); } } private void create_row_box() { var tb = new TextBox(); tb.Name = m_id + "_textbox"; tb.Width = row_box_width; tb.Height = row_box_height; tb.Multiline = true; tb.Size = new Size(row_box_width,row_box_height); tb.ReadOnly = true; tb.Text = "-"; m_form.Controls.Add(tb); m_rowBox_index = m_localSaveControls.Count; m_localSaveControls.Add(tb); } private void create_updown_button(bool bUpOrDown) { var bt = new Button(); bt.Name = m_id + (bUpOrDown ? "_up" : "_down") + "_button"; bt.Width = updown_button_width; bt.Height = updown_button_height; bt.Size = new Size(updown_button_width, updown_button_height); bt.Text = bUpOrDown ? "↑" : "↓"; bt.Font = new Font("メイリオ", 5); m_form.Controls.Add(bt); if (bUpOrDown) { m_upButton_index = m_localSaveControls.Count; } else { m_dwnButton_index = m_localSaveControls.Count; } m_localSaveControls.Add(bt); } private int _get_width_in_localSaveControls(int n) { var cnt = m_localSaveControls[n]; return cnt.Size.Width; } private int _total_with_in_localSaveControls(int n) { var total = 0; for(var i = 0; i<=n;i++) total += _get_width_in_localSaveControls(i); return total; } } }
72f48e74b86ca34e543a7f9989a88e7ab845549d
C#
csharpstudy/lab
/Lab4_파일압축/Solution/FileCompress/Program.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.IO.Compression; namespace FileCompress { class Program { // // 실행방식 : C> FileCompress.exe input.txt // static void Main(string[] args) { // 입력 아큐먼드 처리 if (args.Length != 1) { throw new ArgumentException(); } string input = args[0]; string output = input + ".zip"; // 입출력파일이 존재하는지 체크 if (!File.Exists(input)) { throw new FileNotFoundException("파일명 " + input + "이 존재하지 않습니다"); } if (File.Exists(output)) { throw new FileNotFoundException("파일명 " + output + "이 이미 존재합니다"); } // 츨력 .zip 파일 생성 // 출력 FileStream 객체 생성 // 압축 GZipStream 클래스 객체 생성 // GZipStream 객체 생성. 출력 FileStream 객체와 연결 // 입력 파일 객체 // 입력 FileStream 객체 생성 // 파일 내용 읽으면서 압축 // 예: 한바이트씩 읽으면서 gzip 스트림에 출력 // 파일 핸들 닫기 } } }
fd6c0a015a923461b63023f090b769c7e305392c
C#
mikmyers/IoTHackathon
/Hackathon.Repository/Repositories/HealthCentreRepository.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using Hackathon.Repository.Interfaces; using Hackathon.Entities; namespace Hackathon.Repository.Repositories { public partial class HealthCentreRepository : RepositoryBase<EntityContext>, IHealthCentreRepository { public HealthCentre One(int Id) { HealthCentre result = null; try { using (var context = DataContext) { result = context.HealthCentres .Where(a => a.Id == Id) .FirstOrDefault(); } } catch (Exception ex) { throw ex; } return result; } public IEnumerable<HealthCentre> All() { IList<HealthCentre> result = null; try { using (var context = DataContext) { result = context.HealthCentres .OrderBy(c => c.Name) .ToList(); } } catch (Exception ex) { throw ex; } return result; } } }
985fde1802ed480d83d20ced507202eb5c4ab0b4
C#
FSharpBristol/FSharpTurtleTutorial
/Solved-Versions/CSharp-Version/Commands/TurnLeftCommand.cs
2.890625
3
namespace TurtleRunner.Commands { using TurtleRunner.Models; public class TurnLeftCommand : ICommand { private readonly int _quantityToTurn; public TurnLeftCommand(int quantityToTurn) { _quantityToTurn = quantityToTurn; } public void ExecuteCommand(Turtle turtle) { turtle.Angle += _quantityToTurn; } } }
2209e26c0a8c0203079a8903b58db58c4d4f79c9
C#
lgarcia223/GoldBadgeChallenges
/Challenge_04/KBadgesRepository.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Challenge_04 { public class KBadgesRepository { private List<string> _doorAccessList = new List<string>(); private Dictionary<int, List<string>> BadgeDic = new Dictionary<int, List<string>>(); public List<string> GetList() { return _doorAccessList; } public void AddDoortoList(string door) { _doorAccessList.Add(door); } public void RemoveDoorFromList(string door) { _doorAccessList.Remove(door); } public void AddBadgeToDictionary(KomodoBadge badge) { BadgeDic.Add(badge.BadgeID, badge.DoorList); } public Dictionary<int, List<string>> GetDictionary() { return BadgeDic; } } }
aa965f558bee43a8ac42ab645a348fa86fe752f5
C#
shendongnian/download4
/code3/532080-12290279-28862196-2.cs
2.9375
3
public class MyRow : INotifyPropertyChanged { public event PropertyChanged; private string _stringValue = string.Empty; public string StringValue { get { return _stringValue; } set { if( _stringValue != value ) { _stringValue = value; if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "StringValue" ) ); } } } } // continue with the rest of your properties }
6bce3ca09f111ec7889e46c28e43ee6122e94cc5
C#
CatmanIta/DBGA_Ex
/Assets/Esercizi/Variabili1/BinaryConverter.cs
3.296875
3
using UnityEngine; using System.Collections; public class BinaryConverter : MonoBehaviour { void Start () { // START LOGIC // We create an algorithm that will convert a binary number to an integer // WARNING: we do so only for 8 bits int bit0 = 1; int bit1 = 0; int bit2 = 0; int bit3 = 0; int bit4 = 0; int bit5 = 0; int bit6 = 0; int bit7 = 1; float number = Mathf.Pow(2, 0) * bit0 + Mathf.Pow(2, 1) * bit1 + Mathf.Pow(2, 2) * bit2 + Mathf.Pow(2, 3) * bit3 + Mathf.Pow(2, 4) * bit4 + Mathf.Pow(2, 5) * bit5 + Mathf.Pow(2, 6) * bit6 + Mathf.Pow(2, 7) * bit7 ; Debug.Log(number); // Creare un programma che, dato un prezzo in euro (530.70) restituisca il numero di banconote // usando pezzi da 50, 20 e 5 euro, e il resto a parte. // END LOGIC } }
870da30efa9f07794ff787e1271662c29fcc350a
C#
shendongnian/download4
/first_version_download2/33761-1801159-3605740-5.cs
3.203125
3
private string lastName; public string LastName { get { string s; if (lastName == null) { s = string.Empty; } else { s = item.LastName.Substring(0, item.LastName.Length > 30 ? 30 : item.LastName.Length); } return s; } }
e718384bf8074ab267522a76b2690fda0a6ad088
C#
MentulaGames/XnaGuiItems
/XnaGuiItems/XnaGuiItems/Drawing.cs
2.609375
3
#if MONO extern alias Mono; #else extern alias Xna; #endif namespace Mentula.GuiItems { #if MONO using Mono::Microsoft.Xna.Framework; using Mono::Microsoft.Xna.Framework.Graphics; #else using Xna::Microsoft.Xna.Framework; using Xna::Microsoft.Xna.Framework.Graphics; #endif using Core; using System; using DeJong.Utilities.Logging; #if !DEBUG [System.Diagnostics.DebuggerStepThrough] #endif internal static class Drawing { public static Texture2D FromColor(Color color, Size size, GraphicsDevice device) { Log.Debug(nameof(Drawing), "Created texture from color"); Texture2D result = new Texture2D(device, size.Width, size.Height); Color[] data = new Color[size.Width * size.Height]; for (int i = 0; i < data.Length; i++) { data[i] = color; } result.SetData(data); return result; } public static Texture2D FromColor(Color color, Size size, Rect destinationRectangle, GraphicsDevice device) { Log.Debug(nameof(Drawing), "Created texture from color"); Texture2D result = new Texture2D(device, size.Width, size.Height); Color[] data = new Color[size.Width * size.Height]; for (int y = 0; y < size.Height; y++) { for (int x = 0; x < size.Width; x++) { data[y * size.Width + x] = destinationRectangle.Contains(x, y) ? color : Color.Transparent; } } result.SetData(data); return result; } public static Texture2D FromMultiColor(Color color0, Color color1, Rectangle destination0, Rectangle destination1, GraphicsDevice device) { Log.Debug(nameof(Drawing), "Created texture from multiple colors"); Texture2D result = new Texture2D(device, Math.Max(destination0.Width, destination1.Width), Math.Max(destination0.Height, destination1.Height)); Color[] data = new Color[result.Width * result.Height]; for (int y = destination0.Y; y < destination0.Height; y++) { for (int x = destination0.X; x < destination0.Width; x++) { data[y * result.Width + x] = color0; } } for (int y = destination1.Y; y < destination1.Height; y++) { for (int x = destination1.X; x < destination1.Width; x++) { data[y * result.Width + x] = color1; } } result.SetData(data); return result; } public static Texture2D FromText(string text, SpriteFont font, Color color, Size size, bool multiLine, int lineStart, SpriteBatch sb) { Log.Debug(nameof(Drawing), "Created texture from string"); Texture2D result = new Texture2D(sb.GraphicsDevice, size.Width, size.Height); using (RenderTarget2D target = new RenderTarget2D(sb.GraphicsDevice, size.Width, size.Height)) { sb.GraphicsDevice.SetRenderTarget(target); sb.GraphicsDevice.Clear(Color.Transparent); sb.Begin(); if (multiLine) { float fH = font.GetHeight(); string[] lines = text.Split('\n'); for (int i = lineStart; i < lines.Length; i++) { float y = 1 + (i - lineStart) * fH; sb.DrawString(font, lines[i], new Vector2(1, y), color); } } else sb.DrawString(font, text, Vector2.One, color); sb.End(); sb.GraphicsDevice.SetRenderTarget(null); result.SetData(target.GetColorData()); } return result; } public static Texture2D FromLabels(Pair[] labels, SpriteFont font, Size size, SpriteBatch sb) { Log.Debug(nameof(Drawing), "Created texture from string|color labels"); Texture2D result = new Texture2D(sb.GraphicsDevice, size.Width, size.Height); using (RenderTarget2D target = new RenderTarget2D(sb.GraphicsDevice, size.Width, size.Height)) { sb.GraphicsDevice.SetRenderTarget(target); sb.GraphicsDevice.Clear(Color.Transparent); string[] labelText = Pair.GetKeys(labels); sb.Begin(); for (int i = 0; i < labels.Length; i++) { string prevString = string.Join(" ", labelText, 0, i); if (i > 0) prevString += ' '; float x = 1 + font.MeasureString(prevString).X; sb.DrawString(font, labels[i].Text, new Vector2(x, 1), labels[i].Color.Value); } sb.End(); sb.GraphicsDevice.SetRenderTarget(null); result.SetData(target.GetColorData()); } return result; } public static Texture2D ApplyBorderLabel(this Texture2D texture, BorderStyle style) { Log.Debug(nameof(Drawing), "Applied borders to label"); Texture2D result = new Texture2D(texture.GraphicsDevice, texture.Width, texture.Height); Color[] data = texture.GetColorData(); Color ld, ru; switch (style) { case (BorderStyle.FixedSingle): ru = Color.DimGray; ld = Color.DimGray; break; case (BorderStyle.Fixed3D): ru = Color.DarkSlateGray; ld = Color.White; break; default: return texture; } for (int x0 = 0, x1 = (texture.Height - 1) * texture.Width; x0 < texture.Width; x0++) { data[x0] = ru; data[x1 + x0] = ld; } for (int y0 = 0, y1 = texture.Width - 1; y0 < texture.Height; y0++) { data[y0 * texture.Width] = ru; data[y0 * texture.Width + y1] = ld; } result.SetData(data); return result; } public static Texture2D ApplyBorderButton(this Texture2D texture, ButtonStyle type, bool darkenOnClick) { Log.Debug(nameof(Drawing), "Applied borders to button"); Texture2D result = new Texture2D(texture.GraphicsDevice, texture.Width, texture.Height); Color[] data = texture.GetColorData(); Color bc; switch (type) { case ButtonStyle.Default: bc = Color.CornflowerBlue; break; case ButtonStyle.Hover: bc = Color.DimGray; break; case ButtonStyle.Click: bc = Color.Black; if (darkenOnClick) { for (int y = 1; y < texture.Height - 1; y++) { for (int x = 1; x < texture.Width - 1; x++) { int i = y * texture.Width + x; data[i].R -= 10; data[i].B -= 10; data[i].G -= 10; } } } break; default: return texture; } for (int x0 = 0, x1 = (texture.Height - 1) * texture.Width; x0 < texture.Width; x0++) { data[x0] = bc; data[x1 + x0] = bc; } for (int y0 = 0, y1 = texture.Width - 1; y0 < texture.Height; y0++) { data[y0 * texture.Width] = bc; data[y0 * texture.Width + y1] = bc; } result.SetData(data); return result; } public static Texture2D Clip(this Texture2D texture, Rectangle bounds) { Log.Debug(nameof(Drawing), "Clipped texture"); Texture2D result = new Texture2D(texture.GraphicsDevice, bounds.Width, bounds.Height); Color[] prevData = texture.GetColorData(); Color[] newData = new Color[bounds.Width * bounds.Height]; for (int y = 0; y < bounds.Height; y++) { for (int x = 0; x < bounds.Width; x++) { if (texture.Bounds.Contains(x, y)) newData[y * bounds.Width + x] = prevData[y * texture.Width + x]; } } result.SetData(newData); return result; } public static Texture2D RenderOnto(this Texture2D texture, SpriteBatch sb, Size size, Vector2 position = default(Vector2), float rotation = 0, Vector2 scale = default(Vector2)) { Log.Debug(nameof(Drawing), "Rendering texture onto parent texture"); Texture2D result = new Texture2D(sb.GraphicsDevice, size.Width, size.Height); using (RenderTarget2D target = new RenderTarget2D(sb.GraphicsDevice, size.Width, size.Height)) { sb.GraphicsDevice.SetRenderTarget(target); sb.GraphicsDevice.Clear(Color.Transparent); sb.Begin(); sb.Draw(texture, position, null, Color.White, rotation, Vector2.Zero, scale == Vector2.Zero ? Vector2.One : scale, SpriteEffects.None, 1f); sb.End(); sb.GraphicsDevice.SetRenderTarget(null); result.SetData(target.GetColorData()); } return result; } public static Texture2D Stretch(this Texture2D texture, SpriteBatch sb, Size size) { Log.Debug(nameof(Drawing), "Stretched texture"); Texture2D result = new Texture2D(texture.GraphicsDevice, size.Width, size.Height); using (RenderTarget2D target = new RenderTarget2D(texture.GraphicsDevice, size.Width, size.Height)) { texture.GraphicsDevice.SetRenderTarget(target); texture.GraphicsDevice.Clear(Color.Transparent); sb.Begin(); sb.Draw(texture, new Rectangle(0, 0, size.Width, size.Height), Color.White); sb.End(); texture.GraphicsDevice.SetRenderTarget(null); result.SetData(target.GetColorData()); } return result; } } }
8d9bc7f41a166c925399f4907a2dd7b91771b199
C#
helnik/ORC
/ObjectRuleChecker/OrcResult.cs
2.859375
3
using System; using ObjectRuleChecker.Interfaces; namespace ObjectRuleChecker { public class OrcResult : IOrcResult { public bool IsSuccess { get; } public string Rule { get; } public Exception Exception { get; } public OrcResult(string rule, bool isSuccess, Exception ex = null) { rule.EnsureContext("No rule provided for the ValidationResult"); Rule = rule; IsSuccess = isSuccess; Exception = ex; } public override string ToString() { string result = IsSuccess ? "Passed" : "Failed"; return $"Rule: {Rule} {result}"; } } }
1458a0afcd025e9f546005afbe7fdeb77b727f53
C#
HatchedMango/CreditCardInterestCalculator
/CreditCardInterestCalculator/CardInterestCalculator.cs
2.921875
3
using CreditCardInterestCalculator.models; namespace CreditCardInterestCalculator { public class CardInterestCalculator { private readonly IInterestCalculator interestCalculator; public CardInterestCalculator(IInterestCalculator interestCalculator) { this.interestCalculator = interestCalculator; } public decimal CalculateInterest(Card card, int numMonths) { return interestCalculator.CalculateInterest(card.Balance, card.InterestRate, numMonths); } } }
8879049e19a97ba4a7df6b7e8559e42ea2895c9e
C#
mandatvo1997/2DGame
/Assets/Scripts/BOX.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BOX : MonoBehaviour { public AudioSource audioSource; public AudioClip BoxSound; public int Health = 100; void Awake() { audioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { if (Health <= 0) { audioSource.PlayOneShot(BoxSound); Destroy(gameObject); } } void Damage(int damage) { Health -= damage; } }
ca9a6c7e5ffc10caa49d88c34d9d4349733c6278
C#
vlydik/Task5
/Task5/Controllers/StudentsController.cs
2.703125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using System.Data.SqlClient; using Task5.Models; using System.Globalization; using Task5.DAL; namespace Task4.Controllers { [ApiController] [Route("api/students")] public class StudentsController : ControllerBase { string[] validFormats = new[] { "MM/dd/yyyy", "yyyy/MM/dd", "MM/dd/yyyy HH:mm:ss", "MM/dd/yyyy hh:mm tt", "yyyy-MM-dd HH:mm:ss, fff" }; CultureInfo provider = new CultureInfo("en-US"); private readonly IDbService _dbService; public StudentsController(IDbService dbService) { _dbService = dbService; } [HttpGet] public IActionResult GetStudents(string orderBy) { var students = new List<Student>(); using (var client = new SqlConnection("Data Source = db-mssql;Initial Catalog = s19183; Integrated Security = True")) using (var com = new SqlCommand()) { com.Connection = client; com.CommandText = "select * from Student"; client.Open(); var dr = com.ExecuteReader(); while (dr.Read()) { var st = new Student(); st.FirstName = dr["FirstName"].ToString(); st.LastName = dr["LastName"].ToString(); st.BirthDate = DateTime.ParseExact(dr["BirthDate"].ToString(), validFormats, provider); st.enrollment = new Enrollment { IdSemester = (int)dr["Semester"], studies = new Studies { study = dr["Name"].ToString() } }; students.Add(st); } } return Ok(students); } [HttpGet("{id}")] public IActionResult GetStudent(string id) { var enrollment = new Enrollment(); using (var con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s19183;Integrated Security=True")) { using (var com = new SqlCommand()) { com.Connection = con; com.CommandText = "select * from Student"; com.Parameters.AddWithValue("id", id); con.Open(); var dr = com.ExecuteReader(); while (dr.Read()) { enrollment.IdSemester = (int)dr["Semester"]; } } } return Ok(enrollment); } [HttpPost] public IActionResult CreateStudent(Student student) { var s = new Student(); s.IndexNumber = $"s{new Random().Next(1, 2000)}"; s.FirstName = "Jan"; s.LastName = "Kowalski"; return Ok(s); } [HttpPut("{i}")] public IActionResult PutStudent(int i) { var s = new Student(); s.IndexNumber = $"s{new Random().Next(1, 2000)}"; s.FirstName = "Jan"; s.LastName = "Kowalski"; return Ok(s); } [HttpDelete("{id}")] public IActionResult DeleteStudent(int i) { return Ok(i); } } }
7d82648149afc41fbcdc3302ff1f00754532fd0b
C#
Zazcallabah/IrcNotify
/IrcNotify/User.cs
2.609375
3
using System; using System.Linq; namespace IrcNotify { public class User { static readonly Random R = new Random(); readonly string[] _nicks; public User( string[] nicks ) { Nick = nicks.First(); Login = nicks.Last(); _nicks = nicks; } public string AltNick { get { return _nicks[R.Next( _nicks.Length )] + R.Next( 100 ); } } public string Login { get; set; } public string Nick { get; set; } } }
97e39e9fd6c037ae1296aa758497fc975f3dd39c
C#
ratozumbi/traVRsal-sdk
/Runtime/Helpers/EDebug.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Object = UnityEngine.Object; namespace traVRsal.SDK { public static class EDebug { public static List<Tuple<string, string>> errors = new List<Tuple<string, string>>(); public static List<Tuple<string, string>> warnings = new List<Tuple<string, string>>(); public static void Clear() { errors.Clear(); warnings.Clear(); } public static void LogWarning(string message, Object context = null) { warnings.Add(new Tuple<string, string>(GetDate(), message)); Debug.LogWarning(message, context); } public static void LogError(string message, Object context = null) { errors.Add(new Tuple<string, string>(GetDate(), message)); Debug.LogError(message, context); } public static List<string> GetData(bool returnErrors, bool returnWarnings) { List<string> result = new List<string>(); if (returnErrors) result.AddRange(errors.Select(c => "[" + c.Item1 + "] " + c.Item2).ToList()); if (returnWarnings) result.AddRange(warnings.Select(c => "[" + c.Item1 + "] " + c.Item2).ToList()); result.Sort(); return result; } private static string GetDate() { return DateTime.Now.ToString("HH:mm:ss"); } } }
240420e31c4678c367514c63138c945359d19c2d
C#
hanrick2000/GoogleInterviewPreparation
/CommonAlgo/InterviewBit/Tree/IsBalancedBst.cs
3.375
3
using System; using NUnit.Framework; namespace CommonAlgo.InterviewBit.Tree { public class TreeNodeIb { public TreeNodeIb left; public TreeNodeIb right; public int val; public TreeNodeIb(int val) { this.val = val; } } public class IsBalancedBst { private int GetHeight(TreeNodeIb root) { if (root == null) return -1; return 1 + Math.Max(GetHeight(root.right), GetHeight(root.left)); } [TestCase] public int IsBalanced() { var a = new TreeNodeIb(1); var r = IsBalanced1(a); return r ? 1 : 0; } private bool IsBalanced1(TreeNodeIb a) { if (a == null) return true; var lh = GetHeight(a.left); var rh = GetHeight(a.right); var abs1 = Math.Abs(lh - rh); var r = abs1 <= 1; return r && IsBalanced1(a.left) && IsBalanced1(a.right); } } }
8018e187a6eb3f6a72a7b98975e359394838bac7
C#
hristoenev92/Soft-Uni-Exercises
/upr strukturi ot danni/masiv nm/Program.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace masiv_nm { class Program { static void Main(string[] args) { int n = 0; while (n<4||100<n) { n = int.Parse(Console.ReadLine()); } int[] nm = new int[n]; for (int i = 0; i < n; i++) { nm[i] = int.Parse(Console.ReadLine()); } foreach (var item in nm) { Console.Write(item+" "); } Console.WriteLine(); List<int> result = new List<int>(); if (nm[0]<nm[1]) { result.Add(nm[0]); } for (int i = 1; i < nm.Length-1; i++) { if (nm[i]>nm[i-1]&&nm[i]<nm[i+1]) { result.Add(nm[i]); } } if (nm[nm.Length-1]>nm[nm.Length-2]) { result.Add(nm.Last()); } foreach (var item in result) { Console.Write(item+" "); } Console.WriteLine(); int m = 0; while (m < 3 || Math.Sqrt(n) < m) { m = int.Parse(Console.ReadLine()); } int[,] matrix = new int[m, m]; int br = 0; for (int row = 0; row < m; row++) { for (int column = 0; column < m; column++) { matrix[column, row] = nm[br++]; } } for (int row = 0; row < m; row++) { for (int column = 0; column < m; column++) { Console.Write(matrix[row,column]+" "); } Console.WriteLine(); } } } }
528a575f5a8a88d9de0cd21f3ce5450251fb34f2
C#
boogie-org/symdiff
/Sources/SymDiffUtils/boogieUtils.cs
2.625
3
using Microsoft.Boogie; using Microsoft.Boogie.GraphUtil; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SymDiffUtils { public class BoogieUtils { public static bool InitializeBoogie(string clo) { CommandLineOptions.Install(new CommandLineOptions()); CommandLineOptions.Clo.RunningBoogieFromCommandLine = true; var args = "/doModSetAnalysis".Split(' '); CommandLineOptions.Clo.Parse(args); return false; } //call with null filename to print to console public static void PrintProgram(Program p, string filename) { TokenTextWriter outFile; if (filename != null) outFile = new TokenTextWriter(filename, true); else outFile = new TokenTextWriter(Console.Out, true); p.Emit(outFile); outFile.Close(); } public static bool ResolveProgram(Program p, string filename) { //After p.Resolve, the AST is in p.topLevelDeclarations int errorCount = p.Resolve(); if (errorCount != 0) Console.WriteLine(errorCount + " name resolution errors in " + filename); return errorCount != 0; } public static bool TypecheckProgram(Program p, string filename) { //One of the sideeffect of p.Typecheck, it inlines int errorCount = p.Typecheck(); if (errorCount != 0) Console.WriteLine(errorCount + " type checking errors in " + filename); return errorCount != 0; } private static bool ResolveAndTypeCheck(Program p, string filename) { if (ResolveProgram(p, "")) { Log.Out(Log.Error, "Failed to resolve program"); return true; } if (TypecheckProgram(p, "")) { Log.Out(Log.Error, "Failed to typecheck program"); //Log.LogEmit(Log.Normal, p.Emit); // PrintProgram(p, ""); return true; } return false; } public static bool ResolveAndTypeCheckThrow(Program p, string filename) { if (ResolveAndTypeCheck(p, filename)) throw new Exception("Program " + filename + " does not resolve/typecheck"); return false; } /// <summary> /// TODO: Copied from Rootcause, refactor /// </summary> public class BoogieInlineUtils { public static void Inline(Program program) { //perform inlining on the procedures IEnumerable<Declaration> impls = program.TopLevelDeclarations.Where(x => x is Implementation); foreach (Implementation impl in impls) { impl.OriginalBlocks = impl.Blocks; impl.OriginalLocVars = impl.LocVars; } foreach (Implementation impl in impls) Inliner.ProcessImplementation(program, impl); } public static bool IsInlinedProc(Procedure procedure) { return procedure != null && QKeyValue.FindIntAttribute(procedure.Attributes, "inline", -1) != -1; } /// <summary> /// Adds {:inline "recursionDepth"} to all proceudres reachable within "bound" in "callGraph" /// from "impl" in "prog" /// Excludes impl /// InlineAsSpec uses {:inline spec} instead of {:inline bound} which replaces leaves with a call instead of assume false /// </summary> /// <param name="prog"></param> /// <param name="impl"></param> /// <param name="bound"></param> /// <param name="recursionDepth"></param> private static HashSet<Procedure> AddInlineAttributesUptoDepth( Program prog, Implementation impl, int bound, int recursionDepth, Graph<Procedure> callGraph) { Dictionary<int, HashSet<Procedure>> reachableProcs = ReachableImplsWithinBound(impl, bound, callGraph); HashSet<Procedure> reachAll = new HashSet<Procedure>(); reachableProcs.Values .Iter( x => x.Iter(y => reachAll.Add(y)) ); reachAll.Remove(impl.Proc); reachAll.Iter (x => x.AddAttribute("inline", Expr.Literal(recursionDepth))); return reachAll; } /// <summary> /// All procedures reachable in levels {0,1,..bound} /// Includes impl.Proc for level 0 /// </summary> /// <param name="impl"></param> /// <param name="bound"></param> /// <param name="callGraph"></param> /// <returns></returns> public static Dictionary<int, HashSet<Procedure>> ReachableImplsWithinBound(Implementation impl, int bound, Graph<Procedure> callGraph) { Dictionary<int, HashSet<Procedure>> reachableProcs = new Dictionary<int, HashSet<Procedure>>(); reachableProcs[0] = new HashSet<Procedure>() { impl.Proc }; for (int i = 1; i < bound; ++i) { reachableProcs[i] = new HashSet<Procedure>(); reachableProcs[i - 1].Iter (p => callGraph.Successors(p).Iter(q => reachableProcs[i].Add(q))); } return reachableProcs; } /// <summary> /// Does not quite work as it recursively inlines everything /// </summary> /// <param name="prog"></param> /// <param name="impl"></param> /// <param name="bound"></param> /// <param name="recursionDepth"></param> /// <param name="callGraph"></param> /// <param name="inlineOpt"></param> public static void InlineUptoDepth(Program prog, Implementation impl, int bound, int recursionDepth, Graph<Procedure> callGraph, CommandLineOptions.Inlining inlineOpt) { CommandLineOptions.Clo.ProcedureInlining = inlineOpt; //inline and then use spec, no unsoundness var inlineProcs = AddInlineAttributesUptoDepth(prog, impl, bound, recursionDepth, callGraph); Inline(prog); inlineProcs.Iter(x => { x.Attributes = x.Attributes.Next; }); //remove any inline attributes } } public static Program ParseProgram(string f) { Program p = new Program(); try { // if (Microsoft.Boogie.Parser.Parse(f, out p) != 0) //Boogie API has changed List<string> defs = new List<string>(); if (Parser.Parse(f, defs, out p) != 0) { Console.WriteLine("Failed to read " + f); return null; } } catch (Exception e) { Console.WriteLine(e.ToString()); return null; } return p; } /// <summary> /// Computes for all procedures in the callgraph the distance from a list of changed procedures. /// Changed procedures have distance 0, /// </summary> /// <param name="callGraph"></param> /// <param name="changedProcs"></param> /// <returns>A map from procedure name to distance from any changed procedure.</returns> public static Dictionary<int, HashSet<string>> FindProcsAtDistance(Graph<Procedure> callGraph, IEnumerable<string> changedProcs) { Dictionary<string, int> lengths = new Dictionary<string, int>(); foreach (var proc in callGraph.Nodes) { lengths.Add(proc.Name, int.MaxValue); } foreach (var item in callGraph.Nodes.Where(node => changedProcs.Contains(node.Name))) { TraverseDF(callGraph, item, -1, lengths); } Dictionary<int, HashSet<string>> procsAtDistance = new Dictionary<int, HashSet<string>>(); foreach(var item in lengths) { if (!procsAtDistance.ContainsKey(item.Value)) procsAtDistance[item.Value] = new HashSet<string>(); procsAtDistance[item.Value].Add(item.Key); } return procsAtDistance; } private static void TraverseDF(Graph<Procedure> callGraph, Procedure item, int cost, Dictionary<string, int> costs) { int currentCost = cost + 1; if (costs[item.Name] <= currentCost) { return; } costs[item.Name] = currentCost; foreach (var succ in callGraph.Successors(item)) { TraverseDF(callGraph, succ, currentCost, costs); } foreach (var pred in callGraph.Predecessors(item)) { TraverseDF(callGraph, pred, currentCost, costs); } } } }
1ebd81b4fd1860ae42325593f1faf851b6277ed2
C#
NotHuza/Cerberus-v4
/RivieraStudio.Magic/RivieraStudio.Magic.Titan/RC4Encrypter.cs
3.015625
3
namespace RivieraStudio.Magic.Titan { public class RC4Encrypter : StreamEncrypter { private byte[] _key; private int _x; private int _y; /// <summary> /// Initializes a new instance of the <see cref="RC4Encrypter" /> class. /// </summary> public RC4Encrypter(string baseKey, string nonce) { this.InitState(baseKey, nonce); } /// <summary> /// Destructs this instance. /// </summary> public override void Destruct() { base.Destruct(); this._key = null; this._x = 0; this._y = 0; } /// <summary> /// Initializes this instance. /// </summary> public void InitState(string baseKey, string nonce) { string key = baseKey + nonce; this._key = new byte[256]; this._x = 0; this._y = 0; for (int i = 0; i < 256; i++) { this._key[i] = (byte) i; } for (int i = 0, j = 0; i < 256; i++) { j = (j + this._key[i] + key[i % key.Length]) % 256; byte tmpSwap = this._key[i]; this._key[i] = this._key[j]; this._key[j] = tmpSwap; } for (int i = 0; i < key.Length; i++) { this._x = (this._x + 1) % 256; this._y = (this._y + this._key[this._x]) % 256; byte tmpSwap = this._key[this._y]; this._key[this._y] = this._key[this._x]; this._key[this._x] = tmpSwap; } } /// <summary> /// Decrypts this instance. /// </summary> public override int Decrypt(byte[] input, byte[] output, int length) { return this.Encrypt(input, output, length); } /// <summary> /// Encrypts this instance. /// </summary> public override int Encrypt(byte[] input, byte[] output, int length) { if (length >= 1) { for (int i = 0; i < length; i++) { this._x = (this._x + 1) % 256; this._y = (this._y + this._key[this._x]) % 256; byte tmp = this._key[this._y]; this._key[this._y] = this._key[this._x]; this._key[this._x] = tmp; output[i] = (byte) (input[i] ^ this._key[(this._key[this._x] + this._key[this._y]) % 256]); } } return 0; } } }
83d2f89951ecffb913b5b50de7d70926e309ffcd
C#
swaphack/Kingdom
/Kindom/Assets/Football/Player/PlayerAI.cs
2.546875
3
using System; using UnityEngine; using Football.AI; namespace Football { /// <summary> /// 球员AI /// </summary> public class PlayerAI : Agent { /// <summary> /// 球 /// </summary> private Ball _Ball; public Ball Ball { get { return _Ball; } set { _Ball = value; } } /// <summary> /// 球员 /// </summary> /// <value>The player.</value> public Player Player { get { return this.GetComponent<Player>(); } } /// <summary> /// 注册动作事件 /// </summary> /// <param name="type">Type.</param> /// <param name="methodName">Method name.</param> public void RegisterActorMethod(PlayerCommand type, string methodName) { Actor.AddMethod ((int)type, methodName); } /// <summary> /// 注册状态转换规则 /// </summary> /// <param name="curState">Current state.</param> /// <param name="trigger">Trigger.</param> /// <param name="nextState">Next state.</param> public void RegisterFSMRule(PlayerState curState, PlayerState nextState, PlayerStateTrigger[] triggers) { int[] conditions = new int[triggers.Length]; for (int i = 0; i < triggers.Length; i++) { conditions [i] = (int)triggers [i]; } FSM.AddRule ((int)curState, conditions, (int)nextState); } /// <summary> /// 注册状态绑定事件 /// </summary> /// <param name="state">State.</param> /// <param name="handler">Handler.</param> public void RegisterFSMState(PlayerState state, FiniteStateMachine.StateChangeDelegate handler) { FSM.AddStateHandler ((int)state, handler); } public PlayerAI () { // 基础命令 RegisterActorMethod (PlayerCommand.EPC_TURN, "Turn"); RegisterActorMethod (PlayerCommand.EPC_INTERCEPT, "Intercept"); RegisterActorMethod (PlayerCommand.EPC_MOVE, "Move"); RegisterActorMethod (PlayerCommand.EPC_DASH, "Dash"); RegisterActorMethod (PlayerCommand.EPC_KICK, "Kick"); RegisterActorMethod (PlayerCommand.EPC_SAY, "Say"); /* RegisterFSMRule (PlayerState.EPS_WAIT, PlayerState.EPS_WAIT, waitToWait0); RegisterFSMRule (PlayerState.EPS_WAIT, PlayerState.EPS_MOVE, waitToMove0); RegisterFSMRule (PlayerState.EPS_WAIT, PlayerState.EPS_KICK, waitToWait0); RegisterFSMRule (PlayerState.EPS_MOVE, PlayerState.EPS_WAIT, waitToWait0); RegisterFSMRule (PlayerState.EPS_MOVE, PlayerState.EPS_MOVE, waitToWait0); RegisterFSMRule (PlayerState.EPS_MOVE, PlayerState.EPS_KICK, waitToWait0); RegisterFSMRule (PlayerState.EPS_KICK, PlayerState.EPS_WAIT, waitToWait0); RegisterFSMRule (PlayerState.EPS_KICK, PlayerState.EPS_MOVE, waitToWait0); RegisterFSMRule (PlayerState.EPS_KICK, PlayerState.EPS_KICK, waitToWait0); */ } void Start() { Player.SetProperty (PlayerAttribute.EPA_SPEED_WITH_BALL, 5); Player.SetProperty (PlayerAttribute.EPA_SPEED, 1.5f); Player.SetProperty (PlayerAttribute.EPA_DASH_SPEED, 2); Player.SetProperty (PlayerAttribute.EPA_TURN_SPEED, 20); Player.PutCommand (PlayerCommand.EPC_TURN, new Vector3 (0, 45, 0)); Player.PutCommand (PlayerCommand.EPC_TURN, new Vector3 (0, -45, 0)); Player.PutCommand (PlayerCommand.EPC_SAY, "Hello"); } } }
8f22f13883da63ea5e53330ff02661096697181a
C#
ICS3UProgrammingTishamI/Unit-5-Arrays-Lists-
/2DArraysTishamI/2DArraysTishamI/2DArraysForm.cs
3.75
4
/* * Created by: Tisham Islam * Created on: 19/04/2019 * Created for: ICS3U Programming * Daily Assignment – Day #38 - 2D Arrays * This program creates and displays a 2D array to the user's specifications * then it adds up all the numbers within it, * before returning the average of the array's numbers */ 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 _2DArraysTishamI { public partial class frm2DArrays : Form { public frm2DArrays() { InitializeComponent(); txtArray.Enabled = false; } //random number generator Random numGen = new Random(); //Function: Array Average //Input: int[,] intyBoi (A 2D array) //Output: String //Description: Calculates the average of the numbers within an array, //then returns the average in the form of a string private string ArrayAverage(int[,] intyBoi) { //local variables int arrayTotal = 0; int width; int length; int genericNum; int totalSize; double average; //set the width, length and total size of the array into variables width = intyBoi.GetLength(0); length = intyBoi.GetLength(1); totalSize = intyBoi.Length; //add up all the numbers within the array for (int widthCounter = 0; widthCounter < width; widthCounter++) { for (int lengthCounter = 0; lengthCounter < length; lengthCounter++) { genericNum = intyBoi[widthCounter, lengthCounter]; arrayTotal += genericNum; } } //calculate the average and then round it off to two decimal places, //before returning it in a string average = Math.Round((double)arrayTotal / (double)totalSize, 2); return "The average of all the numbers in this array is equal to: " + Convert.ToString(average); } private void btnCreate_Click(object sender, EventArgs e) { //local variables decimal width; decimal length; string arrayText = ""; int randomNum; //get user length/width width = nudWidth.Value; length = nudLength.Value; //create the array with chosen length/width int[,] generic2DArray = new int[(int)width, (int)length]; for (int widthCounter = 0; widthCounter < width; widthCounter++) { for (int lengthCounter = 0; lengthCounter < length; lengthCounter++) { //generate a number from in between 0 and 9, then add it to the array and the string randomNum = numGen.Next(0, 9 + 1); generic2DArray[widthCounter, lengthCounter] = randomNum; arrayText += " " + randomNum; } //add a line break to show a new row arrayText += Environment.NewLine; } //enable the textbox and insert the string into it txtArray.Text = arrayText; txtArray.Enabled = true; //Display the average of the numbers in the array txtArray.Text += Environment.NewLine + ArrayAverage(generic2DArray); } } }
95bc8e48e3ffac3223c94b2e8f75cc2e1e4c9e8d
C#
human-osaka-game-2018/ChatTools
/KinoshitaTatsuya/ChatTool/ChatTool/Bases/BindableBase.cs
2.9375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace ChatTool.Bases { public abstract class BindableBase : INotifyPropertyChanged { public event PropertyChangedEventHandler? PropertyChanged; protected void OnPropertyChanged([CallerMemberName]string? propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected void SetProperty<T>(ref T strage,T value,[CallerMemberName]string? propertyName = null) { if (object.Equals(strage, value)) return; strage = value; OnPropertyChanged(propertyName); } } }
0b0846434ddfdf8f767c82bb0403237708014dae
C#
shendongnian/download4
/first_version_download2/85692-5651643-12146186-2.cs
2.546875
3
private void runner(int i) { int j = i; bool loadFinished = false; webBrowser1.DocumentCompleted += delegate { loadFinished = true; }; webBrowser1.Navigate("http://www11.itrc.hp.com/service/ewarranty/warrantyInput.do"); while (!loadFinished ) { Thread.Sleep(100); Application.DoEvents(); } webBrowser1.Document.GetElementById("productnumber").InnerText = dt.Rows[j][0].ToString(); webBrowser1.Document.GetElementById("serialnumber1").InnerText = dt.Rows[j][1].ToString(); HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("SELECT"); foreach (HtmlElement elem in elems) { if (elem.Name.ToString() == "country") { elem.SetAttribute("value", "US"); } } int countelement = 0; HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("INPUT"); foreach (HtmlElement element in col) { if (element.Name.ToString() == "") { if (countelement == 1) { element.InvokeMember("click"); do { Application.DoEvents(); } while (webBrowser1.IsBusy); } countelement++; } } string output = ""; int county = 0; HtmlElementCollection elly = webBrowser1.Document.GetElementsByTagName("TABLE"); foreach (HtmlElement el in elly) { if (county == 19) { string[] lines = el.InnerText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { if (line.IndexOf("Start Date") != -1) { output = line.ToString(); dt.Rows[j][2] = output.Remove(0, 10); break; } } } county++; } }
5f08a044bc01e03705593cc33d6c5b24e86f493d
C#
SeniorProjectUF/Senior
/Assets/Scripts/ParticlePosition.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParticlePosition : MonoBehaviour { public float[] xPosPoly; public float[] yPosPoly; public float[] zPosPoly; public float xPosShift; public float yPosShift; public float zPosShift; public float disappearAfter = 0.0f; public bool shouldDisappear = false; public float appearAfter = 0.0f; public bool shouldAppear = false; private TimeManipulation timeMan; private float time; // Use this for initialization void Start () { GameObject mainCamera = GameObject.Find("Main Camera"); timeMan = mainCamera.GetComponent<TimeManipulation>(); } // Update is called once per frame void Update () { time = timeMan.elapsedTime; transform.position = new Vector3(calculatePositionWithPolyAndTime(xPosPoly, xPosShift, time), calculatePositionWithPolyAndTime(yPosPoly, yPosShift, time), calculatePositionWithPolyAndTime(zPosPoly, zPosShift, time)); } float calculatePositionWithPolyAndTime(float[] poly, float shift, float time){ float position = 0; for (int i = 0; i < poly.Length; i++) { position += poly [i] * Mathf.Pow (time - shift, i); } return position; } }
a25fb38e5071d7b95cf82e4c2e7e074ada03be88
C#
zdrigotti/Algorithm-Implementations
/BreadthFirstSearch/Node.cs
3.78125
4
using System.Collections.Generic; namespace BreadthFirstSearch { class Node { public List<Node> Children { get; private set; } public int Value { get; private set; } public Node(int value) { Value = value; Children = new List<Node>(); } /// <summary> /// Adds a new child node /// </summary> /// <param name="child">Child node to add</param> public void AddChild(Node child) { Children.Add(child); } public override bool Equals(object obj) { Node comparisionNode = (Node)obj; return Value == comparisionNode.Value; } public override int GetHashCode() { return Value; } } }
4451a40c2afad5ecb05fe5ab44864ec395acd2ef
C#
chengzhongnan/MongoDBOrm
/ProjectCommon/Unit/EntityMgr.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectCommon.Unit { public class EntityMgr : DefaultEntityContainer, IEntityContainer<EntityBase, short> { protected Dictionary<short, EntityBase> _entityMap { get; private set; } public EntityMgr() { _entityMap = new Dictionary<short, EntityBase>(); } /// <summary> /// 注册实体 /// </summary> /// <param name="entity"></param> public virtual bool CreateEntity<TEntity>() where TEntity : EntityBase, new() { TEntity entity = new TEntity(); return AddObject(entity); } /// <summary> /// 查找实体 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="type"></param> /// <returns></returns> public T FindEntity<T>(short type) where T: EntityBase { return FindEntity(type) as T; } /// <summary> /// 查找实体 /// </summary> /// <param name="type"></param> /// <returns></returns> public EntityBase FindEntity(short type) { if (_entityMap.ContainsKey(type)) return _entityMap[type]; return null; } /// <summary> /// 初始化 /// </summary> public virtual void Init() { foreach (var it in _entityMap) { it.Value.Init(); } } /// <summary> /// 释放 /// </summary> public virtual void Release() { foreach (var it in _entityMap) { it.Value.Release(); } } /// <summary> /// 心跳 /// </summary> /// <param name="elapsed"></param> public virtual void Heartbeat(double elapsed) { foreach (var it in _entityMap) { it.Value.Heartbeat(elapsed); } } bool IEntityContainer<EntityBase, short>.AddObject(EntityBase entity) { if (!_entityMap.ContainsKey(entity.Type)) { _entityMap.Add(entity.Type, entity); return true; } return false; } EntityBase IEntityContainer<EntityBase, short>.GetObject(short key) { return FindEntity(key); } EntityBase IEntityContainer<EntityBase, short>.GetObject(Func<EntityBase, bool> patten) { foreach(var kv in _entityMap) { if (patten(kv.Value)) { return kv.Value; } } return null; } bool IEntityContainer<EntityBase, short>.RemoveObject(short key) { if (_entityMap.ContainsKey(key)) { _entityMap.Remove(key); return true; } return false; } } public class EntityMgr<T, Key> : DefaultEntityContainer, IEntityContainer<T, Key> where T : EntityBase<Key> { protected Dictionary<Key, T> _entityMap { get; private set; } public EntityMgr() { _entityMap = new Dictionary<Key, T>(); } /// <summary> /// 注册实体 /// </summary> /// <param name="entity"></param> public virtual bool CreateEntity<TEntity>() where TEntity : EntityBase, new() { TEntity entity = new TEntity(); return AddObject(entity); } /// <summary> /// 初始化 /// </summary> public virtual void Init() { foreach (var it in _entityMap) { it.Value.Init(); } } /// <summary> /// 释放 /// </summary> public virtual void Release() { foreach (var it in _entityMap) { it.Value.Release(); } } /// <summary> /// 心跳 /// </summary> /// <param name="elapsed"></param> public virtual void Heartbeat(double elapsed) { foreach (var it in _entityMap) { it.Value.Heartbeat(elapsed); } } bool IEntityContainer<T, Key>.AddObject(T obj) { if (_entityMap.ContainsKey(obj.Type)) { return false; } _entityMap.Add(obj.Type, obj); return true; } T IEntityContainer<T, Key>.GetObject(Key key) { if (_entityMap.ContainsKey(key)) { return _entityMap[key]; } return default(T); } T IEntityContainer<T, Key>.GetObject(Func<T, bool> patten) { foreach(var kv in _entityMap) { if (patten(kv.Value)) { return kv.Value; } } return default(T); } bool IEntityContainer<T, Key>.RemoveObject(Key key) { return _entityMap.Remove(key); } } }
82fd61b2a658167c6d645ffa49f340f982728b78
C#
JetFire3201/Kroncky-Magik
/Assets/Scripts/CameraScript.cs
2.609375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; //This Script is for moving the camera around. public class CameraScript : MonoBehaviour { //Camera Script is for moving the Camera around. public float mouseSensitivity; public bool invertMouse; public bool autoLockCursor; private Camera cam; public Transform character; void Awake () { cam = this.gameObject.GetComponent<Camera>(); this.gameObject.name = "SpectatorCamera"; Cursor.lockState = (autoLockCursor)?CursorLockMode.Locked:CursorLockMode.None; } void Update () { float x = Input.GetAxis("Mouse X"); float y = -1*Input.GetAxis("Mouse Y"); transform.RotateAround(this.transform.position,this.transform.up,x*mouseSensitivity); //Rotate the parent object to rotate around itself. if (Cursor.lockState == CursorLockMode.None && Input.GetMouseButtonDown(0)) { Cursor.lockState = CursorLockMode.Locked; } else if (Cursor.lockState == CursorLockMode.Locked && Input.GetKeyDown(KeyCode.Escape)) { Cursor.lockState = CursorLockMode.None; } } }
638e96fbaa0b2d8e9f6aaeed01007aa850a50298
C#
JCCervantes/Tech-Academy-Projects
/C# Visual Studio Projects/PostalCalculatorHelperMethods/PostalCalculatorHelperMethods/Default.aspx.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PostalCalculatorHelperMethods { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Width_TextChanged(object sender, EventArgs e) { } protected void Height_TextChanged(object sender, EventArgs e) { } protected void Length_TextChanged(object sender, EventArgs e) { } protected void GroundButton_CheckedChanged(object sender, EventArgs e) { calculatePostage(.15); } protected void AirButton_CheckedChanged(object sender, EventArgs e) { calculatePostage(.25); } protected void NextDayButton_CheckedChanged(object sender, EventArgs e) { calculatePostage(.45); } protected void calculatePostage(double multiplier) { if ((Width.Text.Trim().Length == 0) || (Height.Text.Trim().Length == 0) || (Length.Text.Trim().Length == 0)) { resultLabel.Text = "You must enter the package dimensions."; return; } else { int volume = (int.Parse(Width.Text)) * (int.Parse(Height.Text)) * (int.Parse(Length.Text)); double Postage = volume * multiplier; resultLabel.Text = String.Format("The postage for this package is {0:C}.", Postage); } } } }
13350c0020f5fc6f999ff95aff148f961cb6ff89
C#
sebasb718/Poem-Generator
/Source Code/Poem Generator/Entities/RulesFactory.cs
3.078125
3
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Poem_Generator.Entities { public class RulesFactory { public static Dictionary<string, Rule> GetDictionaryOfRules(string fileName) { Dictionary<string, Rule> rules = new Dictionary<string, Rule>(); string path = $"{System.IO.Directory.GetCurrentDirectory()}\\{fileName}"; string[] rulesFileLines = FilesHandler.getLinesFromFile(path); foreach (string ruleLine in rulesFileLines) { string[] NameBreakdown = ruleLine.Split(':'); string RuleName = NameBreakdown[0].Trim(); string[] DefinitionBreakdown = NameBreakdown[1].Trim().Split(' '); List<string[]> RuleComponents = new List<string[]>(); foreach (string definition in DefinitionBreakdown) { string[] components = definition.Trim().Split('|'); RuleComponents.Add(components); } Rule rule = new Rule(RuleComponents); rules.Add(RuleName, rule); } return rules; } } }
62e1de1db7c42b2f245d4e5ad7c7dd29a874397d
C#
kurthamilton/InvestmentTracker
/api/InvestmentTracker.Api/Prices/PricesController.cs
2.546875
3
using InvestmentTracker.ApplicationService.Prices; using InvestmentTracker.Domain.Investments; using InvestmentTracker.Domain.Prices; using System; using System.Collections.Generic; using System.Web.Http; namespace InvestmentTracker.Api.Prices { public class PricesController : ControllerBase { private readonly IPriceApplicationService _priceApplicationService; public PricesController(IPriceApplicationService priceApplicationService) { _priceApplicationService = priceApplicationService; } [HttpDelete] public IHttpActionResult Delete(Guid id) { _priceApplicationService.Delete(id); return GetAll(); } [HttpGet] [Route("api/prices/encrypt")] public IHttpActionResult Encrypt(string data, string passPhrase) { return JsonResult(StringCipher.Encrypt(data, passPhrase)); } [HttpGet] public IHttpActionResult Get(Guid id) { Price price = _priceApplicationService.GetById(id); return JsonResult(price); } [HttpGet] public IHttpActionResult GetAll() { IReadOnlyCollection<Price> prices = _priceApplicationService.GetAll(); return JsonResult(prices); } [HttpPost] public IHttpActionResult Post(CreatePriceModel model) { Price price = new Price(model.Date, model.Fund, model.Value); Guid id = _priceApplicationService.Add(price); return Get(id); } [HttpPost] [Route("api/prices/scrape")] public IHttpActionResult Scrape(string investment, string url, string username, string password, string passPhrase, DateTime from, DateTime? to = null, int intervalDays = 1) { InvestmentSettings settings = new InvestmentSettings { Password = StringCipher.Decrypt(password, passPhrase), Url = url, Username = StringCipher.Decrypt(username, passPhrase) }; IReadOnlyCollection<Price> prices = _priceApplicationService.Scrape(investment, settings, from, to, intervalDays); _priceApplicationService.Add(prices); return GetAll(); } } }
6bb4dd69e1b925c18ff4fcab01d99e20dd8fd522
C#
logzio/logzio-dotnet
/src/UnitTests/Log4net/LogzioAppenderTests.cs
2.53125
3
using log4net.Core; using Logzio.DotNet.Core.InternalLogger; using Logzio.DotNet.Core.Shipping; using Logzio.DotNet.Log4net; using NSubstitute; using NUnit.Framework; namespace Logzio.DotNet.UnitTests.Log4net { [TestFixture] public class LogzioAppenderTests { private LogzioAppender _target; private IShipper _shipper; [SetUp] public void Setup() { _shipper = Substitute.For<IShipper>(); _target = new LogzioAppender(_shipper, Substitute.For<IInternalLogger>()); } [Test] public void Append_Appending_CallsShipperWithCorrectValues() { _target.DoAppend(GetLoggingEventWithSomeData()); _target.Close(); _shipper.Received().Ship(Arg.Is<LogzioLoggingEvent>(x => (string)x.LogData["domain"] == "Such domain"), Arg.Any<ShipperOptions>()); } [Test] public void Append_AppendingWithCustomFields_CallsShipperWithCorrectValues() { _target.AddCustomField(new LogzioAppenderCustomField { Key = "DatKey", Value = "DatVal" }); _target.DoAppend(GetLoggingEventWithSomeData()); _target.Close(); _shipper.Received().Ship(Arg.Is<LogzioLoggingEvent>(x => (string)x.LogData["DatKey"] == "DatVal"), Arg.Any<ShipperOptions>()); } private LoggingEvent GetLoggingEventWithSomeData() { return new LoggingEvent(new LoggingEventData { Domain = "Such domain", Level = Level.Info, Message = "That's a message alright" }); } } }
b40dde456cec454c0c22d25aac6a57f3210f3ceb
C#
shendongnian/download4
/first_version_download2/41756-6642468-14502557-2.cs
2.984375
3
private void ClearTextBoxes(Control control) { foreach (Control c in control.Controls) { if (c is TextBox) { ((TextBox)c).Clear(); } if (c.HasChildren) { ClearTextBoxes(c); } if (c is CheckBox) { ((CheckBox)c).Checked = false; } if (c is RadioButton) { ((RadioButton)c).Checked = false; } } }
800c6faf4d4a956c1048e63e2faf7db08824e67e
C#
USAID-DELIVER-PROJECT/ethiopia-hcmis-warehouse
/Code/Windows/Infrastructure/Models/Models/Mapping/TransferMap.cs
2.5625
3
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace HCMIS.Concrete.Models.Mapping { public class TransferMap : EntityTypeConfiguration<Transfer> { public TransferMap() { // Primary Key this.HasKey(t => t.ID); // Properties // Table & Column Mappings this.ToTable("Transfer"); this.Property(t => t.ID).HasColumnName("ID"); this.Property(t => t.OrderID).HasColumnName("OrderID"); this.Property(t => t.FromStoreID).HasColumnName("FromStoreID"); this.Property(t => t.ToStoreID).HasColumnName("ToStoreID"); this.Property(t => t.FromPhysicalStoreID).HasColumnName("FromPhysicalStoreID"); this.Property(t => t.ToPhysicalStoreID).HasColumnName("ToPhysicalStoreID"); this.Property(t => t.TransferTypeID).HasColumnName("TransferTypeID"); // Relationships this.HasRequired(t => t.Order) .WithMany(t => t.Transfers) .HasForeignKey(d => d.OrderID); this.HasRequired(t => t.PhysicalStore) .WithMany(t => t.Transfers) .HasForeignKey(d => d.FromPhysicalStoreID); this.HasOptional(t => t.PhysicalStore1) .WithMany(t => t.Transfers1) .HasForeignKey(d => d.ToPhysicalStoreID); this.HasRequired(t => t.Store) .WithMany(t => t.Transfers) .HasForeignKey(d => d.FromStoreID); this.HasOptional(t => t.Store1) .WithMany(t => t.Transfers1) .HasForeignKey(d => d.ToStoreID); this.HasOptional(t => t.TransferType) .WithMany(t => t.Transfers) .HasForeignKey(d => d.TransferTypeID); } } }
72c2526164385ef04a311677c6a52283aa6be13d
C#
richbryant/bonsai
/Bonsai.Shaders/CreatePerspectiveFieldOfView.cs
2.59375
3
using OpenTK; using System; using System.ComponentModel; using System.Linq; using System.Reactive.Linq; namespace Bonsai.Shaders { [Description("Creates a perspective projection matrix from field of view information.")] public class CreatePerspectiveFieldOfView : Source<Matrix4> { public CreatePerspectiveFieldOfView() { NearClip = 0.1f; FarClip = 1000f; AspectRatio = 1; FovY = MathHelper.PiOver3; } [Range(Math.PI / 180, Math.PI - Math.PI / 180)] [Editor(DesignTypes.SliderEditor, DesignTypes.UITypeEditor)] [Description("The angle of the field of view in the y direction, in radians.")] public float FovY { get; set; } [Description("The aspect ratio of the viewport.")] public float AspectRatio { get; set; } [Category("Z-Clipping")] [Description("The distance to the near clip plane.")] public float NearClip { get; set; } [Category("Z-Clipping")] [Description("The distance to the far clip plane.")] public float FarClip { get; set; } public override IObservable<Matrix4> Generate() { return Observable.Defer(() => Observable.Return(Matrix4.CreatePerspectiveFieldOfView(FovY, AspectRatio, NearClip, FarClip))); } public IObservable<Matrix4> Generate<TSource>(IObservable<TSource> source) { return source.Select(x => Matrix4.CreatePerspectiveFieldOfView(FovY, AspectRatio, NearClip, FarClip)); } } }
1003c81ecc7190bbdf4db3d2c6cca75de9122145
C#
j4zzlee/CommonLibraries
/src/DatabaseModelExtensions/DatabaseSchemaExtensions.cs
2.953125
3
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace DatabaseModelExtensions { /// <summary> /// Determines if the Property should not be /// </summary> /// <seealso cref="System.Attribute" /> public class SchemaIgnoreAttribute : Attribute { } public static class DatabaseSchemaExtensions { public static string GetDatabaseSchemas(this object input) { var props = input.GetType().GetProperties().Where(p => !CustomAttributeExtensions.IsDefined((MemberInfo)p, typeof(SchemaIgnoreAttribute))); return BuildSchemas(props); } public static string GetDatabaseValueSchemas(this object input) { var props = input.GetType().GetProperties().Where(p => !p.IsDefined(typeof(SchemaIgnoreAttribute))); return BuildValueSchemas(props); } public static string GetDatabaseSchemas(this Type type) { var props = type.GetProperties().Where(p => !p.IsDefined(typeof(SchemaIgnoreAttribute))).ToList(); return BuildSchemas(props); } public static string GetDatabaseValueSchemas(this Type type) { var props = type.GetProperties().Where(p => !p.IsDefined(typeof(SchemaIgnoreAttribute))).ToList(); return BuildValueSchemas(props); } private static string FilterSchemaName(string originalName) { switch (originalName) { case "Read": return "[Read]"; case "User": return "[User]"; } return originalName; } private static string BuildSchemas(IEnumerable<PropertyInfo> props) { return props.Aggregate(string.Empty, (current, p) => current + $"{FilterSchemaName(p.Name)},").TrimEnd(','); } private static string BuildValueSchemas(IEnumerable<PropertyInfo> props) { return props.Aggregate(string.Empty, (current, p) => current + $"@{p.Name},").TrimEnd(','); } } }
af3c76ec2aed565982be037725bcdb44bb2024c3
C#
jebakani/Logical_Programming
/LogicalProgramming/PrimeNumberSeries.cs
4.09375
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LogicalProgramming { class PrimeNumberSeries { public void ReadInput() { Console.WriteLine("Welcome to Prime Number Series"); Console.WriteLine("Enter the number:"); //Read input from user int number = Convert.ToInt32(Console.ReadLine()); FindPrimeSeries(number); } private void FindPrimeSeries(int num) { //local variable to check prime or not int isprime; Console.WriteLine("The Prime number between 1 to {0} are",num); for(int iter=2;iter<=num;iter++) { isprime = 1; //Checking the below condition for n number of times for (int primeTester=2;primeTester<=Math.Sqrt(iter);primeTester++) { //check whether the number is divisible by any other number if(iter%primeTester==0) { isprime = 0; break; } } //if it is not divisible by any other number then print as prime number if(isprime==1) { Console.WriteLine("{0}",iter); } } } } }
d4288f783154da2f73e88949a3aacc784c80bd48
C#
KuffelHubert/AquaDroid
/AquaDroid/MainActivity.cs
2.65625
3
using Android.App; using Android.Widget; using Android.OS; using Android.Bluetooth; using System.Collections; using System.Collections.Generic; using Android.Content; using System.Linq; namespace AquaDroid { [Activity(Label = "AquaDroid", MainLauncher = true)] public class MainActivity : Activity { Button btnPaired; ListView devicelist; private BluetoothAdapter myBluetooth = null; private List<BluetoothDevice> pairedDevices; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); btnPaired = (Button)FindViewById(Resource.Id.button1); devicelist = (ListView)FindViewById(Resource.Id.listView1); myBluetooth = BluetoothAdapter.DefaultAdapter; if (myBluetooth == null) { //Show a mensag. that thedevice has no bluetooth adapter Toast.MakeText(ApplicationContext, "Bluetooth Device Not Available", ToastLength.Long).Show(); //finish apk Finish(); } else { if (!myBluetooth.IsEnabled) { //Ask to the user turn the bluetooth on Intent turnBTon = new Intent(BluetoothAdapter.ActionRequestEnable); StartActivityForResult(turnBTon, 1); } } btnPaired.Click += BtnPaired_Click; } private void BtnPaired_Click(object sender, System.EventArgs e) { PairedDevicesList(); } private void PairedDevicesList() { pairedDevices = myBluetooth.BondedDevices.ToList(); ArrayList list = new ArrayList(); if (pairedDevices.Count > 0) { foreach (BluetoothDevice bt in pairedDevices) { list.Add(bt.Name + "\n" + bt.Address); //Get the device's name and the address } } else { Toast.MakeText(ApplicationContext, "No Paired Bluetooth Devices Found.", ToastLength.Long).Show(); } ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, list); devicelist.Adapter = adapter; devicelist.ItemClick += Devicelist_ItemClick; ; //Method called when the device from the list is clicked } private void Devicelist_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { string info = ((TextView)e.View).Text; string address = info.Substring(info.Length - 17); // Make an intent to start next activity. Intent i = new Intent(this, typeof(RelayControl)); //Change the activity. i.PutExtra("EXTRA_ADDRESS", address); //this will be received at ledControl (class) Activity StartActivity(i); } } }
4ef85871f8058fb8270ed8043242b421db403734
C#
Daviberas/ApiRestPersonaAJAX
/PruebaApiREST/src/ENT/clsPersona.cs
2.921875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ENT { public class clsPersona { //Atributos public int Id { get; set; } [Required] [Display (Name = "Nombre")] public String Nombre { get; set; } [Required] [Display(Name = "Apellido")] public String Apellidos { get; set; } [Display(Name = "Fecha de nacimiento")] [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode =true)] public DateTime FechaNac { get; set; } [Display(Name = "Dirección")] public String Direccion { get; set; } [Display(Name = "Teléfono")] public String Telefono { get; set; } //Constructores public clsPersona() { Id = 1; Nombre = ""; Apellidos = ""; FechaNac = new DateTime(); Direccion = ""; Telefono = ""; } public clsPersona(int id, String nombre, String apellidos, DateTime fechaNac, String direccion, String telefono) { Id = id; Nombre = nombre; Apellidos = apellidos; FechaNac = fechaNac; Direccion = direccion; Telefono = telefono; } } }
7943bb010f32b9d7d853cdf16ede8549a6537fe8
C#
trungdq88/FormulasTextBox
/FormulasTextBox.cs
3.140625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace Assignment4 { public class FormulasTextBox : TextBox { /******************************************************/ /* Private fields /******************************************************/ private Boolean _numericOnly; private Color _invalidFormulasColor = Color.Red; private Color _validFormulasColor = Color.Blue; private Color _inputFormulasColor = Color.White; private Boolean _cancelKeyDueToShortcuts; private Boolean IsFormulasValid { get; set; } /******************************************************/ /* Properties and events * See more: * http://stackoverflow.com/a/2081964/1420186 * http://msdn.microsoft.com/en-us/library/system.componentmodel.categoryattribute.aspx /******************************************************/ [Description("Active Numeric Only"), Category("Numeric Only")] public Boolean NumericOnly { get { return _numericOnly; } set { _numericOnly = value; } } [Description("Invalid Formulas Color"), Category("Numeric Only")] public Color InvalidFormulasColor { get { return _invalidFormulasColor; } set { _invalidFormulasColor = value; } } [Description("Valid Formulas Color"), Category("Numeric Only")] public Color ValidFormulasColor { get { return _validFormulasColor; } set { _validFormulasColor = value; } } [Description("Input Formulas Color"), Category("Numeric Only")] public Color InputFormulasColor { get { return _inputFormulasColor; } set { _inputFormulasColor = value; } } /******************************************************/ /** Override methods /******************************************************/ protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); // Shortcut keys to improve input speed. Make it pluggable in the future switch (e.KeyCode) { case Keys.T: _cancelKeyDueToShortcuts = true; AppendText("00"); break; case Keys.N: _cancelKeyDueToShortcuts = true; AppendText("000"); break; default: _cancelKeyDueToShortcuts = false; break; } } /// <summary> /// Decide if the pressed key is need to appended to the text box /// http://msdn.microsoft.com/en-us/library/vstudio/system.windows.forms.control.keydown(v=vs.100).aspx /// </summary> /// <param name="e"></param> protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (_cancelKeyDueToShortcuts) { e.Handled = true; } } protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); // When user is typing the input, use default color; BackColor = _inputFormulasColor; } /// <summary> /// Override OnLeave method to validate formulas when the control lost focus /// </summary> /// <param name="e"></param> protected override void OnLeave(EventArgs e) { base.OnLeave(e); IsFormulasValid = true; if (Text.Length > 0) { if (Text[0] == '=') { // User is going to enter a formulas String input = Text.TrimStart('='); try { Double result = EvaluateExpression(input); Text = result + ""; } catch (Exception ex) { MessageBox.Show(ex.Message, "Expression is invalid"); } } else { // User is going to enter a value try { Double result = Convert.ToDouble(Text); } catch (Exception) { // Input is invalid IsFormulasValid = false; MessageBox.Show("Invalid input value!"); } } } else { Text = "0"; } // Update back color if (IsFormulasValid) { BackColor = _validFormulasColor; } else { BackColor = _invalidFormulasColor; Focus(); } } /// <summary> /// There are many ways to implement this method /// As an ACM student, they would prefer the Binary Expression Tree Aglorithm: /// http://en.wikipedia.org/wiki/Binary_expression_tree /// But ain't body got time for that, I am not relaly good at Aglorithm, so I /// found a nice-tricky solution from Teoman Soygul in StackoverFlow /// http://stackoverflow.com/a/6052679/1420186 /// </summary> /// <param name="expression"></param> /// <returns></returns> private double EvaluateExpression(String expression) { try { DataTable table = new DataTable(); table.Columns.Add("expression", string.Empty.GetType(), expression); DataRow row = table.NewRow(); table.Rows.Add(row); return double.Parse((string)row["expression"]); } catch (Exception) { throw; } } } }
ab1b6f1b18722f0119c40e0a5bcb20cd1c5c813e
C#
howbigbobo/LagacyDotNetDailyCode
/Pineapple/Pineapple.Core.Web/Cache/RequestCache.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using Pineapple.Core.Cache; namespace Pineapple.Core.Web.Cache { public class RequestCache : ICache { public bool Contain(string group, string key) { return HttpContext.Current.Items[BuildKey(group, key)] != null; } public object Get(string group, string key) { return HttpContext.Current.Items[BuildKey(group, key)]; } public void Add(string group, string key, object value) { HttpContext.Current.Items.Add(BuildKey(group, key), value); } public void Remove(string group, string key) { HttpContext.Current.Items.Remove(BuildKey(group, key)); } public void Clear() { } private string BuildKey(string group, string key) { return group + "-" + key; } } }
fea13d90a5ffcc9dc994aa8d7e543fe2d851bd3d
C#
RondonLeonR/2do-Cuatrimestre-2019
/Rondon.Rodolfo/ENTIDADES.SP/Manzana.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.IO; namespace ENTIDADES.SP { [Serializable] public class Manzana : Fruta , ISerializar , IDeserializar { protected string _provinciaOrigen; public string Nombre { get { return "Manzana"; } } public override bool TieneCarozo { get { return true; } } public Manzana(string color, double peso, string provinciaOrigen): base(color,peso) { this._provinciaOrigen = provinciaOrigen; } public override string ToString() { return this.Nombre + " Carozo: "+ this.TieneCarozo.ToString() + " Origen: "+this._provinciaOrigen + base.FrutaToString() ; } public bool Xml(string path) { bool retorno; try { XmlSerializer xml = new XmlSerializer(typeof(Manzana)); using (StreamWriter str = new StreamWriter(path)) { xml.Serialize(str, this); } retorno = true; } catch (Exception) { retorno = false; } return retorno; } bool IDeserializar.Xml(string c, out Fruta fruta) { bool retorno = true; try { XmlSerializer xml = new XmlSerializer(typeof(Fruta)); StreamReader str = new StreamReader(c); Fruta f = (Fruta)xml.Deserialize(str); fruta = f; return retorno; } catch (Exception) { throw; } } } }
7a7ce3421d4e80d6b1c8aef16bb1185026f23635
C#
dilyanaGl/CSharp-OOP-Advanced
/Last Army/Core/GameController.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Last_Army.Entities; using Last_Army.Entities.Mission; using Last_Army.Factory; using Last_Army.Interfaces; namespace Last_Army.Core { public class GameController { private MissionController missionControllerField; private IArmy army; private IWareHouse wareHouse; private SoldiersFactory soldiersFactory; private AmmunitionFactory ammunitionFactory; private MissionFactory missionFactory; private SoldierController soldierController; private StringBuilder result; private Output output; private const string suffix = "Command"; public GameController() { this.wareHouse = new WareHouse(); this.army = new Army(this.WareHouse); this.soldiersFactory = new SoldiersFactory(); this.ammunitionFactory = new AmmunitionFactory(); this.missionFactory = new MissionFactory(); this.soldierController = new SoldierController(this.Army, this.WareHouse); this.MissionControllerField = new MissionController(this.Army, this.WareHouse); this.result = new StringBuilder(); this.output = new Output(this.Army, this.WareHouse, result); } public IArmy Army { get { return army; } set { army = value; } } public IWareHouse WareHouse { get { return wareHouse; } set { wareHouse = value; } } public MissionController MissionControllerField { get { return missionControllerField; } set { missionControllerField = value; } } public void GiveInputToGameController(string input) { var data = input.Split(); string commandName = data[0] + suffix; if (data[1] == "Regenerate") { commandName = data[1] + suffix; } string[] parameters = data.Skip(1).ToArray(); this .GetType() .GetMethod(commandName, BindingFlags.NonPublic | BindingFlags.Instance) .Invoke(this, new object[]{parameters}); } public string RequestResult(string addedResult) { this.MissionControllerField.FailMissionsOnHold(); return output.GiveOutput(addedResult, this.missionControllerField.FailedMissionCounter, this.missionControllerField.SuccessMissionCounter); } private void SoldierCommand(string[] data) { ISoldier soldier = soldiersFactory.CreateSoldier(data); this.army.AddSoldier(soldier, result); } private void RegenerateCommand(string[] data) { soldierController.TeamRegenerate(data[1]); } private void WareHouseCommand(string[] data) { string name = data[0]; int number = int.Parse(data[1]); this.WareHouse.AddAmmunition(name, number); } private void MissionCommand(string[] data) { var mission = missionFactory.CreateMission(data[0], double.Parse(data[1])); result.AppendLine(this.MissionControllerField.PerformMission(mission).Trim()); } } }
ebee13ccc056ead35624912d10ac67ea1978b0e3
C#
michalMalujdy/_UWP_Signal
/Signal.Core/Domain/DataProviding/Serial/SerialTransmission/SerialTransmission.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using Signal.Core.Domain.DataProviding.Serial.Message; namespace Signal.Core.Domain.DataProviding.Serial.SerialTransmission { public class SerialTransmission { public event EventHandler<FullMessageReceivedEventArgs> FullMessagesReceived; public const string MessageEndSign = @"!%"; public StringBuilder TempContent { get; private set; } = new StringBuilder(); public void ReadNext(string messagePart) { TempContent.Append(messagePart); var tempContentString = TempContent.ToString(); if (!tempContentString.Contains(MessageEndSign)) return; ReadMessages(messagePart, tempContentString); } private void ReadMessages(string messagePart, string tempContentString) { var splitMessages = tempContentString .Split(new [] { MessageEndSign }, StringSplitOptions.None); TempContent = new StringBuilder(splitMessages.Last()); var readingsMessages = TryDeserializeMessages(splitMessages); FullMessagesReceived?.Invoke(this, new FullMessageReceivedEventArgs() { ReadingsMessages = readingsMessages }); } private ReadingsMessage TryDeserializeMessage(string message) { try { return JsonConvert.DeserializeObject<ReadingsMessage>(message); } catch (Exception ex) { return null; } } private ICollection<ReadingsMessage> TryDeserializeMessages(IEnumerable<string> messages) { var readingsMessages = new List<ReadingsMessage>(); foreach (var message in messages) { var readingsMessage = TryDeserializeMessage(message); if (readingsMessage != null) readingsMessages.Add(readingsMessage); } return readingsMessages; } } }
83d4a8985248bcdafdf6bf42b22b20b44966898b
C#
Unity-Technologies/ProjectAuditor
/Editor/UI/Framework/TextFilter.cs
2.515625
3
using System; using System.Collections.Generic; using Unity.ProjectAuditor.Editor.CodeAnalysis; using Unity.ProjectAuditor.Editor.Core; namespace Unity.ProjectAuditor.Editor { internal class TextFilter : IProjectIssueFilter { public bool ignoreCase = true; public bool searchDependencies = false; public string searchString = string.Empty; readonly int[] searchablePropertyIndices; public TextFilter(PropertyDefinition[] propertyDefinitions = null) { var indices = new List<int>(); if (propertyDefinitions != null) { foreach (var propertyDefinition in propertyDefinitions) { if (propertyDefinition.format != PropertyFormat.String) continue; if (!PropertyTypeUtil.IsCustom(propertyDefinition.type)) continue; indices.Add(PropertyTypeUtil.ToCustomIndex(propertyDefinition.type)); } } searchablePropertyIndices = indices.ToArray(); } public bool Match(ProjectIssue issue) { if (string.IsNullOrEmpty(searchString)) return true; // return true if the issue matches the any of the following string search criteria if (MatchesSearch(issue.description)) return true; if (MatchesSearch(issue.filename)) return true; foreach (var customPropertyIndex in searchablePropertyIndices) { if (MatchesSearch(issue.GetCustomProperty(customPropertyIndex))) return true; } var dependencies = issue.dependencies; if (dependencies != null) { if (MatchesSearch(dependencies, searchDependencies)) return true; } // no string match return false; } bool MatchesSearch(string text) { return !string.IsNullOrEmpty(text) && text.IndexOf(searchString, ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture) >= 0; } bool MatchesSearch(DependencyNode node, bool recursive) { if (node == null) return false; var callTreeNode = node as CallTreeNode; if (callTreeNode != null) { if (MatchesSearch(callTreeNode.typeName) || MatchesSearch(callTreeNode.methodName)) return true; } if (recursive) for (var i = 0; i < node.GetNumChildren(); i++) { if (MatchesSearch(node.GetChild(i), true)) return true; } return false; } } }
8d43982cc4f613849dbbffc8a25f8efddac182c4
C#
arizomo/HominiMVC
/HominiMVC/Models/Municipio.cs
2.546875
3
using System.ComponentModel.DataAnnotations; namespace HominiMVC.Models { public class Municipio { public int Id { get; set; } [Required(ErrorMessage = "Nombre es requerido")] [StringLength(50, ErrorMessage = "Máximo 50 caracteres")] [Display(Name = "Nombre Municipio")] [RegularExpression("^[a-zA-Z]*$", ErrorMessage = "Solo caracteres del alfabeto")] public string NombreMunicipio { get; set; } [Required(ErrorMessage = "Código es requerido")] [StringLength(3, ErrorMessage = "Máximo 3 dígitos")] [MinLength(3, ErrorMessage = "Codigo Municipio debe ser de 3 números")] [Display(Name = "Código Municipio")] [RegularExpression("^[0-9]*$", ErrorMessage = "Codigo Departamento debe ser numérico")] public string CodigoMunicipio { get; set; } public Departamento Departamento { get; set; } public int DepartamentoId { get; set; } } }
d69af6252881a22df8573fce2980aa91762da37e
C#
MarianoVilla/Clipper
/FFMpegUT/WebR.cs
2.78125
3
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Webber.Core { public delegate void DownloadProgress(double progress, string file); public static class WebR { private static int BufferSize { get; set; } public static DownloadProgress OnProgress; static WebR() { BufferSize = 4096; } public static void Download(string path, string url, bool retryOnTimeout = false) { WebRequest request = WebRequest.Create(url); try { using (var response = request.GetResponse()) { using (var stream = response.GetResponseStream()) { FileInfo file = new FileInfo(path); Stream fileStream = file.Open(FileMode.OpenOrCreate); byte[] buffer = new byte[BufferSize]; long downloadedBytes = 0, totalBytes = response.ContentLength; int length; double initialProgress = 0; while ((length = stream.Read(buffer, 0, BufferSize)) != 0) { fileStream.Write(buffer, 0, length); if (OnProgress != null) { downloadedBytes += length; double progress = Math.Round(((double)downloadedBytes / totalBytes) * 100, 0); if (progress > initialProgress) OnProgress(progress, file.Name); initialProgress = progress; } } fileStream.Close(); fileStream.Dispose(); } } } catch (Exception) { if (retryOnTimeout) { Thread.Sleep(4000); Download(url, path); } } } public static async Task DownloadAsync(string path, params string[] links) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); List<Task> downloadFiles = new List<Task>(); foreach (var link in links) { downloadFiles.Add(new Task(() => { string fileName = link.Remove(0, link.LastIndexOf('/') + 1), filePath = string.Format(@"{0}\{1}", path, fileName); Download(filePath, link); })); downloadFiles.Last().Start(); } await Task.WhenAll(downloadFiles); } public static async Task DownloadAsync(string path, IEnumerable<string> links) { await DownloadAsync(path, links.ToArray()); } //public static string Post() //{ //} public static string QueryString(Dictionary<string, string> collection) { var queryString = System.Web.HttpUtility.ParseQueryString(string.Empty); foreach (var entry in collection) queryString[entry.Key] = entry.Value; return queryString.ToString(); } public static string Get(string url) { WebRequest request = WebRequest.Create(url); string responseString = string.Empty; using (var response = request.GetResponse()) { using (var stream = new StreamReader(response.GetResponseStream())) { responseString = stream.ReadToEnd(); } } return responseString; } //public static async Task<string> GetAsync(string url) //{ // Task.Run(() => { // }); //} /* TO-DO CRUD */ } }
24b545309288a6afb4e8de7469527ebe3413699b
C#
marclayson/cSharpProgrammingFundamentals
/methodsDebuggingAndTroubleshootingCode-Lab/drawAFilledSquare/Program.cs
3.453125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace drawAFilledSquare { class Program { static void Main(string[] args) { int count = int.Parse(Console.ReadLine()); PrintHeader(count); PrintBody(count); PrintFooter(count); } static void PrintHeader(int n) { Console.WriteLine(new string('-', 2 * n)); } static void PrintBody(int n) { Console.Write('-'); for (int i = 0; i < n -1 ; i++) { Console.Write("\\/"); } Console.WriteLine('-'); } static void PrintFooter(int n) { Console.WriteLine(new string('-', 2 * n)); } } }
927e2b294b42c0eca68cfe8b0e2f1f24218dd178
C#
simirulless/MIDPS
/Lab#2/WindowsFormsApplication1/WindowsFormsApplication1/Form1.cs
2.859375
3
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } float operant1, raspuns; int opreatia; private void button4_Click(object sender, EventArgs e) { switch (opreatia) { case 1: raspuns = operant1 - float.Parse(textBox1.Text); textBox1.Text = raspuns.ToString(); break; case 2: raspuns = operant1 + float.Parse(textBox1.Text); textBox1.Text = raspuns.ToString(); break; case 3: raspuns = operant1 * float.Parse(textBox1.Text); textBox1.Text = raspuns.ToString(); break; case 4: raspuns = operant1 / float.Parse(textBox1.Text); textBox1.Text = raspuns.ToString(); break; default: break; } } private void button8_Click(object sender, EventArgs e) { operant1 = float.Parse(textBox1.Text); textBox1.Clear(); textBox1.Focus(); opreatia = 2; } private void button3_Click(object sender, EventArgs e) { int c = textBox1.TextLength; int flag = 0; string text = textBox1.Text; for (int i = 0; i < c; i++) { if (text[i].ToString() == ".") { flag = 1; break; } else { flag = 0; } } if (flag == 0) { textBox1.Text = textBox1.Text + "."; } } public void zero() { if (textBox1.Text == "0") textBox1.Clear(); } private void button5_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "1"; } private void button6_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "2"; } private void button7_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "3"; } private void button2_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "0"; } private void button16_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "4"; } private void button15_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "5"; } private void button14_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "6"; } private void button12_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "7"; } private void button11_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "8"; } private void button10_Click(object sender, EventArgs e) { zero(); textBox1.Text = textBox1.Text + "9"; } private void button24_Click(object sender, EventArgs e) { if (operant1 == 0 && textBox1.TextLength > 0) { operant1 = 0; textBox1.Text = "0" ; } else if (operant1 > 0 && textBox1.TextLength > 0) { textBox1.Clear(); textBox1.Text = "0"; } } private void button22_Click(object sender, EventArgs e) { int lenght = textBox1.TextLength - 1; string text = textBox1.Text; textBox1.Clear(); for (int i = 0; i < lenght; i++) textBox1.Text = textBox1.Text + text[i]; } private void button13_Click(object sender, EventArgs e) { if (textBox1.Text != "") { operant1 = float.Parse(textBox1.Text); textBox1.Clear(); textBox1.Focus(); opreatia = 1; } } private void button9_Click(object sender, EventArgs e) { operant1 = float.Parse(textBox1.Text); textBox1.Clear(); textBox1.Focus(); opreatia = 3; } private void button21_Click(object sender, EventArgs e) { operant1 = float.Parse(textBox1.Text); textBox1.Clear(); textBox1.Focus(); opreatia = 4; } private void button1_Click(object sender, EventArgs e) { float x; x = float.Parse(textBox1.Text); x = -x; textBox1.Text = x.ToString(); } private void button17_Click(object sender, EventArgs e) { float x; x = float.Parse(textBox1.Text); x = 1 / x; textBox1.Text = x.ToString(); } private void button19_Click(object sender, EventArgs e) { double x; x = double.Parse(textBox1.Text); x = Math.Sqrt(x); textBox1.Text = x.ToString(); } private void button18_Click(object sender, EventArgs e) { float x; x = float.Parse(textBox1.Text); x = x * x; textBox1.Text = x.ToString(); } private void button23_Click(object sender, EventArgs e) { textBox1.Clear(); opreatia = 0; textBox1.Text = "0"; } } }
e433398b66ef746063f6f1aa1a9433c7c10d4bc7
C#
mihoci10/B4R73ND3R
/B4R73ND3R/B4R73ND3R/IndependendAssemblyDeserializationBinder.cs
2.796875
3
using System; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization; using System.Reflection; namespace Extendix.ItemReceiver { /// <summary> /// Allows the <see cref="System.Runtime.Serialization.Formatters.Binary.BinaryFormatter"/> to deserialize received objects from a class whose interface is not necessarily defined in the original assembly it was created from before sending. /// </summary> class IndependendAssemblyDeserializationBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { //load the type always from the current executing assembly Type deserializationType = Type.GetType(String.Format("{0}, {1}", typeName, Assembly.GetExecutingAssembly().FullName)); return deserializationType; } } }
74f980e70bede163f6c07d6b64557d19b67620fe
C#
evgenitsn/CSharp-Entity-ASP-Web-Development
/2.C#-Object-Oriented-Programming/00.Exercises/04.Encapsulation-and-Polymorphism/Battleships/Ships/Ship.cs
3.40625
3
using System; namespace Battleships.Ships { public abstract class Ship { private string name; private double lengthInMeters; private double volume; public Ship(string name, double lengthInMeters, double volume) { this.Name = name; this.LengthInMeters = lengthInMeters; this.Volume = volume; } public string Name { get { return this.name; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value", "Name cannot be null or empty."); } this.name = value; } } public double LengthInMeters { get { return this.lengthInMeters; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", "The length of a ship cannot be negative."); } this.lengthInMeters = value; } } public double Volume { get { return this.volume; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", "The volume of a ship cannot be negative."); } this.volume = value; } } public bool IsBattleship { get; set; } public bool IsDestroyed { get; set; } } }
e602794ce2d8c097439e13d85b20ad59dd15b3a2
C#
nzkelvin/timed-service
/src/TimedService/Logger/BasicLoggerFactory.cs
2.984375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TimedService.Config; namespace TimedService.Logger { public class BasicLoggerFactory : ILoggerFactory { private IDictionary<string, ILogger> _loggerRepository = new Dictionary<string, ILogger>(); private object _lockerObj = new object(); private string _logFilePath; public BasicLoggerFactory(IConfigurationHelper configurationHelper) { _logFilePath = configurationHelper.GetSection<TimedServicesConfig>("TimedServices").LogFilePath; } /// <summary> /// If loggers names are the same, a single logger instance will be returned. /// </summary> /// <param name="name"></param> /// <returns></returns> public ILogger ProduceLogger(string name) { var filePath = string.Format(_logFilePath, name); if (!_loggerRepository.ContainsKey(filePath)) { lock (_lockerObj) { if (!_loggerRepository.ContainsKey(filePath)) { _loggerRepository.Add(filePath, new BasicLogger(filePath)); } } } return _loggerRepository[filePath]; } } }
3b5c23d93299d362797756704015246b1c42c1e2
C#
NadaAlOtaibi/Codes
/asStringExample.cs
3.25
3
static void Main(string[] args) { object [] o = new object[5]; o[0] = "Hi"; o[1] = 1; o[2] = "Hello"; o[3] = 534.0; o[3] = null; for (int i = 0; i < o.Length; i++) { string str = o[i] as string; if(str != null) { Console.WriteLine(" ' "+ str + " ' "); } else { Console.WriteLine(" Not a string"); } }
529ea2afc9c79a14b0393a79afc317e2626c64ad
C#
kewos/CSharpNote
/CSharpNote.Data.CSharpPracticeMethod/Implement/TestAwait.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CSharpNote.Common.Attributes; using CSharpNote.Core.Implements; namespace CSharpNote.Data.CSharpPractice.Implement { public class TestAwait : AbstractExecuteModule { [AopTarget] public override void Execute() { Console.WriteLine("start"); var primeListAsync = PrintPrimeAsync(1000); Console.WriteLine("end"); foreach (var prime in primeListAsync.Result) { Console.WriteLine(prime); } } private async Task<List<int>> PrintPrimeAsync(int maxNumber) { var tcs = new TaskCompletionSource<List<int>>(); await Task.Run(() => { var query = Enumerable.Range(2, maxNumber) .Where(x => x == 2 || Enumerable.Range(2, (int) Math.Sqrt(x)).All(y => x%y != 0)); tcs.SetResult(query.ToList()); }); return await tcs.Task; } } }
1aa01b9a77ca8dae5d1c73330910425e0b01aca0
C#
rudarobson/Chip-Burner
/Chip-Burner/Chip-Burner/Communicator/Commander.cs
3.25
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChipBurner.Communicator { public class Commander : IDisposable { /* Commands * 0 -> Begin programming * 1 -> Push Data (write) * 2 -> Pull Data (read) * 3 -> Chip Erase * 4 -> Run */ public int Address { get; set; } private LowLevelWrite _usb { get; set; } private const int MaxPacketsize = 64; public Commander() { Address = 0; _usb = new LowLevelWrite(); } /* 0 - Begin Programming * [0] - 0 * * expects: * Success - 0x53 * Fail - 0x35 */ public bool BeginProgramming() { byte[] cmd = new byte[100]; cmd[0] = 0; _usb.Write(cmd, 1); if (_usb.Read(cmd, 100) > 0) { if (cmd[0] == 0x53) return true; } return false; } /* 1 - Push data (write) * [0] - 1 * [1 ~ 4] - 32 bit Data Address * [5] - number of bytes to write * [6 ~ 6 + number of bytes] - data * * expects: * { 'O', 'K' } */ public void Write(byte[] data,int numBytes) { byte[] packet = new byte[MaxPacketsize]; packet[0] = 1; packet[1] = (byte)((Address >> 24) & 0xFF); packet[2] = (byte)((Address >> 16) & 0xFF); packet[3] = (byte)((Address >> 8) & 0xFF); packet[4] = (byte)(Address & 0xFF); packet[5] = (byte)(numBytes & 0xFF); for (int i = 0; i < numBytes; i++) packet[6 + i] = data[i]; _usb.Write(packet, numBytes + 6); _usb.Read(data, 2); if (!IsOK(data)) throw new Exception("Device MalFunctioning"); } /* 1 - Pull data (read) * [0] - 2 * [1 ~ 4] - 32 bit Data Address * [5] - number of bytes to read * expects: * { byte0, byte1, ..., byte number of bytes to read - 1 } */ public int Read(byte[] data,int numBytes) { byte[] packet = new byte[MaxPacketsize]; packet[0] = 2; packet[1] = (byte)((Address >> 24) & 0xFF); packet[2] = (byte)((Address >> 16) & 0xFF); packet[3] = (byte)((Address >> 8) & 0xFF); packet[4] = (byte)(Address & 0xFF); packet[5] = (byte)(numBytes & 0xFF); _usb.Write(packet, 6); return _usb.Read(data, numBytes); } /* 3 - Chip Erase * [0] - 3 * expects: * { byte0, byte1, ..., byte number of bytes to read - 1 } */ public void ChipErase() { byte[] pck = new byte[2]; pck[0] = 3; _usb.Write(pck, 1); _usb.Read(pck, 2); if(!IsOK(pck)) throw new Exception("Device MalFunctioning"); } /* [4] - Run * [0] - 4 * [1] - 1 for turn on, 0 for turn off */ public void Start(bool run) { byte[] pck = new byte[2]; pck[0] = 4; if (run) pck[1] = 1; else pck[1] = 0; _usb.Write(pck, 2); } private bool IsOK(byte[] ok) { return (ok[0] == 'O' && ok[1] == 'K'); } public FileStream GetUSB() { return _usb.GetStream(); } public void Dispose() { _usb.Dispose(); } } }
dc8c68404a634545c147e7c3e6993a489684c9f5
C#
sulmar/Patterns
/Factory Method Pattern - solution.linq
3.609375
4
<Query Kind="Program" /> void Main() { Console.WriteLine("Please choose objects from the below to built:"); Console.WriteLine("1. Door"); Console.WriteLine("2. Window"); Console.WriteLine("3. Walls"); int objectType = Convert.ToInt16(Console.ReadLine()); IObjectFactory objectFactory = ObjectFactory.GetObject(objectType); objectFactory.Print() } // Define other methods and classes here public interface IObjectFactory { void Print(); } class DoorFactory : IObjectFactory { #region IObjectFactory Members public void Print() { Console.WriteLine("You built a door"); } #endregion } class WindowFactory : IObjectFactory { #region IObjectFactory Members public void Print() { Console.WriteLine("You built a window"); } #endregion } class WallFactory : IObjectFactory { #region IObjectFactory Members public void Print() { Console.WriteLine("You built walls"); } #endregion } class ObjectFactory { static public IObjectFactory GetObject(int objectType) { if (objectType == 1) { return (new DoorFactory()); } else if (objectType == 2) { return (new WindowFactory()); } else if (objectType == 3) { return (new WallFactory()); } else return null; } }
3b7d6e34532866b57d4b7dd014dcd63c7a9e0ba4
C#
LeszekBlazewski/BettingParlor
/BettingParlor-Refactor/Server.cs
2.75
3
using Microsoft.Owin.Hosting; using System; using System.Reflection; using System.Windows.Forms; namespace BettingParlor_Refactor { /// <summary> /// Contains all methods which are used to host and close the server properly. /// </summary> /// <remarks> /// All methods are implemented with the use of SignalR framework. /// For more information check SignalR documentation.</remarks> /// <seealso cref="ClientServerConnectionsHub"/> public class Server { /// <summary> /// Returns the name od administrator which starts the server, when he loggs in. /// </summary> public string GetAdminName => adminName; /// <summary> /// Returns the URL on which server is hosted. /// </summary> public string GetServerUrl => ServerURI; /// <summary> /// Used to close and dispose server properly. /// </summary> public IDisposable SignalR { get; set; } /// <summary> /// Stores URL on which server is hosted. /// <note type="note"> /// The adress provided is used to test the database locally. /// </note> /// </summary> const string ServerURI = "http://localhost:8080"; /// <summary> /// Stores administrator name. /// </summary> string adminName; /// <summary> /// Initializes the fields properly. /// </summary> /// <param name="adminName">Name of the administrator which hosts the server.</param> public Server(string adminName) { this.adminName = adminName; } /// <summary> /// Starts the server on specified URL and checks whether error is thrown when another server is already hosted on same URL. /// </summary> /// <remarks> /// Implemented by the use of SignalR framework. /// Form more information check SignalR documentation.</remarks> public void StartServer(FormLogin formLogin) { try { SignalR = WebApp.Start(ServerURI); } catch (TargetInvocationException) { formLogin.labelStatusText.Invoke(new MethodInvoker(delegate { formLogin.labelStatusText.Text = "Server failed to start.\nA server is already running on " + ServerURI; })); return; } formLogin.StartGameWindowServer(this); //Starts the game window for administrator. } /// <summary> /// Checks whether server is up. If so then disposes the signal to prevent other users from connecting to server. /// </summary> /// <remarks>Function is fired when administrator signs out of his account. /// Than all connection are stopped.</remarks> public void CloseServer() { if (SignalR != null) SignalR.Dispose(); } } }
634018a661e9432d5df77fcebd46c108ec0f3c47
C#
dimaplanoff/ProxyFinder
/Sql.cs
2.5625
3
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProxyService { class Sql { private SqlConnection con = null; public bool connectionIsOpen = false; object sync = new object(); public Sql() { try { con = new SqlConnection(Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\CSHARP").GetValue("ConnectionStringCursor").ToString()); con.Open(); connectionIsOpen = true; } catch { } } public void Dispose() { con.Close(); con.Dispose(); } public int Exec(string queue) { try { lock (sync) { using (SqlCommand cmd = new SqlCommand(queue, con)) { cmd.CommandTimeout = 30; return cmd.ExecuteNonQuery(); } } } catch { return 0; } } public DataTable GetTable(string queue) { DataTable DT = new DataTable(); using (SqlDataAdapter adapt = new SqlDataAdapter(queue, con)) { adapt.SelectCommand.CommandTimeout = 90; adapt.Fill(DT); } return DT; } } }
bec37df4d6700df806619cf426fb304b260a5398
C#
PeteaNiprovo/Amdaris
/Functional Paradigm/Functional Paradigm/Program.cs
3.625
4
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Functional_Paradigm { class Collection : IEnumerator<int>, IEnumerable<int> { private int size = 1; private int lastIndex = -1; private int position = -1; private int[] array; public Collection(int s) { array = new int[size = s]; } public Collection() { array = new int[1]; } public int Current => array[position]; object IEnumerator.Current => throw new NotImplementedException(); public void Add(int data) { lastIndex++; if (lastIndex >= size) Array.Resize(ref array, ++size); array[lastIndex] = data; } public void Set(int index, int data) { if (index >= 0 && index < size) array[lastIndex = index] = data; } public int? Get(int index) { if (index >= 0 && index < size) return array[index]; return null; } public void Dispose() { position = -1; } public bool MoveNext() { position++; return (position < size); } public void Reset() { position = -1; } public IEnumerator<int> GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } static class Extensions { public static bool IsEven(this int data) { return (data % 2 == 0) ? true : false; } public static bool IsOdd(this int data) { return (data % 2 != 0) ? true : false; } public static bool IsPositive(this int data) { return (data > 0) ? true : false; } public static bool IsNegative(this int data) { return (data < 0) ? true : false; } } class DelegateExample { public delegate bool Filter(int value); public bool IsEven(int data) { if (data % 2 == 0) return true; return false; } public bool IsOdd(int data) { if (IsEven(data) == true) return false; return true; } public bool IsPositive(int data) { if (data > 0) return true; return false; } public bool IsNegative(int data) { if (data < 0) return true; return false; } public void Show(int data, Filter filter) { if (filter(data)) Console.WriteLine($"{data} is {filter.Method.Name}"); } public void All(Collection col) { foreach (var item in col) { Show(item, IsEven); Show(item, IsOdd); Show(item, IsPositive); Show(item, IsNegative); Filter del = delegate (int v) { if (v == 0) return true; else return false; }; } } } class AnonymousFunctionsExample { public delegate void Filter(int value); public void Show(Collection collection) { Filter filter = delegate (int data) { if (data % 2 == 0) { Console.WriteLine($"{data} Is Even"); } else { Console.WriteLine($"{data} Is Odd"); } }; filter += delegate (int data) { if (data > 0) { Console.WriteLine($"{data} Is positive"); } else { Console.WriteLine($"{data} Is negative or zero"); } }; foreach (var item in collection) { filter(item); } } } class LamdaExpressionsExample { public delegate void Filter(int data); public void Show(Collection collection) { Filter filter = a => { if (a > 0) Console.WriteLine($"{a} is positive"); else Console.WriteLine($"{a} is negative or zero "); } ; filter += a => { if(a % 2 == 0) Console.WriteLine($"{a} is even"); else Console.WriteLine($"{a} is odd");}; foreach (var item in collection) { filter(item); } } } class Program { static void Main(string[] args) { Collection col = new Collection { 10, 21, 30, -31, -51 }; //DelegateExample a = new DelegateExample(); //a.All(col); //AnonymousFunctionsExample anon = new AnonymousFunctionsExample(); //anon.Show(col); //LamdaExpressionsExample lambda = new LamdaExpressionsExample(); //lambda.Show(col); //Console.WriteLine(((int)(col.Get(0))).IsEven()); var list = col. Where(a => a < 0) .Select(a => a) .ToArray(); foreach (var item in list) { Console.WriteLine(item); } } } }
eafac4b36d18d0ca9272378298f7cfcd7d966ac0
C#
Skaarji/SoftUni
/C# Web Developer/C# Tech Module/6 Objects and Classes/VehicleCatalogue/Program.cs
3.671875
4
using System; using System.Linq; using System.Collections.Generic; namespace VehicleCatalogue { class Program { static void Main(string[] args) { List<string> command = Console.ReadLine().Split().ToList(); List<Cars> cars = new List<Cars>(); List<Trucks> trucks = new List<Trucks>(); while (command[0] != "End") { if (command[0] == "car") { Cars temp = new Cars(); temp.Model = command[1]; temp.Color = command[2]; temp.HP = int.Parse(command[3]); cars.Add(temp); } else if (command[0] == "truck") { Trucks temp = new Trucks(); temp.Model = command[1]; temp.Color = command[2]; temp.HP = int.Parse(command[3]); trucks.Add(temp); } command = Console.ReadLine().Split().ToList(); } string model = Console.ReadLine(); while (model != "Close the Catalogue") { if (cars.Select(x => x.Model).Contains(model)) { int indexOfCar = cars.FindIndex(x => x.Model == model); Console.WriteLine("Type: Car"); Console.WriteLine($"Model: {cars[indexOfCar].Model}"); Console.WriteLine($"Color: {cars[indexOfCar].Color}"); Console.WriteLine($"Horsepower: {cars[indexOfCar].HP}"); } else if (trucks.Select(x => x.Model).Contains(model)) { int indexOftruck = trucks.FindIndex(x => x.Model == model); Console.WriteLine("Type: Truck"); Console.WriteLine($"Model: {trucks[indexOftruck].Model}"); Console.WriteLine($"Color: {trucks[indexOftruck].Color}"); Console.WriteLine($"Horsepower: {trucks[indexOftruck].HP}"); } model = Console.ReadLine(); } double trucksAverage = 0; double carsAverage = 0; if (trucks.Count != 0) { trucksAverage = trucks.Average(x => x.HP); } if (cars.Count != 0) { carsAverage = cars.Average(x => x.HP); } Console.WriteLine($"Cars have average horsepower of: {carsAverage:f2}."); Console.WriteLine($"Trucks have average horsepower of: {trucksAverage:f2}."); } } class Cars { public string Model { get; set; } public string Color { get; set; } public int HP { get; set; } } class Trucks { public string Model { get; set; } public string Color { get; set; } public int HP { get; set; } } }
07fb1b850ba374b0a4cf6d647dec3b0b3207fa18
C#
MufassalAmeer/demoProject
/DemoDB/DemoDB/DAL/SystemDAL.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; namespace DemoDB.DAL { class SystemDAL { public Boolean executeNonQuerys(string quary) { Boolean flag = false; SqlConnection con = null; SqlCommand com = null; try { con = new SqlConnection(DBEstablish.makeConnection()); con.Open(); com = new SqlCommand(quary, con); com.ExecuteNonQuery(); flag = true; } catch (Exception ex) { Console.WriteLine("{0}" + ex.Message); flag = false; } finally { com.Dispose(); con.Close(); } return flag; } public SqlDataReader executeQuerys(string quary) { SqlConnection con = null; SqlCommand com = null; try { con = new SqlConnection(DBEstablish.makeConnection()); con.Open(); com = new SqlCommand(quary, con); return com.ExecuteReader(CommandBehavior.CloseConnection); } catch (SqlException ex) { if (com != null) { com.Dispose(); } if (con != null) { con.Close(); } Console.WriteLine(ex.Message); throw; } catch { if (com != null) { com.Dispose(); } if (con != null) { con.Close(); } throw; } finally { if (com != null) { com.Dispose(); } } } public Boolean IsServerConnected(string connectionString) { using (SqlConnection connection = new SqlConnection(DBEstablish.makeConnection())) { try { connection.Open(); return true; } catch (SqlException) { return false; } } } } }
526a5acf0c3bd7a73dead9aaba23c816d105866a
C#
Tankooni/OwlMan
/OwlMan/Scripts/Enemies/Enemy.cs
2.5625
3
using Godot; using Atmo2.Enemy.AI; using System.Collections.Generic; namespace Atmo2.Enemy { public abstract class Enemy : KinematicBody2D { // So this is maybe not the best design but it is by far the most convenient and not as hacky solution. This should eventually be replaced with some sort of AI player detection system. public static NodePath PlayerPath; [Export] public int Health = 1; public override void _Ready() { } public override void _PhysicsProcess(float delta) { } public void OnDamage(CollisionObject2D collider) { this.Health -= 1; if(this.Health <= 0) { this.QueueFree(); SetPhysicsProcess(false); } } } }
e987f226ff418b974c2533e4f5e967c53a66e34e
C#
communityus/procedural-planets-generator
/myengine/DataBinder.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using Neitri; namespace MyEngine { public class DataBinder { public string targetPropertyName; public object targetObject; public string sourcePropertyName; public object sourceObject; public IPropertyDescriptor targetProperty; public IPropertyDescriptor sourceProperty; public bool canUpdate; public void Start() { sourceProperty = PropertyDescriptorUtils.GetOne(sourceObject.GetType(), sourcePropertyName); targetProperty = PropertyDescriptorUtils.GetOne(targetObject.GetType(), targetPropertyName); canUpdate = sourceProperty != null && targetProperty != null && sourceProperty.Type == targetProperty.Type; } public void Update() { if (canUpdate) { targetProperty.Write(targetObject, sourceProperty.Read(sourceObject)); } } } }
f09e223bde76686beb655a82aa7d262d5e030e8e
C#
s13812/cw10
/cw10/Controllers/EnrollmentsController.cs
2.71875
3
using cw10.DTOs; using cw10.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; namespace cw10.Controllers { [Route("api/enrollments")] [ApiController] public class EnrollmentsController : ControllerBase { private readonly Cw10Context _dbContext; public EnrollmentsController(Cw10Context context) { _dbContext = context; } [HttpPost] public IActionResult EnrollStudent(EnrollStudentRequest request) { var study = _dbContext.Studies.FirstOrDefault(s => s.Name == request.Studies); if (study == null) { return NotFound("Nie ma takich studiow"); } var enrollment = _dbContext.Enrollments.FirstOrDefault(e => e.Semester == 1 && e.IdStudy == study.IdStudy); if (enrollment == null) { enrollment = new Enrollment { IdEnrollment = _dbContext.Enrollments.Max(e => e.IdEnrollment) + 1, Semester = 1, IdStudy = study.IdStudy, StartDate = DateTime.Now }; _dbContext.Enrollments.Add(enrollment); } if (_dbContext.Students.Any(s => s.IndexNumber == request.IndexNumber)) { return BadRequest("Index zajety"); } var student = new Student { IndexNumber = request.IndexNumber, FirstName = request.FirstName, LastName = request.LastName, BirthDate = request.BirthDate, IdEnrollment = enrollment.IdEnrollment }; _dbContext.Students.Add(student); _dbContext.SaveChanges(); return Ok(new { index = student.IndexNumber, study = study.Name, enrollment.IdEnrollment, enrollment.Semester, enrollment.StartDate }); } [HttpPost("promotions")] public IActionResult PromoteStudents(PromoteStudentsRequest request) { var enrollment = _dbContext.Enrollments.FirstOrDefault(e => e.Semester == request.Semester && e.IdStudy == _dbContext.Studies.FirstOrDefault(s => s.Name == request.Studies).IdStudy); if (enrollment == null) { return NotFound("Nie ma takiego wpisu"); } var newEnrollment = _dbContext.Enrollments.FirstOrDefault(e => e.IdStudy == enrollment.IdStudy && e.Semester == enrollment.Semester + 1); if (newEnrollment == null) { newEnrollment = new Enrollment { IdEnrollment = _dbContext.Enrollments.Max(e => e.IdEnrollment) + 1, Semester = enrollment.Semester + 1, IdStudy = enrollment.IdStudy, StartDate = DateTime.Now }; _dbContext.Enrollments.Add(newEnrollment); } foreach (var stu in _dbContext.Students.Where(s => s.IdEnrollment == enrollment.IdEnrollment)) { stu.IdEnrollment = newEnrollment.IdEnrollment; } _dbContext.SaveChanges(); return Ok(new { newEnrollment.IdEnrollment, request.Studies, newEnrollment.Semester, newEnrollment.StartDate }); } } }
5760f6244e41838e99106d299969e1750f0aed24
C#
ricklove/BushRun
/Assets/Code/Views/PlayerHeadView.cs
2.65625
3
using UnityEngine; using System.Collections.Generic; using System.Linq; public class PlayerHeadView { //public HeadType HeadType { get; set; } private HeadType _lastHeadType; private PlayerData _playerData = null; private Dictionary<HeadType, List<Sprite>> _heads = new Dictionary<HeadType, List<Sprite>>(); private SpriteRenderer _headRenderer; private float _nextChangeTime = 0; private int _iHead = 0; public void Initialize(GameObject head) { if (_headRenderer == null) { _headRenderer = head.GetComponentInChildren<SpriteRenderer>(); } } public void Update(IPlayerViewModel playerViewModel) { if (playerViewModel.PlayerData != _playerData) { _playerData = playerViewModel.PlayerData; _heads[HeadType.Idle] = _playerData.Sprites.Where(s => s.SpriteType == SpriteType.HeadIdle).Select(s => s.Sprite).ToList(); _heads[HeadType.Happy] = _playerData.Sprites.Where(s => s.SpriteType == SpriteType.HeadHappy).Select(s => s.Sprite).ToList(); _heads[HeadType.Hurt] = _playerData.Sprites.Where(s => s.SpriteType == SpriteType.HeadHurt).Select(s => s.Sprite).ToList(); } var headType = playerViewModel.PlayerState == PlayerState.Happy ? HeadType.Happy : playerViewModel.PlayerState == PlayerState.Hurt ? HeadType.Hurt : HeadType.Idle; if (Time.time > _nextChangeTime || headType != _lastHeadType) { _nextChangeTime = Random.Range(Time.time, Time.time + 10); _lastHeadType = headType; // Show heads var heads = _heads[headType]; if (heads == null || heads.Count <= 0) { heads = _heads[HeadType.Idle]; } if (heads == null) { return; } _iHead++; if (_iHead >= heads.Count) { _iHead = 0; } _headRenderer.sprite = heads[_iHead]; } } } public enum HeadType { Idle, Happy, Hurt }
0efabfefce0f41805f72b6950b019371df96c0cb
C#
zizhGuo/GSD2
/Bus.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElevationMaster { internal class Bus { static readonly DateTime globalStartTime; static Bus() { globalStartTime = DateTime.Now; Console.WriteLine("Static constructor sets global start time to {0}", globalStartTime.ToLongTimeString()); } int RouteNumber { get; set; } public Bus(int routeNumber) { RouteNumber = routeNumber; Console.WriteLine("Bus{0} is created.", RouteNumber); } public void Drive() { TimeSpan timeSpan = DateTime.Now - globalStartTime; Console.WriteLine("{0} is starting its route {1.N2} minutes after global start time {2}", this.RouteNumber, timeSpan, globalStartTime); } } }