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
16b5cf570f536a628270c4efa0521e9fe2cd26fa
C#
thuananh0611/project_1
/project_1/project_1/Entities/SP.cs
2.84375
3
using System; using System.Collections.Generic; using System.Text; namespace project_1.Entities { public class SP { //khai báo các thông tin liên quan đến dịch vụ #region Các thành phần dữ liệu private int manv; private int masp; private string tensp; private double gia; private string donvi; private string ngay; #endregion #region Các thuộc tính public int Manv { get { return manv; } set { if (value == 1) manv = value; } } public int Masp { get { return masp; } set { if (value >= 0) masp = value; } } public string Tensp { get { return tensp; } set { tensp = value; } } public double Gia { get { return gia; } set { if (value > 0) gia = value; } } public string Donvi { get { return donvi; } set { donvi = value; } } public string Ngay { get { return ngay; } set { ngay = value; } } #endregion #region Các phương thức public SP() { } //Phương thức thiết lập sap chép public SP(SP sp) { this.manv = sp.manv; this.masp = sp.masp; this.tensp = sp.tensp; this.gia = sp.gia; this.donvi = sp.donvi; this.ngay = sp.ngay; } public SP(int manv,int masp, string tensp, double gia, string donvi, string ngay) { this.manv = manv; this.masp = masp; this.tensp = tensp; this.gia = gia; this.donvi = donvi; this.ngay = ngay; } #endregion } }
6107b414d29363940280200400bd37fe91ec72f4
C#
JayedHoshen/c_sharp-practic
/second/multidimentionArray.cs
4.1875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace multidimentionalArray { class multiArray { static void Main(string[] args) { int i, j; // declaring multidimentional array string[,] Books = new string[3, 3]; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { Console.Write("Enter Book Name for {0} Row and {1} Column:\t", i+1, j+1); Books[i, j] = Console.ReadLine(); } } Console.WriteLine("\n\n===================================="); Console.WriteLine("All the element of books array is: \n\n"); // formatting output Console.Write("\t1\t2\t3\n\n"); // outer loop for accessing rows for (i = 0; i < 3; i++) { Console.Write("{0}.\t", i+1); // inner or nested loop for accessing column of each row for (j = 0; j < 3; j++) { Console.Write("{0}\t", Books[i, j]); } Console.Write("\n"); } Console.WriteLine("\n\n==============================="); Console.ReadLine(); } } }
79b1fcd68943bb9304ac588f12029e8d05f1863e
C#
ronaldoxgh/breakaleg
/Breakaleg.Core/Models/IfCode.cs
2.6875
3
using Breakaleg.Core.Dynamic; namespace Breakaleg.Core.Models { public class IfCode : CodePiece { public ExprPiece Condition; public CodeBlock Then; public CodeBlock Else; public override ExitResult Run(NameContext context) { if (Condition.EvalBool(context)) return Then != null ? Then.Run(context.NewChild()) : null; else return Else != null ? Else.Run(context.NewChild()) : null; } public override string ToString() { return string.Format("IF({0};{1};{2})", Condition, Then, Else); } } }
04db716d38756279ef9e9f0eca2e44bfa78b975e
C#
NataliiaOsintseva/Patterns
/ComputerFactory/Warehouse/ComputersWarehouse/AsusComputer.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ComputerFactory.Warehouse.ComponentsWarehouse; using ComputerFactory.Warehouse.ComponentsWarehouse.BIOS; using ComputerFactory.Warehouse.ComponentsWarehouse.CPU; using ComputerFactory.Warehouse.ComponentsWarehouse.Display; using ComputerFactory.Warehouse.ComponentsWarehouse.HDD; using ComputerFactory.Warehouse.ComponentsWarehouse.Manipulator; using ComputerFactory.Warehouse.ComponentsWarehouse.OS; using ComputerFactory.Warehouse.ComponentsWarehouse.RAM; namespace ComputerFactory.Warehouse.ComputersWarehouse { class AsusComputer : IComputer { public AbstractBios Bios { get; set; } public AbstractCPU Cpu { get; set; } public AbstractDisplay Display { get; set; } public AbstractHDD Hdd { get; set; } public AbstractManipulator Keyboard { get; set; } public AbstractManipulator Mouse { get; set; } public AbstractMotherBoard Motherboard { get; set; } public AbstractOS Os { get; set; } public AbstractRAM Ram { get; set; } public void Run() { Console.WriteLine("\nAsus is up and running! Let's do some fun, %username%!"); } } }
4454034bbee8c300c1d6789742a5adb50393d2b3
C#
vlad72-1/SIGame_megalab2020
/Rocket/Rocket.cs
2.75
3
using SIGameLibrary; using System; using System.Drawing; using System.Runtime.InteropServices; using System.Threading; namespace Rocket { [ProgId("SIGame.Component.Rocket"), Guid("792D8170-D68B-4CC0-8100-7CF280BC0789"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IRocket))] [ComVisible(true)] public class Rocket : IRocket // Ракета { private int _x; // X координата private int _y; // Y координата private bool _alive; // Жив ли поток private int _delay; // Задержка между движением ракеты private Thread _thread; // Поток private dynamic _dispatcher; // Диспетчер public Point Position { get => new Point(_x, _y); } // Позиция public dynamic Assign(params object[] parameters) // Инициализация объекта снаряда { if (parameters.Length != 4) throw new ArgumentException("Ivalid argument number!"); _dispatcher = (dynamic)parameters[0]; _x = (int)parameters[1]; _y = (int)parameters[2]; _delay = (int)(150 / (float)parameters[3]); return this; } private void ThreadLoop() // Цикл потока { while (_alive) { if (_y >= 0) _y--; else _dispatcher.DestroyRocket(this); Thread.Sleep(_delay); } } public void Launch() // Запуск ракеты { _alive = true; _thread = new Thread(ThreadLoop); _thread.Start(); } public void Destroy() // Уничтожить ракету { _alive = false; } public void Draw(DBCharScreen screen) // Нарисовать ракету { screen.Draw(_x, _y, "*", ConsoleColor.Green); } } }
b720c344bc2c9ff9c245ec70dc357cb45bb24454
C#
steamhunter/TotL
/PathFinder/fightHandler.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PathFinder.Character; namespace PathFinder { public class FightHandler { //public static CharacterEnemyBase[] enemylist = new CharacterEnemyBase[8]; public static List<CharacterEnemyBase> enemyList = new List<CharacterEnemyBase>(); static int usedSlots = 0; public static void addEnemy(CharacterEnemyBase enemy) { enemyList.Add( enemy); } public static void endFight() { for (int i = 0; i < usedSlots; i++) { enemyList[i].isdead = true; } enemyList = new List<CharacterEnemyBase>(); Vars.gamestate = gamestates.notinitialized; } public static int lenght() { return usedSlots; } } }
c41482e51ea7aadb72603096258a7275d4b95b58
C#
WizMe-M/Calculator
/MainWindow.xaml.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Calculator { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow : Window { string current = "0"; string sign = ""; string total = ""; public MainWindow() { InitializeComponent(); } private void ClickOperation(object sender, RoutedEventArgs e) { try { string chosenSign = (string)((Button)e.OriginalSource).Content; CheckExcessZeroOrDot(); if (sign.Equals("")) { total = current; sign = chosenSign; current = "0"; result.Content = total + sign; input.Content = current; } else { if (chosenSign.Equals("=")) { Equality(chosenSign); } else { DoOperation(); result.Content = current + chosenSign; input.Content = "0"; total = current; sign = chosenSign; current = "0"; } } } catch (Exception exc) { MessageBox.Show(exc.Message); } } private void Dot(object sender, RoutedEventArgs e) { try { if (!current.Contains(',')) current += ","; input.Content = current; } catch (Exception exc) { MessageBox.Show(exc.Message); } } private void ClickAddNumber(object sender, RoutedEventArgs e) { try { string s = (string)((Button)e.OriginalSource).Content; if (sign.Equals("=")) { current = "0"; result.Content = ""; total = ""; sign = ""; } if (current[0] == '0') { if (current.Length == 1) { current = s; } else current += s; } else current += s; input.Content = current; } catch (Exception exc) { MessageBox.Show(exc.Message); } } private void Neg(object sender, RoutedEventArgs e) { try { double num = double.Parse(current); current = (-num).ToString(); input.Content = current; } catch (Exception exc) { MessageBox.Show(exc.Message); } } void Equality(string chosenSign) { result.Content = total + sign + current + chosenSign; DoOperation(); input.Content = current; //current = "0"; sign = chosenSign; } void DoOperation() { try { double num1 = double.Parse(total); double num2 = double.Parse(current); // И выполняем операцию switch (sign) { case "+": current = (num1 + num2).ToString(); break; case "-": current = (num1 - num2).ToString(); break; case "*": //double x = Math.Round(num1 * num2, 5); current = (num1 * num2).ToString(); break; case "/": current = (num1 / num2).ToString(); break; } } catch (Exception exc) { current = ""; sign = ""; total = ""; result.Content = ""; input.Content = ""; MessageBox.Show(exc.Message); } } void CheckExcessZeroOrDot() { while (current[current.Length - 1] == '0' || current[current.Length - 1] == ',') if (current.Contains(',')) current = current.Substring(0, current.Length - 1); else break; } private void CE_Click(object sender, RoutedEventArgs e) { if (sign.Equals("=")) { total = ""; sign = ""; } current = "0"; input.Content = current; result.Content = total + sign; } private void C_Click(object sender, RoutedEventArgs e) { current = "0"; sign = ""; total = ""; result.Content = total + sign; input.Content = current; } private void DLT_CLick(object sender, RoutedEventArgs e) { if (sign.Equals("=")) { total = ""; sign = ""; result.Content = ""; current = "0"; } else { current = current.Substring(0, current.Length - 1); if (current.Equals("")) current = "0"; input.Content = current; } } private void Opposite(object sender, RoutedEventArgs e) { double num = double.Parse(current); num = 1 / num; current = num.ToString(); input.Content = current; } private void Square(object sender, RoutedEventArgs e) { double num = double.Parse(current); num = Math.Pow(num,2); current = num.ToString(); input.Content = current; } private void Sqrt(object sender, RoutedEventArgs e) { double num = double.Parse(current); num = Math.Sqrt(num); current = num.ToString(); input.Content = current; } private void GetPercent(object sender, RoutedEventArgs e) { double num = double.Parse(current); num /= 100; current = num.ToString(); input.Content = current; } } }
9625ec36238c6c247dff35c7eeb87c8e7dcf0a83
C#
mikkeldamm/boligf
/Boligf/Boligf.Api/Models/View/AssociationAddress.cs
2.59375
3
using Boligf.Api.Domain.Events; using System.Collections.Generic; namespace Boligf.Api.Models.View { public class AssociationAddress { public string Id { get; set; } public string StreetAddress { get; set; } public string No { get; set; } public string Floor { get; set; } public string Door { get; set; } public string Zip { get; set; } public string City { get; set; } public string Country { get; set; } public string FullAddress { get { return string.Format("{0} {1}, {2}. {3}", StreetAddress, No, Floor, Door); } } public List<Resident> Residents { get; set; } public AssociationAddress() { Residents = new List<Resident>(); } public void MapFromEvent(AddressAddedToAssociation domainEvent) { this.Id = domainEvent.Id; this.StreetAddress = domainEvent.StreetAddress; this.No = domainEvent.No; this.Floor = domainEvent.Floor; this.Door = domainEvent.Door; this.City = domainEvent.City; this.Zip = domainEvent.Zip; this.Country = domainEvent.Country; } } }
bc11166944f34ce67cde94807eb8619faf3b6c75
C#
kil98q/Zaaien-en-Oogsten
/Assets/_Scripts/SeasonClock.cs
2.640625
3
using UnityEngine; using System.Collections; public class SeasonClock : MonoBehaviour { private float _movePointer = (360f / 60f /1000f); [SerializeField] private Transform _pointer; [SerializeField] private float _speed =1f; private float lastTick = 0; private float totalms = 0; // Update is called once per frame void FixedUpdate () { System.DateTime _time = System.DateTime.Now; float currentTick = _time.Millisecond; //currentTick gaat per milli seconde if (currentTick < lastTick) //als currentTick kleiner is dan lastTick (0) { currentTick += 1000; //currentTick wordt verhoogd naar 1000 } float frame = currentTick - lastTick; //het verschil berekenen tussen current and last totalms += frame; //totalms = 0 elke keer optellen met frame (current - last) _pointer.localRotation = Quaternion.Euler(0f, 0f, -totalms * _movePointer * _speed); //de wijser 360 graden bewegen op de Z-axis lastTick = _time.Millisecond; } }
66c0b1a511013048aaf6e4d0bf04f3d7f22577d8
C#
kingex1124/Algorithm
/LeetCode/LeetCode/Tree/BinarySearchTree/Q257BinaryTreePaths.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCode.LeetCode.Tree { public class Q257BinaryTreePaths { public Q257BinaryTreePaths() { } /// <summary> /// 九章遞迴解法 /// List DFT /// </summary> /// <param name="root"></param> /// <returns></returns> public IList<string> BinaryTreePaths3(TreeNode root) { List<string> paths = new List<string>(); if (root == null) return paths; IList<string> leftPath = BinaryTreePaths3(root.left); IList<string> rightPath = BinaryTreePaths3(root.right); //由下往上塞路徑 foreach (var path in leftPath) paths.Add(root.val + "->" + path); foreach (var path in rightPath) paths.Add(root.val + "->" + path); if (paths.Count == 0) paths.Add("" + root.val); return paths; } /// <summary> /// 自己寫的 迭代解法 /// Queue /// BFT /// </summary> /// <param name="root"></param> /// <returns></returns> public IList<string> BinaryTreePaths2(TreeNode root) { List<string> result = new List<string>(); if (root == null) return result; Queue<TreeNode> queue = new Queue<TreeNode>(); Queue<string> depths = new Queue<string>(); queue.Enqueue(root); depths.Enqueue(root.val.ToString()); while (queue.Count != 0) { TreeNode node = queue.Dequeue(); string path = depths.Dequeue(); //在往下都是空的就表示走到最深了 if (node.left == null && node.right == null) result.Add(path); if (node.left != null) { queue.Enqueue(node.left); depths.Enqueue(path + "->" + node.left.val.ToString()); } if (node.right != null) { queue.Enqueue(node.right); depths.Enqueue(path + "->" + node.right.val.ToString()); } } return result; } /// <summary> /// 自己寫的遞迴寫法 /// </summary> /// <param name="root"></param> /// <returns></returns> public IList<string> BinaryTreePaths1(TreeNode root) { List<string> result = new List<string>(); if (root != null) helper(root, root.val.ToString(), result); return result; } public void helper(TreeNode node, string path, List<string> result) { if (node.left == null && node.right == null) result.Add(path); if (node.left != null) helper(node.left, path + "->" + node.left.val, result); if (node.right != null) helper(node.right, path + "->" + node.right.val, result); } /// <summary> /// 自己解的 跌代解法 /// Sack /// DFT /// </summary> /// <param name="root"></param> /// <returns></returns> public IList<string> BinaryTreePaths(TreeNode root) { List<string> result = new List<string>(); if (root == null) return result; Stack<TreeNode> stack = new Stack<TreeNode>(); Stack<string> depths = new Stack<string>(); stack.Push(root); depths.Push(root.val.ToString()); while (stack.Count != 0) { TreeNode node = stack.Pop(); string path = depths.Pop(); //在往下都是空的就表示走到最深了 if (node.left == null && node.right == null) result.Add(path); if (node.right != null) { stack.Push(node.right); depths.Push(path + "->" + node.right.val.ToString()); } if (node.left != null) { stack.Push(node.left); depths.Push(path + "->" + node.left.val.ToString()); } } return result; } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } } }
b3330c570e8ffa3384a0eaeb42dc9fa6580e321a
C#
stefanNaumov/CourierManager
/TeamAlexandrite/.svn/pristine/84/84ac76ebc4652050dd7ec6853abc3d16d49aae41.svn-base
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CourierManager { public class InvalidIDNumberException : ApplicationException { private readonly string iDNumber; public string IDNumber { get { return iDNumber; } } public InvalidIDNumberException(string msg, Exception innerEx, string iDNumber) : base(msg,innerEx) { this.iDNumber = iDNumber; } public InvalidIDNumberException(string msg, string iDNumber) : this(msg, null, iDNumber) { } } }
7e4825be62637c1d26da50cf6f13e065b8de585c
C#
MilPredo/BringMe
/Assets/Resources/Scripts/Powerup/Punch.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace RummageBattle { public class Punch : Powerup { [SerializeField] private float damage = 10; [SerializeField] private float duration = 1f; private float currentDuration = 0; //public IDamageable<float> target; private bool isTriggered = false; void Update() { if (target == null) return; if (!isTriggered) return; currentDuration += Time.deltaTime; if (currentDuration >= duration) { Debug.Log("Duration: " + currentDuration); isTriggered = false; currentDuration = 0; } } public override bool Trigger() { Debug.Log("Triggered"); if (!isTriggered) { target.ApplyDamage(damage); if (target.GetHealth() <= 0) { target = null; } } isTriggered = true; return true; } } }
750f7d07314a8f339d8d74e4a28f3dee8af61e92
C#
lemish/HackerRank
/HackerRank/StacksAndQueues/BalancedBrackets.cs
3.734375
4
using System.Collections.Generic; using System.Linq; namespace HackerRank.StacksAndQueues { /// <summary> /// Balanced Brackets /// <see href="https://www.hackerrank.com/challenges/balanced-brackets/"/> /// </summary> public class BalancedBrackets { public static string IsBalanced(string s) { if (string.IsNullOrEmpty(s)) { return "YES"; } var openBrackets = new HashSet<char> { '(', '[', '{' }; var closeToOpenBrackets = new Dictionary<char, char> { { ')', '(' }, { ']', '[' }, { '}', '{' } }; var stack = new Stack<char>(); for (var index = 0; index < s.Length; index++) { var bracket = s[index]; if (openBrackets.Contains(bracket)) { stack.Push(bracket); } else if (closeToOpenBrackets.ContainsKey(bracket)) { if (!stack.Any()) { stack.Push(bracket); break; } else if (stack.Peek() == closeToOpenBrackets[bracket]) { stack.Pop(); } else { break; } } } var isBalanced = stack.Count == 0; return isBalanced ? "YES" : "NO"; } } }
284b050e876da2dd9f48e51ebe5c6a7216a51c65
C#
sowrd299/GlowPillow
/Assets/Scripts/StatsReader.cs
3.375
3
using System.IO; using System.Collections.Generic; using UnityEngine; static class StatsReader { public static Dictionary<string,float[]> ReadStats(string url) { /*reads the given (csv) file formated: * * lineName,val0,val1,val2... * * and then returns the dictionary <lineNames,vals[]> */ var r = new Dictionary<string, float[]>(); string fileData = File.ReadAllText(url); foreach (string line in fileData.Split('\n')) { string[] lineData = line.Split(','); var vals = new List<float>(); for(int i = 1; i < lineData.Length; ++i) { vals.Add(float.Parse(lineData[i])); } Debug.Log("Adding " + lineData[0]); r.Add(lineData[0], vals.ToArray()); } return r; } }
3a03f1c6d577695859ed005069c673fcc3a13127
C#
FeedHedgehog/ModernUIApp1
/ModernUI.Common.Infrastructure/Configuration/IConfiguration.cs
2.515625
3
namespace ModernUI.Common.Infrastructure.Configuration { using System.Collections.Generic; /// <summary> /// 配置信息 /// </summary> public interface IConfiguration { /// <summary> /// 关联的文件路径 /// </summary> string FilePath { get; set; } /// <summary> /// 配置信息名称 /// </summary> string ConfigurationName { get; set; } /// <summary> /// 刷新配置信息,从文件中读取 /// </summary> void Refresh(); /// <summary> /// 持久化配置信息 /// </summary> void Persist(); /// <summary> /// 根据配置节点信息设置字段的值 /// </summary> /// <param name="configurationNode">配置节点的信息</param> void SetField(ConfigurationNode configurationNode); /// <summary> /// 获取所有配置节点信息 /// </summary> /// <returns>所有配置节点信息</returns> IEnumerable<ConfigurationNode> GetConfigurationNodes(); } }
48a9a882b1ef8189fc6a5ff50c7dd9b0ee4f6d4c
C#
IvanPudev/TelerikAcademy
/C#/OOP/OOPFundamentalPrinciplesPart1/Animals/TomCat.cs
2.828125
3
using System; using System.Linq; namespace Animals { class TomCat : Cat { public TomCat(string name, short age, Enum.Gender sex = Enum.Gender.Male) : base(name, age, sex) { } } }
68d1b3b28e99e6e9eae266e0ab16742eb90be747
C#
ooleoole/hyperway
/Mx.Tools/Objects.cs
2.9375
3
namespace Mx.Tools { public class Objects { public static int HashSet(object[] a) { if (a == null) return 0; int result = 1; foreach (object element in a) { result = 31 * result + (element?.GetHashCode() ?? 0); } return result; } public static int HashAll(params object[] a) { return Objects.HashSet(a); } } }
3d015f1271e3e70657f2408bf3f16a881c66d528
C#
carojaspaz/Solid
/Solid/D/ApiService.cs
2.5625
3
using System; namespace Solid.Principles.D { public class ApiService : IService { public void getData(string entity){ Console.WriteLine("Consultar Datos Api: {0}", entity); } } }
fe44b242e3ec8647bcea2a75808b895b3df1c1d7
C#
xjc90s/Bogus
/Source/Benchmark/PR300_BenchDecimal.cs
2.8125
3
using System; using System.Threading; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using Bogus; namespace Benchmark { [SimpleJob(RuntimeMoniker.NetCoreApp31), SimpleJob(RuntimeMoniker.Net471)] [MarkdownExporter, MemoryDiagnoser, RPlotExporter] public class PR300_BenchDecimal { private CustomRandomizer r; [GlobalSetup] public void Setup() { r = new CustomRandomizer(); } [Benchmark] public decimal OldMethod() { return r.Decimal(); } [Benchmark] public decimal JDGMethod() { return r.DecimalJDG(); } [Benchmark] public decimal JDGMethodNoAlloc() { return r.DecimalJDGNoAlloc(); } [Benchmark] public decimal JDGMethodNoAllocMult() { return r.DecimalJDGNoAllocMult(); } } public class CustomRandomizer : Randomizer { internal static Lazy<object> Locker = new Lazy<object>(() => new object(), LazyThreadSafetyMode.ExecutionAndPublication); private readonly Random localSeed = new Random(); public int NumberJDG(int min = 0, int max = 1) { //lock any seed access, for thread safety. lock (Locker.Value) { if (max < int.MaxValue) return localSeed.Next(min, max + 1); if (min > int.MinValue) return 1 + localSeed.Next(min - 1, max); int sample1 = localSeed.Next(); int sample2 = localSeed.Next(); int topHalf = (sample1 >> 8) & 0xFFFF; int bottomHalf = (sample2 >> 8) & 0xFFFF; return (topHalf << 16) | bottomHalf; } } public decimal DecimalJDG(decimal min = 0.0m, decimal max = 1.0m) { // Decimal: 128 bits wide // bit 0: sign bit // bit 1-10: not used // bit 11-15: scale (values 29, 30, 31 not used) // bit 16-31: not used // bit 32-127: mantissa (96 bits) // Max value: 00000000 FFFFFFFF FFFFFFFF FFFFFFFF // = 79228162514264337593543950335 // Max value with max scaling: 001C0000 FFFFFFFF FFFFFFFF FFFFFFFF // = 7.9228162514264337593543950335 // Step 1: Generate a value with uniform distribution between 0 and this value. // This ensures the greatest level of precision in the distribution of bits; // the resulting value, after it is adjusted into the caller's desired range, // should not skip any possible values at the least significant end of the // mantissa. int[] bits = new int[4]; bits[0] = NumberJDG(int.MinValue, int.MaxValue); bits[1] = NumberJDG(int.MinValue, int.MaxValue); bits[2] = NumberJDG(int.MinValue, int.MaxValue); bits[3] = 0x1C0000; decimal result = new decimal(bits); // Step 2: Scale the value and adjust it to the desired range. This may decrease // the accuracy by adjusting the scale as necessary, but we get the best possible // outcome by starting with the most precise scale. return result * (max - min) / 7.9228162514264337593543950335m + min; } public decimal DecimalJDGNoAlloc(decimal min = 0.0m, decimal max = 1.0m) { int lo = NumberJDG(int.MinValue, int.MaxValue); int mid = NumberJDG(int.MinValue, int.MaxValue); int hi = NumberJDG(int.MinValue, int.MaxValue); byte scale = 0x1C; decimal result = new decimal(lo, mid, hi, false, scale); return result * (max - min) / 7.9228162514264337593543950335m + min; } public decimal DecimalJDGNoAllocMult(decimal min = 0.0m, decimal max = 1.0m) { int lo = NumberJDG(int.MinValue, int.MaxValue); int mid = NumberJDG(int.MinValue, int.MaxValue); int hi = NumberJDG(int.MinValue, int.MaxValue); byte scale = 0x1C; decimal result = new decimal(lo, mid, hi, false, scale); return result * (max - min) * 0.1262177448353618888658765704m + min; } } }
9f23d4e1e915cae6d30a1dd9a40a72a1720fb73c
C#
PraveshGG/GetApiApp
/GetApiApp/MainPage.xaml.cs
2.90625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using System.Net.Http; using Newtonsoft.Json; using GetApiApp.Models; using SQLite; namespace GetApiApp { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(true)] public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private const string url = "https://jsonplaceholder.typicode.com/photos"; private HttpClient _Client = new HttpClient(); protected override async void OnAppearing() { //Sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation var content = await _Client.GetStringAsync(url); //Deserializes or converts JSON String into a collection of Post List<Photos> posts = JsonConvert.DeserializeObject<List<Photos>>(content); //Assigning the ObservableCollection to MyListView in the XAML of this file Post_List.ItemsSource = posts; base.OnAppearing(); } private void FavToolbarItem_Clicked(Object sender,EventArgs e) { Navigation.PushAsync(new SavedPosts()); } private void Posts_listView_ItemSelected(Object sender, SelectedItemChangedEventArgs e) { var PostSelected = e.SelectedItem as Photos; Photos post = new Photos() { albumId = PostSelected.albumId, id = PostSelected.id, title = PostSelected.title, url = PostSelected.url, thumbnailUrl = PostSelected.thumbnailUrl }; //if (e.SelectedItem != null) //{ // DisplayAlert("Tapped", PostSelected.title, "OK"); //} //! added using SQLite; using (SQLiteConnection conn = new SQLiteConnection(App.DatabasePath)) { conn.CreateTable<Photos>(); int itemsInserted = conn.Insert(post); if (itemsInserted > 0) DisplayAlert("Done", "Note saved", "Ok"); else DisplayAlert("Error", "Note not saved", "Ok"); } } } }
74e37e698accd659f9b92a03b0f28085399943df
C#
nebosite/talisman
/src/WindowsClient/Helpers/OutlookHelper.cs
2.546875
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Outlook; namespace Talisman { // -------------------------------------------------------------------------- /// <summary> /// Helper class for working with outlook /// </summary> // -------------------------------------------------------------------------- public class OutlookHelper { /// <summary> /// /// </summary> Application _outlookApplication; Application OutlookApp { get { if(_outlookApplication == null) { _outlookApplication = GetApplicationObject(); } return _outlookApplication; } } // -------------------------------------------------------------------------- /// <summary> /// /// </summary> // -------------------------------------------------------------------------- Application GetApplicationObject() { try { Application application = null; var processes = Process.GetProcessesByName("OUTLOOK"); var all = Process.GetProcesses(); // Check whether there is an Outlook process running. if (Process.GetProcessesByName("OUTLOOK").Count() > 0) { try { // If so, use the GetActiveObject method to obtain the process and cast it to an Application object. application = Marshal.GetActiveObject("Outlook.Application") as Application; return application; } catch (COMException e) { if ((uint)e.ErrorCode != 0x800401E3) { throw new ApplicationException("Error trying to access outlook: " + e.ErrorCode + " " + e.Message, e); } } } // If not, create a new instance of Outlook and log on to the default profile. application = new Application(); NameSpace nameSpace = application.GetNamespace("MAPI"); nameSpace.Logon("", "", Missing.Value, Missing.Value); nameSpace = null; // Return the Outlook Application object. return application; } catch (COMException e) { if ((uint)e.ErrorCode == 0x800401E3) { throw new ApplicationException("This user does not have rights to access the running outlook application. \r\n" + "Workarounds: Run under a different context (non-administrator)\r\n" + " Close Outlook (This will bring up a dialog box)\r\n" + " Turn off UAC."); } throw; } } // -------------------------------------------------------------------------- /// <summary> /// Send an email through outlook /// </summary> // -------------------------------------------------------------------------- public void SendMail(string toAddress, string subject, string body) { var newMail = (MailItem)OutlookApp.CreateItem(OlItemType.olMailItem); foreach (var recipient in toAddress.Split(new char[] { ';', ',' })) { newMail.Recipients.Add(recipient.Trim()); } newMail.Subject = subject; newMail.Body = body; Account acc = null; //Look for our account in the Outlook foreach (Account account in OutlookApp.Session.Accounts) { acc = account; break; } newMail.SendUsingAccount = acc; newMail.Send(); } int failureCount = 0; // -------------------------------------------------------------------------- /// <summary> /// Get items from outlook that are time sensitive in some lookahead window /// </summary> // -------------------------------------------------------------------------- public TimeRelatedItem[] GetNextTimerRelatedItems(double hoursAhead = 8) { try { var folders = OutlookApp.Session.Folders; List<TimeRelatedItem> returnItems = new List<TimeRelatedItem>(); var endDate = DateTime.Now.AddHours(8); GetTimeRelatedTimesFromFolder(OlDefaultFolders.olFolderCalendar, endDate, returnItems); GetTimeRelatedTimesFromFolder(OlDefaultFolders.olFolderTasks, endDate, returnItems); failureCount = 0; return returnItems.ToArray(); } catch(System.Exception) { _outlookApplication = null; // Forget the reference so that we will reconnect next time. failureCount++; if (failureCount > 2) throw; } return new TimeRelatedItem[0]; } // -------------------------------------------------------------------------- /// <summary> /// Process a folder for time related items /// </summary> // -------------------------------------------------------------------------- private void GetTimeRelatedTimesFromFolder(OlDefaultFolders defaultFolderId, DateTime endTime, List<TimeRelatedItem> returnItems) { var folder = (Folder)OutlookApp.Session.GetDefaultFolder(defaultFolderId); ProcessFolder(folder, endTime, returnItems); } // -------------------------------------------------------------------------- /// <summary> /// Process a folder for time related items /// </summary> // -------------------------------------------------------------------------- private void ProcessFolder(Folder folder, DateTime endTime, List<TimeRelatedItem> returnItems) { DateTime now = DateTime.Now; // Initial restriction is Jet query for date range string timeSlotFilter = "[Start] >= '" + now.ToString("g") + "' AND [Start] <= '" + endTime.ToString("g") + "'"; var items = folder.Items; items.Sort("[Start]"); items.IncludeRecurrences = true; items = items.Restrict(timeSlotFilter); foreach (object item in items) { var appointment = item as AppointmentItem; var task = item as TaskItem; if (appointment != null) { var newItem = new TimeRelatedItem(); var locationText = string.IsNullOrWhiteSpace(appointment.Location) ? "" : $" in {appointment.Location}"; newItem.Title = appointment.Subject; newItem.Start = appointment.Start; newItem.End = appointment.End; newItem.Location = appointment.Location; newItem.Contents = appointment.Body; var recurrencePattern = appointment.GetRecurrencePattern(); if (appointment.RecurrenceState == OlRecurrenceState.olApptOccurrence && recurrencePattern.RecurrenceType == OlRecurrenceType.olRecursWeekly) { // TODO: Think about weekly recurrence? } else { // TODO: No weekly recurring? } returnItems.Add(newItem); } else if (task != null) { var newItem = new TimeRelatedItem(); newItem.Title = task.Subject; newItem.Start = task.ReminderTime; // TODO: incorperate outlook tasks } else { // TODO: What about these things that are not tasks? } } foreach (Folder subFolder in folder.Folders) { ProcessFolder(subFolder, endTime, returnItems); } } } }
e241e59995390ba12c8ceba754dd8c50c331a1d1
C#
RocketBoy86/LowPolyBowling
/Assets/Scripts/BallStartPosController.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using System.Timers; using UnityEngine; public class BallStartPosController : MonoBehaviour { public Transform ballStartPosTransform; public Rigidbody ballStartPosRigidbody; private Vector3 movePos; private Quaternion startAngle; // Start is called before the first frame update void Start() { movePos.y = ballStartPosTransform.position.y; movePos.z = ballStartPosTransform.position.z; startAngle = ballStartPosTransform.rotation; } // Update is called once per frame void Update() { // want transform to move from -3 to +10 across the X axis until user presses B key if (ballStartPosTransform.position.x >= 10) { movePos.x = ballStartPosTransform.position.x - 0.01f; ballStartPosTransform.SetPositionAndRotation(movePos, startAngle); } else if (ballStartPosTransform.position.x <= -3) { movePos.x = ballStartPosTransform.position.x + 0.01f; ballStartPosTransform.SetPositionAndRotation(movePos, startAngle); } } }
e61d358e97a64cc82f39ca55490af0ef55b7901d
C#
petercoker/coding-with-mosh
/mosh-csharp-basic/mosh-csharp-basic/working_with_text/exercise with working with text/exercise 3.cs
3.765625
4
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace mosh_csharp_basic.working_with_text.exercise_with_working_with_text { public class exercise_3 { public void Ex3() { //3 - Write a program and ask the user to enter a time value in the 24 - hour time format(e.g. 19:00). // A valid time should be between 00:00 and 23:59. // If the time is valid, display "Ok"; otherwise, display "Invalid Time". // If the user doesn't provide any values, consider it as invalid time. Console.Write("Enter a time in 24 hour time format e.g 19:00: "); string input = Console.ReadLine(); if (String.IsNullOrWhiteSpace(input)) { Console.WriteLine("Invalide Time"); return; } string[] timeValues = input.Split(':'); if (timeValues.Length != 2) { Console.WriteLine("Invalid Time"); return; } try { int hour = Convert.ToInt32(timeValues[0]); int minute = Convert.ToInt32(timeValues[1]); if (hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59) { Console.WriteLine("Ok"); } else { Console.WriteLine("Invalid Time"); } } catch (Exception) { Console.WriteLine("Invalid Time"); } //***Mosh answer*** //Console.Write("Enter time: "); //string input = Console.ReadLine(); //if (String.IsNullOrWhiteSpace(input)) //{ // Console.WriteLine("Invalid Time"); // return; //} //string[] components = input.Split(':'); //if (components.Length != 2) //{ // Console.WriteLine("Invalid Time"); // return; //} //try //{ // int hour = Convert.ToInt32(components[0]); // int minute = Convert.ToInt32(components[1]); // if (hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59) // Console.WriteLine("Ok"); // else // Console.WriteLine("Invalid Time"); //} //catch (Exception) //{ // Console.WriteLine("Invalid Time"); //} } } }
bca729dc9c14efa1424cce04eee66804e7cf821a
C#
jeowf/pong-multiplayer-unity
/Pong/Assets/Scenes/Paddle.cs
2.65625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum PlayerType { PLAYER_1, PLAYER_2 } public class Paddle : MonoBehaviour { public PlayerType player; public float limit = 3.7f; public float speed = 1f; private float _inputY = 0f; void Start() { } // Update is called once per frame void Update() { ReadInput(); Vector3 dir = Vector3.up * _inputY * speed * Time.deltaTime; if ((transform.position + dir).y < limit && (transform.position + dir).y > -limit) { transform.position = transform.position + dir; } } private void ReadInput() { if (player == PlayerType.PLAYER_1) { if (Input.GetKey(KeyCode.W)) _inputY = 1.0f; else if (Input.GetKey(KeyCode.S)) _inputY = -1.0f; else _inputY = 0.0f; } else { if (Input.GetKey(KeyCode.UpArrow)) _inputY = 1.0f; else if (Input.GetKey(KeyCode.DownArrow)) _inputY = -1.0f; else _inputY = 0.0f; } } private void OnTriggerEnter2D(Collider2D collision) { Ball ball = collision.transform.GetComponent<Ball>(); if (ball != null) { ball.AlterDirection(collision.transform.position - transform.position); ball.IncrementVelocity(); } } }
7c87ab636e7e41e1700d5e688919f92fb07febfe
C#
Hasidi/Anticipatory_Troubleshooting
/AnticipatoryTroubleShooting/SurvivalFunctions/EllipseCurve.cs
3.359375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnticipatoryTroubleShooting.SurvivalFunctions { class EllipseCurve : SurvivalFunction { double _a; public EllipseCurve(double aFactor) { _a = aFactor; } public override double survive(double age) { if (age > _a) throw new InvalidOperationException(); double ans = Math.Sqrt((_a + age) * (_a - age)) / _a; return ans; } public override void setParameter(double param) { _a = param; } public override string ToString() { return "{ a: " + _a + "}"; } } }
624698f5fec77bf96e294af84bfca7712f4ac6f7
C#
cjpleasant88/MSSA
/EX_2C_Recursive_Methods/Ex 2C Recursive.cs
3.828125
4
using System; namespace EX_2C_Recursive_Methods { class Program { static void Main(string[] args) { Console.WriteLine("\n\tHomeWorkProgram.EX_2C_Recursive_Methods.Program.cs"); WhichPart(); } //Determines which Part of the homework to run between the averages and the Fibanacci series public static void WhichPart() { Console.WriteLine("\nPress any button to continue...."); Console.ReadKey(); Console.Clear(); Console.WriteLine("********************************************************************************"); Console.WriteLine("\n----> Hit 'CTRL + C' at any time to exit this Program <----"); Console.WriteLine("\n\nAlso, please don't enter characters unless asked, not quite sure how to catch those yet..."); Console.WriteLine("\n\tWhich Part of the Homework would you like to run?"); Console.WriteLine("Push '1' for the Averaging of Test Scores (Parts 1-3)"); Console.WriteLine("Push '2' to Find phi using the Fibanacci Series (Part 4)"); Console.Write("\nYour Choice: "); int difficultyLevel = int.Parse(Console.ReadLine()); if (difficultyLevel == 1 || difficultyLevel == 2) { switch (difficultyLevel) { case 1: AskDifficulty(); break; case 2: FibanacciSeries(); break; } } //This is for if any other number than 1-2 is entered else { Console.WriteLine("That is not an option!?"); WhichPart(); } } //Determines which difficulty Level to determine Average and call that method public static void AskDifficulty() { Console.WriteLine("\n\tWhich difficulty of Averaging do you want to use? (1-3)"); Console.WriteLine("(1) Basic Difficulty (Part 1)"); Console.WriteLine("(2) Intermediate Difficulty (Part 2)"); Console.WriteLine("(3) Advanced Difficulty (Part 3)"); Console.Write("\nYour Choice: "); int difficultyLevel = int.Parse(Console.ReadLine()); if (difficultyLevel == 1 || difficultyLevel == 2 || difficultyLevel == 3) { switch (difficultyLevel) { case 1: BasicAverage(); break; case 2: IntermediateAverage(); break; case 3: AdvancedAverage(); break; } } //This is for if any other number than 1-3 is entered else { Console.WriteLine("That is not an option!?"); AskDifficulty(); } } //Baisc Difficulty - Average of exactly 10 test Scores public static void BasicAverage() { Console.WriteLine("--------------------------------------------------------\n"); Console.WriteLine("PART 1"); Console.WriteLine("Please Enter 10 Test scores between 0 and 100, Hit enter between each test!"); double sum = 0; double average = 0; for (int i = 0; i < 10; i++) { Console.Write($"What is Test Score {i + 1}: "); sum += GetEntry(); } average = sum / 10; GiveGrade(average); } //Intermediate Difficulty - Average of user defined number of tests public static void IntermediateAverage() { Console.WriteLine("--------------------------------------------------------\n"); Console.WriteLine("PART 2"); Console.Write("How many Tests do you want to enter: "); int numOfTests = Convert.ToInt32(Console.ReadLine()); Console.WriteLine($"Please Enter your {numOfTests} Test scores between 0 and 100, Hit enter between each test!\n"); double sum = 0; double average = 0; for (int i = 0; i < numOfTests; i++) { Console.Write($"What is Test Score {i + 1}: "); sum += GetEntry(); } average = sum / numOfTests; GiveGrade(average); } //Advanced Difficulty - Gives average of the number of tests entered until -1 is seen public static void AdvancedAverage() { Console.WriteLine("--------------------------------------------------------\n"); Console.WriteLine("PART 3"); Console.WriteLine("Give me your all your tests scores, I can help you out with the average."); int numOfTests = 0; Console.WriteLine($"Please Enter your Test scores between 0 and 100, Hit enter between each test!\n"); Console.WriteLine("When you are done, Enter a '-1' as a Test Score!\n"); double sum = 0; double average = 0; bool enterAnotherTest = true; double testScore = 0; for (int i = 0; enterAnotherTest; i++) { if (enterAnotherTest == true) { Console.Write($"What is Test Score {i + 1}: "); testScore = GetEntry(); if (testScore == -1) { enterAnotherTest = false; } else { sum += testScore; numOfTests++; } } } Console.WriteLine($"\n\tYou gave me {numOfTests} Tests to Average!"); average = sum / numOfTests; GiveGrade(average); } //Determines if user entered a Valid Test Score public static double GetEntry() { bool isValid = false; double userEntry = 0; char toStop = 'N'; while (!isValid) { userEntry = double.Parse(Console.ReadLine()); //If it is Valid, returns the user Score if (userEntry >= 0 && userEntry <= 100) { isValid = true; } //If it is not Valid tells the user else { Console.Write($"\n***ERROR***: {userEntry} is not valid,\n\n what is that test score again: "); //Asks the user if they want to stop adding scores if they want to continue entering more if (userEntry == -1) { Console.Write("\n....Wait, are you done entering Tests? [Y / N]: "); if (char.Parse(Console.ReadLine()) == 'Y') { return userEntry; } else { Console.Write("Oh ok, what is that test score again: "); } } } } return userEntry; } //Once the average is computed, this method converts to a Letter grade public static void GiveGrade(double average) { Console.WriteLine("--------------------------------------------------------\n"); Console.WriteLine($"Your Test Average is :{average}"); if (average > 89.49) { Console.WriteLine("You have an A in the class so far, WOW!"); } else if (average > 79.49) { Console.WriteLine("You have a B in the class so far, great job!"); } else if (average > 69.49) { Console.WriteLine("You have a C in the class so far, keep it up!"); } else if (average > 59.49) { Console.WriteLine("You have a D in the class so far, study much?"); } else { Console.WriteLine("You have an F, change your ways!"); } Console.WriteLine("\n--------------------------------------------------------"); //returns to pick another part of the homework WhichPart(); } //The initialization of the Fibanacci Program public static void FibanacciSeries() { int i = 1; long oldNum = 1; long currentNum = 1; long sum = oldNum + currentNum; double phi = 0; Console.WriteLine("\nWe are going to use the Fibanacci Series to estimate the value of Phi."); Console.Write("\n\nHow many numbers of the Fibancci Series do you want to compute: "); int seriesNumber = GetSeriesNumber(); Console.WriteLine("\nPART 4"); (i, oldNum, currentNum) = MoreMathStuff(i, seriesNumber, oldNum, currentNum, sum); Console.WriteLine($"{i}. phi is {(double)currentNum/(double)oldNum}"); WhichPart(); } //Retrieves and validates a number from the user public static int GetSeriesNumber() { bool isValid = false; int userEntry = 0; while (!isValid) { userEntry = int.Parse(Console.ReadLine()); if (userEntry >= 0 && userEntry <= 100) { isValid = true; } else { Console.WriteLine($"\n***ERROR***: {userEntry} is not valid,\n\n please keep it between 0 and 100!"); Console.Write("How many numbers do you want to compute again: "); } } return userEntry; } //The computations for the Fibanacci Portion public static (int, long, long) MoreMathStuff(int i, int seriesNumber, long oldNum, long currentNum, long sum) { if (seriesNumber > 1) { Console.WriteLine($"{i}. {oldNum} + {currentNum} = {sum}"); seriesNumber--; oldNum = currentNum; currentNum = sum; sum = oldNum + currentNum; //Console.WriteLine($"{i}. {oldNum} + {currentNum} = {sum}"); i++; return (MoreMathStuff(i, seriesNumber, oldNum, currentNum, sum)); } return (i, oldNum, currentNum); } } }
74828f2d52eea032f546803a8e43822e25204266
C#
hughfernandez/MVVMHello
/MVVMHello/ViewModels/MainWindowViewModel.cs
2.84375
3
using MVVMHello.DAL; using MVVMHello.Models; using System.Collections.Generic; using System.Windows.Input; namespace MVVMHello.ViewModels { public class MainWindowViewModel : ViewModelBase { #region Properties private List<Customer> customers; public List<Customer> Customers { get { return customers; } set { if (customers == value) { return; } customers = value; OnPropertyChanged("Customers"); } } #endregion #region Commands private ICommand customerCommand; public ICommand CustomerCommand { get { if (customerCommand == null) { customerCommand = new RelayCommand(param => this.CustomerCommandExecute(), null); } return customerCommand; } } #endregion public MainWindowViewModel() { } private void CustomerCommandExecute() { var customerService = new CustomerService(); var result = customerService.GetCustomer(); Customers = new List<Customer>(result); } } }
602a5f5d05cdc516b6bdb514d29e53024f608a68
C#
bmjoy/Immortal
/Assets/ootii/Framework_v1/Code/Collections/DictionaryExt.cs
3.625
4
using System; using System.Collections.Generic; namespace com.ootii.Collections { /// <summary> /// Extension for the standard dictionary that allows us to add functions /// </summary> public static class DictionaryExt { /// <summary> /// Search the dictionary based on value and return the key /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="rDictionary">Object the extension is tied to</param> /// <param name="rValue">Value that we are searching for</param> /// <returns>Returns the first key associated with the value</returns> public static TKey FindKeyByValue<TKey, TValue>(this Dictionary<TKey, TValue> rDictionary, TValue rValue) { // Ensure we have a valid option if (rDictionary == null) { throw new ArgumentNullException("rDictionary"); } // Search for the value and return the associated key foreach (KeyValuePair<TKey, TValue> lPair in rDictionary) { if (rValue.Equals(lPair.Value)) { return lPair.Key; } } // If not found, report it throw new KeyNotFoundException("Value not found"); } } }
e3b9d0c98df8c045d800189f014b3805fffc5e4c
C#
tipson007/project002
/GoogleMini/GoogleMinusMinus/GoogleMinusMinus/HTMLProcessing/HTMLProcessor.cs
2.875
3
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using HtmlAgilityPack; namespace GoogleMini.HTMLProcessing { public class HTMLProcessor { private string pageUri; private Lazy<Task<HtmlDocument>> document; public HTMLProcessor(string pageUri = "") { this.pageUri = pageUri; document = new Lazy<Task<HtmlDocument>>(async () => { using (var httpClient = new HttpClient()) { var content = await httpClient.GetStringAsync(pageUri); var doc = new HtmlDocument(); doc.LoadHtml(content); return doc; } }, false); } public void LoadFromFile(string filePath) { document = new Lazy<Task<HtmlDocument>>(() => { var doc = new HtmlDocument(); doc.Load(filePath); return Task.FromResult(doc); }, false); } public async Task<string> GetTitleTag() { var titleNode = (await document.Value).DocumentNode.Descendants("title").FirstOrDefault(); return titleNode?.OuterHtml; } public async Task<IEnumerable<string>> GetAnchorTags() { return (await document.Value).DocumentNode.Descendants("a").Select(n => n.OuterHtml); } public async Task<IEnumerable<string>> GetScriptTags() { return (await document.Value).DocumentNode.Descendants("script").Select(n => n.OuterHtml); } } }
81fd0afd05df8d94bc344458c460d93f2d4899a7
C#
arguzmx/pika-gd
/Infraestructura/PIKA.Infraestructura.Comun/Seguridad/MascaraPermisos.cs
2.53125
3
using System; using System.Collections.Generic; using System.Text; using System.Text.Json.Serialization; using System.Xml.Serialization; namespace PIKA.Infraestructura.Comun.Seguridad { public class MascaraPermisos { public const int PDenegarAcceso = 1; public const int PLeer = 2; public const int PEscribir = 4; public const int PEliminar = 8; public const int PAdministrar = 16; public const int PEjecutar = 32; public MascaraPermisos() { Leer = false; Escribir = false; Eliminar = false; Admin = false; Ejecutar = false; NegarAcceso = false; } public bool Leer { get; set; } public bool NegarAcceso { get; set; } public bool Escribir { get; set; } public bool Eliminar { get; set; } public bool Admin { get; set; } public bool Ejecutar { get; set; } /// <summary> /// Devuelve la lsita de permisos apra un módulo o aplicación administrable /// </summary> /// <returns></returns> public static int PermisosAdministrables(){ return PLeer + PEscribir + PEliminar + PAdministrar + PEjecutar; } public int Mascara { get { return ObtenerMascara(); } } public void EstablacerMascara(int Mask) { NegarAcceso = (Mask & PDenegarAcceso) > 0 ? true : false; Leer = (Mask & PLeer) > 0 ? true : false; Escribir = (Mask & PEscribir) > 0 ? true : false; Eliminar = (Mask & PEliminar) > 0 ? true : false; Admin = (Mask & PAdministrar) > 0 ? true : false; Ejecutar = (Mask & PEjecutar) > 0 ? true : false; } public int ObtenerMascara() { int mask = 0; mask = NegarAcceso ? mask + PDenegarAcceso : mask; mask = Leer ? mask + PLeer : mask; mask = Escribir ? mask + PEscribir : mask; mask = Eliminar ? mask + PEliminar : mask; mask = Admin ? mask + PAdministrar : mask; mask = Ejecutar ? mask + PEjecutar : mask; return mask; } } }
54714f92e422d87841110620c507eb2b9c12d4d6
C#
ninjacoder88/software-fundamentals
/06-Graphs/01-Graphs/WeightedGraph/Program.cs
3.015625
3
using System; namespace WeightedGraph { public class Program { public static void Main(string[] args) { Vertex a = new Vertex() { Name = "A" }; Vertex b = new Vertex() { Name = "B" }; Vertex c = new Vertex() { Name = "C" }; Vertex d = new Vertex() { Name = "D" }; Vertex e = new Vertex() { Name = "E" }; Graph g = new Graph(); g.AddEdge(a, b, 1); g.AddEdge(b, c, 1); g.AddEdge(b, d, 2); g.AddEdge(d, e, 1); g.AddEdge(c, e, 1); g.FindPathDFS(a, e); } } }
e1d6aca45803e59c210d6f75bc2e9c01654c923f
C#
SeNeReKo/LibNLPCommon_CSharp
/simpletokenizing/TokenPatternBuilder.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LibNLPCSharp.util; namespace LibNLPCSharp.simpletokenizing { public partial class TokenPatternBuilder { //////////////////////////////////////////////////////////////// // Constants //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // Variables //////////////////////////////////////////////////////////////// private static Tokenizer tokenizer = new Tokenizer(false, Tokenizer.EnumSpaceProcessing.RemoveDuplicateSpaces, true, ""); private static readonly TokenPattern PATTERN_EXCLAMATIONMARK = TokenPattern.MatchDelimiter('!'); private static readonly LinearPatternSequence PATTERN_KVP = new LinearPatternSequence( TokenPattern.MatchAnyWord(true), TokenPattern.MatchDelimiter(':', false), TokenPattern.MatchAnyWord(true) ); private static Dictionary<string, TokenPattern> singleTokenCache = new Dictionary<string, TokenPattern>(); //////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////// private TokenPatternBuilder() { } //////////////////////////////////////////////////////////////// // Properties //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // Methods //////////////////////////////////////////////////////////////// public static LinearPatternSequenceCollection Parse(params string[] text) { return Parse(true, text); } public static LinearPatternSequenceCollection Parse(bool bCaseSensitive, params string[] text) { LinearPatternSequenceCollection c = new LinearPatternSequenceCollection(); foreach (string s in text) { LinearPatternSequence lpc = Parse(bCaseSensitive, s); if (lpc != null) c.Add(lpc); } c.Sort(); return c; } public static LinearPatternSequenceCollection Parse(IEnumerable<string> text) { return Parse(true, text); } public static LinearPatternSequenceCollection Parse(bool bCaseSensitive, IEnumerable<string> text) { LinearPatternSequenceCollection c = new LinearPatternSequenceCollection(); foreach (string s in text) { LinearPatternSequence lpc = Parse(bCaseSensitive, s); if (lpc != null) c.Add(lpc); } c.Sort(); return c; } /// <summary> /// Parse a text that contains information about a single token. /// </summary> /// <param name="text"></param> /// <param name="bAllowCaching">If <code>true</code> the token pattern once parsed will be returned from /// a cache. This implies that you do not modify that token pattern after it has been returned by this method. /// If <code>false</code> is specified parsing occurs every time and always a new token pattern object is /// returned.</param> /// <returns></returns> public static TokenPattern ParseSingle(string text, bool bAllowCaching, bool bCaseSensitive) { if (bAllowCaching) { TokenPattern tp; if (singleTokenCache.TryGetValue(text, out tp)) return tp; tp = __ParseSingle(text, bCaseSensitive); singleTokenCache.Add(text, tp); return tp; } else { return __ParseSingle(text, bCaseSensitive); } } private static TokenPattern __ParseSingle(string text, bool bCaseSensitive) { TokenStream ts = new TokenStream(tokenizer.Tokenize(text)); while (ts.Peek().IsSpace) ts.Read(); TokenPattern tp = EatTokenPattern(ts, text, bCaseSensitive); if (!ts.IsEOS) { // try to parse content relevancy information if (ts.TryEat(PATTERN_EXCLAMATIONMARK) != null) { tp.IsContent = true; } else { throw new Exception("Syntax error at character position: " + ts.CharacterPosition + " (" + ts.Peek().ToString() + ") [\"" + text + "\"]"); } } if (!ts.IsEOS) { // try to parse key value pair TokenPatternResult extra; if ((extra = PATTERN_KVP.TryEat(ts)) != null) { tp.Tags = new SKVPSet(true, new SKVP(extra.ContentTokens[0].Text, extra.ContentTokens[1].Text)); } else { throw new Exception("Syntax error at character position: " + ts.CharacterPosition + " (" + ts.Peek().ToString() + ") [\"" + text + "\"]"); } } while (ts.Peek().IsSpace) ts.Read(); if (!ts.IsEOS) throw new Exception("Syntax error at character position: " + ts.CharacterPosition + " (" + ts.Peek().ToString() + ") [\"" + text + "\"]"); return tp; } public static LinearPatternSequence Parse(string text) { return Parse(true, text); } public static LinearPatternSequence Parse(bool bCaseSensitive, string text) { TokenStream tokenStream = new TokenStream(tokenizer.Tokenize(text)); List<TokenPattern> parsedPatterns = new List<TokenPattern>(); foreach (TokenStream ts in tokenStream.SplitAtSpaces()) { TokenPattern tp = EatTokenPattern(ts, text, bCaseSensitive); if (!ts.IsEOS) { // try to parse content relevancy information if (ts.TryEat(PATTERN_EXCLAMATIONMARK) != null) { tp.IsContent = true; } else { throw new Exception("Syntax error at character position: " + ts.CharacterPosition + " (" + ts.Peek().ToString() + ") [\"" + text + "\"]"); } } if (!ts.IsEOS) { // try to parse key value pair TokenPatternResult extra; if ((extra = PATTERN_KVP.TryEat(ts)) != null) { tp.Tags = new SKVPSet(true, new SKVP(extra.ContentTokens[0].Text, extra.ContentTokens[1].Text)); } else { throw new Exception("Syntax error at character position: " + ts.CharacterPosition + " (" + ts.Peek().ToString() + ") [\"" + text + "\"]"); } } if (!ts.IsEOS) throw new Exception("Syntax error at character position: " + ts.CharacterPosition + " (" + ts.Peek().ToString() + ") [\"" + text + "\"]"); parsedPatterns.Add(tp); } if (parsedPatterns.Count == 0) return null; return new LinearPatternSequence(parsedPatterns); } private static TokenPattern EatTokenPattern(TokenStream ts, string text, bool bCaseSensitive) { TokenPattern tp = __EatTokenPattern0(ts, text); if (!bCaseSensitive) tp = tp.ToCaseInsensitive(); return tp; } private static TokenPattern __EatTokenPattern0(TokenStream ts, string text) { TokenPattern tp; if ((tp = __TryEatSpace(ts)) != null) return tp; if ((tp = __TryEatString(ts)) != null) return tp; if ((tp = __TryEatWord(ts)) != null) return tp; if ((tp = __TryEatDelimiter(ts, text)) != null) return tp; throw new Exception("Syntax error at character position: " + ts.CharacterPosition + " (" + ts.Peek().ToString() + ") [\"" + text + "\"]"); } private static bool __ToIsContent(Token token, string text) { if (token.Text.Equals(".")) return false; if (token.Text.Equals("!")) return true; throw new Exception("Syntax error at character position: " + token.CharacterPosition + " (" + token.ToString() + ") [\"" + text + "\"]"); } private static char __ToDelimChar(Token token, string text) { if (token.Text.Length != 1) { throw new Exception("Syntax error at character position: " + token.CharacterPosition + " (" + token.ToString() + ") [\"" + text + "\"]"); } return token.Text[0]; } } }
cc68a9f593266016ea0bac9c92f5957963008290
C#
krassy11/TheGaragePayment
/source/TheGaragePayment/WebApiTest/Controllers/ValuesController.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Web.Http; namespace WebApiTest.Controllers { [AllowAnonymous] public class ValuesController : ApiController { // GET api/values public Animal Get() { var newAdimal = new Animal() { Name = "Jivotnoto" }; string name = "pesho"; //return new string[] { "value1", "value2" }; return newAdimal; } // GET api/values/5 public string Get(int id) { return "value"; } //// POST api/values //public void Post([FromBody]Animal Name) //{ //} public string Post([FromBody]Animal Name) { //var newAdimal = new Animal() { Name = "Jivotnoto" }; string response = "Demo"; return response; } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } } }
14cc1cc45580886f41fbac932ffa3793c905a2a6
C#
georgidelchev/CSharp-Programming-Advanced
/02 - [CSharp OOP]/16 - [Unit Testing - Lab]/AxeTests.cs
2.796875
3
using System; using NUnit.Framework; [TestFixture] public class AxeTests { private const int AXE_STARTING_ATTACK = 100; private const int UNBROKEN_AXE_STARTING_DURABILITY = 200; private const int BROKEN_AXE_STARTING_DURABILITY = 0; private const int DUMMY_STARTING_HEALTH = 100; private const int DUMMY_STARTING_EXP = 200; private const int DURABILITY_AFTER_WEAPON_ATTACK = 199; private const string WEAPON_FAIL_ATTACK_MESSAGE = "Weapon doen not lose any durability."; private const string ATTACK_WITH_BROKEN_WEAPON_MESSAGE = "You can not attack with broken weapon."; private Axe unbrokenAxe; private Axe brokenAxe; private Dummy dummy; [SetUp] public void SetUpWeapon() { this.unbrokenAxe = new Axe(AXE_STARTING_ATTACK, UNBROKEN_AXE_STARTING_DURABILITY); this.brokenAxe = new Axe(AXE_STARTING_ATTACK, BROKEN_AXE_STARTING_DURABILITY); } [SetUp] public void SetUpDummy() { this.dummy = new Dummy(DUMMY_STARTING_HEALTH, DUMMY_STARTING_EXP); } [Test] public void Weapon_Losing_Durability_After_Each_Attack() { // Act this.unbrokenAxe.Attack(this.dummy); // Assert Assert.That(this.unbrokenAxe.DurabilityPoints, Is.EqualTo(DURABILITY_AFTER_WEAPON_ATTACK), WEAPON_FAIL_ATTACK_MESSAGE); } [Test] public void Attacking_With_A_Broken_Weapon() { // Assert Assert.Throws<InvalidOperationException> (() => this.brokenAxe.Attack(this.dummy), // Act ATTACK_WITH_BROKEN_WEAPON_MESSAGE); } }
860014cbf379c72ba037f94e20b5d76bdec4358f
C#
technomoney/BVT2-rev2017_3
/Assets/_Heathen Engineering/SystemsCore/Framework/Scriptable/DoubleReference.cs
3.015625
3
using System; namespace HeathenEngineering.Scriptable { [Serializable] public class DoubleReference : VariableReference<double> { public double ConstantValue; public DoubleVariable Variable; public DoubleReference(double value) { Mode = VariableReferenceType.Constant; ConstantValue = value; } public override double Value { get { return Mode != VariableReferenceType.Referenced || Variable == null ? ConstantValue : Variable.Value; } set { if (Mode != VariableReferenceType.Static) { if (Mode == VariableReferenceType.Referenced && Variable != null) Variable.SetValue(value); else ConstantValue = value; } } } public static implicit operator double(DoubleReference reference) { return reference.Value; } } }
a2f8acdbcbc3983448691d0651ba3996ab47acbd
C#
protodroid-IB/TheEdgeLord
/Assets/Scripts/LightBeamController.cs
2.75
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LightBeamController : MonoBehaviour { public float maxDistance = 10; public float beamWidth = 0.5f; public Color initialColor; private enum ColorState { Red, Orange, Blue, Green, Yellow, Purple }; [SerializeField] private ColorState startingColor = ColorState.Red; [SerializeField] private Material[] beamMatArray; //This prefab object should have the "LightBeam" tag, a renderer, a trigger collider and kinematic rigidbody public GameObject lightBeamPrefab; //Current number of rays private int rayNumbers = 0; //Max rays allowed private int maxRays = 5; //Raycast offset in order to avoid multiple collisions with same surface private float rayOffset = 0.02f; private List<Beam> rays = new List<Beam>(); private GameObject[] beamObjects; public struct Beam { //This abstract structure holds all positional and rendereing data for each beam segment public Beam(Vector3 startPoint, Vector3 endPoint, Color beamColor, Collider collider = null) { start = startPoint; end = endPoint; color = beamColor; collisionObject = collider; } public Vector3 start; public Vector3 end; public Collider collisionObject; public Color color; } // Use this for initialization void Start () { //Pre-load a series of beam segments to avoid instantiating multiple times at run-time beamObjects = new GameObject[maxRays]; for (int i = 0; i < maxRays; i++) { GameObject beamClone = Instantiate(lightBeamPrefab); beamClone.transform.parent = transform; beamClone.name = "LightBeam " + (i+1); beamObjects[i] = beamClone; beamClone.SetActive(false); } } void Update () { //As we wish to recalculate all beams each frame, begin by clearing and de-activating all related variables foreach(GameObject beam in beamObjects) { beam.SetActive(false); } rayNumbers = 0; rays.Clear(); //Call function to draw the first beam segment DrawNewRay(); } void DrawNewRay() { //Determine where this ray should start and how it should be colored based on whether it is the first ray Vector3 rayStart = (rays.Count > 0 ? rays[rayNumbers-1].end : transform.position) + transform.forward*0.1f; Color rayColor = (rays.Count > 0 && rays[rayNumbers-1].collisionObject.GetComponent<Renderer>()) ? rays[rayNumbers-1].collisionObject.GetComponent<Renderer>().material.color : initialColor; bool drawNewRay = false; bool raycastHit = false; //Perform raycast and detect whether it has hit anything, and whether that thing was a LightBeam Ray ray = new Ray(rayStart, transform.forward); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(ray,out hit,maxDistance)) { raycastHit = true; if(hit.collider.gameObject.tag == "LightBeam") { drawNewRay = true; } } //Determine where the ray ends based on it's collision Vector3 rayEnd = raycastHit ? hit.point : (rayStart + transform.forward * maxDistance); //Debug.DrawLine(ray.origin, rayEnd, rayColor); //Populate all related information into a Beam structure and save it to a list rays.Add(new Beam(ray.origin ,rayEnd, rayColor, hit.collider)); //Call function to position the beamObject prefab that corresponds to this ray PositionRayObject(); rayNumbers++; //If this ray hit a LightBeam and we havent reached the max amount of rays, run this function again for the next ray if(drawNewRay && rayNumbers < maxRays) DrawNewRay(); } void PositionRayObject(){ //Activate the beam object correspoinding to the current ray, and determine its correct position, color and scale beamObjects[rayNumbers].SetActive(true); CheckColorState(); beamObjects[rayNumbers].GetComponent<Renderer>().material.color = rays[rayNumbers].color; beamObjects[rayNumbers].transform.LookAt(rays[rayNumbers].end); beamObjects[rayNumbers].transform.position = FindMidPoint(rays[rayNumbers].start,rays[rayNumbers].end); beamObjects[rayNumbers].transform.localScale = new Vector3 (beamWidth, beamWidth, (rays[rayNumbers].start - rays[rayNumbers].end).magnitude); } private Vector3 FindMidPoint(Vector3 vector1, Vector3 vector2){ //Middlepoint formula - defines the mid point between two 3d positions return new Vector3 ((vector1.x + vector2.x)/2,(vector1.y + vector2.y)/2,(vector1.z + vector2.z)/2); } void CheckColorState() { switch(startingColor) { case ColorState.Red: beamObjects[rayNumbers].GetComponent<Renderer>().material = beamMatArray[0]; break; case ColorState.Orange: beamObjects[rayNumbers].GetComponent<Renderer>().material = beamMatArray[1]; break; case ColorState.Blue: beamObjects[rayNumbers].GetComponent<Renderer>().material = beamMatArray[2]; break; case ColorState.Green: beamObjects[rayNumbers].GetComponent<Renderer>().material = beamMatArray[3]; break; case ColorState.Yellow: beamObjects[rayNumbers].GetComponent<Renderer>().material = beamMatArray[4]; break; case ColorState.Purple: beamObjects[rayNumbers].GetComponent<Renderer>().material = beamMatArray[5]; break; default: beamObjects[rayNumbers].GetComponent<Renderer>().material = beamMatArray[0]; break; } } }
aa0e1de104fb9cfe48aca1b20d930974af02db89
C#
TraceLD/BetterSsmp
/Ssmp/Extensions/NetworkStreamExtensions.cs
2.953125
3
using System.Net.Sockets; using System.Threading.Tasks; using System; using System.IO; namespace Ssmp.Extensions { public static class NetworkStreamExtensions { public static async Task<int> ReadBufferLength(this NetworkStream ns, byte[] buffer) { var index = 0; while (index < buffer.Length) { int bytes; try { bytes = await ns.ReadAsync(buffer.AsMemory(index, buffer.Length - index)); } catch (Exception e) { if (e is IOException or ObjectDisposedException) { break; } throw; } if (bytes <= 0) { break; } index += bytes; } return index; } } }
1514086923c9be672567209169348b368c1ae21d
C#
jb1361/Class-files-repo
/C311 Programming languages/Hw8/HW6/divideException.cs
2.5625
3
using System; using System.Collections.Generic; using System.Text; public class divideException : Exception { string field; public divideException() { field = "Cannot Divide By 0"; } public string toString() { return field; } }
728051819e26c340c3651e6708907dc525eb5518
C#
aimeesophia/advent-of-code-2020
/Day02/Program.cs
3.09375
3
using System; using System.Collections.Generic; using Day02.Enums; namespace Day02 { class Program { static void Main() { var passwordDatabaseList = GetPasswordDatabaseList(); var numberOfValidMinMaxAmountOfRequiredCharacterPasswords = PasswordValidator.Validate(ValidationType.MinMaxAmountOfRequiredCharacter, passwordDatabaseList); var numberOfValidPositionOfRequiredCharacterPasswords = PasswordValidator.Validate(ValidationType.PositionOfRequiredCharacter, passwordDatabaseList); Console.WriteLine("The number of valid passwords using the min/max amount of required character validation type is: {0}", numberOfValidMinMaxAmountOfRequiredCharacterPasswords); Console.WriteLine("The number of valid passwords using the position of required character validation type is: {0}", numberOfValidPositionOfRequiredCharacterPasswords); } private static List<string> GetPasswordDatabaseList() { return new List<string> { "1-8 n: dpwpmhknmnlglhjtrbpx", "11-12 n: frpknnndpntnncnnnnn", "4-8 t: tmttdtnttkr", "12-18 v: vvvvvvvqvvvvvqvvgf", "3-4 c: cccc", "17-18 z: zzzzzzzzdzzzzzzgzr", "5-6 l: llltzl", "4-5 g: fzfng", "3-6 b: bjsbbxbb", "4-5 b: dbbbl", "1-4 t: tttcrt", "8-11 t: tttwtttwttn", "16-17 m: mmmmmmmmmmmmmmmbp", "8-11 f: fffffffqfmzfff", "10-12 n: nnnnnnnnnncvnnnf", "5-15 b: ztmcfqsrbvbbbqbxw", "12-13 m: mmmmmmrwmnmmr", "5-6 d: sddddznddddkzdbpdv", "14-15 l: lsllllskllllllllll", "3-4 z: zvrz", "2-8 h: fthhhqhghhtf", "2-4 x: xhtxsp", "6-10 q: qqlxqcvqwqqx", "1-3 q: qqqqqqqqqqqq", "6-15 l: qlllllllllllllghl", "1-13 k: tkkkkkkkkkkklkk", "8-12 k: kqkcqknklfkkvqp", "15-16 f: hnjnmgfxdfrffdfff", "3-11 k: ckkknpdlkkfkk", "1-4 z: vzzz", "4-7 c: gxgfcrcv", "12-14 x: xxfxxxqxxxxxxq", "4-19 g: gggwggggggggggggggxg", "5-8 c: cdcqnmccxh", "7-8 x: xxxxxxxcx", "2-5 f: fmffjfff", "2-3 w: wwbw", "10-16 g: spbndcgjvnwbgcrvtg", "4-5 t: ttttttt", "6-10 d: dpdddddddl", "1-4 s: ssszsss", "8-12 f: ffffffffffffhfwffc", "1-2 f: gmff", "4-5 s: sssswss", "12-17 v: vvvvjvvvfvvvvvvvvvv", "3-5 n: tlndn", "14-19 n: nnnnjjnnnnnnnwwlnnsn", "17-18 d: dddcdddsdddddddddddd", "5-17 x: zgsxphpttbdhqhxmxwms", "1-3 f: ffffff", "2-3 f: ffgf", "8-11 r: dvrjxddrrgdrckrrxmp", "9-12 n: nnrvnnnnxnhnnnnnnn", "7-11 p: kxpsfsppppkplqxpmpfb", "7-9 j: rjjjjjkjjjnj", "3-4 g: lwng", "9-10 h: lhzwfzlnhh", "5-6 s: wlbdsfs", "13-15 x: xgxqzxtpxgxqxjx", "1-3 q: xqqq", "15-17 d: ddfddtdddddhdfddddd", "10-12 r: sgxrtkmwzrnrrgmscc", "2-5 g: mggjg", "7-9 t: trltttttt", "7-13 b: bbbbbbqbbbbbgb", "4-16 l: lllllllllllgllxjcll", "14-15 v: vxvvvvtvvnvvwgv", "8-9 m: xjmjklmfdnw", "7-12 k: xhklkjhhwfrdkrlkkx", "2-3 l: mlxfls", "9-10 k: vhlgnkppkx", "10-11 t: ttttktttttpt", "1-3 q: qpkwvqb", "6-7 k: kkvwjbkb", "3-5 j: qpnmjjndh", "8-12 z: zznzgzttvzzzzzg", "8-11 n: wznmgnfnnfp", "9-12 v: vvvvvvvvvvvvv", "5-9 h: hhhhzhhhhhh", "1-6 q: qsqqqdqqqqqqqq", "2-5 c: cclfc", "1-5 z: vwpzzzfzzzz", "5-7 c: gcqcfcgzzcp", "9-10 g: ggggggggszggggg", "5-15 q: flqhqdqhqkqwcqqq", "2-4 l: llpd", "13-15 h: qbnzqnnfhchstbp", "3-5 t: ttdttt", "2-3 c: cccc", "6-8 v: vvvvvdcvmv", "6-7 n: bnnnnnn", "10-16 t: tvztwtrbtttttqtt", "2-5 m: zsvmmbbshz", "3-13 f: xkfqfqrsmbjhj", "3-5 c: cccjzjt", "13-14 w: wwwwwwwwwwwwww", "11-12 c: vcclpbccpqjgc", "3-11 p: hqrlgpffspphvthb", "3-12 z: zzjzzzzzzzzpz", "3-10 s: ddqhwpqbxs", "3-8 d: dddddddd", "4-10 j: ktgsjzkqpjcjwcs", "18-19 t: ttttdtttttttttttttf", "6-11 s: jndthsskqbg", "2-7 w: gpfhzwm", "12-15 k: kkkkdkkkkkkckks", "3-5 w: wdwnxw", "2-4 w: wwtw", "11-12 v: vvvvvvvvvvcfvv", "12-15 h: wxlhgdxhhgttxhhnrgh", "8-9 v: bptwkqvjxjdbhnzmbx", "6-10 m: wrmmnqgmch", "6-8 p: pppxcxprbcpppp", "6-7 r: rrrrrkmrrrr", "11-15 g: tpgkggggggvggfgtb", "5-6 m: mmmmmmm", "8-14 f: fkvwkmrfftmjczhf", "12-13 q: rqqqqqqqqqqhqqqq", "12-14 f: fffffffffffnffff", "9-10 d: crsbdsddwdpddcpddd", "1-4 b: gbjbx", "2-3 n: nnnnnsnn", "3-14 t: chtkhtdlddrztt", "9-10 d: ldzdsdvxfmp", "5-6 j: hrwjjj", "1-4 l: lpllllblzll", "10-12 l: glhnxlpdnlvq", "5-6 q: jqzfqqt", "3-11 z: npvzgdvpmnz", "6-7 g: fgggrgg", "4-10 f: xrtfnrcbgbkdf", "1-14 f: ftvftwfxwmfmbftsd", "3-6 s: scjsfcs", "3-6 v: hvvvxvnvvvgtvgv", "8-10 z: zzzzzzzzzszhfzzz", "1-14 z: szzzwdzwzzqzzzz", "8-14 f: wffhsjdfrslfpfnq", "4-5 k: kckkkkkx", "7-12 d: dddkkdkwddvhs", "6-7 c: ckpmczj", "1-15 h: hhjjhjhhhbhbhcckxh", "2-4 n: xjhn", "7-10 t: ttttttwttttttttttltt", "1-5 v: vkbdvvgv", "1-4 z: zzzlzzzzzzzzzzzz", "3-5 f: fffffnc", "1-2 c: pcfgl", "8-12 m: mmmmmmmmrmmmm", "10-14 l: lllllllllfvllblldlll", "4-11 s: fwrbwnpttjpmnmsfnhs", "9-11 m: zmmrrxcmsmmmqmgmmmmm", "2-7 s: sqslsssj", "18-19 p: ppppppppppmppdppwpz", "6-8 k: qmfwhkkkd", "7-8 v: vvvlsvhzgv", "8-14 g: ggggggggggggggggg", "3-4 r: rrrnr", "7-8 m: kghmmmjm", "3-5 g: ggtnbzggbxklprk", "11-13 q: bqqqqqqqqqqfhqr", "3-4 z: zzzz", "17-18 b: bbbbbbbbbbbbbbbbsrb", "2-4 f: wpff", "5-6 z: zvrlwf", "7-10 p: pppbdqwgwptpppp", "2-12 v: vzvvvvvvvvvmv", "3-11 f: fffqffffffcfff", "7-10 v: vbsvvkgcwjxvdkvvv", "18-19 l: lwmlllllllllvllfllll", "13-17 s: gwssszsshssssstxs", "2-3 k: kkdk", "5-11 k: kkkkkkkkkkkkkkk", "1-6 l: gllllll", "1-5 c: jccccccccc", "1-6 v: vdjvld", "7-8 n: kjnknwnngnv", "16-18 w: wwwwwwwwwwwkwtwwws", "5-8 b: qbfjbcdg", "13-14 d: ddddddddfdkdkddjd", "7-8 w: nwwwcwwwkfwwjwwl", "13-15 q: qqqqqqqqgqqqgqq", "11-12 c: cmccjcqccknzcrcc", "4-6 x: wvlnxbb", "5-7 j: fmjffjj", "3-5 q: xrqqnrhqjst", "12-19 n: nnnqnnqnmbvnjnnqnnn", "13-19 s: sqssvscdhssslsshwstt", "15-17 k: kkkkkkkkkkhkkkcktkkj", "3-5 s: cpsbs", "10-12 b: bbbgbxhwsvbc", "1-9 v: vjvdvdvlvkx", "13-15 z: zzzzczzzzzzzgczzz", "17-18 r: rrrrrrrrrrrrrrrrrr", "3-8 z: tbmczfgz", "9-11 h: dthhhhhhhhvhhhnhhh", "11-13 l: qfzlnljldmllf", "1-3 s: sscs", "5-17 q: qfvrqphfjffckgmpj", "2-6 f: rjfjvfgpf", "5-6 h: hhghkh", "12-17 s: ssssssssssssssssssrs", "12-13 g: gggggggggggbl", "12-13 m: mmmmmmmmmmmtcmmmm", "16-17 x: rzcfxbdxxdstzdxmp", "7-9 b: smbzgbbwzbzbb", "11-13 f: ffskffvfgfflf", "1-2 r: pmrwrmrbrrr", "3-4 n: nnngnnnn", "8-10 w: wcwwrptwwlcq", "4-7 n: nnnpndn", "1-4 l: lllpll", "7-13 q: fqqfdqqqqxrlkq", "6-7 f: fnrftkfffdf", "8-10 s: cwtgnssstsmq", "2-9 d: ddjkgsxkdsddgf", "10-11 l: lwpjlpkzqlllltrln", "4-20 n: sndnlnnnjpnncsjnrnnn", "1-16 l: rltllllllllllllnllbl", "15-19 w: gwtskpwwmnwnvmwrzmz", "4-9 s: mxsssztlsslsmnbvwjdr", "9-11 c: cccccdhcjckcccc", "3-7 s: szsrrqjl", "1-3 n: nnnnn", "3-4 x: zcbj", "16-18 s: sdsssssssssslsstsss", "9-20 w: cnprwwnfdjlwqwswqwwz", "16-17 v: vvvvvsvvvvvvvvvcvv", "4-7 g: gxzgngg", "5-6 s: sssssrs", "11-13 q: qqqqqqqqqqjzq", "8-10 x: xxxxxxxvxx", "12-13 b: sbbbbbbbbbbbbbb", "4-6 f: ffffff", "7-8 d: ddtddddd", "1-6 z: vzzzzzz", "16-18 s: ssssssssssssssvssb", "6-15 s: xbqsssxwsscsfbl", "12-17 z: zzzzzzzzzzznzzzzvz", "4-10 d: xwcdtdbpmtt", "3-8 v: vjvjnxbw", "4-11 q: fdflhjpvqmq", "10-12 s: rqvjgslssssf", "3-4 m: mmmmm", "6-10 x: xxxxxxxxxxxx", "4-5 g: ggggg", "8-10 q: cwgbqqsxqgfqqz", "9-19 l: lhzllnmlcgrbzrmzwln", "5-14 x: xqqzxxnxxswwvxxxz", "4-11 x: xxxlxxxxxxxx", "13-17 d: ndrzwljrbcptswkfd", "5-15 l: lnllhlllllllclpllll", "1-2 s: cdsv", "3-4 j: fpqj", "4-7 r: rrrtrrxtr", "9-11 h: hthhhhhhvkbhr", "8-14 l: rllllllsllnlll", "2-3 t: tvtt", "8-18 h: hhhnhvhwhhhhphhhhwhl", "1-3 d: ddmdd", "14-18 q: nhqkrqdflknwbqvgph", "3-4 z: zkzx", "1-4 z: zfwgzzgrzcs", "2-4 k: lkpxr", "3-4 h: hhhhh", "7-16 t: ltjttttftttttttdct", "7-8 z: zlsxvwzxs", "1-2 t: twtt", "10-16 q: qqqqqqqqztqqqqwqqqqq", "4-6 r: hgtrvrrfdwrgqw", "3-6 z: bwzlzzzz", "7-8 z: zzhzzcczqzzz", "5-7 h: fjfhhphdc", "13-16 p: tpnzmdbvwwpstpxprm", "1-10 q: qqqdqqvqqfqqqqq", "11-15 z: zzzmhtzzszbkzlz", "2-4 x: hjhxkpmjwjkrsjdklzfc", "1-2 m: kmgjnkwvfqxtmqc", "9-10 j: kjlpjjjjxj", "6-7 x: wxcxpxrxxx", "17-18 k: kkkkkkkkkkkkkkkkkkk", "5-7 d: pdddddd", "2-4 p: pspp", "2-11 n: nbnznnnnnnxnn", "4-6 c: cxccdccgnf", "13-14 c: cccccccccgdccccpf", "1-3 q: qqrhsdcqqfbr", "4-6 l: rqbrnjgmttlvbxjlrrh", "15-18 k: kkkfkgkkkkkkkkckkz", "13-15 r: rrrrrrrrrrrrrrrr", "10-11 b: bbnbcrblhpb", "2-7 z: znlzklzc", "5-11 f: bfzcdfxmljrmnw", "1-4 k: kkkkkckckkkk", "3-4 w: wzww", "2-4 l: vlllll", "14-15 w: rzvrjrqgkcxhwwp", "6-7 k: kkkkkldm", "5-7 l: hbhllbn", "8-11 x: xxxxxxxmxxxx", "1-12 d: jddvddvddddqdddd", "1-17 n: jnndrnnnsqnnwnnnmnnn", "11-14 n: kgzqtdnqbbvmqj", "2-3 d: hvkd", "11-15 k: kkkdkkkkkkkkkwwk", "4-5 v: vvvvk", "2-3 x: bgbh", "3-6 q: vqvmnp", "1-4 n: nnnn", "6-10 x: xxxxxxxxxhxlsxxx", "1-16 x: xxdxxxxxxxxxxxxb", "4-7 j: jnwdsjzr", "5-6 g: bglmhg", "2-4 p: pppp", "7-17 h: hhhhhhfhhhhhhhhhfhh", "8-16 h: hhxthhhhchqqhhhhh", "3-6 k: kkkkkpkkkkrkk", "3-4 z: gqzs", "10-12 f: fffffffffzfsfffffff", "9-11 f: fcgpwqfxnvf", "8-10 j: jxjjjjjjjrjjnjbjzjj", "6-7 h: bkttbhkzcmmnqs", "1-13 w: kwwwwwwwwwwwnww", "2-8 p: pspqpppzpjhp", "1-13 n: nnnznnlnnnnfvnnnnnnn", "2-3 n: nnqpnn", "5-6 n: nmbdnn", "13-15 d: jrdsdkddjvddsdsrh", "6-9 n: ntnwnnknnncnnnnl", "2-6 z: zzzzzznvz", "9-13 c: ccccccccqcccw", "5-7 x: qxxfxhmt", "8-10 z: zzzzzzzltz", "12-14 k: kkkkkkkkktkjknkkgd", "6-9 z: jxjszgwzx", "5-16 c: cccgscjpcccccccxd", "6-7 g: lggjvgjghbtgggg", "8-14 r: vtpbpwrcdqlrrfrrrrrs", "6-14 w: twcwwnwwwqxwrwwmwf", "3-6 s: mssbzssstgtmlw", "1-12 m: mmwmmmmmmmmmmmmr", "5-11 l: lclgllllclll", "7-9 j: jjjjjjjjjj", "2-14 n: wntdjqhtcqvnknjlfq", "3-5 v: vvvvvn", "7-8 p: hjcphnpm", "2-7 w: wwwwwwswwwww", "13-14 q: qqqqqqqqqqqqqqqq", "4-5 d: kddmxcqqgzpddwddd", "1-7 b: bfrhwgjtbchbzpcqmt", "3-4 k: nkkk", "6-7 q: qqsqqwqqq", "1-10 g: gggggggggwgggg", "1-4 k: kkkkkk", "2-8 m: mtmmmmmnmmm", "1-5 d: ldddd", "5-8 s: szsssbqqsssssfsscsps", "5-10 m: rljqkbcmbmxqsnbmzp", "1-4 w: wfwwcrwnxxwwwdwh", "9-12 v: wvqwvbvpsvvlvvvvvv", "3-4 l: lljx", "7-8 r: fzxvcbrmh", "3-4 z: bvng", "4-8 r: cskrnqrrjkvdtfv", "13-14 q: qlqqxqqqqhqqqqqqm", "14-20 n: zknbnnbnnznkhcnpnnzn", "6-8 m: mmmmsmmn", "8-15 x: xhxcxxxxfxhxwxt", "11-12 b: wfmnwdltwjcb", "3-13 t: rgjpbdbmdjhmx", "1-2 x: hgrhrwxzwzdx", "1-3 v: pvxvvdrvvv", "3-13 q: qjqmvqkcbbqhqfqqq", "4-8 h: vvzmthcpwrlnwhst", "2-10 b: bphlmgjftzrwm", "1-9 h: fhhhhhhhl", "14-15 c: wrtccjwcccwvhcv", "2-3 f: nftrf", "1-8 l: ljcklkbllsb", "1-7 w: zwwwbwwwwww", "10-11 m: hkmfghpvhzm", "8-19 r: szrrwmrrrbrrrrtrrhxl", "3-4 j: jprp", "4-10 h: hmbhqncmxft", "8-12 d: dddddddtddddd", "9-10 l: llllllllll", "7-10 x: xxxnkxxxxxxxnxxxf", "10-13 b: nbzzkzwjxbbwbgtsk", "11-16 l: llllldllllllllwllll", "4-5 d: ljzdlxwxmzxldwfwmqd", "1-13 d: dgfddmwsghdsdnddd", "15-16 j: bnfcxqjjjsdpznjprbjj", "2-11 w: wlwwwwwwwwwwwwwwwww", "5-8 z: zzlkzfzt", "5-7 x: nqpjxxs", "5-9 j: jgjjbjjjm", "2-5 h: jvbhf", "11-14 b: kqxfgwbbpnrjrjb", "6-7 h: zjhhnhrr", "2-7 c: crjcccgcc", "4-5 z: gzczx", "4-6 k: kkkrkkkxrtk", "9-10 j: jjjjjjjjmj", "8-12 b: bzdmbbbbbbcbdbmbdbh", "2-6 t: wtjtptrptstx", "1-11 w: wlmqwzkzmtwkd", "11-12 h: khrbhmxhkbbh", "10-18 x: sbttcdvmcxjxnjfjrkn", "11-12 w: wwwsnwwwwcwz", "5-18 g: zmgggvgmtrghhfwgbgjz", "12-16 d: clxdsflvkpcsdmtqdwbd", "15-17 p: ppppppppppspppxpzpp", "4-5 k: kgrfk", "2-4 l: lhfl", "10-15 x: wdlvcxwtpjfflvzl", "3-4 m: jwmmcjdxhkgbmtblmgfr", "18-19 d: dqdjdqhddtdffddkmgd", "5-9 h: hfngbhhchhkhkqmqgf", "17-20 m: kmfmzrmmnmclsmthmfmt", "7-12 p: ppppppppppphp", "19-20 h: hhhhhhhhhhhhhxhjfghf", "1-7 n: wkjsncn", "1-6 x: xxxxxxxx", "14-19 q: qwqgqqqqqrqqqqqqqqqq", "7-16 n: nnnnnnzjnnmknnnqnnn", "8-9 s: ssbssssbss", "4-5 k: ckxvkhz", "3-4 s: ssss", "3-4 d: hwdsd", "1-15 f: jfffffffffffffq", "2-5 p: jppgpwwvhv", "15-16 f: pllnmftdbzxhfkxf", "5-10 w: vbwgswxwlwwwkwlw", "1-2 g: glgg", "10-15 c: cchccccclctcccdcc", "4-5 r: rrgrrhmwrsrr", "3-10 k: rwkcnwknkk", "2-15 t: ttttttttttttttttt", "11-12 l: lllllllllllql", "4-6 m: jqdlzxvmv", "10-12 l: lllwlmslllljflwll", "1-2 s: mssss", "3-7 h: plhgfjhchm", "15-16 q: qqqqqqqqqqqjqqhsqqq", "11-14 p: shpzpcmvscpccprdmmp", "2-4 w: lgjn", "5-7 q: vqkcstq", "8-17 b: hbbbpbbtbbxbbbbjmb", "8-15 b: bbbbbbbbbbbbbbr", "14-16 s: sssjssssssssspsssss", "9-13 w: wwwwwwkwkwwwxwww", "4-7 k: xkkkkkwkkkkjkkkkk", "4-6 m: bmvmnl", "6-12 r: qrxvfrhcrtrrrm", "2-8 t: rttwgtztkddbzbdd", "1-4 x: sxbxxxd", "1-2 b: bxqbqh", "2-5 w: glmnxmlcmwkphwmxfk", "12-13 n: nnhfnrnnsnfnnnmn", "3-4 b: bqbbbbx", "4-5 v: vvvgj", "6-7 m: mmmmmsb", "3-4 z: qqblwc", "15-16 t: tttqdtttttttttmt", "2-3 f: fffl", "2-11 x: xpkxxxxbwrmxxvmx", "11-15 p: lsxpjkwqjxqgwkpp", "4-7 h: mvkszlvhkrfqpzfhdwbm", "8-13 j: jjjjjjjjjjjjjjjjj", "7-8 z: bdzzzzrz", "3-6 v: vvvvvvv", "10-12 f: ffxxffbfmnffffj", "9-12 t: tjttwhtxtttttt", "4-5 n: pdnnn", "3-4 p: phprxnv", "11-13 j: jjjjjjjjjjjjzj", "7-10 g: ggggjgggdwggmgjvg", "2-3 q: jxqqfqz", "4-7 t: rghbdhgt", "5-6 c: xrfcxcccctsp", "2-4 j: ljpjspjbfkbmhzwbxmzc", "7-8 s: ssssssvm", "1-6 r: srrrrrwv", "1-17 k: lkkkkkkkkkkkkzkkqkkk", "10-13 j: xjjjhjjfjjjfljzmjbjm", "8-9 q: qztvqqwqbv", "3-4 v: vbvc", "2-11 g: nwhdjzrvwxgngsh", "8-13 k: kkztkkkxkkkgkclrrkk", "9-10 n: tnnknzlsbnnn", "5-6 v: vlvvpv", "9-11 d: ddddddsddpvddddd", "17-18 x: blxxxlkvxxpxftmjxxwp", "6-9 z: zztzzkzzzh", "3-5 j: sjkjq", "4-11 k: kkkdkkvkkkkkkck", "5-7 n: nnnnvsjn", "5-7 k: kkkknkk", "7-10 m: qdbmmmmtrvxggmmqlss", "10-12 t: tttttttttrtvttttt", "3-6 l: lsljmcgv", "8-10 j: tjhnmwrjrtjmj", "15-16 l: cllllrhwllzlnlll", "12-14 m: mmmmmmmmmmmlmqm", "3-4 m: mmrmmmmmm", "2-6 p: psglpp", "1-3 f: ffwwffffzf", "3-4 z: zjzz", "13-14 m: bzmmpmvclmzkmf", "1-2 s: sssp", "12-15 q: qqqqqqqqqqqgqqhqq", "6-8 q: qhldnvqb", "1-4 n: nnnn", "9-10 t: rgzqzlndrtlzzdbtcrxh", "15-16 w: wwwwwwwwwwwwwwwwww", "2-4 h: hghhf", "1-3 x: twhx", "13-15 l: zhlsnvjllxqlqdq", "1-3 b: jbzbjrfbjfrgsml", "2-12 t: znskzrlnbjktpftd", "3-12 b: grbvbwjbbsbgbpb", "6-18 t: tttttztttttttttttttt", "9-11 j: jjjsjjhjjqjjjrjnl", "1-16 w: tgrwwwwwwwwwfkww", "1-5 d: ddfdqdd", "8-18 w: wwwwwwwwwwwwwwwwwww", "5-16 s: rvlmcczcgbxbtxxqxm", "1-4 z: zzqznzwtkg", "2-6 j: zqpcvv", "6-7 t: zttmtth", "3-5 g: gggggg", "8-9 j: jjjjjjjpjjjjjjjjj", "11-19 k: ndlbdtjkdhgfrrvmtrk", "5-6 s: ssnssss", "6-7 f: zgzfqfg", "16-18 k: kkkkkdzckbjmcjdfkkk", "1-7 c: cccchmv", "6-8 h: hkhhhhhhhhw", "3-4 m: mmgm", "3-4 j: jwjwj", "1-2 t: jtttz", "3-5 n: nnnns", "2-9 l: wdpwdpcqlkrrt", "6-11 d: ddddddddddpdsv", "9-11 v: vvhqvpnvglvvvxv", "3-8 v: dlvvkvmk", "8-11 f: fmdfmcffsfdng", "9-10 q: tqqqjqqqgqqqq", "3-17 m: mzmxdgwfrgjjkrbjmvv", "2-4 d: xwtdpd", "10-11 v: vvvvvvvvvvn", "6-8 l: fxcllfhl", "17-18 n: nnnnnnnnnnnnnnnnjz", "1-2 n: lnnsn", "2-3 v: vvlj", "11-12 s: ssssvssshsvc", "7-8 n: njnnnnssn", "1-8 h: hhhhhhhhthh", "11-12 j: jfjjjjbbgjjj", "5-7 n: cltwnfn", "4-9 c: wgcccmxxr", "10-13 n: xnnnszfnndhcnmnzc", "7-8 n: nnnrnnrkqzn", "7-10 f: ffffffbffff", "2-16 z: zzzzzzzzzzzzzzzrz", "13-14 q: qqqqqqqqqqqqnb", "4-9 q: qcqkvlqgqdqnq", "11-17 l: ppvjfgvhnxvzpdphlcxg", "4-5 j: qjqpmjpj", "3-4 n: mnqq", "4-7 w: wwwbwww", "3-9 n: mbpgnnfzn", "10-13 j: jjwjjhjjjwjjj", "2-6 f: zcdrsgqszfn", "1-7 x: xmzkwtx", "1-5 q: jzfqgdqrsqqqqgq", "4-17 p: npvpppcljpcgjfbhpppp", "5-11 g: grgggfggggggg", "8-12 n: hdcnbplfnnmn", "2-4 j: jnfw", "13-14 d: mfgvkdrkzggddd", "5-7 k: kkkkfkpkk", "7-9 q: tqqrgqqjwqfpg", "1-2 g: rdgxg", "18-19 w: wwwwwwwwwswwwwwwwwz", "8-12 q: qqqqcqzkvdqqqqspqf", "12-16 p: xfzcfvpdrpnlpppmpq", "4-5 q: qdqkb", "6-12 p: glpppnpsppppppgnpp", "1-18 g: ggggggggggggggggggg", "1-7 h: hfhwsjxmnhd", "1-8 h: hhjhphhchhhdh", "8-11 z: zzzzkzzzzcr", "13-18 w: qwhwvxwwbtdwlqwwww", "4-11 n: nntnsnnngnnknnnptpn", "1-8 c: cmccflmjccc", "12-14 d: qgdrdhjddddddd", "1-10 r: xrbmrrrwbcrrr", "4-8 t: pjsfzxsst", "3-6 h: hhfhdhl", "5-6 m: mmmmmmmmmmm", "8-9 c: jfrkcrrrccqcqsh", "8-9 w: wwwwwwwbww", "3-6 w: tvwpkvwwgwwqlcwzg", "11-13 n: qnvnknfnccnngnnn", "11-17 q: qqqqqqqqqqqqqqqqlq", "5-9 k: whkkkkkkmmkkclkfjl", "8-13 d: dddddddcdddddd", "6-7 c: cckccckcc", "6-9 n: nnnnkvnzn", "2-10 x: fxdtdbbfpxfcdd", "3-9 r: rrrxrrrrrrrlrrjr", "3-10 d: ddgkdqdrfwdd", "3-12 p: pppqpppphcppp", "10-12 r: frrrrrwrrlrrrrrf", "14-19 x: vxxzxqtxjgpxxxxvjxxx", "1-12 v: vvvvvvvvvvvrvvv", "11-13 c: cccccccccchmcccc", "4-10 t: tmbpgnmtwksfwcmttbwt", "3-5 c: mdcncrcj", "9-10 f: ffffgsfqfmf", "8-9 t: dzpdqtttqtptltttm", "8-9 h: wwpqhshhhbv", "12-17 s: sssssmsztqtbspssds", "11-13 n: pnndnbnnvwznnnxsnnnn", "6-10 n: nmxsvjlfnd", "2-7 h: thlghzhf", "6-9 s: rshshxpvlstdsd", "16-17 c: ccccccbcccphccvcqc", "6-11 q: jqqqqwsbqxqq", "7-9 b: bbfjbbcbmsbvpglbh", "1-11 m: mmmmmmmmmmmmmmm", "15-17 x: xxxxxxxxxxxxxxxxvx", "9-11 l: lllsldlllllljp", "3-5 g: jgjnq", "2-3 w: wgwz", "4-5 h: jhfdpqqhsh", "1-4 s: hrfxfxlx", "3-5 r: kxrnsr", "3-10 p: fpjppptppvpppp", "5-12 m: dmclmfrmgbhlms", "4-6 g: kdmmtgnxrgmgxggwmfd", "4-10 f: xfshwrfrvx", "1-3 v: dvmznrksd", "7-18 n: xnsnnnnngnsnqjglwln", "6-10 f: lffftlmfbfp", "7-8 t: twjmbttjthpt", "4-6 j: gjjltn", "4-5 c: vfflxckkdh", "10-15 b: kwcwcjtlsbbtfvbldglk", "7-13 d: ddddddqddxddddd", "1-4 w: wwwmw", "4-8 d: lvddtrwzt", "4-9 t: ttttztttt", "5-6 k: kkrpkkkqtkffkwkk", "1-3 f: kqfxxfb", "3-6 g: ksgqlggb", "11-12 f: ffffffdrffzf", "10-11 b: jbbbbbbbbbbbb", "16-17 s: sssssdssssssssskn", "17-18 d: dmddddddddddddddrzdd", "1-12 j: jvjjjqjcjtjj", "2-4 b: npbbbkx", "4-14 n: tnntfngpnbknnnnnrn", "4-13 n: mnfsnnnnnnnnznn", "6-10 s: sssssnssszsvs", "8-9 m: mmxzpmhjj", "2-4 k: pkgf", "2-7 k: nkbtszkfzp", "11-12 f: nxpbhffpzrff", "5-14 x: czhvltwfxbxzsxzjtwxx", "16-19 r: rrrrrrrrrrrrrrrrrrwr", "2-4 m: mmmmvm", "4-5 r: qrdrw", "13-14 b: bbbhbbbbckbbpb", "5-7 j: nwppmqkjxhtjf", "8-11 z: zzwfwzbszzxzg", "3-11 x: bxlfxjqxxgbwxxzcx", "5-7 x: xxxxpxq", "1-4 s: sssss", "2-3 r: rvrr", "6-7 b: bbbblkbzbbbnbbbbbj", "1-3 g: gxgv", "13-15 w: wwwwwwwwwwwwxwhww", "3-4 c: rccc", "4-15 p: cflwnhwfvntlxppmbg", "7-12 m: xhmpvvmmmxhm", "8-11 w: wmwwlwwcwdw", "8-10 f: ghfcwzfffkfp", "7-8 f: ffqcmdfww", "3-4 z: qzjz", "4-5 k: kkbqk", "1-2 x: xqxczjtkfjt", "2-17 h: hxhhhhhhhhhhhhhhhhhh", "2-5 r: rrrmclqkcvkztr", "10-13 q: fqgqqrgdxqfqq", "8-9 j: jjjjjjdhjjj", "6-7 q: sqqqhqvn", "3-4 r: rrxw", "13-15 j: jjjjjjjpjjjjjjx", "4-6 v: rpvvvvrcfvqgfmsj", "12-18 z: zzzzzzzzzdzjzzzdzn", "8-10 n: ncnnnnmnnbhw", "11-13 v: vvvvvvvvvvvvv", "4-8 p: pdtpxpzw", "5-10 z: zzqwxzmmfr", "2-4 n: nknnn", "3-4 c: dchb", "10-17 h: lrpvfmmpwhgqphjphhhv", "5-8 v: vrvmvvvnmvv", "10-11 z: zzhzzzzzzzp", "2-4 p: ppfpfp", "4-7 z: zzzzzzjz", "9-12 j: jjbwxjjjfjjwzmjc", "12-17 f: fffffffffffdffffffff", "5-7 t: dtlttvh", "3-4 c: cmmnccv", "1-8 j: tcjrqxjjk", "10-14 h: vhhchthrhhhhhvhqhp", "4-11 c: njrqmwpznxqtcc", "1-15 g: xgdpwcqghrglgcgtggg", "2-7 n: nkngnrnnqt", "9-15 x: xxxxxsrxnxxfxxxxxxx", "3-4 s: dsmf", "4-5 r: rrrrcr", "10-13 q: mqqqkqqqqzqqg", "1-2 m: grtml", "6-15 m: mmmmmfxmmftmmqm", "15-18 g: ggjghfggvwgnhdggtb", "1-5 k: ckkkfkqckqzk", "4-5 h: kdllpjbn", "2-4 b: jbgbf", "5-8 v: vcvvqvvnhsz", "8-9 m: fmmjmmmtm", "4-6 l: lvhxdl", "1-7 j: wjjjjjj", "1-12 k: kkkkkkkkfkkpkkkkkj", "3-5 r: rrrrr", "3-4 x: vsqg", "3-5 m: bszmmmcmnbdmhx", "5-7 j: jjhfjjjk", "9-12 v: nshvfvvwxvqv", "10-15 v: dnthqhrpvsbznqdllwmg", "8-9 g: jkgfzjgbcch", "3-4 q: qqqw", "2-3 m: mrcmmm", "5-11 z: wzqzztfwzrz", "1-4 p: zppf", "3-4 l: dcvq", "2-6 n: ngnnnnn", "6-7 z: zczzznz", "2-3 k: kglkkkjk", "5-7 v: vvvgsbtfwk", "2-12 q: qkgbwqjzqqqfqqqqqqqq", "2-4 f: fpcq", "17-18 b: bxtmblftbfbgbxbfdb", "4-5 q: gqqjjz", "10-11 l: llqllllllgl", "2-4 r: jjrn", "3-17 p: wfplgttzpngcvfzppw", "2-3 v: vvmvt", "10-17 k: kkkkkkktkxkkkkkkjkkk", "8-9 z: pzdbjgbpzrxhhzc", "3-12 z: blzpzxcqhvrsnvgml", "14-15 q: qcffbpwbfqgxsqtrf", "4-9 m: tthmftsxwrrmxx", "2-3 r: zrrrr", "7-14 l: blvhllgflllhcp", "3-18 x: lplsnpshxmhsgmqdnr", "12-15 f: rffdjffxfmffcfkff", "11-12 q: qqqqqqqqqqqxq", "7-9 b: bhbzrjfbvbbmgbbpkb", "1-2 p: pppp", "11-15 g: gtzgrghgwqgpqglx", "1-7 t: tpttkxtptkgh", "1-5 k: kkkkx", "10-16 w: rthbwwqvcwggwpds", "10-12 g: rpxxnxptslrgrpktg", "5-8 h: hhhhhhhhhh", "2-4 t: lthtsgbs", "11-17 z: zzzzzzzzzzfzztzzzz", "3-14 t: jttzstslpnvfftwmqqlq", "4-10 l: tstfqpvlcl", "6-16 t: cdtvtttrttwhmtvt", "4-7 b: lbbwbbm", "3-9 z: zrqbqzkdz", "4-5 f: zlfsfzfgfzffpffff", "1-4 m: jhmr", "2-3 n: nnnvnnn", "3-5 k: ktkjk", "14-15 z: zzzzzzzzzzzzzzfn", "12-13 m: mmmmmmmmmmmpmmm", "3-4 s: spmssqbmnl", "1-3 g: sgggggggfg", "5-6 n: hnwnnd", "7-11 r: rrrcrrvrrrrrrrrr", "11-12 s: ssssssssssmw", "2-4 n: rnvv", "4-10 l: lmhplmllvdlnblmd", "2-12 q: rbqwfbbqmsqfqfqqq", "16-17 q: zqqqqqqqqqqqqqqnqq", "18-19 p: dspfknrkgfxjdxvflbp", "2-5 b: bbldb", "3-4 k: kkfk", "2-13 f: wfjhbcfrjfwxs", "11-15 r: rrjrrrrrrrrrrrvrrrr", "9-10 f: fffffffffhf", "13-16 j: hsjjbjjpvvjsjrjsjz", "6-8 l: ghlllffll", "15-16 m: mvtxqmkfmfmbmvndm", "4-5 h: zhhhhhh", "3-4 x: mfzfnpcwxjxkhrrsszfc", "17-18 d: qwdkqdsddddhdsxxwk", "6-8 n: ngqnnnnzn", "14-15 w: qwdbpsnwwwqwwww", "10-13 h: hsrhnfxdhhxqb", "2-4 k: kpjqgbpsq", "12-13 x: xxxxxxxxxxxzrxxxxxx", "7-10 j: jjjjjjbjjgk", "11-15 q: mwqnxtrhwjqdqpz", "2-9 b: cvcbxgxntx", "5-7 x: xxdxxxc", "4-7 d: dddtddkd", "6-8 f: cnrfgfjn", "3-4 h: ghhhh", "12-15 z: mnqsvtxzclhzkzjz", "5-6 m: gmdcmm", "3-4 h: hhph", "16-20 k: kkkkkkkkkkknkkkkkkkk", "9-10 h: hhhhhhhhhhkhh", "4-5 c: ccpcdf", "6-11 l: lllllqlrljcl", "9-12 z: zzzdzszzfzzn", "9-10 b: bbbbbbbbfb", "4-13 v: vvvcbvrvnvvvw", "4-5 f: ffffv", "4-6 m: mdmzdf", "1-13 f: ffffffdffffsf", "4-5 t: jttbtpttrttt", "5-6 x: kxxxqb", "3-5 t: twttpt", "1-3 f: tfbd", "1-7 w: fprwwwwwwwwwwzw", "6-7 h: hhmhnkhhjhn", "6-7 c: cpcwddc", "6-8 q: ltsqwdqf", "2-3 j: jjbjj", "4-10 t: gtztntwkmt", "5-6 d: xdwddddd", "13-18 n: nnnnmnhzjrnnnlnnnrn", "5-6 q: qqqqqqq", "3-9 v: wvznrqpvvmhh", "1-2 n: nbln", "10-11 j: fsrjsvjjjwljzljsjpkj", "1-4 n: cfnnf", "13-16 j: qvlgjwhmsspdjgfxcl", "2-6 k: kkkqkzh", "1-6 f: ftcfff", "12-16 g: ggggggggggggghgwg", "4-14 w: hwwwpwwwbwwwww", "3-14 c: cccccccccxccbwcccc", "7-8 x: xxxxczsc", "18-19 l: cplmllplhzbddwjlpvf", "2-4 x: dxxxqr", "5-8 w: vpxjwqwlfmzhbwwflj", "3-6 v: vjlvvvvqqd", "8-11 n: znnznnnnwnnn", "9-10 c: ccccccccchc", "3-12 l: hpljmhqcgfslm", "4-5 s: dcqvxjczbxgxcrhksmvt", "9-11 d: dddrnbfrfdhpndd", "3-4 n: nssj", "1-8 w: vwwwwwwww", "7-12 h: hhhhhhhhhhhdhh", "4-5 t: twtst", "6-7 q: qrwqqqq", "6-7 h: hghhnmbh", "12-18 p: jvkpcjdkjssppmppjpp", "4-5 s: ssslks", "2-9 c: ccccccccccccccc", "2-3 c: dvcvxcgpzjck", "4-6 w: zmwnwlw", "8-11 q: qqqqgqqqqqq", "13-14 n: xfgnpvcwxmwfnrgnp", "6-10 h: hhhhhhhhhhhh", "3-6 z: gzcfwpkz", "5-6 t: wtvhtttkmtttjt", "7-16 f: fffwffffmfffffvf", "6-10 d: lddddddddqg", "3-5 t: dttttxlzlmwhd", "8-12 w: wwwwwwwrwwwnw", "6-7 v: spvcvvvpj", "4-6 z: zzkzdzcwpzh", "5-8 j: jjjjjjjzj", "7-11 z: fxvhznzvzzz", "9-12 s: sslksssscssrssvsvl", "3-6 t: qtlwfw", "10-11 l: vwssgxtszll", "16-18 w: jvqrpdxlmjhwvdndtw", "19-20 s: sssssssssxssssssssss", "2-6 c: dzncll", "15-17 f: qtlwcgtffxfrgflfcnv", "3-4 p: qsjwvpbtjzpppqp", "2-8 h: hzhhhhhth", "3-4 g: rgdgggg", "3-5 g: czzgkgbpns", "6-7 t: tttttth", "3-5 m: mvnmmmxzml", "15-18 s: sswsssssszzssssssp", "2-7 k: kzcrwpdjrtkkrgd", "3-4 h: hshn", "5-17 h: hrhhhhhhhhhhhhhhhhh", "1-4 g: gcggglpfzgljnpstkngl", "2-16 d: wbvwfvtdtjjnthkd", "4-5 c: cmbccqtzjmnmcpjpwbkn", "2-4 v: vjnvwnh", "4-11 l: lllllllrllhllll", "1-2 m: ltmmm", "7-9 l: lslmlrbcsqll", "16-19 q: qqqlqqqgqqqqrqqxtqfq", "10-15 z: zwdzzdrsztsztrlz", "11-12 g: ggvfgbgggmgg", "8-9 d: dvjddddldd", "4-5 g: wjrgmb", "2-4 q: mqgq", "4-6 j: jxjmjjfjxzx", "1-2 l: ltvckkmlpkkll", "4-7 v: djftvvdmv", "4-5 p: ppppppp", "6-12 z: jjxfvzzbmwmz", "2-5 b: vpbnd", "3-8 t: tttlthtntttt", "4-6 r: xrrrrf", "1-2 j: jjzqjjjjgs", "3-4 c: ccczc", "1-7 j: jjjjhdjjjj", "3-6 k: jkfkkk", "3-5 s: smssssnsl", "5-11 d: tkqddsqhppmdkwwqvtdm", "10-12 w: khrwhqwpcwww", "15-19 t: ttttttttttttttpttttt", "2-3 z: zrgz", "14-17 p: gpzppppvjppppppppfp", "15-17 p: ppvppppppppqppdpppzp", "3-9 b: cbbpcbbbhbbbbnbbb", "2-8 k: lvkstqvhssd", "2-6 c: clcccccc", "6-9 s: cgsssgsdw", "1-4 p: pgpppp", "9-16 z: zzzpmzzzxzzztzfz", "14-15 j: jjjjjjjjjjjjjjtjj", "5-9 b: rkctbdgbkcwvjxtz", "13-16 d: dddddzddddkddddddddd", "1-6 x: xlxxxhbgxfbmxzx", "3-17 m: lbbsnfclmmctgfkvf", "2-4 s: ssspss", "8-12 w: wwwwwtwwgwwdww", "2-4 t: ttgt", "1-3 m: dmwjcbhlv", "1-13 g: gggpghgcrggggntg", "11-17 x: wxxxzxxtxxxxxxjxxxxx", "14-15 j: jxjjhvxcdpbvjhknjrf", "13-17 t: ttttttttttttttttpt", "13-16 j: jjjjjjjjjjjjwjjjjj", "7-9 w: wwwwwwhwm", "3-5 w: rwwwc", "4-5 l: zlltpl", "2-4 j: nmbjjj", "13-14 b: bqhbvsxbjvhchnnzbtb", "2-3 k: cgtn", "4-6 h: sfmjhnm", "10-11 r: nrmcvgbdldn", "2-6 r: rqrrrrr", "14-18 r: rrrrrrrrrvrrrdrrrrr", "10-11 g: jdgggcctgsg", "9-14 f: stfflfrpjfffhxff", "4-6 c: cccxcjcwc", "13-17 w: rwwwwkwwwgwgswxfpwwc", "7-9 g: ggggggcgrg", "6-10 j: fjmjjjjdjkjmj", "10-12 h: qswhkndjhqkh", "4-12 z: zfzzzzzzzzkzzzzzzz", "1-9 t: tqtttwtbxtgtzp", "13-14 p: bppppppvpkpbppppp", "7-11 m: phxfmmwmmwm", "4-14 d: ddddddhdddddcbddd", "1-6 l: mlllllll", "6-13 z: nzzzztzznjcckznz", "3-8 p: pppppppppppp", "10-17 r: rrrrrrrrrdrrrrrrrr", "15-18 j: bvswjgxvwdjcgdjqjjr", "5-6 q: rqqkqq", "7-15 k: kfkjsqlkzngkkvrmkzkv", "2-6 p: gpwhqpbpgdrprbbp", "1-7 x: rxxwxxxxxxrfxxfxqxx", "14-15 x: xxxxxxfxxxxxxxxxgxxx", "9-10 f: frskkfnffh", "1-11 s: qsssssspsssss", "4-11 g: zkxvrprgzxjcbg", "11-14 g: ggggggggggggggggg", "6-7 q: qqqqvqhq" }; } } }
7a9b8f32b590d3880107826d6aaba955badb6dd7
C#
omikad/omikad-stuff
/ProblemSets/ProblemSets/Services/StringHelper.cs
3.5
4
using System; using System.Collections.Generic; namespace ProblemSets.Services { public static class StringHelper { public static string Join<T>(this string separator, IEnumerable<T> values) { return string.Join(separator, values); } public static string CommonPrefix(this string s1, string s2) { if (s1 == null || s2 == null) return ""; int equalLen; for (equalLen = 0; equalLen < s1.Length && equalLen < s2.Length; equalLen++) if (s1[equalLen] != s2[equalLen]) break; return s1.Substring(0, equalLen); } private static readonly string[] newLineArray = { Environment.NewLine, "\r", "\n" }; public static string[] SplitToLines(this string s) { return s.Split(newLineArray, StringSplitOptions.RemoveEmptyEntries); } private static readonly char[] spacesArray = { ' ', '\t' }; public static string[] SplitBySpaces(this string s) { return s.Split(spacesArray, StringSplitOptions.RemoveEmptyEntries); } } }
c58150d20702a314fd3e8dc2780f5ad79520163d
C#
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
/fulldocset/add/codesnippet/CSharp/p-system.drawing.graphic_1_1.cs
3.015625
3
private void ChangePageScaleAndTranslateTransform(PaintEventArgs e) { // Create a rectangle. Rectangle rectangle1 = new Rectangle(20, 20, 50, 100); // Draw its outline. e.Graphics.DrawRectangle(Pens.SlateBlue, rectangle1); // Change the page scale. e.Graphics.PageScale = 2.0F; // Call TranslateTransform to change the origin of the // Graphics object. e.Graphics.TranslateTransform(10.0F, 10.0F); // Draw the rectangle again. e.Graphics.DrawRectangle(Pens.Tomato, rectangle1); // Set the page scale and origin back to their original values. e.Graphics.PageScale = 1.0F; e.Graphics.ResetTransform(); SolidBrush transparentBrush = new SolidBrush(Color.FromArgb(50, Color.Yellow)); // Create a new rectangle with the coordinates you expect // after setting PageScale and calling TranslateTransform: // x = (10 + 20) * 2 // y = (10 + 20) * 2 // Width = 50 * 2 // Length = 100 * 2 Rectangle newRectangle = new Rectangle(60, 60, 100, 200); // Fill in the rectangle with a semi-transparent color. e.Graphics.FillRectangle(transparentBrush, newRectangle); }
b844edf402796a9390f6985a23f76fbeb7fcb3ac
C#
rockcs1992/PLATE-X
/DAL/ServerOrderService.cs
2.515625
3
using System; using System.Data; using System.Text; using System.Data.SqlClient; namespace DAL { /// <summary> /// ݷ:ServerOrderService /// </summary> public partial class ServerOrderService { public ServerOrderService() {} #region BasicMethod /// <summary> /// Ƿڸü¼ /// </summary> public bool Exists(int id) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) from ServerOrder"); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,4) }; parameters[0].Value = id; return DBHelperSQL.Exists(strSql.ToString(),parameters); } /// <summary> /// һ /// </summary> public static int Add(Model.ServerOrder model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into ServerOrder("); strSql.Append("serverType,pid,cid,regionId,address,serverTime,ageArea,workExperience,salaryArea,personGood,languageId,proxyId,sisterId,title,orderDesc,status,remark,otherInfo,otherRemark,addTime,addUser,infoType)"); strSql.Append(" values ("); strSql.Append("@serverType,@pid,@cid,@regionId,@address,@serverTime,@ageArea,@workExperience,@salaryArea,@personGood,@languageId,@proxyId,@sisterId,@title,@orderDesc,@status,@remark,@otherInfo,@otherRemark,@addTime,@addUser,@infoType)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@serverType", SqlDbType.Int,4), new SqlParameter("@pid", SqlDbType.Int,4), new SqlParameter("@cid", SqlDbType.Int,4), new SqlParameter("@regionId", SqlDbType.Int,4), new SqlParameter("@address", SqlDbType.VarChar,150), new SqlParameter("@serverTime", SqlDbType.DateTime), new SqlParameter("@ageArea", SqlDbType.Int,4), new SqlParameter("@workExperience", SqlDbType.Int,4), new SqlParameter("@salaryArea", SqlDbType.Int,4), new SqlParameter("@personGood", SqlDbType.Int,4), new SqlParameter("@languageId", SqlDbType.Int,4), new SqlParameter("@proxyId", SqlDbType.NChar,10), new SqlParameter("@sisterId", SqlDbType.Int,4), new SqlParameter("@title", SqlDbType.VarChar,150), new SqlParameter("@orderDesc", SqlDbType.VarChar,1500), new SqlParameter("@status", SqlDbType.Int,4), new SqlParameter("@remark", SqlDbType.VarChar,1500), new SqlParameter("@otherInfo", SqlDbType.NText), new SqlParameter("@otherRemark", SqlDbType.VarChar,150), new SqlParameter("@addTime", SqlDbType.DateTime), new SqlParameter("@addUser", SqlDbType.Int,4), new SqlParameter("@infoType", SqlDbType.Int,4)}; parameters[0].Value = model.serverType; parameters[1].Value = model.pid; parameters[2].Value = model.cid; parameters[3].Value = model.regionId; parameters[4].Value = model.address; parameters[5].Value = model.serverTime; parameters[6].Value = model.ageArea; parameters[7].Value = model.workExperience; parameters[8].Value = model.salaryArea; parameters[9].Value = model.personGood; parameters[10].Value = model.languageId; parameters[11].Value = model.proxyId; parameters[12].Value = model.sisterId; parameters[13].Value = model.title; parameters[14].Value = model.orderDesc; parameters[15].Value = model.status; parameters[16].Value = model.remark; parameters[17].Value = model.otherInfo; parameters[18].Value = model.otherRemark; parameters[19].Value = model.addTime; parameters[20].Value = model.addUser; parameters[21].Value = model.infoType; object obj = DBHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// һ /// </summary> public bool Update(Model.ServerOrder model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update ServerOrder set "); strSql.Append("serverType=@serverType,"); strSql.Append("pid=@pid,"); strSql.Append("cid=@cid,"); strSql.Append("regionId=@regionId,"); strSql.Append("address=@address,"); strSql.Append("serverTime=@serverTime,"); strSql.Append("ageArea=@ageArea,"); strSql.Append("workExperience=@workExperience,"); strSql.Append("salaryArea=@salaryArea,"); strSql.Append("personGood=@personGood,"); strSql.Append("languageId=@languageId,"); strSql.Append("proxyId=@proxyId,"); strSql.Append("sisterId=@sisterId,"); strSql.Append("title=@title,"); strSql.Append("orderDesc=@orderDesc,"); strSql.Append("status=@status,"); strSql.Append("remark=@remark,"); strSql.Append("otherInfo=@otherInfo,"); strSql.Append("otherRemark=@otherRemark,"); strSql.Append("addTime=@addTime,"); strSql.Append("addUser=@addUser,"); strSql.Append("infoType=@infoType"); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@serverType", SqlDbType.Int,4), new SqlParameter("@pid", SqlDbType.Int,4), new SqlParameter("@cid", SqlDbType.Int,4), new SqlParameter("@regionId", SqlDbType.Int,4), new SqlParameter("@address", SqlDbType.VarChar,150), new SqlParameter("@serverTime", SqlDbType.DateTime), new SqlParameter("@ageArea", SqlDbType.Int,4), new SqlParameter("@workExperience", SqlDbType.Int,4), new SqlParameter("@salaryArea", SqlDbType.Int,4), new SqlParameter("@personGood", SqlDbType.Int,4), new SqlParameter("@languageId", SqlDbType.Int,4), new SqlParameter("@proxyId", SqlDbType.NChar,10), new SqlParameter("@sisterId", SqlDbType.Int,4), new SqlParameter("@title", SqlDbType.VarChar,150), new SqlParameter("@orderDesc", SqlDbType.VarChar,1500), new SqlParameter("@status", SqlDbType.Int,4), new SqlParameter("@remark", SqlDbType.VarChar,1500), new SqlParameter("@otherInfo", SqlDbType.NText), new SqlParameter("@otherRemark", SqlDbType.VarChar,150), new SqlParameter("@addTime", SqlDbType.DateTime), new SqlParameter("@addUser", SqlDbType.Int,4), new SqlParameter("@infoType", SqlDbType.Int,4), new SqlParameter("@id", SqlDbType.Int,4)}; parameters[0].Value = model.serverType; parameters[1].Value = model.pid; parameters[2].Value = model.cid; parameters[3].Value = model.regionId; parameters[4].Value = model.address; parameters[5].Value = model.serverTime; parameters[6].Value = model.ageArea; parameters[7].Value = model.workExperience; parameters[8].Value = model.salaryArea; parameters[9].Value = model.personGood; parameters[10].Value = model.languageId; parameters[11].Value = model.proxyId; parameters[12].Value = model.sisterId; parameters[13].Value = model.title; parameters[14].Value = model.orderDesc; parameters[15].Value = model.status; parameters[16].Value = model.remark; parameters[17].Value = model.otherInfo; parameters[18].Value = model.otherRemark; parameters[19].Value = model.addTime; parameters[20].Value = model.addUser; parameters[21].Value = model.infoType; parameters[22].Value = model.id; int rows=DBHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// Deleteһ /// </summary> public bool Delete(int id) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from ServerOrder "); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,4) }; parameters[0].Value = id; int rows=DBHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// Delete /// </summary> public bool DeleteList(string idlist ) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from ServerOrder "); strSql.Append(" where id in ("+idlist + ") "); int rows=DBHelperSQL.ExecuteSql(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } /// <summary> /// õһʵ /// </summary> public Model.ServerOrder GetModel(int id) { StringBuilder strSql=new StringBuilder(); strSql.Append("select top 1 id,serverType,pid,cid,regionId,address,serverTime,ageArea,workExperience,salaryArea,personGood,languageId,proxyId,sisterId,title,orderDesc,status,remark,otherInfo,otherRemark,addTime,addUser,infoType from ServerOrder "); strSql.Append(" where id=@id"); SqlParameter[] parameters = { new SqlParameter("@id", SqlDbType.Int,4) }; parameters[0].Value = id; Model.ServerOrder model=new Model.ServerOrder(); DataSet ds=DBHelperSQL.Query(strSql.ToString(),parameters); if(ds.Tables[0].Rows.Count>0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// õһʵ /// </summary> public Model.ServerOrder DataRowToModel(DataRow row) { Model.ServerOrder model=new Model.ServerOrder(); if (row != null) { if(row["id"]!=null && row["id"].ToString()!="") { model.id=int.Parse(row["id"].ToString()); } if(row["serverType"]!=null && row["serverType"].ToString()!="") { model.serverType=int.Parse(row["serverType"].ToString()); } if(row["pid"]!=null && row["pid"].ToString()!="") { model.pid=int.Parse(row["pid"].ToString()); } if(row["cid"]!=null && row["cid"].ToString()!="") { model.cid=int.Parse(row["cid"].ToString()); } if(row["regionId"]!=null && row["regionId"].ToString()!="") { model.regionId=int.Parse(row["regionId"].ToString()); } if(row["address"]!=null) { model.address=row["address"].ToString(); } if(row["serverTime"]!=null && row["serverTime"].ToString()!="") { model.serverTime=DateTime.Parse(row["serverTime"].ToString()); } if(row["ageArea"]!=null && row["ageArea"].ToString()!="") { model.ageArea=int.Parse(row["ageArea"].ToString()); } if(row["workExperience"]!=null && row["workExperience"].ToString()!="") { model.workExperience=int.Parse(row["workExperience"].ToString()); } if(row["salaryArea"]!=null && row["salaryArea"].ToString()!="") { model.salaryArea=int.Parse(row["salaryArea"].ToString()); } if(row["personGood"]!=null && row["personGood"].ToString()!="") { model.personGood=int.Parse(row["personGood"].ToString()); } if(row["languageId"]!=null && row["languageId"].ToString()!="") { model.languageId=int.Parse(row["languageId"].ToString()); } if(row["proxyId"]!=null) { model.proxyId=row["proxyId"].ToString(); } if(row["sisterId"]!=null && row["sisterId"].ToString()!="") { model.sisterId=int.Parse(row["sisterId"].ToString()); } if(row["title"]!=null) { model.title=row["title"].ToString(); } if(row["orderDesc"]!=null) { model.orderDesc=row["orderDesc"].ToString(); } if(row["status"]!=null && row["status"].ToString()!="") { model.status=int.Parse(row["status"].ToString()); } if(row["remark"]!=null) { model.remark=row["remark"].ToString(); } if(row["otherInfo"]!=null) { model.otherInfo=row["otherInfo"].ToString(); } if(row["otherRemark"]!=null) { model.otherRemark=row["otherRemark"].ToString(); } if(row["addTime"]!=null && row["addTime"].ToString()!="") { model.addTime=DateTime.Parse(row["addTime"].ToString()); } if(row["addUser"]!=null && row["addUser"].ToString()!="") { model.addUser=int.Parse(row["addUser"].ToString()); } if(row["infoType"]!=null && row["infoType"].ToString()!="") { model.infoType=int.Parse(row["infoType"].ToString()); } } return model; } /// <summary> /// б /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select id,serverType,pid,cid,regionId,address,serverTime,ageArea,workExperience,salaryArea,personGood,languageId,proxyId,sisterId,title,orderDesc,status,remark,otherInfo,otherRemark,addTime,addUser,infoType "); strSql.Append(" FROM ServerOrder "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } return DBHelperSQL.Query(strSql.ToString()); } /// <summary> /// ǰ /// </summary> public DataSet GetList(int Top,string strWhere,string filedOrder) { StringBuilder strSql=new StringBuilder(); strSql.Append("select "); if(Top>0) { strSql.Append(" top "+Top.ToString()); } strSql.Append(" id,serverType,pid,cid,regionId,address,serverTime,ageArea,workExperience,salaryArea,personGood,languageId,proxyId,sisterId,title,orderDesc,status,remark,otherInfo,otherRemark,addTime,addUser,infoType "); strSql.Append(" FROM ServerOrder "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } strSql.Append(" order by " + filedOrder); return DBHelperSQL.Query(strSql.ToString()); } /// <summary> /// ȡ¼ /// </summary> public int GetRecordCount(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) FROM ServerOrder "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } object obj = DBHelperSQL.GetSingle(strSql.ToString()); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// ҳȡб /// </summary> public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex) { StringBuilder strSql=new StringBuilder(); strSql.Append("SELECT * FROM ( "); strSql.Append(" SELECT ROW_NUMBER() OVER ("); if (!string.IsNullOrEmpty(orderby.Trim())) { strSql.Append("order by T." + orderby ); } else { strSql.Append("order by T.id desc"); } strSql.Append(")AS Row, T.* from ServerOrder T "); if (!string.IsNullOrEmpty(strWhere.Trim())) { strSql.Append(" WHERE " + strWhere); } strSql.Append(" ) TT"); strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex); return DBHelperSQL.Query(strSql.ToString()); } /* /// <summary> /// ҳȡб /// </summary> public DataSet GetList(int PageSize,int PageIndex,string strWhere) { SqlParameter[] parameters = { new SqlParameter("@tblName", SqlDbType.VarChar, 255), new SqlParameter("@fldName", SqlDbType.VarChar, 255), new SqlParameter("@PageSize", SqlDbType.Int), new SqlParameter("@PageIndex", SqlDbType.Int), new SqlParameter("@IsReCount", SqlDbType.Bit), new SqlParameter("@OrderType", SqlDbType.Bit), new SqlParameter("@strWhere", SqlDbType.VarChar,1000), }; parameters[0].Value = "ServerOrder"; parameters[1].Value = "id"; parameters[2].Value = PageSize; parameters[3].Value = PageIndex; parameters[4].Value = 0; parameters[5].Value = 0; parameters[6].Value = strWhere; return DBHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds"); }*/ #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
09a60a3fa779d0c05423260df332f9bb3630640b
C#
DennisCorvers/ByteStream
/ByteStream/ByteStream/Mananged/ByteWriter.cs
3.140625
3
using ByteStream.Interfaces; using ByteStream.Utils; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; namespace ByteStream.Mananged { public struct ByteWriter : IWriter { private const int DEFAULTSIZE = 64; #pragma warning disable IDE0032 private byte[] m_buffer; private int m_offset; private readonly bool m_isFixedSize; #pragma warning restore IDE0032 /// <summary> /// The length of the <see cref="ByteWriter"/>. /// </summary> public int Length => m_buffer.Length; /// <summary> /// The current write offset. /// </summary> public int Offset => m_offset; /// <summary> /// Determines if the <see cref="ByteWriter"/> has a fixed size. /// </summary> public bool IsFixedSize => m_isFixedSize; /// <summary> /// Gets the internal buffer used by the <see cref="ByteWriter"/>. /// Do not modify the buffer while performing write operations. /// </summary> public byte[] Buffer => m_buffer; /// <summary> /// Creates a new instance of <see cref="ByteWriter"/> with an empty byffer. /// </summary> /// <param name="initialSize">The initial size of the buffer.</param> /// <param name="isFixedSize">Determines if the buffer is allowed to increase its size automatically.</param> public ByteWriter(int initialSize, bool isFixedSize) { if (initialSize < 1) throw new ArgumentException(nameof(initialSize)); m_buffer = new byte[initialSize]; m_isFixedSize = isFixedSize; m_offset = 0; } /// <summary> /// Creates a new instance of <see cref="ByteWriter"/> from an existing buffer. /// </summary> /// <param name="data">The buffer to use with this writer.</param> public ByteWriter(byte[] data) : this(data, true) { } /// <summary> /// Creates a new instance of <see cref="ByteWriter"/> from an existing buffer. /// </summary> /// <param name="buffer">The buffer to use with this writer.</param> /// <param name="isFixedSize">Determines if the buffer is allowed to increase its size automatically.</param> public ByteWriter(byte[] data, bool isFixedSize) { m_buffer = data ?? throw new ArgumentNullException(nameof(data)); m_isFixedSize = isFixedSize; m_offset = 0; } /// <summary> /// Creates a new instance of <see cref="ByteWriter"/> from an existing buffer. /// </summary> /// <param name="data">The byte array to wrap.</param> /// <param name="offset">The write offset.</param> public ByteWriter(byte[] data, int offset) { m_buffer = data ?? throw new ArgumentNullException(nameof(data)); if ((uint)offset >= data.Length) throw new ArgumentOutOfRangeException(nameof(offset), "Offset is larger than array length."); m_isFixedSize = true; m_offset = offset; } /// <summary> /// Increases the write offset by some amount. /// </summary> /// <param name="amount">The amounts of bytes to skip.</param> public void SkipBytes(int amount) { if (amount < 1) throw new ArgumentOutOfRangeException(nameof(amount), "Amount needs to be at least 1."); EnsureCapacity(amount); m_offset += amount; } /// <summary> /// Resizes the current buffer to the current write offset. /// Performs an array copy. /// </summary> public void Trim() { ArrayExtensions.ResizeUnsafe(ref m_buffer, m_offset); } /// <summary> /// Resets the offset to zero. /// </summary> public void Clear() { m_offset = 0; } /// <summary> /// Reserves 4-bytes of space for a size value at the start of the <see cref="ByteWriter"/>. /// </summary> public void ReserveSizePrefix() { SkipBytes(sizeof(int)); } /// <summary> /// Writes the total size at the start of the <see cref="ByteWriter"/> as an <see cref="int"/>. /// </summary> public int PrefixSize() { BinaryHelper.Write(m_buffer, 0, m_offset); return m_offset; } /// <summary> /// Writes a blittable struct or primitive value to the <see cref="ByteWriter"/>. /// </summary> /// <typeparam name="T">The type of the blittable struct/primitive.</typeparam> public void Write<T>(T value) where T : unmanaged { unsafe { int size = sizeof(T); EnsureCapacity(size); BinaryHelper.Write(m_buffer, m_offset, value); m_offset += size; } } /// <summary> /// Tries to write a blittable struct or primitive value to the <see cref="ByteWriter"/>. /// </summary> /// <typeparam name="T">The type of the blittable struct/primitive.</typeparam> /// <returns>Returns false if the value couldn't be written.</returns> public bool TryWrite<T>(T value) where T : unmanaged { unsafe { int size = sizeof(T); if (m_offset + size > Length) return false; BinaryHelper.Write(m_buffer, m_offset, value); m_offset += size; } return true; } /// <summary> /// Writes a byte array to the <see cref="ByteWriter"/>. /// </summary> /// <param name="includeSize">TRUE to include the size as an uint16</param> public void WriteBytes(byte[] value, bool includeSize = false) { if (includeSize) { if (value.Length > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(value), "Maximum size of 65.535 exceeded."); Write((ushort)value.Length); } EnsureCapacity(value.Length); BinaryHelper.WriteBytes(m_buffer, m_offset, value); m_offset += value.Length; } /// <summary> /// Writes a string as a double-byte character set. Each character requires 2 bytes. /// </summary> /// <param name="includeSize">TRUE to include the size as an uint16</param> public void WriteUTF16(string value, bool includeSize = false) { if (includeSize) { if (value.Length > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(value), "Maximum size of 65.535 exceeded."); Write((ushort)value.Length); } EnsureCapacity(value.Length * sizeof(char)); StringHelper.WriteUTF16(m_buffer, m_offset, value); m_offset += value.Length * sizeof(char); } /// <summary> /// Writes a string in ANSI encoding. Each character requires 1 byte. /// </summary> /// <param name="includeSize">TRUE to include the size as an uint16</param> public void WriteANSI(string value, bool includeSize = false) { if (includeSize) { if (value.Length > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(value), "Maximum size of 65.535 exceeded."); Write((ushort)value.Length); } EnsureCapacity(value.Length); StringHelper.WriteANSI(m_buffer, m_offset, value); m_offset += value.Length; } /// <summary> /// Writes a string to the <see cref="ByteWriter"/>. /// Includes the bytesize as a uint16. /// </summary> public void WriteString(string value, Encoding encoding) { int byteCount = encoding.GetByteCount(value); if (byteCount > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(value), "String is too large to be written."); EnsureCapacity(byteCount + sizeof(ushort)); Write((ushort)byteCount); StringHelper.WriteString(m_buffer, m_offset, value, encoding); } /// <summary> /// Copies the inner buffer to a supplied buffer. /// </summary> /// <param name="buffer">The destination for the data.</param> public void CopyTo(byte[] buffer) { CopyTo(buffer, 0, m_offset); } /// <summary> /// Copies the inner buffer to a supplied buffer. /// </summary> /// <param name="buffer">The destination for the data.</param> public void CopyTo(byte[] buffer, int destinationIndex) { CopyTo(buffer, destinationIndex, m_offset); } /// <summary> /// Copies the inner buffer to a supplied buffer. /// </summary> /// <param name="buffer">The destination for the data.</param> /// <param name="length">The total length to copy (starting from 0)</param> public void CopyTo(byte[] buffer, int destinationIndex, int length) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if ((uint)(destinationIndex + length) > buffer.Length) throw new ArgumentOutOfRangeException("Copy action exceeds the supplied buffer!"); if ((uint)length > Length) throw new ArgumentOutOfRangeException(nameof(length)); m_buffer.CopyToUnsafe(0, buffer, destinationIndex, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureCapacity(int bytesToAdd) { int newAmount = m_offset + bytesToAdd; if (newAmount > Length) ResizeInternal(newAmount); } private void ResizeInternal(int resizeTo) { if (m_isFixedSize) ExceptionHelper.ThrowFixedBufferExceeded(); ArrayExtensions.ResizeUnsafe(ref m_buffer, MathUtils.NextPowerOfTwo(resizeTo)); } } }
07177b96cdd96e9101f72a8ca95c2fa362e93ffb
C#
sensoguyz-realsense-hackathon/extension-generator
/RealSense/ViewModel/MainWindowViewModel.cs
2.671875
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Input; using System.Xml.Serialization; using GeneratorLibrary; using Newtonsoft.Json; using RealSense.Commands; using OpenFileDialog = Microsoft.Win32.OpenFileDialog; namespace RealSense.ViewModel { public class MainWindowViewModel : ViewModelBase { public const string PathToProject = "instahandless"; public const string RealSenseExtensionString = "RealSense Extension"; #region Private Fields private string _configFilePath; private string _directoryPath; private string _fileName; private string _directoryName; #endregion #region Public Fields public string FileName { get { return _fileName; } set { _fileName = value; OnProprtyChanged("FileName"); } } public string DirectoryName { get { return _directoryName; } set { _directoryName = value; OnProprtyChanged("DirectoryName"); } } public ICommand ChooseConfigCommand { get; set; } public ICommand ChooseDirectoryCommand { get; set; } public ICommand CompileCommand { get; set; } #endregion #region Ctors public MainWindowViewModel() { ChooseConfigCommand = new RelayCommand(ChooseConfigExecute); ChooseDirectoryCommand = new RelayCommand(ChooseDirectoryExecute); CompileCommand = new RelayCommand(CompileExecute, CompileCanExecute); } #endregion #region Private Methods void ChooseConfigExecute() { var dialog = new OpenFileDialog(); dialog.Filter = "Json file | *.json"; if (dialog.ShowDialog() ?? false) { _configFilePath = dialog.FileName; FileName = dialog.SafeFileName; } } void ChooseDirectoryExecute() { var dialog = new FolderBrowserDialog(); if (dialog.ShowDialog()==DialogResult.OK) { _directoryPath = dialog.SelectedPath; DirectoryName = Path.GetFileName(dialog.SelectedPath); } } bool CompileCanExecute() { return !string.IsNullOrEmpty(FileName) && !string.IsNullOrEmpty(DirectoryName); } void CompileExecute() { try { var json = File.ReadAllText(_configFilePath); dynamic config = JsonConvert.DeserializeObject(json); var path = _directoryPath + "/" + config.name + " " + RealSenseExtensionString; if (Directory.Exists(path)) if ( MessageBox.Show("Current extension already generated.\n\nDo you want replace this extension?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) Directory.Delete(path, true); else return; FolderManager.CopyDir(new DirectoryInfo(PathToProject), _directoryPath + "/" + config.name + " " + RealSenseExtensionString); } catch (Exception ex) { // MessageBox.Show("Something goes wrong"); MessageBox.Show(ex.Message); } MessageBox.Show("Extension generate sucessfully", "Generate complete", MessageBoxButtons.OK); } #endregion } }
68bff3e376b05a94f554ea50242dec8f67c0c3d1
C#
sibbl/advent-of-code-2020
/AdventOfCode2020/Day12/Solution12.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AdventOfCode2020.Day12 { public static class Solution12 { private static Task<IEnumerable<string>> ReadInputAsync() => InputReader.ReadLinesAsync("Day12/input.txt"); private record Instruction(char Action, int Value) { public static Instruction FromString(string line) => new(line[0], int.Parse(line[1..])); } private enum DirectionsMovementBehavior { DirectionsMoveShip, DirectionsMoveWayPoint }; private class Vector { public long X { get; set; } public long Y { get; set; } public Vector(long x, long y) => (X, Y) = (x, y); public static Vector operator +(Vector v1, Vector v2) => new(v1.X + v2.X, v1.Y + v2.Y); public static Vector operator *(Vector v1, Vector v2) => new(v1.X * v2.X, v1.Y * v2.Y); public static Vector operator *(Vector v, long value) => new(v.X * value, v.Y * value); } private class Route { private readonly IEnumerable<Instruction> _instructions; private readonly DirectionsMovementBehavior _directionsMovementBehavior; private Vector _position = new(0, 0); private Vector _movementVector; public Route(IEnumerable<string> instructionInput) : this(instructionInput, new Vector(1, 0), DirectionsMovementBehavior.DirectionsMoveShip) { } public Route(IEnumerable<string> instructionInput, Vector movementVector, DirectionsMovementBehavior directionsMovementBehavior) { _instructions = instructionInput.Select(Instruction.FromString); _movementVector = movementVector; _directionsMovementBehavior = directionsMovementBehavior; } private void MoveIntoDirection(char direction, int value) { var vector = direction switch { 'E' => new Vector(1, 0), 'W' => new Vector(-1, 0), 'N' => new Vector(0, 1), 'S' => new Vector(0, -1), _ => throw new Exception("Invalid direction " + direction) }; switch (_directionsMovementBehavior) { case DirectionsMovementBehavior.DirectionsMoveShip: _position += vector * value; break; case DirectionsMovementBehavior.DirectionsMoveWayPoint: _movementVector += vector * value; break; default: throw new NotImplementedException("Behavior not implemented: " + _directionsMovementBehavior); } } private void Turn(char turnAction, int degrees) { if (turnAction == 'L') { degrees *= -1; } while (degrees < 0) { degrees += 360; } _movementVector = (degrees % 360) switch { 0 => _movementVector, 90 => new Vector(_movementVector.Y, _movementVector.X * -1), 180 => new Vector(_movementVector.X * -1, _movementVector.Y * -1), 270 => new Vector(_movementVector.Y * -1, _movementVector.X), _ => throw new ArgumentException("Unsupported degrees: " + degrees) }; } public Vector MoveToEndPosition() { foreach (var (action, value) in _instructions) { switch (action) { case 'E': case 'S': case 'W': case 'N': MoveIntoDirection(action, value); break; case 'L': case 'R': Turn(action, value); break; case 'F': _position += (_movementVector * value); break; default: throw new NotImplementedException("Action not implemented: " + action); } } return _position; } } #region Problem One public static async Task<long> ProblemOneAsync(IEnumerable<string> lines = null) { lines ??= await ReadInputAsync(); var endPosition = new Route(lines).MoveToEndPosition(); return Math.Abs(endPosition.X) + Math.Abs(endPosition.Y); } #endregion #region Problem Two public static async Task<long> ProblemTwoAsync(IEnumerable<string> lines = null) { lines ??= await ReadInputAsync(); var endPosition = new Route(lines, new Vector(10, 1), DirectionsMovementBehavior.DirectionsMoveWayPoint) .MoveToEndPosition(); return Math.Abs(endPosition.X) + Math.Abs(endPosition.Y); } #endregion } }
bfa0d3c68b3389f3b2c7781db06b7cdd5d9f86e7
C#
jahanzaib4587/ATM_Project
/LogicLayers/UserMenuItems.cs
2.96875
3
using DataAccessLayer; using ObjectModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace LogicLayers { public class UserMenuItems { readonly parentInput p; readonly List<UserObj> list; public DateTime today; public UserMenuItems() { p = new parentInput(); list = p.ReadData(); today = DateTime.Today; } public void FastCash(NameAndPswd val, int value) { int userId = 0; for (int i = 0; i < list.Count; i++) { if (list[i].ID == val.SignedUserName) { if (value <= list[i].cash) { userId = list[i].UserID; list[i].cash = list[i].cash - value; list[i].date = today; CopyTransactionData(list, userId, "withdraw", value); Console.WriteLine("Cash Suceessfully Withdrawn"); char c; receiptCheck: Console.Write("\nDo you wish to print a receipt(y/n)?"); try { c = System.Convert.ToChar(Console.ReadLine()); } catch (Exception) { Console.WriteLine("Please enter valid value (y/n)!"); goto receiptCheck; } if (c.Equals('y') || c.Equals('Y')) { Console.WriteLine($"\nAccount #{list[i].UserID}\nDate: {list[i].date.ToString("dd/MM/yyyy")}\n\nWithdrawn : {value}\nBalance :{list[i].cash}\n"); break; } else if (c.Equals('n') || c.Equals('N')) { break; } else { Console.WriteLine("\nPlease choose right choice from (y/n)"); goto receiptCheck; } } else { Console.WriteLine("You dont have enough balance"); break; } } } p.writeData(list); } public void NormalCash(NameAndPswd val, decimal value) { int userId = 0; for (int i = 0; i < list.Count; i++) { if (list[i].ID == val.SignedUserName && value <= list[i].cash) { userId = list[i].UserID; list[i].cash = list[i].cash - value; //today = DateTime.Today; list[i].date = today; Console.WriteLine($"\nAccount #{list[i].UserID}\nDate: {list[i].date.ToString("dd/MM/yyyy")}\n\nWithdrawn : {value}\nBalance :{list[i].cash}\n"); CopyTransactionData(list, userId, "withdraw", System.Convert.ToInt32(value)); p.writeData(list); } } } ///DeositCash public void DepositCash(NameAndPswd val, decimal value) { int userId = 0; for (int i = 0; i < list.Count; i++) { if (list[i].ID == val.SignedUserName) { userId = list[i].UserID; list[i].cash = list[i].cash + value; list[i].date = today; Console.WriteLine("Cash Deposited Suceessfully."); CopyTransactionData(list, userId, "deposit", System.Convert.ToInt32(value)); char c; receiptCheck: Console.Write("\nDo you wish to print a receipt(y/n)?"); try { c = System.Convert.ToChar(Console.ReadLine()); } catch (Exception) { Console.WriteLine("Please enter valid value (y/n)!"); goto receiptCheck; } if (c.Equals('y') || c.Equals('Y')) { Console.WriteLine($"\nAccount #{list[i].UserID}\nDate: {list[i].date.ToString("dd/MM/yyyy")}\n\nDeposited : {value}\nBalance :{list[i].cash}\n"); break; } else if (c.Equals('n') || c.Equals('N')) { break; } else { Console.WriteLine("Please enter valid value (y/n)!"); goto receiptCheck; } } } p.writeData(list); } public void DisplayBalance(NameAndPswd val) { for (int i = 0; i < list.Count; i++) { if (list[i].ID == val.SignedUserName) { Console.WriteLine($"Account #{list[i].UserID}\nDate: {today.ToString("dd/MM/yyyy")}\n\nBalance: {list[i].cash}\n "); break; } } } public void DeleteAccount(int AccNo) { int AccNoCheck; for (int i = 0; i < list.Count; i++) { if (list[i].UserID == AccNo && list[i].UserType != "admin") { AccountNoCheck: Console.WriteLine($"You wish to delete the account held by Mr.{list[i].ID}; \nIf this information is correct please re-enter the account number: "); try { AccNoCheck = System.Convert.ToInt32(Console.ReadLine()); } catch (Exception) { Console.WriteLine("Please Enter valid account No."); goto AccountNoCheck; } if (AccNo == AccNoCheck) { list.RemoveAt(i); Console.WriteLine("\nAccount Deleted Successfully\n"); p.writeData(list); return; } } } } /// <summary> public void searchForAccount(UserObj obj, string AccId, string name, string type, string balance, string status) { List<UserObj> lst = new List<UserObj>(); for (int i = 0; i < list.Count; i++) { if ((AccId.Equals("") ? true : list[i].UserID == obj.UserID) && (balance.Equals("") ? true : list[i].cash == obj.cash) && (name.Equals("") ? true : list[i].ID.Equals(obj.ID)) && (type.Equals("") ? true : list[i].type.Equals(obj.type)) && (status.Equals("") ? true : list[i].status.Equals(obj.status))) { lst.Add(list[i]); } } Console.WriteLine("SEARCH MENU:\n"); foreach (UserObj o in lst) { string s = string.Format( "\nAccount ID User ID Holders Name Type Balance Status\n {0,-10} {1,-10} {2,-15} {3,-10} {4,-8} {5,-10} ", o.UserID, o.ID, o.name, o.type, o.cash, o.status ); Console.WriteLine(s); } } /// </summary> public void UpdateAccount(int AccNo) { for (int i = 0; i < list.Count; i++) { if (list[i].UserID == AccNo) { Console.WriteLine($"Account # {list[i].UserID}\nType: {list[i].UserType}\nHolder: {list[i].name}\nBalance: {list[i].cash}\nStatus: {list[i].status}\n\n"); Console.WriteLine($"Please enter in the field you wish to update(leave blank otherwise)\nLogin: "); string logIn = Console.ReadLine(); Console.Write("Holder's Name: "); string name = Console.ReadLine(); pinCheck: Console.Write("Enter 5-digit Pin Code: "); string pin; pin = Console.ReadLine(); try { if (pin.ToString().Length > 0) { if (pin.ToString().Length == 5) { list[i].pswd = System.Convert.ToInt32(pin); } else { Console.WriteLine("Enter valid 5-digit pin"); goto pinCheck; } } } catch { Console.WriteLine("Enter valid 5-digit pin"); goto pinCheck; } if (logIn.Length > 0) { list[i].ID = logIn; } if (name.Length > 0) { list[i].name = name; } Console.WriteLine("\nAccount Information Updated Successfully\n"); p.writeData(list); } } } public void AccountsByAmount(int maxAmount, int minAmount) { Console.WriteLine("\n===== Search Results =====\n"); for (int i = 0; i < list.Count; i++) { if (list[i].cash >= minAmount && list[i].cash <= maxAmount) { string s = string.Format( "User ID Holders Name Amount Date\n {0,-6} {1,-18} {2,-10} {3,-8} ", list[i].UserID, list[i].name, list[i].cash, list[i].date.ToString("dd/MM/yyyy") ); Console.WriteLine(s); } } } public void ReduceAmount(decimal amount, NameAndPswd SignedInUser) { int userId = 0; for (int i = 0; i < list.Count; i++) { if (list[i].ID.Equals(SignedInUser.SignedUserName)) { userId = list[i].UserID; Console.Write($"Previoius Balance :{list[i].cash}\n"); list[i].cash -= amount; Console.WriteLine($"Remaining Balance: { list[i].cash}\nYou have successfully Transferred Rs.{amount}\n"); CopyTransactionData(list, userId, "Cash Transfer", System.Convert.ToInt32(amount)); } } p.writeData(list); } public void CashTransfer(decimal amount, int AccNo, NameAndPswd SignedInUser) { for (int i = 0; i < list.Count; i++) { if (list[i].UserID == AccNo) { list[i].cash += amount; ReduceAmount(amount, SignedInUser); CopyTransactionData(list, AccNo, "Cash Recieved", System.Convert.ToInt32(amount)); } } p.writeData(list); } public int nextUserId() { int lastUserId = 0; for (int i = 0; i < list.Count; i++) { lastUserId = list[i].UserID; } return lastUserId + 1; } public bool checkAccountBalance(int amount, NameAndPswd SignedInUser) { bool result = false; for (int i = 0; i < list.Count; i++) { if (list[i].ID.Equals(SignedInUser.SignedUserName)) { if (list[i].cash >= amount) { result = true; break; } } } return result; } public bool checkAccountNumber(int AccNo) { bool result = false; for (int i = 0; i < list.Count; i++) { if (list[i].UserID == AccNo) { result = true; break; } } return result; } public void createNewUser() { UserObj obj = new UserObj(); enterAgain: Console.Write("Login: "); string logIn = Console.ReadLine(); if (logIn.Length > 0) { obj.ID = logIn; } else { Console.WriteLine("Please enter right user name"); goto enterAgain; } pinCode: Console.Write("Pin Code: "); try { int pswd = System.Convert.ToInt32(Console.ReadLine()); if (pswd.ToString().Length == 5) { obj.pswd = pswd; } else { Console.WriteLine("Please enter 5-digit pin"); goto pinCode; } } catch (Exception) { Console.Write("You have intered invalid Pin! Please enter 5-digit pin in numbers only"); goto pinCode; } enterAgainName: Console.Write("Holder's Name: "); string name = Console.ReadLine(); if (name.Length > 0) { obj.name = name; } else { Console.WriteLine("Please enter valid logIn Id"); goto enterAgainName; } typeCheck: Console.Write("Type (saving,current): "); string type = Console.ReadLine(); if (type.Equals("saving") || type.Equals("current")) { obj.type = type; } else { Console.WriteLine("You have entered invalid value! Please enter correct account type (saving OR current)"); goto typeCheck; } startingBalance: Console.Write("Starting Balance: "); try { obj.cash = System.Convert.ToDecimal(Console.ReadLine()); } catch { Console.WriteLine("You have entered invalid value! Please enter correct amount"); goto startingBalance; } statusCheck: Console.Write("Status (active/deactive): "); string status = Console.ReadLine(); if (status.Equals("active") || status.Equals("deactive")) { obj.status = status; } else { Console.WriteLine("You have entered invalid value! Please enter correct account status"); goto statusCheck; } obj.UserID = nextUserId(); obj.UserType = "user"; obj.date = DateTime.Today; parentInput p = new parentInput(); p.CreateNewAccount(obj); Console.WriteLine($"\nAccount Successfully Created - the account number assigned is: {obj.UserID}"); } public void CopyTransactionData(List<UserObj> list, int UserId, string type, int cash) { TransactionsReadWrite tr = new TransactionsReadWrite(); TransactionObj obj = new TransactionObj(); for (int i = 0; i < list.Count; i++) { if (list[i].UserID == UserId) { obj.TransactionType = type; obj.ID = list[i].ID; obj.name = list[i].name; obj.amount = cash; obj.date = System.Convert.ToDateTime(DateTime.Today.ToString("dd/MM/yyyy")); } } tr.AddNewTransaction(obj); } public void AccountsByDate(string startDate, string endDate) { TransactionsReadWrite t = new TransactionsReadWrite(); List<TransactionObj> list; list = t.ReadTransactionData(); for (int i = 0; i < list.Count; i++) { if (list[i].date.Date >= System.Convert.ToDateTime(startDate).Date && list[i].date.Date <= System.Convert.ToDateTime(endDate).Date) { string s = string.Format( "Transaction Type User ID Holders Name Amount Date\n {0,-16} {1,-8} {2,-12} {3,-8} {4}", list[i].TransactionType, list[i].ID, list[i].name, list[i].amount, list[i].date.ToString("dd/MM/yyyy") ); Console.WriteLine(s); } else { Console.WriteLine("No record found"); } } } } }
8102fc51718f6998d9fa3e2752e8374a7610ec0a
C#
rainchan/weitao
/WT.Services/WT.Services.AccessToken/trunk/src/WT.Services.AccessToken.Repository/WeiXinAccessTokenRepository.cs
2.6875
3
using System; using WT.Services.AccessToken.Models; namespace WT.Services.AccessToken.Repository { class WeiXinAccessTokenRepository : CacheRepository<WeiXinAccessTokenItem> { private const string CacheKey = "LocalWeiXinAccessTokenItem"; /// <summary> /// 缓存时间(分钟) /// </summary> private const int CacheExpire = 90; /// <summary> /// 获取实例 /// </summary> public static WeiXinAccessTokenRepository Instance = null; static WeiXinAccessTokenRepository() { Instance = new WeiXinAccessTokenRepository(); } /// <summary> /// /// </summary> /// <returns></returns> public override WeiXinAccessTokenItem Get() { var token = base.Get(); if (token == null || String.IsNullOrEmpty(token.access_token)) { return null; } return token; } protected override string GetCacheKey() { return CacheKey; } protected override DateTime GetCacheExpire() { return DateTime.Now.AddMinutes(CacheExpire); } } }
d9592a6fe594795977bc91c6051b12cfdd4f882c
C#
ExoMemphiz/Testing_Framework
/Testing_Framework/DataHandling/VigoHandling.cs
2.5625
3
using System; using VigoInterfaceMTA; namespace Testing_Framework.DataHandling { public class VigoHandling { private static VigoInterface vigo; public static String GetValueAsString(String fullID) { return GetValueAsString(fullID, ""); } public static String GetValueAsString(String physID, String partialID) { VigoInterface vigo = GetVigo(); String str = ""; vigo.GetString(physID + partialID, ref str); return str; } public static bool SetValue(String fullID, object value) { return SetValue(fullID, "", value); } public static bool SetValue(String physID, String partialID, object value) { VigoInterface vigo = GetVigo(); return vigo.setValue(physID + partialID, value); } private static VigoInterface GetVigo() { if (vigo == null) { vigo = new VigoInterface(); } return vigo; } } }
959af47f81691ca14c355d26f463f0508cb52b0a
C#
jbraulio85/dotnet-test-kalum2021
/ModelsView/CarrerasTecnicasViewModel.cs
2.59375
3
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using kalum2021.Models; using kalum2021.Views; using MahApps.Metro.Controls.Dialogs; using System.Linq; using kalum2021.DataContext; namespace kalum2021.ModelsView { public class CarrerasTecnicasViewModel : INotifyPropertyChanged, ICommand { private ObservableCollection<CarrerasTecnicas> _Carreras; public ObservableCollection<CarrerasTecnicas> carreras { get { if (this._Carreras == null) { this._Carreras = new ObservableCollection<CarrerasTecnicas>(dBContex.CarrerasTecnicas.ToList()); } return this._Carreras; } set { this._Carreras = value; } } public CarrerasTecnicasViewModel Instancia { get; set; } public CarrerasTecnicas Seleccionado { get; set; } public event PropertyChangedEventHandler PropertyChanged; public event EventHandler CanExecuteChanged; private IDialogCoordinator dialogCoordinator; private KalumDBContext dBContex = new KalumDBContext(); public CarrerasTecnicasViewModel(IDialogCoordinator instance) { this.Instancia = this; this.dialogCoordinator = instance; } public void NotificarCambio(string propiedad) { if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propiedad)); } } public void agregarElemento(CarrerasTecnicas nuevo) { this.carreras.Add(nuevo); } public bool CanExecute(object parametro) { return true; } public async void Execute(object parametro) { if(parametro.Equals("Nuevo")) { this.Seleccionado = null; CarreraTecnicaView nuevaCarrera = new CarreraTecnicaView(Instancia); nuevaCarrera.Show(); } else if(parametro.Equals("Eliminar")) { if(this.Seleccionado == null) { await this.dialogCoordinator.ShowMessageAsync(this,"Carreras","Debe de seleccionar un elemento", MessageDialogStyle.Affirmative); } else { MessageDialogResult respuesta = await this.dialogCoordinator.ShowMessageAsync(this,"Eliminar Carrera", "¿Está seguro de eliminar el registro?",MessageDialogStyle.AffirmativeAndNegative); if(respuesta == MessageDialogResult.Affirmative) { try { int posicion = this.carreras.IndexOf(this.Seleccionado); this.dBContex.Remove(this.Seleccionado); this.dBContex.SaveChanges(); this.carreras.RemoveAt(posicion); await this.dialogCoordinator.ShowMessageAsync(this,"Carreras","El registro fue eliminado correctamente"); }catch (Exception e) { await this.dialogCoordinator.ShowMessageAsync(this,"Error",e.Message); } } } } else if(parametro.Equals("Modificar")) { if(this.Seleccionado == null) { await this.dialogCoordinator.ShowMessageAsync(this,"Carreras","Debe de seleccionar un elemento", MessageDialogStyle.Affirmative); } else { CarreraTecnicaView modificarCarrera = new CarreraTecnicaView(Instancia); modificarCarrera.ShowDialog(); } } } } }
53279a5311f28ac076bc4dbc9aac8fb12fe493fe
C#
qimolin/logic-engineering
/logic-engineering/Operators/Implication.cs
2.859375
3
using System.Collections.Generic; namespace logic_engineering { public class Implication : PropNode { public Implication() { this.Value = '>'; } public override bool Evaluate(Dictionary<char, bool> cases) { bool left = Left.Evaluate(cases); bool right = Right.Evaluate(cases); // Switcheroo-1 law return !left || right; } public override string Nandify() { string nand = $"%({Left.Nandify()},%({Right.Nandify()},{Right.Nandify()}))"; return nand; } } }
2e5c8bab5a1c6458642ecce8984858e4c598c52c
C#
LogoFX/logofx-client-mvvm-viewmodel-extensions
/src/LogoFX.Client.Mvvm.ViewModel.Extensions/IPagingViewModel.cs
2.8125
3
namespace LogoFX.Client.Mvvm.ViewModel.Extensions { /// <summary> /// Represents paging view model, i.e. an object that can display a collection of view models in pages. /// </summary> public interface IPagingViewModel { /// <summary> /// Gets or sets the total pages count. /// </summary> /// <value> /// The total pages count. /// </value> int TotalPages { get; set; } /// <summary> /// Gets or sets the left value of the page rectangle. /// </summary> /// <value> /// The left value of the page rectangle. /// </value> double PageLeft { get; set; } /// <summary> /// Gets or sets the width of the page. /// </summary> /// <value> /// The width of the page. /// </value> double PageWidth { get; set; } /// <summary> /// Gets or sets the current page. /// </summary> /// <value> /// The current page. /// </value> int CurrentPage { get; set; } /// <summary> /// Restores the selection. /// </summary> void RestoreSelection(); } }
ba5d8a60ccd0538f88299cfc642776ee9ed66fb5
C#
tookindie/CSharpPlayersGuideSolutions
/Level38-LambdaExpressions/TheLambdaSieve/Program.cs
4.09375
4
using System; Console.Write("Which filter do you want to use? (1=Even, 2=Positive, 3=MultipleOfTen) "); int choice = Convert.ToInt32(Console.ReadLine()); Sieve sieve = choice switch { 1 => new Sieve(n => n % 2 == 0), 2 => new Sieve(n => n > 0), 3 => new Sieve(n => n % 10 == 0) }; while (true) { Console.Write("Enter a number: "); int number = Convert.ToInt32(Console.ReadLine()); string goodOrEvil = sieve.IsGood(number) ? "good" : "evil"; Console.WriteLine($"That number is {goodOrEvil}."); } public class Sieve // This is just a wrapper around a `Func<int, bool>` variable. We could have used just that instead in this specific situation. { private Func<int, bool> _decisionFunction; public Sieve(Func<int, bool> decisionFunction) => _decisionFunction = decisionFunction; public bool IsGood(int number) { return _decisionFunction(number); } } // Answer this question: Does this change make the program shorter or longer? // // The program got _slightly_ shorter. I think I removed 3 lines of code and maybe a blank line. // // Answer this question: Does this change make the program easier to read or harder? // // I'll admit, when designing this problem, I had assumed it would make the program both shorter // and easier to read--a win-win. In actuality, it makes it only a little shorter (the `Sieve` // class and the looping mechanism dominate the line count). But notably, in terms of // readability, I'm not convinced it makes it better there either. The problem with readability // in this case is that a line like `2 => new Sieve(n => n > 0),` doesn't immediately make // it clear that I did it right. I have to look up what the `2` means from above. // // Had I done the switch as a string instead of an int, and had the line looked like // `"even" => new Sieve(n => n > 0),` then I might say that it does make the code easier to // understand. // // While it didn't have the attributes I had initially presumed, it is still a meaningful // thing to think about. You always want your code to be understandable upon reading it, // and while lambdas often improve readability _and_ shorten the code, that is not a hard // and fast rule. You must always be keeping the tradeoffs in mind as you deal with specific // situations.
84de591cbfd862fe7c3de4d4a3d702884467c4eb
C#
starkos/industrious-redux
/Industrious.Redux/MockStore.cs
2.90625
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Industrious.Redux.Internals; namespace Industrious.Redux { /// <summary> /// A mock version of the store to assist with testing. Captures, but does /// not dispatch, incoming actions, and enables simulation of store changes. /// </summary> public class MockStore<TState> : StoreBase<TState> { readonly List<Object> _dispatchedActions = new List<Object>(); public MockStore(TState initialState = default(TState)) { CurrentState = initialState; ReceivedActions = new ReadOnlyCollection<Object>(_dispatchedActions); } /// <summary> /// Replaces the store state with a new value. Does not fire any projections, /// use <see cref="Publish{T}(ValueProjector{TState, T}, T)" /> to do so. /// </summary> public void SetState(TState state) { CurrentState = state; } public override void Dispatch(Object action) { _dispatchedActions.Add(action); } /// <summary> /// Returns a list of all actions that have been received by the store, /// in the order in which they were received. /// </summary> public ReadOnlyCollection<Object> ReceivedActions { get; } /// <summary> /// Send a value to all subscribers of a projection, simulating a change /// to the store state. /// </summary> /// <param name="projector"> /// The projection function being simulated. The function is not called. /// </param> /// <param name="value"> /// The value to be sent to the project subscribers. /// </param> public void Publish<T>(ValueProjector<TState, T> projector, T value) { if (projector == null) throw new ArgumentNullException(nameof(projector)); var observable = GetObservableForProjection<T>(projector); observable?.PublishValue(value); } /// <summary> /// Send a value to all subscribers of a collection item projection, /// simulating a change to the item state. /// </summary> /// <param name="projector"> /// The projection function being simulated. The function is not called. /// </param> /// <param name="key"> /// The collection key of the item being simulated. /// </param> /// <param name="value"> /// The value to be sent to the project subscribers. /// </param> public void Publish<T, K>(ElementProjector<TState, T, K> projector, K key, T value) { if (projector == null) throw new ArgumentNullException(nameof(projector)); var observable = GetObservableForProjection<T>(Tuple.Create(projector, key)); observable?.PublishValue(value); } } }
5114debb883ba5380281f105bcb528768e7a18b8
C#
dredix/photorganiser
/FileUtils.cs
3.03125
3
using System; using System.IO; using System.Windows.Media.Imaging; namespace photorganiser { public static class FileUtils { // http://stackoverflow.com/a/2281704/1014 public static DateTime? GetDateTakenFromImage(FileInfo file) { try { using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { BitmapSource img = BitmapFrame.Create(fs); BitmapMetadata md = (BitmapMetadata)img.Metadata; return DateTime.Parse(md.DateTaken); } } catch (Exception) { return null; } } public static bool FileCompare(FileInfo file1, FileInfo file2) { if (file1.Length != file2.Length) return false; using (FileStream fs1 = file1.OpenRead()) using (FileStream fs2 = file2.OpenRead()) { for (int i = 0; i < file1.Length; i++) { if (fs1.ReadByte() != fs2.ReadByte()) return false; } } return true; } } }
a49a2e2dd9c430e7226f5cbb90720aacd40c522d
C#
atrodriguez88/Secretaria
/Secretaria/DXWindowsApplication1/Clases/Carrera.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.OleDb; using System.Data; using System.Drawing; namespace DXWindowsApplication1 { class Carrera { private int IdCArrera; private string nombre; private int idFacultad; public Carrera(int a) { IdCArrera = 0; nombre = ""; idFacultad = a; } public int GetIdCarr() { return IdCArrera; } public bool Add(string nombre, int idFacultad) { string query = "INSERT INTO Carrera (nombre, idFacultad) VALUES ('" + nombre + "', " + idFacultad + ")"; Conexion con = new Conexion(); return con.Actualizar(query); } public static DataTable Todo() { string query = "Select * from Carrera"; Conexion con = new Conexion(); DataTable tabla = con.Selecionar(query); return tabla; } public static DataTable Todo_Nombre(string n) { string query = "Select * from Carrera WHERE nombre ='" + n + "'"; Conexion con = new Conexion(); DataTable tabla = con.Selecionar(query); return tabla; } public static DataTable TodoCarrera_id(int facultad) { string query = "Select * from Carrera WHERE idFacultad =" + facultad + ""; Conexion con = new Conexion(); DataTable tabla = con.Selecionar(query); return tabla; } public static DataTable ID(string nombre) { string query = "Select IdCArrera from Carrera WHERE nombre ='" + nombre + "'"; Conexion con = new Conexion(); DataTable tabla = con.Selecionar(query); return tabla; } public static DataTable Nombre_Dado_ID(int id) { string query = "Select * from Carrera WHERE IdCArrera =" + id + ""; Conexion con = new Conexion(); DataTable tabla = con.Selecionar(query); return tabla; } public static bool Actualizar(int id, string nuevo, int idFacultad) { string query = "UPDATE Carrera SET nombre = '" + nuevo + "', idFacultad = '" + idFacultad + "' WHERE IdCArrera =" + id + " "; Conexion con = new Conexion(); return con.Actualizar(query); } public static bool Eliminar(int id) { string query = "DELETE FROM Carrera WHERE IdCArrera =" + id + " "; Conexion con = new Conexion(); return con.Actualizar(query); } } }
667ab3e64a07274a5bd7c1f2535f5f73a287150d
C#
benjamine/PiroPiro
/PiroPiro.Selenium/SeleniumElement.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PiroPiro.Contract; using OpenQA.Selenium; using SizSelCsZzz; namespace PiroPiro.Selenium { public class SeleniumElement : Element { private IWebElement element; private SeleniumBrowser SeleniumBrowser; public SeleniumElement(IWebElement element, SeleniumBrowser browser) : base(browser) { this.element = element; this.SeleniumBrowser = browser; } #region ElementImpl protected override IEnumerable<Element> DoQuery(string selector) { return element.FindElements(BySizzle.CssSelector(selector)) .Select(e => new SeleniumElement(e, SeleniumBrowser)); } protected override Element DoQuerySingle(string selector) { return new SeleniumElement(element.FindElement(BySizzle.CssSelector(selector)), SeleniumBrowser); } protected override string DoGetTagName() { return element.TagName; } public override string Text { get { return element.Text; } } public override string Html { get { throw new NotImplementedException(); } } public override string DoGetAttribute(string name) { return element.GetAttribute(name); } public override bool Displayed { get { return element.Displayed && element.Size.Height > 0 && element.Size.Width > 0; } } public override bool Enabled { get { return element.Enabled; } } protected override void DoClick() { element.Click(); } protected override void DoSendKeys(string keys) { element.SendKeys(keys); } protected override void DoClear() { element.Clear(); } protected override void DoSetFile(string path) { // WARNING: selenium driver doesn't support clear on input[type=file], so only send keys SendKeys(path); } protected override PiroPiro.Contract.Element DoGetIFrameContent() { return new SeleniumElement(SeleniumBrowser.Driver.SwitchTo() .Frame(element) .FindElement(By.TagName("html")), SeleniumBrowser); } protected override void DoLeaveIFrameContent() { SeleniumBrowser.Driver.SwitchTo().DefaultContent(); } #endregion } }
63475619dc9f74cf629e9f1a71744b4bcba0f046
C#
touseefbsb/ComboBoxToEnumBug
/App1/App1/IdToIndexConverter.cs
2.515625
3
using System; using Windows.UI.Xaml.Data; namespace App1 { public class IdToIndexConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) => System.Convert.ToInt32(value) - 1; //not needed for one way data binding public object ConvertBack(object value, Type targetType, object parameter, string language) => ((int)value) + 1; } }
b478f6a835d07b6c135b9834fa0459b21bc1226f
C#
sono8stream/AtPractice
/AtTest/CodeForces/1363/D.cs
3.109375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; using static System.Math; namespace AtTest.CodeForces._1363 { class D { static void ain(string[] args) { //var sw = new System.IO.StreamWriter(OpenStandardOutput()) { AutoFlush = false }; //SetOut(sw); Method(args); //Out.Flush(); } static void Method(string[] args) { int t = ReadInt(); for(int i = 0; i < t; i++) { int[] nk = ReadInts(); int n = nk[0]; int k = nk[1]; var sets = new HashSet<int>[n]; for(int j = 0; j < k; j++) { int[] vals = ReadInts(); sets[j] = new HashSet<int>(); for(int l = 1; l < vals.Length; l++) { sets[j].Add(vals[l]); } } Write("? " + n); for(int j = 1;j<= n; j++) { Write(" " + j); } WriteLine(); int max = ReadInt(); int bottom = 0; int top = n - 1; while (bottom < top) { int mid = (bottom + top) / 2; Write("? "+(mid-bottom+1)); for(int j = bottom + 1; j <= mid + 1; j++) { Write(" " + j); } WriteLine(); int now = ReadInt(); if (now == max) { top = mid; } else { bottom = mid + 1; } } int maxIdx = bottom; int maxContainsIdx = 0; for (; maxContainsIdx < k; maxContainsIdx++) { if (sets[maxContainsIdx].Contains(maxIdx + 1)) { break; } } int secondMax; if (maxContainsIdx < k) { Write("? " + (n - sets[maxContainsIdx].Count)); for (int j = 1; j <= n; j++) { if (!sets[maxContainsIdx].Contains(j)) { Write(" " + j); } } WriteLine(); secondMax = ReadInt(); } else { secondMax = max; } Write("! "); for(int j = 0; j < k; j++) { if (j == maxContainsIdx) { Write(" " + secondMax); } else { Write(" " + max); } } WriteLine(); ReadLine(); } } private static string Read() { return ReadLine(); } private static char[] ReadChars() { return Array.ConvertAll(Read().Split(), a => a[0]); } private static int ReadInt() { return int.Parse(Read()); } private static long ReadLong() { return long.Parse(Read()); } private static double ReadDouble() { return double.Parse(Read()); } private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); } private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); } private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); } } }
1f1430792dd461d953115466d7834788e974ed50
C#
DaneVinson/Chameleon
/Chameleon.WinApp.Host/Program.cs
2.59375
3
using Microsoft.Owin.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Chameleon.WinApp.Host { internal class Program { static void Main(string[] args) { string baseAddress = "http://localhost:6886/"; using (WebApp.Start<Startup>(baseAddress)) { Console.WriteLine($"Host running and listening at {baseAddress}"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Console.ReadKey(); } } internal static bool StartForm(string typeName) { var nameParts = typeName.Split('.'); var assemblyQualifiedName = $"{typeName}, {String.Join(".", nameParts.Take(nameParts.Length - 1).ToArray())}"; var type = Type.GetType(assemblyQualifiedName); if (type == null) { return false; } Form form = Activator.CreateInstance(type) as Form; if (form == null) { return false; } var task = Task.Run(() => { form.ShowDialog(); }); task.Wait(1); return true; } } }
b077685d0e8f591c32902205df24c4ec9f8cd67d
C#
Hajdulord/Szakdolgozat
/Assets/Scripts/Misc/PlayMusic.cs
2.8125
3
using UnityEngine; namespace HMF.Thesis.Misc { /// Class for starting ans stoping the music when in range. public class PlayMusic : MonoBehaviour { [SerializeField] private AudioSource _source = null; ///< Reference to the audioSource. /// If the player is in range starts plaing music. private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.tag == "Player") { _source.Play(); } } /// If the player is in range stops plaing music. private void OnTriggerExit2D(Collider2D other) { if (other.gameObject.tag == "Player") { _source.Stop(); } } } }
cb0c93a450f1a10c8ad44bb8d8c3480879f8aebf
C#
Grosadi/Prog4_2048
/OENIK_PROG4_2019_1_ZNN2DN_UKCWGN/OENIK_PROG4_2019_1_ZNN2DN_UKCWGN/HighScoreVM.cs
2.671875
3
// <copyright file="HighScoreVM.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> namespace OENIK_PROG4_2019_1_ZNN2DN_UKCWGN { using System.Collections.ObjectModel; using _2048.Data; using _2048.Repository; using GalaSoft.MvvmLight; /// <summary> /// HighScore View Model. /// </summary> public class HighScoreVM : ViewModelBase { private GameRepository repo; private ObservableCollection<PLAYER> players; /// <summary> /// Initializes a new instance of the <see cref="HighScoreVM"/> class. /// </summary> public HighScoreVM() { this.repo = new GameRepository(); this.players = new ObservableCollection<PLAYER>(this.repo.GetPlayerByScore()); } /// <summary> /// Gets or sets the players of the viewmodel. /// </summary> public ObservableCollection<PLAYER> Players { get { return this.players; } set { this.Set(ref this.players, value); } } /// <summary> /// Save the changes of the DB. /// </summary> public void SaveChanges() { this.repo.SaveChanges(); } /// <summary> /// Add new player to the DB. /// </summary> /// <param name="name">Name of the player.</param> /// <param name="score">Score of the player.</param> /// <param name="highest">Highest tile of the player.</param> public void AddPlayer(string name, int score, int highest) { this.repo.AddPlayer(name, score, highest); } } }
dfd4fe917160e560b7e2d2705bba776defe88a0f
C#
mnffy/kadastr
/Project/Cadastral/Controllers/LandController.cs
2.546875
3
using Cadastral.DAO; using Cadastral.DataModel; using Cadastral.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Cadastral.Controllers { public class LandController : Controller { private CadastraDBEntities _edmx = new CadastraDBEntities(); private LandDAO _land = new LandDAO(); // GET: Land public async Task<ActionResult> Index(string searchString) { var lands = await _land.GetLands(); List<LandViewModel> result = new List<LandViewModel>(); result = lands; //если переменная searchString не пустая if (!string.IsNullOrEmpty(searchString)) { //попробуем найти по адерсу result = lands.Where(x => x.Address.Contains(searchString)).ToList(); //если не получилось найти по адресу if (!result.Any()) //попробуем найти по имени result = lands.Where(x => x.Owner.Name.Contains(searchString)).ToList(); //если не получилось найти по имени if (!result.Any()) //попробуем найти по фамилии result = lands.Where(x => x.Owner.Surname.Contains(searchString)).ToList(); //если не получилось найти по фамилии if (!result.Any()) //попробуем найти по имени и фамилии result = lands.Where(x => x.Owner.Owner.Contains(searchString)).ToList(); decimal costOrArea = 0; //а может входная переменная число?! bool val = decimal.TryParse(searchString, out costOrArea); //если да if (val) { //попробуем найти по цене result = lands.Where(x => x.Cost <= costOrArea).ToList(); //если не получилось if (!result.Any()) //попробуем найти по площади result = lands.Where(x => x.Area <= costOrArea).ToList(); } } return View(result); } [HttpGet] [Authorize] public ActionResult CreateLand() { InitDynamicViewBag(); var user = _edmx.AspNetUsers.FirstOrDefault(x => x.UserName == User.Identity.Name); var owner = _edmx.Owners.FirstOrDefault(x => x.UserId == user.Id); var land = new LandViewModel { Name = owner.Name, Surname = owner.Surname, CurrentUserId = user.Id, Cadastr = new CadastrViewModel { CadastrId = 2, CadastrName = "Land" } }; return View(land); } private void InitDynamicViewBag() { var landTypes = new SelectList(_edmx.LandTypes.ToList(), "LandTypeId", "Name"); var owns = _edmx.Owners.Select(x => new OwnerViewModel { OwnerId = x.OwnerId, Name = x.Name, Surname = x.Surname }); var owners = new SelectList(owns.ToList(), "OwnerId", "Owner"); var cadastras = new SelectList(_edmx.Cadastrs.ToList(), "CadastrId", "Name"); ViewBag.LandTypes = landTypes; ViewBag.Owners = owners; ViewBag.Cadastras = cadastras; } [HttpPost] [Authorize] public async Task<ActionResult> CreateLand(LandViewModel model) { try { if (model.Owner == null) { var user = _edmx.AspNetUsers.FirstOrDefault(x => x.UserName == User.Identity.Name); var owner = _edmx.Owners.FirstOrDefault(x => x.UserId == user.Id); model.Owner = new OwnerViewModel(); model.Owner.OwnerId = owner.OwnerId; model.Cadastr = new CadastrViewModel(); model.Cadastr.CadastrId = 2; } if (model != null) await _land.CreateLand(model); else throw new Exception(); } catch (Exception ex) { ModelState.AddModelError("", ex); } return RedirectToAction("Index"); } [HttpGet] [Authorize] public async Task<ActionResult> EditLand(int id) { InitDynamicViewBag(); LandViewModel land = new LandViewModel(); try { land = await _land.GetLandById(id); } catch (Exception ex) { ModelState.AddModelError("", ex); } return View(land); } [HttpPost] [Authorize] public async Task<ActionResult> EditLand(LandViewModel model) { try { if (model.Owner == null) { var user = _edmx.AspNetUsers.FirstOrDefault(x => x.UserName == User.Identity.Name); var owner = _edmx.Owners.FirstOrDefault(x => x.UserId == user.Id); model.Owner = new OwnerViewModel(); model.Owner.OwnerId = owner.OwnerId; model.Cadastr = new CadastrViewModel(); model.Cadastr.CadastrId = 2; } if (model != null) await _land.EditLand(model); else throw new Exception(); } catch (Exception ex) { ModelState.AddModelError("", ex); } return RedirectToAction("Index"); } [HttpGet] [Authorize(Roles = "Administration,Moderator")] public async Task<ActionResult> Delete(int id) { var land = await _land.GetLandById(id); return View(land); } [HttpPost] [Authorize(Roles = "Administration,Moderator")] public async Task<ActionResult> Delete(LandViewModel model) { try { if (model != null) await _land.RemoveLand(model); else throw new Exception(); } catch (Exception ex) { ModelState.AddModelError("", ex); } return RedirectToAction("Index"); } } }
12b2c7632daa26fcd2e58e0dc43b5194e97377b0
C#
marouen-lamiri/Concentration
/Assets/Code/Card.cs
2.578125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Card : MonoBehaviour { public int m_value; public bool m_color; bool m_shown = false; public bool isCard( GameObject obj ) { return obj.transform.position == transform.position; } public bool isShown() { return m_shown; } public bool getColor() { return m_color; } public int getValue() { return m_value; } public void showCard() { transform.rotation = Quaternion.Euler(.0f, .0f, .0f); m_shown = true; } public void hideCard() { transform.rotation = Quaternion.Euler(180.0f, .0f, .0f); m_shown = false; } public bool compareAttribute( Card card, bool color ) { return m_value == card.getValue() && ( !color || m_color == card.getColor() ); } }
cdefb608ef08cf126f775e4e4ad475b4c3de10bb
C#
McXmart/AutoMapperDemo
/AutoMapperDemo/AutoMapperDemo/AutoMapperDemo/Convert.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using AutoMapperDemo.Utils; namespace AutoMapperDemo { public class Convert { static void Main(string[] args) //static void Main2(string[] args) { #region 自定义值转换 Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>() //.ForMember(d => d.Total, s => s.ResolveUsing<CustomResolver>()) //.ForMember(d => d.Value3, opt => opt.Ignore())//属性忽略 //.ForMember(d => d.Value3, opt => opt.UseValue<int>(800))//属性填充固定值 ); Source src = new Source() { Value1 = 1, Value2 = 2, Value3 = "3" }; Destination dest = Mapper.Map<Destination>(src); Console.WriteLine( "转换成功:转换记录的Total为{0}。", dest.Total ); Console.ReadKey(); #endregion Console.WriteLine("======="); #region 自定义类型转换器 Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>() .ConvertUsing<TypeConverter>() ); Source src2 = new Source() { Value1 = 1, Value2 = 2, Value3 = "3" }; Destination dest2 = Mapper.Map<Destination>(src2); Console.WriteLine( "转换成功:转换记录的Value3为{0}。", dest2.Value3 ); Console.ReadKey(); #endregion } public class CustomResolver : ValueResolver<Source, int> { protected override int ResolveCore(Source source) { return source.Value1 + source.Value2; } } public class TypeConverter : TypeConverter<Source, Destination> { protected override Destination ConvertCore(Source source) { Destination dest = new Destination(); dest.Value3 = System.Convert.ToInt32(source.Value3) + 1; return dest; } } } }
a571ccfa8b21ed4eda3a50e40c9af96f97a26841
C#
sangvvlan/hrm
/Business/Business/CHAMCONGBusiness.cs
2.59375
3
using System.Data; using DataObject; using Data; namespace Business { public class CHAMCONGBusiness { public int Insert(CHAMCONG ObjCHAMCONG) { DataCHAMCONG objData = new DataCHAMCONG(); return objData.DataInsertCHAMCONG(ObjCHAMCONG); } public int Update(CHAMCONG ObjCHAMCONG) { DataCHAMCONG objData = new DataCHAMCONG(); return objData.DataUpdateCHAMCONG(ObjCHAMCONG); } public int Delete(CHAMCONG ObjCHAMCONG) { DataCHAMCONG objData = new DataCHAMCONG(); return objData.DataDeleteCHAMCONG(ObjCHAMCONG); } public DataTable GetList( ) { DataCHAMCONG objData = new DataCHAMCONG(); return objData.DataGetListCHAMCONG(); } public DataTable Details(CHAMCONG ObjCHAMCONG) { DataCHAMCONG objData = new DataCHAMCONG(); return objData.DataDetailsCHAMCONG(ObjCHAMCONG); } public DataTable DetailsByField(string FieldName,string value) { DataCHAMCONG objData = new DataCHAMCONG(); return objData.DataDetailsByFieldCHAMCONG(FieldName,value); } } } // End Class
4880f81bf52e6b78b8f8ed63380b075018ef6741
C#
Burgyn/MMLib
/MMLib.RapidPrototyping/Generators/PersonGenerator.cs
2.875
3
using MMLib.RapidPrototyping.Generators.Repositories; using MMLib.RapidPrototyping.Models; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; using MMLib.Extensions; namespace MMLib.RapidPrototyping.Generators { /// <summary> /// Generator, which know generate persons. /// </summary> public class PersonGenerator : IPersonGenerator { #region Constants private const string EMAIL_SUFIX = "com"; #endregion #region Private fields private IWordGenerator _firstNameGenerator; private IWordGenerator _lastNameGenerator; private IWordGenerator _emailProviderGenerator; #endregion #region Constructors /// <summary> /// Constructor. Using a time-dependent default seed value. FirstName and SecondName repository are uset from IoCDContainer. /// </summary> public PersonGenerator() { ResolveGenerators(); } /// <summary> /// Constructor. /// </summary> /// <param name="seed">A number used to calculate a starting value for the pseudo-random sequence. If a negative number is specified, the absolute value of the number is used.</param> public PersonGenerator(int seed) { ResolveGenerators(); SetSeed(seed); } #endregion #region Public interfaces /// <summary> /// Generate next person. /// </summary> /// <returns>Generated person.</returns> public IPerson Next() { Contract.Ensures(Contract.Result<IPerson>() != null); Person person = new Person(); person.FirstName = _firstNameGenerator.Next(); person.LastName = _lastNameGenerator.Next(); person.Mail = string.Format("{0}@{1}.{2}", person.LastName.RemoveDiacritics(), _emailProviderGenerator.Next(), EMAIL_SUFIX); return person; } /// <summary> /// Generate more persons. /// </summary> /// <param name="count">Count of generating persons.</param> /// <returns>Generated persons</returns> public IEnumerable<IPerson> Next(int count) { Contract.Ensures(Contract.Result<IEnumerable<IPerson>>() != null); Contract.Ensures(count > 0); IEnumerable<IPerson> persons; persons = from i in Enumerable.Range(0, count) select Next(); return persons; } #endregion #region Private helpers private void ResolveGenerators() { _firstNameGenerator = new WordGenerator(RepositoryDependencyFactory.ResolveFirstNameRepository()); _lastNameGenerator = new WordGenerator(RepositoryDependencyFactory.ResolveLastNameRepository()); _emailProviderGenerator = RepositoryDependencyFactory.Resolve<IWordGenerator>(); } private void SetSeed(int seed) { _firstNameGenerator.SetSeed(seed); _lastNameGenerator.SetSeed(seed); _emailProviderGenerator.SetSeed(seed); } #endregion } }
ad7429ceb803c7a83e5952f669156ad43f73faa9
C#
Adventure4Life/Test-Adventure-V2
/TestAdventure/TestAdventure/_Debug/Debugging.cs
2.96875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestAdventure { static class DeBugging { public static void TestSomething() { Console.WriteLine(CommandDictonary.GetCommandList().Count); foreach (KeyValuePair<string, string> item in CommandDictonary.GetCommandList()) { Console.WriteLine("{0} : {1}", item.Key, item.Value); } } public static void TestOriginalDataFiles() { Console.WriteLine(Level.Layout[0, 0].Name()); Console.WriteLine(Level.Layout[0, 0].LookDescription()); foreach (Exit exit in Level.Layout[0, 0].Exits()) { Console.WriteLine("\n" + exit.name); Console.WriteLine(exit.open); if (exit.look_area_open != null) { Console.WriteLine(exit.look_area_open); } if (exit.look_area_closed != null) { Console.WriteLine(exit.look_area_closed); } if (exit.look_at_closed != null) { Console.WriteLine(exit.look_at_closed); } if (exit.look_at_open != null) { Console.WriteLine(exit.look_at_open); } if (exit.use_Closed != null) { Console.WriteLine(exit.use_Closed); } if (exit.use_Open != null) { Console.WriteLine(exit.use_Open); } } foreach (Items item in Level.Layout[0, 0].ItemList()) { Console.WriteLine("\n"+item.name); Console.WriteLine(item.PickedupAllowed); Console.WriteLine(item.description_Default); Console.WriteLine(item.description_Dropped); Console.WriteLine(item.description_Gone); Console.WriteLine(item.getItem_Success); Console.WriteLine(item.getItem_NotAllowed); } } public static void Test_Tokenisation() { Console.WriteLine("\n: Raw Input : "); Console.WriteLine(UserInput.GetRawInput()); Console.WriteLine("\nCleaned Tokens"); foreach (string line in UserInput.GetCleanedInputTokens()) { Console.WriteLine(line); } Console.WriteLine("\nStemmed Tokens"); foreach (string line in UserInput.GetStemmedInputTokens()) { Console.WriteLine(line); } } public static void Exit() { Console.CursorVisible = false; Console.WriteLine("\n*** Press Any Key to Exit ***"); Console.ReadKey(true); } } }
0b01c4af2e47e4caa9acfa8ca7e25930983a6034
C#
wenderson1/ShopCrud
/Controllers/HomeController.cs
2.734375
3
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Shop.Data; using Shop.Models; namespace Shop.Controllers { [Route("v1")] public class HomeController : ControllerBase { [HttpGet] [Route("")] public async Task<ActionResult<dynamic>>Get([FromServices] DataContext context) { var employee = new User{Id = 1, Username="Robin",Role="Employee"}; var manager = new User{Id = 2, Username="batman",Role="Manager"}; var category = new Category{Id=1,Title="Informatica"}; var product = new Product{Id=1,Category=category,Title="Mouse",Price=300,Description="Mouse Gamer"}; context.Users.Add(employee); context.Users.Add(manager); context.Categories.Add(category); context.Products.Add(product); await context.SaveChangesAsync(); return Ok(new { message="Dados configurados" }); } } }
36beca8385978dc0f4f41118e7aff3dd8bcff0d1
C#
BlackDragonBE/MissleBall
/Assets/BlackDragonBE/Scripts/DragonLib/Patterns/ObservableValue.cs
3.578125
4
using System; // Example Usage: // A class: public ObservableValue<int> Health = new ObservableValue<int>(100); // Other class: MyClass.Health.OnValueChanged += HealthChanged; /// <summary> /// A generic value that can be observed. /// The OnValueChanged Action gets invoked every time this value gets changed. /// </summary> /// <typeparam name="T"></typeparam> public class ObservableValue<T> { public event Action<T> OnValueChanged; private T _value; public T Value { get { return _value; } set { _value = value; OnValueChanged.InvokeSafely(_value); } } public ObservableValue(T t) { _value = t; } }
3acc6a123fa49843fb08919666e63d18241e0123
C#
Ed-Fi-Exchange-OSS/Credential-Manager
/Ed-Fi.Credential.Business.Common/BaseBusiness.cs
2.765625
3
using System.Collections.Generic; using System.Linq; using Ed_Fi.Credential.Data; namespace Ed_Fi.Credential.Business { public interface IBusiness { } public interface IBaseBusiness<TEntity> : IBusiness where TEntity : class { IEnumerable<TEntity> Read(); void Create(string wamsId, TEntity entity, bool save = true); void Update(string wamsId, TEntity entity, bool save = true); void Destroy(string wamsId, TEntity entity, bool save = true); TEntity Find<TId>(TId id); IQueryable<TEntity> Query(); void SaveChanges(string wamsId); } public abstract class BaseBusiness<TEntity> : IBaseBusiness<TEntity> where TEntity : class { public IDbContext Context { get; } protected BaseBusiness(IDbContext context) { Context = context; } public TEntity Find<TId>(TId id) { var entity = Context.FindEntity<TEntity, TId>(id); return entity; } public IQueryable<TEntity> Query() { var query = Context.Query<TEntity>(); return query; } public IEnumerable<TEntity> Read() { var entity = Context.Query<TEntity>().ToList(); return entity; } public void Create(string wamsId, TEntity entity, bool save = true) { Context.AddEntity(entity); if (save) { SaveChanges(wamsId); } } public void Update(string wamsId, TEntity entity, bool save = true) { Context.UpdateEntity(entity); if (save) { SaveChanges(wamsId); } } public void Destroy(string wamsId, TEntity entity, bool save = true) { Context.RemoveEntity(entity); if (save) { SaveChanges(wamsId); } } public void SaveChanges(string wamsId) { Context.SaveChanges(wamsId); } } }
7fda06f7ac2ab00f20fb59ee503231d9c97d0263
C#
ARLM-Attic/linq2web
/Source/CodeGenerator/AST/Expression/TernaryExpr.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace linqtoweb.CodeGenerator.AST { /*public class IfExpression:Expression { }*/ /// <summary> /// expr ? expr : expr /// </summary> public class TernaryCondExpression : Expression { public readonly Expression ConditionExpr, Expr1, Expr2; public TernaryCondExpression(ExprPosition position, Expression condition, Expression expr1, Expression expr2) :base(position) { if (condition == null || expr1 == null || expr2 == null) throw new ArgumentNullException(); this.ConditionExpr = condition; this.Expr1 = expr1; this.Expr2 = expr2; } internal override ExpressionType EmitCs(EmitCodeContext codecontext) { ExpressionType condType, expr1Type, expr2Type; codecontext.Write("("); condType = ConditionExpr.EmitCs(codecontext); codecontext.Write(")?("); expr1Type = Expr1.EmitCs(codecontext); codecontext.Write("):("); expr2Type = Expr2.EmitCs(codecontext); codecontext.Write(")"); if (!condType.Equals(ExpressionType.BoolType)) throw new GeneratorException(Position, "Condition must be of type bool."); if (!expr1Type.Equals(expr2Type)) throw new GeneratorException(Position, "Type mishmash, " + expr1Type.ToString() + " and " + expr2Type.ToString()); return expr1Type; } } }
ed1599bbc7e1d6bdb1608423a6b7a186f0480161
C#
terry-u16/AtCoder
/Yorukatsu054/Yorukatsu054/Yorukatsu054/Questions/QuestionC.cs
3.015625
3
using Yorukatsu054.Questions; using Yorukatsu054.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Yorukatsu054.Questions { /// <summary> /// https://atcoder.jp/contests/abc149/tasks/abc149_d /// </summary> public class QuestionC : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { var nk = inputStream.ReadIntArray(); var jankenCount = nk[0]; var restriction = nk[1]; var rspPoints = inputStream.ReadIntArray(); var hostileHands = inputStream.ReadLine().Select(ToInt).ToArray(); var myHands = Enumerable.Repeat(-1, jankenCount).ToArray(); var pointSum = 0; for (int i = 0; i < hostileHands.Length; i++) { var winnable = (hostileHands[i] + 2) % 3; if (i - restriction < 0 || myHands[i - restriction] != winnable) { myHands[i] = winnable; pointSum += rspPoints[winnable]; } } yield return pointSum; } int ToInt(char c) { switch (c) { case 'r': return 0; case 's': return 1; case 'p': return 2; default: return -1; } } } }
dd520689393303b6e25696ae8cedf5640cbf0093
C#
VitaliiAndreev/WarThunder_PresetRandomizer
/Client.Wpf/Controls/UpDownBattleRatingPairControl.xaml.cs
2.75
3
using Core.DataBase.WarThunder.Enumerations; using Core.DataBase.WarThunder.Objects.Interfaces; using Core.Enumerations; using Core.Objects; using System; using System.Windows; using System.Windows.Controls; namespace Client.Wpf.Controls { /// <summary> Interaction logic for UpDownBattleRatingPairControl.xaml. </summary> public partial class UpDownBattleRatingPairControl : UserControl { #region Properties /// <summary> The maximum allowed <see cref="IVehicle.EconomicRank"/> defined by the control's state. </summary> public int MaximumEconomicRank => _maximumUpDownControl.Value; /// <summary> The minimum allowed <see cref="IVehicle.EconomicRank"/> defined by the control's state. </summary> public int MinimumEconomicRank => _minimumUpDownControl.Value; #endregion Properties #region Events /// <summary> A routed event for <see cref="ValueChanged"/>. </summary> public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent(nameof(ValueChanged), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UpDownBattleRatingPairControl)); /// <summary> Occurs when <see cref="Value"/> changes. </summary> public event RoutedEventHandler ValueChanged { add { AddHandler(ValueChangedEvent, value); } remove { RemoveHandler(ValueChangedEvent, value); } } #endregion Events #region Constructors /// <summary> Creates a new control. </summary> public UpDownBattleRatingPairControl() { InitializeComponent(); _maximumUpDownControl.MaximumValue = EReference.MaximumEconomicRank; _minimumUpDownControl.MinimumValue = EInteger.Number.Zero; } #endregion Constructors #region Methods: Event Handlers /// <summary> Adjusts boundaries for the adjacent control. </summary> /// <param name="sender"> The object that has triggered the event. One of the <see cref="UpDownBattleRatingControl"/>s is expected. </param> /// <param name="eventArguments"> Not used. </param> private void OnValueChanged(object sender, RoutedEventArgs eventArguments) { if (sender.Equals(_maximumUpDownControl)) { _minimumUpDownControl.MaximumValue = _maximumUpDownControl.Value; RaiseValueChanged(); } else if (sender.Equals(_minimumUpDownControl)) { _maximumUpDownControl.MinimumValue = _minimumUpDownControl.Value; RaiseValueChanged(); } } #endregion Methods: Event Handlers /// <summary> Raises the <see cref="ValueChangedEvent"/> event. </summary> public void RaiseValueChanged() => RaiseEvent(new RoutedEventArgs(ValueChangedEvent, this)); /// <summary> Initializes initial values. </summary> /// <param name="interval"> The interval to use for initialization. </param> public void Initialize(Interval<int> interval) { _maximumUpDownControl.Value = Math.Min(interval.RightItem, EReference.MaximumEconomicRank); _minimumUpDownControl.Value = Math.Max(interval.LeftItem, EInteger.Number.Zero); } } }
3c7ec7ba9284f7475543cf712f06c708195b09a4
C#
dzimchuk/power-video-player
/Players/WindowsForms/AdvancedUI/ToolBarManager/ToolBar.cs
2.640625
3
using System; using System.Windows.Forms; namespace Dzimchuk.AUI { /// <summary> /// This class automaticly sets Appearance to Flat and Divider to false; /// </summary> public class ToolBar : System.Windows.Forms.ToolBar { public ToolBar(string strTitle) { Text = strTitle; Appearance = ToolBarAppearance.Flat; Divider = false; } } }
cc755dc8832d017433aacedfea132d3e351d2d68
C#
teknofest-2021/dijidom-database-webapi
/Operations/MeasurementOperations/Queries/GetAllMeasurementByPlantID/GetAllMeasurementByPlantIDQuery.cs
2.515625
3
using System.Linq; using System.Collections.Generic; using dijidom_database_webapi.Data; namespace dijidom_database_webapi.Operations.MeasurementOperations.Queries.GetAllMeasurementByPlantID { public class GetAllMeasurementByPlantIDQuery { private readonly IDijiDomDBContext _dbContext; public GetAllMeasurementByPlantIDQuery(IDijiDomDBContext dbContext) { _dbContext = dbContext; } public int PlantID { get; set; } public List<GetAllMeasurementByPlantIDViewModel> Handle() { var result = from mesurement in _dbContext.Measurements.Where(p => p.PlantID==PlantID) join plant in _dbContext.Plants on mesurement.PlantID equals plant.PlantID join soil in _dbContext.Soils on mesurement.SoilID equals soil.SoilID join ambient in _dbContext.Ambients on mesurement.AmbientID equals ambient.AmbientID join planttype in _dbContext.PlantTypes on plant.TypeID equals planttype.TypeID orderby mesurement.MeasurementID ascending select new GetAllMeasurementByPlantIDViewModel { AirHumidity = ambient.AirHumidity, AirQuality = ambient.AirQuality, AirTemperature = ambient.AirTemperature, PlantID = plant.PlantID, PlantHeight = mesurement.PlantHeight, PlantName = plant.PlantName, SowingDate = plant.SowingDate.ToString("dd/MM/yyyy HH:mm"), SoilHumidity = soil.SoilHumidity, SoilTemperature = soil.SoilTemperature, TypeName = planttype.TypeName, MeasurementDate = mesurement.MeasurementDate.ToString("dd/MM/yyyy HH:mm") }; return result.ToList(); } } }
36014acbb903a3048b8cfb2c78ff20ef1a6ce798
C#
ASHIQ40788/BinaryTree
/BinaryTree.cs
3.75
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BinarySearchTree { public class MyBinaryTree<T> where T : IComparable { public T nodeData { get; set; } public MyBinaryTree<T> leftTree { get; set; } public MyBinaryTree<T> rightTree { get; set; } public static int leftCount; public static int rightCount; bool result = false; public MyBinaryTree(T nodeData) { this.nodeData = nodeData; this.leftTree = null; this.rightTree = null; } /// <summary> /// UC1- Inserting a Node. /// </summary> /// <param name="item"></param> public void Insert(T item) { T currentNodeValue = this.nodeData; int value = currentNodeValue.CompareTo(item); if ((value) > 0) { if (this.leftTree == null) { this.leftTree = new MyBinaryTree<T>(item); Console.WriteLine("Inserting" + item); } else this.leftTree.Insert(item); } else { if (this.rightTree == null) { this.rightTree = new MyBinaryTree<T>(item); Console.WriteLine("Inserting " + item); } else { this.rightTree.Insert(item); Console.WriteLine("Inserting " + item); } } } /// <summary> /// UC2-Finding Size of the Required Node. /// </summary> public void GetSize() { Console.WriteLine("Size" + " " + (1 + leftCount + rightCount)); } ///// <summary> ///// UC3-Search for a Node ///// </summary> //method for search node in BST public bool Search(T item, MyBinaryTree<T> node) { //Check whether the node is null or not.If null it means tree is empty. if (node == null) { return false; } //if nodeData is equals to item that means node has been found. if (node.nodeData.Equals(item)) { Console.WriteLine("Found the element in BST" + " " + node.nodeData); result = true; } //If item is less than node data it moves to left side(+1) to search for. if (item.CompareTo(node.nodeData) < 0) { Search(item, node.leftTree); } //If item is greater than node data it moves to right side(-1) to search for. if (item.CompareTo(node.nodeData) > 0) { Search(item, node.rightTree); } return result; //result value stores here. } public void Display() { if (this.leftTree != null) { leftCount++; this.leftTree.Display(); } Console.WriteLine(this.nodeData.ToString()); if (this.rightTree != null) { rightCount++; this.rightTree.Display(); } } } }
c44b2fff2169728ae99aff8f62a35f2638ae5043
C#
8BitSensei/Augur
/Augur/Services/PrinterService.cs
2.921875
3
using LiteDB; using LiteDbTest.Interfaces; using LiteDbTest.Models; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace LiteDbTest { public class PrinterService : IPrinterService { private LiteDatabase _db; private IDataService _dataService; public PrinterService(LiteDatabase db, IDataService dataService) { _db = db; _dataService = dataService; } public void NodesToCsv() { var entities = _db.GetCollection<Entity>("entities").Query().ToArray(); var csv = new StringBuilder(); foreach (var entity in entities) { var newLine = string.Format("{0},{1}", entity.Name, entity.Occurences.Count); csv.AppendLine(newLine); } File.WriteAllText(@"C:\Temp\nodeList.csv", csv.ToString()); } public void EdgesToCsv() { var entities = _db.GetCollection<Entity>("entities").Query().ToArray(); var csv = new StringBuilder(); var completedEntities = new List<string>(); foreach (var entity in entities) { var connections = _dataService.GetEntityConections(entity.Name); foreach (var connection in connections.Item2) { for (var i = 0; i < connection.weight; i++) { if (completedEntities.Contains(connection.name)) continue; var newLine = string.Format("{0},{1}", entity.Name, connection.name); csv.AppendLine(newLine); } completedEntities.Add(entity.Name); } } File.WriteAllText(@"C:\Temp\edgeList.csv", csv.ToString()); } } }
f526f9e59d5fab243ec48f0789cb2f69f5eb3051
C#
shendongnian/download4
/code7/1167578-30884715-93008888-2.cs
3.046875
3
public class MyTypeConverter : TypeConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType); List<Member> members = value as List<Member>; if (members == null) return "-"; return string.Join(", ", members.Select(m => m.Name)); } public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { List<PropertyDescriptor> list = new List<PropertyDescriptor>(); List<Member> members = value as List<Member>; if (members != null) { foreach (Member member in members) { if (member.Name != null) { list.Add(new MemberDescriptor(member, list.Count)); } } } return new PropertyDescriptorCollection(list.ToArray()); } private class MemberDescriptor : SimplePropertyDescriptor { public MemberDescriptor(Member member, int index) : base(member.GetType(), index.ToString(), typeof(string)) { Member = member; } public Member Member { get; private set; } public override object GetValue(object component) { return Member.Name; } public override void SetValue(object component, object value) { Member.Name = (string)value; } } }
fb97fbd40ccd7750297ff80a1343073da93abd24
C#
cj1024/OneDriveTestApp
/OneDriveExtentions/Converters/ByteCountToStringConverter.cs
3.078125
3
using System; using System.Collections.Generic; using System.Globalization; using System.Windows.Data; namespace OneDriveExtentions.Converters { public class ByteCountToStringConverter : IValueConverter { private static readonly IList<string> UnitList = new[] { "Byte", "KB", "MB", "GB", "TB", "PB" }; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double longValue; if (double.TryParse(value.ToString(), out longValue)) { var unit = UnitList.GetEnumerator(); while (unit.MoveNext()) { if (longValue < 1024) { return string.Format("{0:0.##} {1}", longValue, unit.Current); } longValue = longValue / 1024; } } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }
6cefa751c698981f01f3041a81c07b7c1cad11e7
C#
frankdarkluo/csharphomework
/homework1/1.4/1.4/Program.cs
3.046875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1._4 { class Program { static void Main(string[] args) { Console.Write("a="); string a = Console.ReadLine(); Console.Write("b="); string b = Console.ReadLine(); double x = Convert.ToDouble(a); double y = Convert.ToDouble(b); Console.WriteLine("a*b=" + (x * y)); Console.ReadKey(); } } }
591c437b26f9e25ee28c9931770d6733287cc1a2
C#
jeff-dias/SalesProcessor
/SalesProcessor/Util/Log.cs
2.625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SalesProcessor.Util { public class Log { private readonly string _file; private readonly string _folder; public Log() { _folder = $@"{Environment.CurrentDirectory.Replace(@"\bin\Debug", "").Replace(@"\bin\Release", "").Replace(@"\bin\HML", "")}\Log"; _file = $@"{_folder}\{GetDateTimeBrazil().ToString("yyyyMMddHH")}.txt"; if (!Directory.Exists(_folder)) Directory.CreateDirectory(_folder); if (!File.Exists(_file)) File.Create(_file).Close(); } public void Info(string input) { File.AppendAllText(_file, $"{GetDateTimeBrazil().ToString()} : {input} \r\n"); } public void Error(string input) { File.AppendAllText(_file, $"{GetDateTimeBrazil().ToString()} : #BUSINESS_ERROR {input} \r\n"); } public void Error(Exception ex) { var innerException = ex.InnerException; var msg = ex.Message; while (innerException != null) { msg += $" => {innerException.Message}"; innerException = innerException.InnerException; } if (!string.IsNullOrEmpty(ex.StackTrace)) msg += $" => {ex.StackTrace}"; File.AppendAllText(_file, $"{GetDateTimeBrazil().ToString()} : #EXCEPTION_ERROR {msg} \r\n"); //SendEmailLog(msg, ex); } public string ReturnException(Exception ex) { var innerException = ex.InnerException; var msg = ex.Message; while (innerException != null) { msg += $" => {innerException.Message}"; innerException = innerException.InnerException; } if (!string.IsNullOrEmpty(ex.StackTrace)) msg += $" => {ex.StackTrace}"; return msg; } internal DateTime GetDateTimeBrazil() { return TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time")); } } }
42b9ca3fb6d108f7684288f931109f44a261f127
C#
KyleADOlson/CombatManager
/CombatManagerCore/ExportData.cs
2.625
3
/* * ExportData.cs * * Copyright (C) 2010-2012 Kyle Olson, kyle@kyleolson.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace CombatManager { public class ExportData : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private List<Monster> _Monsters = new List<Monster>(); private List<Spell> _Spells = new List<Spell>(); private List<Feat> _Feats = new List<Feat>(); private List<Condition> _Conditions = new List<Condition>(); public List<Monster> Monsters { get { return _Monsters; } set { if (_Monsters != value) { _Monsters = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Monsters")); } } } } public List<Spell> Spells { get { return _Spells; } set { if (_Spells != value) { _Spells = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Spells")); } } } } public List<Feat> Feats { get { return _Feats; } set { if (_Feats != value) { _Feats = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Feats")); } } } } public List<Condition> Conditions { get { return _Conditions; } set { if (_Conditions != value) { _Conditions = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Conditions")); } } } } public static ExportData DataFromDBs() { ExportData data = new ExportData(); foreach (Monster m in MonsterDB.DB.Monsters) { data.Monsters.Add(m); } data.Monsters.Sort((a, b) => a.Name.CompareTo(b.Name)); foreach (Spell s in Spell.DBSpells) { data.Spells.Add(s); } data.Feats.Sort((a, b) => a.Name.CompareTo(b.Name)); foreach (Feat f in Feat.DBFeats) { data.Feats.Add(f); } data.Feats.Sort((a, b) => a.Name.CompareTo(b.Name)); foreach (Condition c in Condition.CustomConditions) { data.Conditions.Add(c); } data.Conditions.Sort((a, b) => a.Name.CompareTo(b.Name)); return data; } public void Append(ExportData data) { foreach (Monster m in data.Monsters) { _Monsters.Add(m); } foreach (Spell s in data.Spells) { _Spells.Add(s); } foreach (Feat f in data.Feats) { _Feats.Add(f); } foreach (Condition c in data.Conditions) { _Conditions.Add(c); } } } }
4139fb42bd255507d20a101ddcec077e97791e7a
C#
IonutPutinica/allSDJProjects
/Database/Controllers/ValuesController.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace Database.Controllers { [Route("api/people")] [ApiController] public class ValuesController : ControllerBase { private MotherloadContext people; public ValuesController(MotherloadContext people){ this.people = people; if (people.People.Count() == 0) { // Create a new Person if collection is empty, // which means you can't delete all People. people.People.Add(new Person { Name = "Mihail", CPR = "6969696969" }); people.SaveChanges(); } } // GET api/people [HttpGet] public ActionResult<List<Person>> GetAll() { return people.People.ToList(); } // GET api/people/{cpr} [HttpGet("{CPR}", Name = "GetPerson")] public ActionResult<Person> Get(string CPR) { var person = people.People.Find(CPR); if(person == null){ return NotFound(); } else{ return person; } } // POST api/people [HttpPost] public IActionResult Create([FromBody] Person person){ people.People.Add(person); people.SaveChanges(); return CreatedAtRoute("GetPerson", new {CPR = person.CPR}, person); } // PUT api/people/{cpr} [HttpPut("{CPR}")] public IActionResult Update(string CPR, Person person){ var human = people.People.Find(CPR); if( human == null){ return NotFound(); } else{ human.Name = person.Name; human.MobileNumber = person.MobileNumber; people.People.Update(human); people.SaveChanges(); return NoContent(); } } // DELETE api/people/{cpr} [HttpDelete("{CPR}")] public IActionResult Delete(int CPR) { var person = people.People.Find(CPR); if (person == null){ return NotFound(); } else{ people.People.Remove(person); people.SaveChanges(); return NoContent(); } } } }
0c73217cfe920f3dd3a9951944d2740c1589d478
C#
XavierSbert/spdvi
/BasicControlWinForms/act4b/Form1.cs
2.8125
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace act4b { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedItem == "+") { textBox4.Text = "+"; }else textBox4.Text = "-"; } private void textBox4_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int n1 = int.Parse(textBox1.Text); int n2 = int.Parse(textBox2.Text); String simb = textBox4.Text; if (simb == "+") { int suma = n1 + n2; textBox3.Text = suma.ToString(); } else { String sresta = "-"; int resta = n1 - n2; textBox3.Text = resta.ToString(); textBox4.Text = sresta; } } private void button2_Click(object sender, EventArgs e) { textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox1.Focus(); } } }
d1077c5afbe1e402920da245bba0826d3cec308b
C#
alveraboquet/CryptoExchangeApi
/Common.Contracts/Extensions.cs
3.015625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Common.Contracts { public static class Extensions { public static string FormatAs(this string format, params object[] args) { return string.Format(format, args); } public static bool AlmostEquals(this decimal d1, decimal d2, int precision = 8) { decimal epsilon = (decimal)Math.Pow(10.0, -precision); return (Math.Abs(d1 - d2) <= epsilon); } public static decimal StdDevP(this IEnumerable<decimal> values) { decimal avg = values.Average(); decimal stdDev = (decimal)Math.Sqrt(values.Average(v => Math.Pow((double)(v - avg), 2))); return stdDev; } public static string GetAssemblyQualifiedNameVersionInvariant(this Type type) { var typename = type.AssemblyQualifiedName; typename = Regex.Replace(typename, @", Version=\d+.\d+.\d+.\d+", string.Empty); typename = Regex.Replace(typename, @", Culture=\w+", string.Empty); typename = Regex.Replace(typename, @", PublicKeyToken=\w+", string.Empty); return typename; } } }
1f47a3833357e1915a16aacddf6eea0c4320aa67
C#
eyaldar/ChocolateStore
/src/ChocolateStore/PackageCacher.cs
2.5625
3
using System; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using Ionic.Zip; using System.Xml.Linq; using System.Dynamic; using System.Collections.Generic; namespace ChocolateStore { class PackageCacher { private const string INSTALL_FILE = "tools/chocolateyInstall.ps1"; public delegate void FileHandler(string fileName); public delegate void DownloadFailedHandler(string url, Exception ex); public event FileHandler SkippingFile = delegate { }; public event FileHandler DownloadingFile = delegate { }; public event DownloadFailedHandler DownloadFailed = delegate { }; public void CachePackage(string dir, string url) { var packagePath = DownloadFile(url, dir); using (var zip = ZipFile.Read(packagePath)) { var packageName = Path.GetFileNameWithoutExtension(packagePath); var entry = zip.FirstOrDefault(x => string.Equals(x.FileName, INSTALL_FILE, StringComparison.OrdinalIgnoreCase)); if (entry != null) { string content = GetZipEntryContent(entry); string newContent = CacheUrlFiles(Path.Combine(dir, packageName), content); newContent.Remove(0, newContent.IndexOf(content.First())); zip.UpdateEntry(INSTALL_FILE, newContent); zip.Save(); } GetDependencies(dir, url, zip); } } private void GetDependencies(string dir, string url, ZipFile zip) { var nuspecFile = zip.FirstOrDefault(x => x.FileName.EndsWith("nuspec", StringComparison.OrdinalIgnoreCase)); List<string> dependenciesList = GetDependenciesListFromNuspec(nuspecFile); var packageNameWithoutVersion = Path.GetFileNameWithoutExtension(nuspecFile.FileName); var urlFormat = url.Remove(url.IndexOf(packageNameWithoutVersion)) + "{0}"; GetDependencies(dependenciesList, dir, urlFormat); } private void GetDependencies(List<string> dependenciesList, string dir, string url) { foreach (var dependecy in dependenciesList) { CachePackage(dir, string.Format(url, dependecy)); } } private static string GetZipEntryContent(ZipEntry entry) { string content = null; using (MemoryStream ms = new MemoryStream()) { entry.Extract(ms); content = Encoding.Default.GetString(ms.ToArray()); } return content; } private static List<string> GetDependenciesListFromNuspec(ZipEntry nuspecFileEntry) { ExpandoObject root = new ExpandoObject(); List<string> dependenciesList = new List<string>(); string content = GetZipEntryContent(nuspecFileEntry); var xDoc = XDocument.Load(new StringReader(content)); XmlToDynamic.Parse(root, xDoc.Elements().First(), "dependencies"); if (root.Any()) { dynamic result = root; var dependencies = result.dependencies as List<dynamic>; foreach (var dependency in dependencies) { var realDependency = dependency as IDictionary<String, object>; dependenciesList.Add(realDependency["id"] as string); } } return dependenciesList; } private string CacheUrlFiles(string folder, string content) { const string pattern = "(?<=['\"])http\\S*(?=['\"])"; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } return Regex.Replace(content, pattern, new MatchEvaluator(m => DownloadFile(m.Value, folder))); } private string DownloadFile(string url, string destination) { try { var request = WebRequest.Create(url); var response = request.GetResponse(); var fileName = Path.GetFileName(response.ResponseUri.LocalPath); var filePath = Path.Combine(destination, fileName); if (File.Exists(filePath)) { SkippingFile(fileName); } else { DownloadingFile(fileName); using (var fs = File.Create(filePath)) { response.GetResponseStream().CopyTo(fs); } } return filePath; } catch (Exception ex) { DownloadFailed(url, ex); return url; } } } }
badc9f6c27188bc4983bd44d87de324aa6bc69cc
C#
Dragomir2020/Plant-Warfare-Unity
/PlantWarfare/Assets/Scripts/General/MusicManager.cs
2.875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MusicManager : MonoBehaviour { /// <summary> /// Array of the Audio Clips for each level. /// </summary> public AudioClip[] levelMusicChangeArray; /// <summary> /// The audio source used to play the audio clip. /// </summary> private AudioSource audioSource; /// <summary> /// Awake this instance. /// </summary> void Awake(){ DontDestroyOnLoad (this); } /// <summary> /// Start this instance. /// </summary>// void Start () { audioSource = GetComponent<AudioSource> (); } /// <summary> /// Loads new music for each level /// </summary> /// <param name="level">Level.</param> private void OnLevelWasLoaded(int level){ AudioClip music = levelMusicChangeArray [level]; //If music is attached if (music != null){ audioSource.clip = music; audioSource.loop = true; audioSource.Play (); } } /// <summary> /// Changes the volume. /// </summary> /// <param name="volume">Volume.</param> public void ChangeVolume(float volume){ audioSource.volume = volume; } }
9a526212343d6fa1c1c4277c30aae47aa6c24e65
C#
MarquesBruno/ClientBook
/ClientBook/Repositorio/CompraRepositorio.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using ClientBook.Banco; using ClientBook.Entidade; namespace ClientBook.Repositorio { public class CompraRepositorio { private static DataBase GetDataBase() { DataBase db = new DataBase(); if (!db.DatabaseExists()) db.CreateDatabase(); return db; } public static List<string> GetOne() { DataBase db = GetDataBase(); var query = from comp in db.Compra orderby comp.id descending select comp.produto; List<string> lista = query.ToList<string>(); return lista; } public static List<CompraEntidade> Get(int pCompra) { DataBase db = GetDataBase(); var query = from comp in db.Compra orderby comp.id descending select comp; List<CompraEntidade> lista = new List<CompraEntidade>(query.AsEnumerable()); return lista; } public static void Create(CompraEntidade pCompra) { int ponto = 0; DataBase db = GetDataBase(); var query = from comp in db.Compra orderby comp.id descending select comp; List<CompraEntidade> lista = new List<CompraEntidade>(query.AsEnumerable()); db.Compra.InsertOnSubmit(pCompra); db.SubmitChanges(); } public static void Delete(int pCompra) { DataBase db = GetDataBase(); var query = from c in db.Compra where c.id == pCompra select c; db.Compra.DeleteOnSubmit(query.ToList()[0]); db.SubmitChanges(); } public static void DeleteObject(CompraEntidade pCompra) { DataBase db = GetDataBase(); var query = from c in db.Compra where c.id == pCompra.id select c; db.Compra.DeleteOnSubmit(query.ToList()[0]); db.SubmitChanges(); } } }
42bee396e70efd3e278ac8b7e73d364fad1d8d7f
C#
HedinRakot/Zierer
/ProfiCraftsman/ProfiCraftsman/ProfiCraftsman.Lib/Data/AdditionalCostTypesMapping.cs
2.625
3
using ProfiCraftsman.Contracts.Entities; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace ProfiCraftsman.Lib.Data { /// <summary> /// Mappping table dbo.AdditionalCostTypes to entity <see cref="AdditionalCostTypes"/> /// </summary> internal sealed class AdditionalCostTypesMapping: EntityTypeConfiguration<AdditionalCostTypes> { public static readonly AdditionalCostTypesMapping Instance = new AdditionalCostTypesMapping(); /// <summary> /// Initializes a new instance of the <see cref="AdditionalCostTypesMapping" /> class. /// </summary> private AdditionalCostTypesMapping() { ToTable("AdditionalCostTypes", "dbo"); // Primary Key HasKey(t => t.Id); //Properties Property(t => t.Id) .HasColumnName(AdditionalCostTypes.Fields.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) .IsRequired(); Property(t => t.Name) .HasColumnName(AdditionalCostTypes.Fields.Name) .IsRequired() .IsUnicode() .HasMaxLength(128); Property(t => t.CreateDate) .HasColumnName(AdditionalCostTypes.Fields.CreateDate) .IsRequired(); Property(t => t.ChangeDate) .HasColumnName(AdditionalCostTypes.Fields.ChangeDate) .IsRequired(); Property(t => t.DeleteDate) .HasColumnName(AdditionalCostTypes.Fields.DeleteDate); //Relationships } } }
18b23591d7c86f19fcd9f31db66ea04a7aae03e6
C#
francescozoccheddu/VGD
/Assets/Scripts/Gameplay/Action/LifeHistory.cs
2.78125
3
using System.Linq; using UnityEngine; using Wheeled.Core.Utils; namespace Wheeled.Gameplay.Action { public interface IReadOnlyLifeHistory { int? GetHealthOrNull(double _time); void GetLastDeathInfo(double _time, out DamageNode? _outDeath, out DamageNode? _outExplosion); } public static class LifeHistoryHelper { public static ELifeState GetLifeState(int? _health) { if (_health == null) { return ELifeState.Unknown; } else if (IsExploded(_health.Value)) { return ELifeState.Exploded; } else if (IsAlive(_health.Value)) { return ELifeState.Alive; } else { return ELifeState.Dead; } } public static int GetHealth(this IReadOnlyLifeHistory _history, double _time) { return _history.GetHealthOrNull(_time) ?? 0; } public static bool IsAlive(int _health) { return _health > 0; } public static bool IsExploded(int _health) { return _health <= LifeHistory.c_explosionHealth; } public static bool IsAlive(this IReadOnlyLifeHistory _history, double _time) { return IsAlive(_history.GetHealth(_time)); } public static bool IsExploded(this IReadOnlyLifeHistory _history, double _time) { return IsExploded(_history.GetHealth(_time)); } public static ELifeState GetLifeState(this IReadOnlyLifeHistory _history, double _time) { return GetLifeState(_history.GetHealthOrNull(_time)); } public static double? GetTimeSinceLastDeath(this IReadOnlyLifeHistory _history, double _time) { _history.GetLastDeathInfo(_time, out DamageNode? node, out _); return _time - node?.time; } } public class LifeHistory : IReadOnlyLifeHistory { public const int c_fullHealth = 100; public const int c_explosionHealth = -50; private readonly LinkedListHistory<double, DamageInfo> m_damages; private readonly LinkedListHistory<double, int> m_health; private HistoryNode<double, int>? m_trimmedNode; public LifeHistory() { m_damages = new LinkedListHistory<double, DamageInfo>(); m_health = new LinkedListHistory<double, int>(); } public void PutDamage(double _time, DamageInfo _info) { m_damages.Add(_time, _info); } public void PutHealth(double _time, int _health) { m_health.Set(_time, _health); } public int? GetHealthOrNull(double _time) { HistoryNode<double, int>? healthNode = GetLastHealthNode(_time); if (healthNode == null) { return null; } int health = healthNode.Value.value; foreach (HistoryNode<double, DamageInfo> damageNode in m_damages .Between(healthNode.Value.time, _time)) { health = Mathf.Min(damageNode.value.maxHealth, health - damageNode.value.damage); } return health; } public void Trim(double _time) { int? health = GetHealthOrNull(_time); if (health != null) { m_trimmedNode = new HistoryNode<double, int> { time = _time, value = health.Value }; } m_health.ForgetOlder(_time, true); m_damages.ForgetOlder(_time, true); } public void GetLastDeathInfo(double _time, out DamageNode? _outDeath, out DamageNode? _outExplosion) { _outDeath = null; _outExplosion = null; HistoryNode<double, int>? healthNode = m_health.Last(_time, _n => _n.value > 0); if (m_trimmedNode?.value > 0 && m_trimmedNode?.time > healthNode?.time) { healthNode = m_trimmedNode; } if (healthNode == null) { return; } int health = healthNode.Value.value; int lastHealth = health; foreach (HistoryNode<double, DamageInfo> damageNode in m_damages .Between(healthNode.Value.time, _time)) { lastHealth = health; health = Mathf.Min(damageNode.value.maxHealth, health - damageNode.value.damage); if (LifeHistoryHelper.IsAlive(lastHealth) && !LifeHistoryHelper.IsAlive(health)) { _outDeath = new DamageNode { damage = damageNode.value, time = damageNode.time }; } if (!LifeHistoryHelper.IsExploded(lastHealth) && LifeHistoryHelper.IsExploded(health)) { _outExplosion = new DamageNode { damage = damageNode.value, time = damageNode.time }; break; } } } private HistoryNode<double, int>? GetLastHealthNode(double _time) { HistoryNode<double, int>? fromHistory = m_health.Last(_time); if (fromHistory?.time < m_trimmedNode?.time != true) { return fromHistory; } else { return m_trimmedNode; } } } public struct DamageNode { public double time; public DamageInfo damage; } public enum ELifeState { Alive, Dead, Exploded, Unknown } }
8ee88b7b77f8fc7be86dd5968147e5e401ece38e
C#
nhthuc/CoCaRoAI
/CoCaRo/BanCo.cs
2.734375
3
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoCaRo { class BanCo { private int _sodong; private int _socot; public int Socot { get { return _socot; } set { _socot = value; } } public int Sodong { get { return _sodong; } set { _sodong = value; } } public BanCo() { Sodong = 0; Socot = 0; } public BanCo(int soDong, int soCot) { this.Sodong = soDong; this.Socot = soCot; } public void VeBanCo(Graphics g) { for (int i = 0; i <= Socot; i++) { g.DrawLine(CaroChess.pen, i * OCo._chieuRong, 0, i * OCo._chieuRong, Sodong * OCo._chieuCao); } for (int i = 0; i <= Sodong; i++) { g.DrawLine(CaroChess.pen, 0, i * OCo._chieuCao, Socot * OCo._chieuRong, i * OCo._chieuCao); } } public void VeQuanCo(Graphics g, Point point, SolidBrush sb) { g.FillEllipse(sb, point.X + 2, point.Y + 2, OCo._chieuRong - 4, OCo._chieuCao - 4); } public void XoaQuanCo(Graphics g, Point point, SolidBrush sb) { g.FillRectangle(sb, point.X + 2, point.Y + 2, OCo._chieuRong - 4, OCo._chieuCao - 4); } } }
c90fe37d72d479639e546ecc4e14db28d0788122
C#
YasakaShun/TaskTimer
/TaskTimer/MainGraph.xaml.cs
2.75
3
using System; using System.Globalization; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; namespace TaskTimer { /// <summary> /// MainGraph.xaml の相互作用ロジック /// </summary> public partial class MainGraph : UserControl { public MainGraph() { InitializeComponent(); } /// <summary> /// DataGrid の選択行の内容をクリップボードにコピー。 /// Ctrl + C での標準のコピーの内容を変更する。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void datagrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e) { e.ClipboardRowContent.Clear(); e.ClipboardRowContent.Add( new DataGridClipboardCellContent( e.Item, (sender as DataGrid).Columns[0], e.Item.ToString() ) ); } } public class TimeSpanToWidth : IValueConverter { const double UnitWidth = 30.0; const double MaxWidth = UnitWidth * 7; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // TimeSpan はnull許容型ではないので、asは使えない。 if (!(value is TimeSpan)) { return 0; } var timeSpan = (TimeSpan)value; var retVal = timeSpan.TotalDays * UnitWidth; if (timeSpan.TotalDays < 1) { retVal = timeSpan.TotalHours * UnitWidth / 24.0; } return Math.Min(retVal, MaxWidth); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class TimeSpanToString : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // TimeSpan はnull許容型ではないので、asは使えない。 if (!(value is TimeSpan)) { return 0; } var timeSpan = (TimeSpan)value; if (timeSpan.Days < 1 && timeSpan.Hours == 0) { return $"{timeSpan.Hours}時間"; } else { return string.Format( "{0}{1}", timeSpan.Days < 1 ? "" : $"{timeSpan.Days}日", timeSpan.Hours == 0 ? "" : $"{timeSpan.Hours}時間" ); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
592bf2db29610f97e709d72968efc0bbd8efacad
C#
ma7ko/vizuelnoProgramiranje
/mojaPacman/WindowsFormsApp3/Form1.cs
2.515625
3
using WindowsFormsApp3.Properties; 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 WindowsFormsApp3 { public partial class Form1 : Form { Timer timer; ClassPacman pacman; static readonly int TIMER_INTERVAL = 250; static readonly int WORLD_WIDTH = 15; static readonly int WORLD_HEIGHT = 10; Image foodImage; bool[][] foodWorld; Image stapica; bool[][] canMove; int izedeno = 0; public Form1() { InitializeComponent(); // Vcituvanje na slika od resursi foodImage = Resources.food; stapica = Resources.trap; DoubleBuffered = true; newGame(); } public void newGame() { pacman = new ClassPacman(); this.Width = ClassPacman.radius * 2 * (WORLD_WIDTH + 1); this.Height = ClassPacman.radius * 2 * (WORLD_HEIGHT + 1); // овде кодот за иницијализација на матрицата foodWorld foodWorld = new bool[WORLD_HEIGHT][]; canMove = new bool[WORLD_HEIGHT][]; for(int i=0;i<WORLD_HEIGHT;i++) { canMove[i] = new bool[WORLD_WIDTH]; for(int j=0;j<WORLD_WIDTH;j++) { canMove[i][j] = true; } } canMove[1][1] = false; canMove[2][1] = false; canMove[3][1] = false; //barikada 1 canMove[7][1] = false; canMove[8][1] = false; canMove[9][1] = false; //barikada 2 canMove[4][3] = false; canMove[5][3] = false; canMove[6][3] = false; //barikada 3 canMove[3][6] = false; canMove[4][6] = false; canMove[5][6] = false; //barikada 4 canMove[0][8] = false; canMove[1][8] = false; canMove[2][8] = false; //barikada 5 canMove[7][10] = false; canMove[8][10] = false; canMove[9][10] = false; //barikada 6 canMove[2][11] = false; canMove[3][11] = false; canMove[4][11] = false; //barikada 7 canMove[5][13] = false; canMove[6][13] = false; canMove[7][13] = false; //barikada 8 for(int i=0;i<WORLD_HEIGHT;i++) { foodWorld[i] = new bool[WORLD_WIDTH]; for(int j = 0; j < WORLD_WIDTH; j++) { if(canMove[i][j]==true) { foodWorld[i][j] = true; } else { foodWorld[i][j] = false; } } } // овде кодот за иницијализација и стартување на тајмерот timer2 = new Timer(); timer2.Interval = TIMER_INTERVAL; timer2.Tick += new EventHandler(timer2_Tick); timer2.Start(); } //private void panel1_Paint(object sender, PaintEventArgs e) // { //} private void timer2_Tick(object sender, EventArgs e) { // овде вашиот код int calculatedXPos = Math.Abs(pacman.Xpos / 40); int calculatedYpos = Math.Abs(pacman.Ypos / 38); //so it wont go out of bounds if (calculatedXPos == WORLD_WIDTH) { calculatedXPos--; } if (calculatedYpos == WORLD_HEIGHT) { calculatedYpos--; } //check if there is food on the coords and eat it if (foodWorld[calculatedYpos][calculatedXPos]) { foodWorld[calculatedYpos][calculatedXPos] = false; izedeno++; } if (canMove[calculatedYpos][calculatedXPos]) { pacman.Move(); } else { if (pacman.nasoka == ClassPacman.NASOKA.levo) pacman.nasoka = ClassPacman.NASOKA.desno; else if (pacman.nasoka == ClassPacman.NASOKA.desno) pacman.nasoka = ClassPacman.NASOKA.levo; else if (pacman.nasoka == ClassPacman.NASOKA.dolu) pacman.nasoka = ClassPacman.NASOKA.gore; else if (pacman.nasoka == ClassPacman.NASOKA.gore) pacman.nasoka = ClassPacman.NASOKA.dolu; pacman.Move(); } Invalidate(true); } private void Form1_KeyUp_1(object sender, KeyEventArgs e) { // не заборавајте да го додадете настанот на самата форма // вашиот код овде switch (e.KeyCode) { case Keys.Up: if (pacman.nasoka != ClassPacman.NASOKA.gore) { pacman.ChangeDirection(ClassPacman.NASOKA.gore); } break; case Keys.Down: if (pacman.nasoka != ClassPacman.NASOKA.dolu) { pacman.ChangeDirection(ClassPacman.NASOKA.dolu); } break; case Keys.Left: if (pacman.nasoka != ClassPacman.NASOKA.levo) { pacman.ChangeDirection(ClassPacman.NASOKA.levo); } break; case Keys.Right: if (pacman.nasoka != ClassPacman.NASOKA.desno) { pacman.ChangeDirection(ClassPacman.NASOKA.desno); } break; default: break; } Invalidate(); } private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.Clear(Color.White); for (int i = 0; i < foodWorld.Length; i++) { for (int j = 0; j < foodWorld[i].Length; j++) { if (foodWorld[i][j]) { g.DrawImageUnscaled(foodImage, j * ClassPacman.radius * 2 + (ClassPacman.radius * 2 - foodImage.Height) / 2, i * ClassPacman.radius * 2 + (ClassPacman.radius * 2 - foodImage.Width) / 2); } else if(canMove[i][j]==false) { g.DrawImageUnscaled(stapica, j * ClassPacman.radius * 2 + (ClassPacman.radius * 2 - stapica.Height) / 2, i * ClassPacman.radius * 2 + (ClassPacman.radius * 2 - stapica.Width) / 2); } } } pacman.Draw(g); } } }
ff1df37e926eb78d024b098e605084595063732b
C#
VertexShader/junction
/Tests/test_framework_and_libraries.cs
2.5625
3
using NUnit.Framework; using Should; namespace Tests { [TestFixture] class test_framework_and_libraries { [Test] public void should_always_work() { const string someValue = "stuff"; Assert.AreEqual("stuff", someValue, "NUnit is working."); } [Test] public void should_have_should_working() { const bool trueYeah = true; trueYeah.ShouldBeTrue("Should is working."); } } }
9a08aaa9c2d3f8107f878a33401e0c98b662ff9b
C#
gmlan/Middlewares
/Infrastructure/Com.Gmlan.Middlewares.MongoDB/Model/MongoDBConfig.cs
2.6875
3
namespace Com.Gmlan.Middlewares.MongoDB.Model { public class MongoDbConfig { /// <summary> /// Default parameterless constructor /// </summary> public MongoDbConfig() { } /// <summary> /// Constructor for MongoDbConfig /// </summary> /// <param name="constr">MogoDB connection string</param> /// <param name="database">database name to connect</param> public MongoDbConfig(string constr, string database) { ConnectionString = constr; Database = database; } public string ConnectionString { get; set; } public string Database { get; set; } } }
16e9fde92856a704fe9d4f16b3a6ccca6df3949f
C#
zoha-shobbar/URL-Shortener
/ShortenerURL/Repository/ShortUrlRepository.cs
2.828125
3
using MongoDB.Bson; using MongoDB.Driver; using ShortenerModel; using System; using System.Collections.Generic; using System.Text; namespace Repository { public class ShortUrlRepository : IShortUrlRepository { private readonly IMongoCollection<ShortURLModel> _mongoCollection; public ShortUrlRepository(string mongoDBConnectionString, string dbName, string collectionName) { var client = new MongoClient(mongoDBConnectionString); var database = client.GetDatabase(dbName); _mongoCollection = database.GetCollection<ShortURLModel>(collectionName); } public IEnumerable<ShortURLModel> GetAllUrls() { return _mongoCollection.Find(x => true).ToList(); } public ShortURLModel GetUrl(string shortUrl) { System.Linq.Expressions.Expression<Func<ShortURLModel, bool>> predicate = c => c.ShortenedURL == shortUrl; var q = _mongoCollection.Find(predicate).FirstOrDefault(); return q; } public ShortURLModel GetByActualUrl(string longUrl) { System.Linq.Expressions.Expression<Func<ShortURLModel, bool>> predicate = c => c.ActualURL == longUrl; var q = _mongoCollection.Find(predicate).FirstOrDefault(); return q; } public ShortURLModel Create(ShortURLModel model) { try { _mongoCollection.InsertOne(model); return model; } catch (Exception) { return null; } } //public ShortURLModel Update(string id, ShortURLModel model) //{ // var docId = new ObjectId(id); // _mongoCollection.ReplaceOne(m => m.Id == docId, model); // return model; //} public ShortURLModel Update( ShortURLModel model) { _mongoCollection.ReplaceOne(m => m.Id == model.Id, model); return model; } } }
646e4de050c3794ee1c734145d93e3f93bb332da
C#
rnwood/smtp4dev
/Rnwood.Smtp4dev/CommandLineParser.cs
2.578125
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using CommandLiners; using Mono.Options; namespace Rnwood.Smtp4dev { public static class CommandLineParser { public static MapOptions<CommandLineOptions> TryParseCommandLine(IEnumerable<string> args, bool isDesktopApp) { MapOptions<CommandLineOptions> map = new MapOptions<CommandLineOptions>(); StringWriter errorStream = new StringWriter(); bool help = false; bool hadBadArgs = false; OptionSet options = new OptionSet { { "h|help|?", "Shows this message and exits", _ => help = true}, { "baseappdatapath=","Set the base config and appData path", data => map.Add(data, x => x.BaseAppDataPath)}, { "hostname=", "Specifies the server hostname. Used in auto-generated TLS certificate if enabled.", data => map.Add(data, x => x.ServerOptions.HostName) }, { "allowremoteconnections", "Specifies if remote connections will be allowed to the SMTP and IMAP servers. Use -allowremoteconnections+ to enable or -allowremoteconnections- to disable", data => map.Add((data !=null).ToString(), x => x.ServerOptions.AllowRemoteConnections) }, { "smtpport=", "Set the port the SMTP server listens on. Specify 0 to assign automatically", data => map.Add(data, x => x.ServerOptions.Port) }, { "db=", "Specifies the path where the database will be stored relative to APPDATA env var on Windows or XDG_CONFIG_HOME on non-Windows. Specify \"\" to use an in memory database.", data => map.Add(data, x => x.ServerOptions.Database) }, { "messagestokeep=", "Specifies the number of messages to keep", data => map.Add(data, x=> x.ServerOptions.NumberOfMessagesToKeep) }, { "sessionstokeep=", "Specifies the number of sessions to keep", data => map.Add(data, x=> x.ServerOptions.NumberOfSessionsToKeep) }, { "tlsmode=", "Specifies the TLS mode to use. None=Off. StartTls=On demand if client supports STARTTLS. ImplicitTls=TLS as soon as connection is established.", data => map.Add(data, x=> x.ServerOptions.TlsMode) }, { "tlscertificate=", "Specifies the TLS certificate to use if TLS is enabled/requested. Specify \"\" to use an auto-generated self-signed certificate (then see console output on first startup)", data => map.Add(data, x=> x.ServerOptions.TlsCertificate) }, { "tlscertificateprivatekey=", "Specifies the TLS certificate private key. Ignored if tlscertificate is blank", data => map.Add(data, x=> x.ServerOptions.TlsCertificatePrivateKey) }, { "relaysmtpserver=", "Sets the name of the SMTP server that will be used to relay messages or \"\" if messages relay should not be allowed", data => map.Add(data, x=> x.RelayOptions.SmtpServer) }, { "relaysmtpport=", "Sets the port number for the SMTP server used to relay messages", data => map.Add(data, x=> x.RelayOptions.SmtpPort) }, { "relayautomaticallyemails=", "A comma separated list of recipient addresses for which messages will be relayed automatically. An empty list means that no messages are relayed", data => map.Add(data, x=> x.RelayOptions.AutomaticEmailsString) }, { "relaysenderaddress=", "Specifies the address used in MAIL FROM when relaying messages. (Sender address in message headers is left unmodified). The sender of each message is used if not specified.", data => map.Add(data, x=> x.RelayOptions.SenderAddress) }, { "relayusername=", "The username for the SMTP server used to relay messages. If \"\" no authentication is attempted", data => map.Add(data, x=> x.RelayOptions.Login) }, { "relaypassword=", "The password for the SMTP server used to relay messages", data => map.Add(data, x=> x.RelayOptions.Password) }, { "relaytlsmode=", "Sets the TLS mode when connecting to relay SMTP server. See: http://www.mimekit.net/docs/html/T_MailKit_Security_SecureSocketOptions.htm", data => map.Add(data, x=> x.RelayOptions.TlsMode) }, { "imapport=", "Specifies the port the IMAP server will listen on - allows standard email clients to view/retrieve messages", data => map.Add(data, x=> x.ServerOptions.ImapPort) }, { "nousersettings", "Skip loading of appsetttings.json file in %APPDATA%", data => map.Add((data !=null).ToString(), x=> x.NoUserSettings) }, { "debugsettings", "Prints out most settings values on startup", data => map.Add((data !=null).ToString(), x=> x.DebugSettings) }, { "recreatedb", "Recreates the DB on startup if it already exists", data => map.Add((data !=null).ToString(), x=> x.ServerOptions.RecreateDb) }, { "locksettings", "Locks settings from being changed by user via web interface", data => map.Add((data !=null).ToString(), x=> x.ServerOptions.LockSettings) }, { "installpath=", "Sets path to folder containing wwwroot and other files", data => map.Add(data, x=> x.InstallPath) }, { "disablemessagesanitisation", "Disables message HTML sanitisation.", data => map.Add((data !=null).ToString(), x=> x.ServerOptions.DisableMessageSanitisation) } }; if (!isDesktopApp) { options.Add("service", "Required to run when registered as a Windows service. To register service: sc.exe create Smtp4dev binPath= \"{PathToExe} --service\"", _ => { }); options.Add( "urls=", "The URLs the web interface should listen on. For example, http://localhost:123. Use `*` in place of hostname to listen for requests on any IP address or hostname using the specified port and protocol (for example, http://*:5000)", data => map.Add(data, x => x.Urls)); options.Add( "basepath=", "Specifies the virtual path from web server root where SMTP4DEV web interface will be hosted. e.g. \"/\" or \"/smtp4dev\"", data => map.Add(data, x => x.ServerOptions.BasePath)); } try { List<string> badArgs = options.Parse(args); if (badArgs.Any()) { errorStream.WriteLine("Unrecognised command line arguments: " + string.Join(" ", badArgs)); hadBadArgs = true; } } catch (OptionException e) { errorStream.WriteLine("Invalid command line: " + e.Message); hadBadArgs = true; } if (help || hadBadArgs) { errorStream.WriteLine(); errorStream.WriteLine(" > For information about default values see documentation in appsettings.json."); errorStream.WriteLine(); options.WriteOptionDescriptions(errorStream); throw new CommandLineOptionsException(errorStream.ToString()) { IsHelpRequest = help }; } else { Console.WriteLine(); Console.WriteLine(" > For help use argument --help"); Console.WriteLine(); } return map; } } }
32de205ed69e088b93f8c042b09fc1e84ef699c9
C#
rauldoblem/Tac
/Tac.SnippetTests/BasicInputOutput.cs
2.578125
3
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Tac.Backend.Public; using Tac.Model; using Tac.Model.Instantiated; using Tac.Syntaz_Model_Interpeter; using Tac.Syntaz_Model_Interpeter.Run_Time_Objects; using Xunit; using static Tac.Backend.Public.AssemblyBuilder; using Prototypist.LeftToRight; namespace Tac.SnippetTests { internal static class BasicInputOutput { internal static (Func<T>, Action) ToInput<T>(IReadOnlyList<T> list) { var at = 0; return (() => list[at++], () => Assert.Equal(list.Count, at)); } internal static (Action<T>, Action) ToOutput<T>(IReadOnlyList<T> list) { var outputs = new List<T>(); return ( (x) => outputs.Add(x), () => { Assert.Equal(list.Count, outputs.Count); list.Zip(outputs, (x, y) => { Assert.Equal(x, y); return 0; }).ToArray(); }); } public static IAssembly<InterpetedAssemblyBacking> Input(Func<double> numberSource, Func<string> stringSource, Func<bool> boolSource) { return new AssemblyBuilder(new NameKey("in")) .AddMethod( new NameKey("read-number"), (IInterpedEmpty x) => TypeManager.Double(numberSource()), MethodType.CreateAndBuild( new EmptyType(), new NumberType())) .AddMethod( new NameKey("read-string"), (IInterpedEmpty x) => TypeManager.String(stringSource()), MethodType.CreateAndBuild( new EmptyType(), new StringType())) .AddMethod( new NameKey("read-bool"), (IInterpedEmpty x) => TypeManager.Bool(boolSource()), MethodType.CreateAndBuild( new EmptyType(), new BooleanType())) .Build(); } public static IAssembly<InterpetedAssemblyBacking> Output(Action<double> numberDestination, Action<string> stringDestination, Action<bool> boolDestination) { return new AssemblyBuilder(new NameKey("out")) .AddMethod( new NameKey("write-number"), (IBoxedDouble x) => { numberDestination(x.Value); return TypeManager.Empty().Cast<IInterpedEmpty>(); }, MethodType.CreateAndBuild( new NumberType(), new EmptyType())) .AddMethod( new NameKey("write-string"), (IBoxedString x) => { stringDestination(x.Value); return TypeManager.Empty().Cast<IInterpedEmpty>(); }, MethodType.CreateAndBuild( new StringType(), new EmptyType())) .AddMethod( new NameKey("write-bool"), (IBoxedBool x) => { boolDestination(x.Value); return TypeManager.Empty().Cast<IInterpedEmpty>(); }, MethodType.CreateAndBuild( new BooleanType(), new EmptyType())) .Build(); } } }
88937d67e3b7cfe88a1aa414df54e99b3de24022
C#
Inforward/Web
/Bespoke.Model/User.cs
2.6875
3
using System; using System.Collections.Generic; namespace Bespoke.Models { public class User : EntityBase { public string Email { get; set; } public string PasswordHash { get; set; } public string PasswordSalt { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ProfileImageUrl { get; set; } public string Name { get { var name = string.Empty; if (!string.IsNullOrEmpty(FirstName)) name += FirstName; if (!string.IsNullOrEmpty(LastName)) { if (name.Length > 0) name += " "; name += LastName; } return name; } } public UserRegistrationMethods UserRegistrationMethod { get; set; } public long? FacebookUserId { get; set; } public List<Connection> FacebookFriends { get; set; } } public class Connection { public long Id { get; set; } public string Name { get; set; } } public enum UserRegistrationMethods { Email = 1, Facebook = 2, Google = 3 } }
bb440da9b2a8ddd98d9eaba7dec7d83cd06fe6d1
C#
JanDvorakCZ/RaEd
/Projekt/SeparateColor.cs
3.28125
3
using System.ComponentModel; using System.Drawing; using System.Runtime.CompilerServices; namespace RoP_RaEd { class SeparateColor : INotifyPropertyChanged { private byte _a, _r, _g, _b; public event PropertyChangedEventHandler PropertyChanged; public byte A { get { return _a; } set { _a = value; OnPropertyChanged(); } } public byte R { get { return _r; } set { _r = value; OnPropertyChanged(); } } public byte G { get { return _g; } set { _g = value; OnPropertyChanged(); } } public byte B { get { return _b; } set { _b = value; OnPropertyChanged(); } } public SeparateColor(byte a, byte r, byte g, byte b) { A = a; R = r; G = g; B = b; } public SeparateColor(Color c) { A = c.A; R = c.R; G = c.G; B = c.B; } private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } public Color ToDefaultColor() { return Color.FromArgb(A, R, G, B); } } }