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
|
|---|---|---|---|---|---|---|
1d4b4964f32af5c67bdc6869eec0fe67ed27d3ae
|
C#
|
vchelaru/FlatRedBall
|
/FRBDK/Glue/GameCommunicationPlugin/GlueControl/ViewModels/TestViewModel.cs
| 2.6875
| 3
|
using FlatRedBall.Glue.MVVM;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media;
namespace GameCommunicationPlugin.GlueControl.ViewModels
{
class TestViewModel : ViewModel
{
//public int Health
//{
// get => Get<int>();
// set => Set(value);
//}
int mHealth;
public int Health
{
get => mHealth;
set
{
if(mHealth != value)
{
mHealth = value;
NotifyPropertyChanged(nameof(Health));
}
}
}
public int MaxHealth
{
get => Get<int>();
set => Set(value);
}
[DependsOn(nameof(Health))]
[DependsOn(nameof(MaxHealth))]
public SolidColorBrush HealthColor =>
Health/MaxHealth < .1 ? Brushes.Black
: Brushes.Red;
[DependsOn(nameof(Health))]
public string HealthDisplay
{
get => $"Health: {Health}";
}
[DependsOn(nameof(Health))]
public bool IsSubtractEnabled => Health > 0;
public TestViewModel()
{
MaxHealth = 100;
}
}
}
|
b9c454f2bcd16b3907f43dd0fd8a4305357a5a0b
|
C#
|
inin2007/C-Sharp
|
/w3resource/exercise26.cs
| 3.734375
| 4
|
using System;
public class Exercise26
{
public static void Main( )
{
Console.WriteLine("Sum of the first 500 prime numbers:");
long x = 0;
int y = 0;
int j = 2;
while (y < 500)
{
if (h(j))
{
x += j;
y++;
}
j++;
}
Console.WriteLine(x.ToString());
}
public static bool h(int i)
{
int n = (int)Math.Floor(Math.Sqrt(i));
if (i == 1) return false;
if (i == 2) return true;
for (int q = 2; q <= n; ++q)
{
if (i%q == 0) return false;
}
return true;
}
}
|
3342e158c17b090e3fbbab23fbece031151e7a74
|
C#
|
zcstkhk/RhinoInside.NX
|
/RhinoInside.NX.Extensions/NX/NXOpen/Structs/Quaternion.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NXOpen;
namespace RhinoInside.NX.Extensions
{
public struct Quaternion
{
#region 字段
public double Q1;
public double Q2;
public double Q3;
public double Q4;
public static readonly Quaternion Identity = new Quaternion(1.0, 0.0, 0.0, 0.0);
#endregion
#region 构造函数
public Quaternion(double _q1, double _q2, double _q3, double _q4)
{
Q1 = _q1;
Q2 = _q2;
Q3 = _q3;
Q4 = _q4;
}
// Token: 0x0600020A RID: 522 RVA: 0x0000DE83 File Offset: 0x0000C083
public Quaternion(double w, Vector4d vec)
{
Q1 = w;
Q2 = vec.X;
Q3 = vec.Y;
Q4 = vec.Z;
}
// Token: 0x0600020B RID: 523 RVA: 0x0000DEB1 File Offset: 0x0000C0B1
public Quaternion(Vector3d axis, double angle)
{
this = Quaternion.Identity;
AxisAngle = new Vector4d(axis, angle);
}
// Token: 0x0600020D RID: 525 RVA: 0x0000DEEA File Offset: 0x0000C0EA
public Quaternion(Matrix4x4 m)
{
this = Identity;
Matrix = m.GetRotation();
}
#endregion
#region 属性
public double Scalar
{
get
{
return Q1;
}
set
{
Q1 = value;
}
}
public Vector3d Vector
{
get
{
return new Vector3d(Q2, Q3, Q4);
}
set
{
Q2 = value.X;
Q3 = value.Y;
Q4 = value.Z;
}
}
public Vector4d AxisAngle
{
get
{
double num = Math.Sqrt(1.0 - Q1 * Q1);
if (num < 1E-10)
num = 1.0;
return new Vector4d(Q2 / num, Q3 / num, Q4 / num, 2.0 * Math.Acos(Clamp(Q1)));
}
set
{
if (value.Length < Globals.DistanceTolerance)
{
this = Quaternion.Identity;
}
else
{
if (double.IsNaN(value.X) || double.IsNaN(value.Y) || double.IsNaN(value.Z) || value.X * value.X + value.Y * value.Y + value.Z * value.Z == 0.0)
{
throw new ArgumentException("Invalid rotation axis");
}
double num = value.W * 0.5;
double num2 = Math.Sin(num);
double q = Math.Cos(num);
Q1 = q;
Q2 = value.X * num2;
Q3 = value.Y * num2;
Q4 = value.Z * num2;
}
}
}
#endregion
#region 基本重载函数
public double this[int index]
{
get
{
double result;
if (index == 0)
result = Q1;
else
{
if (index == 1)
result = Q2;
else
{
if (index != 2)
result = Q4;
else
result = Q3;
}
}
return result;
}
set
{
if (index == 0)
Q1 = value;
else
{
if (index == 1)
Q2 = value;
else
{
if (index == 2)
Q3 = value;
else
Q4 = value;
}
}
}
}
#endregion
public Matrix3x3 Matrix
{
get
{
Matrix3x3 identity = Matrix3x3Ex.Identity;
double num = 2.0 / Norm();
identity.Xx = 1.0 - num * (Q3 * Q3 + Q4 * Q4);
identity.Xy = num * (Q2 * Q3 + Q1 * Q4);
identity.Xz = num * (Q2 * Q4 - Q1 * Q3);
identity.Yx = num * (Q2 * Q3 - Q1 * Q4);
identity.Yy = 1.0 - num * (Q2 * Q2 + Q4 * Q4);
identity.Yz = num * (Q3 * Q4 + Q1 * Q2);
identity.Zx = num * (Q2 * Q4 + Q1 * Q3);
identity.Zy = num * (Q3 * Q4 - Q1 * Q2);
identity.Zz = 1.0 - num * (Q2 * Q2 + Q3 * Q3);
return identity;
}
set
{
double num = value.Xx + value.Yy + value.Zz + 1.0;
if (num > 1E-10)
{
double num2 = 0.5 / Math.Sqrt(num);
Q1 = 0.25 / num2;
Q2 = (value.Yz - value.Zy) * num2;
Q3 = (value.Zx - value.Xz) * num2;
Q4 = (value.Xy - value.Yx) * num2;
}
else
{
if (value.Xx > value.Yy && value.Xx > value.Zz)
{
double num3 = 0.5 / Math.Sqrt(1.0 + value.Xx - value.Yy- value.Zz);
Q1 = (value.Zy - value.Yz) * num3;
Q2 = 0.25 / num3;
Q3 = (value.Yx + value.Xy) * num3;
Q4 = (value.Zx+ value.Xz) * num3;
}
else
{
if (value.Yy > value.Zz)
{
double num4 = 0.5 / Math.Sqrt(1.0 + value.Yy- value.Xx - value.Zz);
Q1 = (value.Zx- value.Xz) * num4;
Q2 = (value.Yx + value.Xy) * num4;
Q3 = 0.25 / num4;
Q4 = (value.Zy + value.Yz) * num4;
}
else
{
double num5 = 0.5 / Math.Sqrt(1.0 + value.Zz - value.Xx - value.Yy);
Q1 = (value.Yx - value.Xy) * num5;
Q2 = (value.Zx+ value.Xz) * num5;
Q3 = (value.Zy + value.Yz) * num5;
Q4 = 0.25 / num5;
}
}
}
Normalize();
}
}
// Token: 0x06000209 RID: 521 RVA: 0x0000DE63 File Offset: 0x0000C063
// Token: 0x0600020F RID: 527 RVA: 0x0000DF24 File Offset: 0x0000C124
public static bool operator ==(Quaternion lhs, Quaternion rhs)
{
return lhs.Q1 == rhs.Q1 && lhs.Q2 == rhs.Q2 && lhs.Q3 == rhs.Q3 && lhs.Q4 == rhs.Q4;
}
// Token: 0x06000210 RID: 528 RVA: 0x0000DF74 File Offset: 0x0000C174
public static bool operator !=(Quaternion lhs, Quaternion rhs)
{
return !(lhs == rhs);
}
// Token: 0x06000211 RID: 529 RVA: 0x0000DF90 File Offset: 0x0000C190
public override bool Equals(object obj)
{
return obj is Quaternion && this == (Quaternion)obj;
}
// Token: 0x06000212 RID: 530 RVA: 0x0000DFC0 File Offset: 0x0000C1C0
public override int GetHashCode()
{
return Q1.GetHashCode() ^ Q2.GetHashCode() ^ Q3.GetHashCode() ^ Q4.GetHashCode();
}
// Token: 0x06000213 RID: 531 RVA: 0x0000E004 File Offset: 0x0000C204
public static Quaternion operator +(Quaternion lhs, Quaternion rhs)
{
return new Quaternion(lhs.Q1 + rhs.Q1, lhs.Q2 + rhs.Q2, lhs.Q3 + rhs.Q3, lhs.Q4 + rhs.Q4);
}
// Token: 0x06000214 RID: 532 RVA: 0x0000E050 File Offset: 0x0000C250
public Quaternion Add(Quaternion rhs)
{
return new Quaternion(Q1 + rhs.Q1, Q2 + rhs.Q2, Q3 + rhs.Q3, Q4 + rhs.Q4);
}
// Token: 0x06000215 RID: 533 RVA: 0x0000E09C File Offset: 0x0000C29C
public static Quaternion operator -(Quaternion lhs, Quaternion rhs)
{
return new Quaternion(lhs.Q1 - rhs.Q1, lhs.Q2 - rhs.Q2, lhs.Q3 - rhs.Q3, lhs.Q4 - rhs.Q4);
}
// Token: 0x06000216 RID: 534 RVA: 0x0000E0E8 File Offset: 0x0000C2E8
public Quaternion Subtract(Quaternion rhs)
{
return new Quaternion(Q1 - rhs.Q1, Q2 - rhs.Q2, Q3 - rhs.Q3, Q4 - rhs.Q4);
}
// Token: 0x06000217 RID: 535 RVA: 0x0000E134 File Offset: 0x0000C334
public static Quaternion operator *(Quaternion lhs, Quaternion rhs)
{
return lhs.Multiply(rhs);
}
// Token: 0x06000218 RID: 536 RVA: 0x0000E150 File Offset: 0x0000C350
public Quaternion Multiply(Quaternion rhs)
{
return new Quaternion(Q1 * rhs.Q1 - Q2 * rhs.Q2 - Q3 * rhs.Q3 - Q4 * rhs.Q4, Q1 * rhs.Q2 + Q2 * rhs.Q1 + Q3 * rhs.Q4 - Q4 * rhs.Q3, Q1 * rhs.Q3 - Q2 * rhs.Q4 + Q3 * rhs.Q1 + Q4 * rhs.Q2, Q1 * rhs.Q4 + Q2 * rhs.Q3 - Q3 * rhs.Q2 + Q4 * rhs.Q1);
}
// Token: 0x06000219 RID: 537 RVA: 0x0000E244 File Offset: 0x0000C444
public static Quaternion operator *(Quaternion lhs, double rhs)
{
return new Quaternion(lhs.Q1 * rhs, lhs.Q2 * rhs, lhs.Q3 * rhs, lhs.Q4 * rhs);
}
// Token: 0x0600021A RID: 538 RVA: 0x0000E27C File Offset: 0x0000C47C
public Quaternion Multiply(double rhs)
{
return new Quaternion(Q1 * rhs, Q2 * rhs, Q3 * rhs, Q4 * rhs);
}
// Token: 0x0600021B RID: 539 RVA: 0x0000E2B4 File Offset: 0x0000C4B4
public static Quaternion operator *(double lhs, Quaternion rhs)
{
return new Quaternion(lhs * rhs.Q1, lhs * rhs.Q2, lhs * rhs.Q3, lhs * rhs.Q4);
}
// Token: 0x0600021C RID: 540 RVA: 0x0000E2EC File Offset: 0x0000C4EC
public static Quaternion operator /(Quaternion lhs, double rhs)
{
return new Quaternion(lhs.Q1 / rhs, lhs.Q2 / rhs, lhs.Q3 / rhs, lhs.Q4 / rhs);
}
// Token: 0x0600021D RID: 541 RVA: 0x0000E324 File Offset: 0x0000C524
public Quaternion Divide(double rhs)
{
return new Quaternion(Q1 / rhs, Q2 / rhs, Q3 / rhs, Q4 / rhs);
}
// Token: 0x0600021E RID: 542 RVA: 0x0000E35C File Offset: 0x0000C55C
public static Quaternion operator -(Quaternion rhs)
{
return new Quaternion(-rhs.Q1, -rhs.Q2, -rhs.Q3, -rhs.Q4);
}
// Token: 0x0600021F RID: 543 RVA: 0x0000E390 File Offset: 0x0000C590
public double Norm()
{
return Q1 * Q1 + Q2 * Q2 + Q3 * Q3 + Q4 * Q4;
}
// Token: 0x06000220 RID: 544 RVA: 0x0000E3DC File Offset: 0x0000C5DC
public double Magnitude()
{
return Math.Sqrt(Q1 * Q1 + Q2 * Q2 + Q3 * Q3 + Q4 * Q4);
}
// Token: 0x06000221 RID: 545 RVA: 0x0000E42C File Offset: 0x0000C62C
public void Normalize()
{
double num = Magnitude();
Q1 /= num;
Q2 /= num;
Q3 /= num;
Q4 /= num;
}
// Token: 0x06000222 RID: 546 RVA: 0x0000E47C File Offset: 0x0000C67C
public void Invert()
{
double num = 1.0 / Norm();
Q1 *= num;
Q2 = -Q2 * num;
Q3 = -Q3 * num;
Q4 = -Q4 * num;
}
// Token: 0x06000223 RID: 547 RVA: 0x0000E4D8 File Offset: 0x0000C6D8
public Quaternion Inverse()
{
double num = 1.0 / Norm();
return new Quaternion(Q1 * num, -Q2 * num, -Q3 * num, -Q4 * num);
}
// Token: 0x06000224 RID: 548 RVA: 0x0000E524 File Offset: 0x0000C724
public Quaternion Conjugate()
{
return new Quaternion(Q1, -Q2, -Q3, -Q4);
}
// Token: 0x06000225 RID: 549 RVA: 0x0000E558 File Offset: 0x0000C758
public double Dot(Quaternion rhs)
{
return Q1 * rhs.Q1 + Q2 * rhs.Q2 + Q3 * rhs.Q3 + Q4 * rhs.Q4;
}
// Token: 0x06000226 RID: 550 RVA: 0x0000E5A4 File Offset: 0x0000C7A4
public Quaternion Interpolate(Quaternion quat, double slerp)
{
double num = Dot(quat);
Quaternion result;
if (num < 0.0)
result = Interpolate(-quat, slerp);
else
{
double rhs;
double rhs2;
if (num > -0.9999999999 && num < 0.9999999999)
{
double num2 = Math.Acos(num);
double num3 = Math.Sin(num2);
rhs = Math.Sin((1.0 - slerp) * num2) / num3;
rhs2 = Math.Sin(slerp * num2) / num3;
}
else
{
rhs = 1.0 - slerp;
rhs2 = slerp;
}
result = this * rhs + quat * rhs2;
}
return result;
}
public override string ToString()
{
return string.Format("[{0} {1} {2} {3}]", new object[]
{
Q1,
Q2,
Q3,
Q4
});
}
internal static double Clamp(double d)
{
double result;
if (d < -1.0)
result = -1.0;
else
{
if (d > 1.0)
result = 1.0;
else
result = d;
}
return result;
}
}
}
|
3696ce32cdb702ea56866ff3f19f98b0d8aead4f
|
C#
|
ElliotOne/CSharpFull
|
/_zz_OtherTopics/_08_DynamicKeyword.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _zz_OtherTopics
{
class _08_DynamicKeyword
{
void ThisIsMAin()
{
dynamic value = 0;
Console.WriteLine("Value = " + value);
value = "Hello";
Console.WriteLine("Value = " + value);
value = new dynamicClassEx();
value.Name = "Name!";
}
}
class dynamicClassEx
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
}
|
8fabea6c305b13063541c0a4bd79efe018e8563f
|
C#
|
geethasamynathan/INTCDE21ID008
|
/MVCDemo1/EmployeeRepository.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MVCDemo1.Models
{
public class EmployeeRepository : IEmployeeRepository
{
public List<Employee> employees = new List<Employee>();
public EmployeeRepository()
{
Employee emp1 = new Employee(){ Id=1, Name="Saahil",Department="HR"};
Employee emp2 = new Employee() { Id = 2, Name = "Asritha", Department = "Accounts" };
Employee emp3 = new Employee() { Id = 3, Name = "Akansha", Department = "IT" };
employees.Add(emp1);
employees.Add(emp2);
employees.Add(emp3);
}
public Employee GetEmployeeById(int id)
{
Employee emp= employees.Find(e => e.Id==id);
return emp;
}
public List<Employee> GetEmployees()
{
return employees;
}
public void Save(Employee employee)
{
// throw new NotImplementedException();
}
}
}
|
7c226790e91196e69aa76e7d21e0022d155b0fa9
|
C#
|
sharewebcode/Web
|
/CSharp/WPF/Zero_To_FileWrite/WPF_FileContentDelete2/ViewModels/SelectionFileDataSource.cs
| 2.703125
| 3
|
using System.ComponentModel;
namespace WPF_FileContentDelete.ViewModels
{
public class SelectionFileDataSource : INotifyPropertyChanged
{
private string filePath;
private long fileSize;
public string FilePath
{
get { return filePath; }
set
{
if( filePath != value )
{
filePath = value;
OnPropertyChanged( nameof( FilePath ) );
}
}
}
public long FileSize
{
get { return fileSize; }
set
{
if( fileSize != value )
{
fileSize = value;
OnPropertyChanged( nameof( FileSize ) );
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged( string propertyName )
{
PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}
#endregion
}
}
|
cc729f9ad90202901ed6a6efe23d17901fd9fdec
|
C#
|
kuier/JianZhiOfferCSharp
|
/5-用两个栈实现队列/Program.cs
| 3.546875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5_用两个栈实现队列
{
class Solution
{
private Stack<int> stack1 = new Stack<int>();
private Stack<int> stack2 = new Stack<int>();
public void push(int node)
{
stack1.Push(node);
}
public int pop()
{
if (stack2.Count ==0)
{
int m = stack1.Count;
for (int i = 0; i < m; i++)
{
stack2.Push(stack1.Pop());
}
return stack2.Pop();
}
else
{
return stack2.Pop();
}
}
}
class Program
{
static void Main(string[] args)
{
Solution s = new Solution();
s.push(1);
s.push(2);
s.push(3);
Console.WriteLine(s.pop());
Console.WriteLine(s.pop());
s.push(4);
Console.WriteLine(s.pop());
s.push(5);
Console.WriteLine(s.pop());
Console.WriteLine(s.pop());
Console.Read();
}
}
}
|
dd6401c4c9d82e59f1b314b3f5ba6b490ca57e55
|
C#
|
nixonyong911/C-Sharp_Typing_Game
|
/exampleMenu/Main.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
using System.IO;
namespace exampleMenu
{
public partial class Menu : Form
{
private int currentLevel;
SoundPlayer sndplayr = new SoundPlayer(exampleMenu.Properties.Resources.Ring05);
public Menu()
{
InitializeComponent();
StartGamePanel.Visible = false;
OptionPanel.Visible = false;
TimeTrialPanel.Visible = false;
sndplayr.Play();
sndplayr.PlayLooping();
}
private void buttonStart_Click(object sender, EventArgs e)
{
StartGamePanel.Visible = true;
}
private void buttonOption_Click(object sender, EventArgs e)
{
OptionPanel.Visible = true;
}
private void buttonCredits_Click(object sender, EventArgs e)
{
MessageBox.Show("Created by Wong Weng Keong and Nixon Yong. The Greatest Jedi of All!", "Creator of Final Typing XIII!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void buttonBackMenu_Click(object sender, EventArgs e)
{
StartGamePanel.Visible = false;
}
private void buttonTimeTrial_Click(object sender, EventArgs e)
{
//sndplayr.Stop();
//keyboard a = new keyboard();
//a.Show();
TimeTrialPanel.Visible = true;
}
private void buttonHighScore_Click(object sender, EventArgs e)
{
int point_score = 0;
string[] time_score = File.ReadAllLines("highscore_time.txt");
using (StreamReader sr = new StreamReader("highscore_point.txt"))
{
point_score = Convert.ToInt32(sr.ReadLine());
}
MessageBox.Show("Point Game HighScore: " + point_score
+ "\nTime Game Easy HighScore: " + time_score[0]
+ "\nTime Game Medium HighScore: " + time_score[1]
+ "\nTime Game Hard HighScore: " + time_score[2]
, "\n", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void buttonBackOption_Click(object sender, EventArgs e)
{
OptionPanel.Visible = false;
}
private void buttonSoundOff_Click(object sender, EventArgs e)
{
sndplayr.Stop();
buttonSoundOff.Enabled = false;
buttonSoundOn.Enabled = true;
}
private void buttonSoundOn_Click(object sender, EventArgs e)
{
sndplayr.Play();
sndplayr.PlayLooping();
buttonSoundOn.Enabled = false;
buttonSoundOff.Enabled = true;
}
private void buttonBackTT_Click(object sender, EventArgs e)
{
TimeTrialPanel.Visible = false;
}
private void EasyTT_Click(object sender, EventArgs e)
{
currentLevel = 1;
sndplayr.Stop();
keyboard a = new keyboard(currentLevel);
a.Show();
}
private void MediumTT_Click(object sender, EventArgs e)
{
currentLevel = 2;
sndplayr.Stop();
keyboard a = new keyboard(currentLevel);
a.Show();
}
private void HardTT_Click(object sender, EventArgs e)
{
currentLevel = 3;
sndplayr.Stop();
keyboard a = new keyboard(currentLevel);
a.Show();
}
private void buttonPoints_Click(object sender, EventArgs e)
{
sndplayr.Stop();
point a = new point();
a.Show();
}
}
}
|
7d0d7cdb9ff5e4442afaee17cbb8093b8dc464b5
|
C#
|
mihov/TelerikAkademy2016
|
/CSharp-Part-2/03. Methods/11. Adding polynomials/AddingPolynomials.cs
| 3.703125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class AddingPolynomials
{
static void Main()
{
Console.ReadLine();
int[] firstPolynomial = SplitStrToInt(Console.ReadLine());
int[] secondPolynomial = SplitStrToInt(Console.ReadLine());
Console.WriteLine(String.Join(" ", AddPly(firstPolynomial, secondPolynomial)));
}
private static int[] AddPly(int[] firstPolynomial, int[] secondPolynomial)
{
int size = firstPolynomial.GetLength(0);
int[] result = new int[size];
for (int i = 0; i < size; i++)
{
result[i] = firstPolynomial[i] + secondPolynomial[i];
}
return result;
}
static int[] SplitStrToInt(string text)
{
string[] tokens = text.Split(' ');
return Array.ConvertAll<string, int>(tokens, int.Parse);
}
}
|
43f2b70ffda3ea2dff01dd1a88254f9510f0ecd8
|
C#
|
vermie/AnyMapper
|
/AnyMapper.Test.Unit/PropertyMapperTests.cs
| 2.765625
| 3
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AnyMapper.Tests.Unit
{
[TestClass]
public class PropertyMapperTests
{
[TestCleanup]
public void Cleanup()
{
Mapper.DebugFlush();
}
public class T1
{
public int Property { get; set; }
public T2 T2 { get; set; }
}
public class T2
{
public int Property { get; set; }
public T1 T1 { get; set; }
}
[TestMethod]
public void MemberPrimitivesAreMapped()
{
var typeMapper = Mapper.CreateMapper<T1, T2>();
typeMapper.Property(t => t.Property).MapsTo(t => t.Property);
var t1 = new T1() { Property = 1 };
var t2 = Mapper.Map<T1, T2>(t1);
Assert.AreEqual(t1.Property, t2.Property);
}
[TestMethod]
public void MemberObjectsAreMapped()
{
var typeMapper = Mapper.CreateMapper<T1, T2>();
typeMapper.Property(t => t.Property).MapsTo(t => t.Property);
typeMapper.Property(t => t.T2).MapsTo(t => t.T1);
var t1 = new T1() { T2 = new T2() { Property = 1 } };
var t2 = Mapper.Map<T1, T2>(t1);
Assert.IsNotNull(t2.T1);
Assert.AreEqual(t1.T2.Property, t2.T1.Property);
var t3 = Mapper.Map<T2, T1>(t2);
Assert.IsNotNull(t3);
Assert.IsNotNull(t2.T1);
Assert.AreEqual(t1.T2.Property, t3.T2.Property);
}
[TestMethod]
public void MemberObjectsAreMappedBothWays()
{
var typeMapper = Mapper.CreateMapper<T1, T2>();
typeMapper.Property(t => t.Property).MapsTo(t => t.Property);
typeMapper.Property(t => t.T2).MapsTo(t => t.T1);
var t1 = new T1() { T2 = new T2() { Property = 1 } };
var t2 = Mapper.Map<T1, T2>(t1);
var t3 = Mapper.Map<T2, T1>(t2);
Assert.IsNotNull(t3);
Assert.IsNotNull(t2.T1);
Assert.AreEqual(t1.T2.Property, t3.T2.Property);
}
[TestMethod]
public void OriginalObjectsAreNotDestroyed()
{
var typeMapper = Mapper.CreateMapper<T1, T2>();
typeMapper.Property(t => t.Property).MapsTo(t => t.Property);
var t1 = new T1();
var t2 = new T2();
var originalT2 = t2;
Mapper.Map<T1, T2>(t1, t2);
Assert.AreSame(originalT2, t2);
}
[TestMethod]
public void OriginalObjectsAreMerged()
{
var typeMapper = Mapper.CreateMapper<T1, T2>();
typeMapper.Property(t => t.Property).MapsTo(t => t.Property);
var t1 = new T1() { Property = 1 };
var t2 = new T2();
var originalT2 = t2;
Mapper.Map<T1, T2>(t1, t2);
Assert.AreEqual(t1.Property, originalT2.Property);
}
}
}
|
408d09f6f00308217e1866055e09d3899187b2a1
|
C#
|
dexterdelandro/Krawl
|
/Krawl/Krawl/GameArchitecture/GameObject.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace Krawl.GameArchitecture
{
public class GameObject
{
#region Variables
/// <summary>
/// Collection of all active GameObjects
/// </summary>
public static List<GameObject> AllGameObjects = new List<GameObject>();
private SpriteRenderer spriteRenderer;
private List<Component> attachedComponents = new List<Component>();
private Vector2 position = Vector2.Zero;
private float rotation = 0f;
private Vector2 scale = Vector2.One;
private string name;
#endregion
#region Properties
public Vector2 Position { get => position; set => position = value; }
public Vector2 PositionCenter
{
get => new Vector2(position.X + ((SpriteRend.Sprite.Width * scale.X) / 2f), position.Y + ((SpriteRend.Sprite.Height * scale.Y) / 2f));
set => position = new Vector2(value.X - ((SpriteRend.Sprite.Width * scale.X) / 2f), value.Y - ((SpriteRend.Sprite.Height * scale.Y) / 2f));
}
public float Rotation { get => rotation; set => rotation = value; }
public Vector2 Scale { get => scale; set => scale = value; }
public SpriteRenderer SpriteRend { get => spriteRenderer; set => spriteRenderer = value; }
public string Name { get => name; set => name = value; }
#endregion
public GameObject()
{
AllGameObjects.Add(this);
Start();
}
public virtual void Start()
{
}
public virtual void Update()
{
foreach (Component comp in attachedComponents)
comp.Update();
}
public virtual void Draw(SpriteBatch batch)
{
if (SpriteRend != null)
{
SpriteRend.Draw(batch);
}
}
/// <summary>
/// Get component by type.
/// </summary>
/// <typeparam name="T">Type of component.</typeparam>
/// <returns></returns>
public T GetComponent<T>() where T : Component
{
foreach (Component comp in attachedComponents)
if (comp is T)
return comp as T;
return null;
}
/// <summary>
/// Add a Component to this Gameobject.
/// </summary>
/// <typeparam name="T">Type of Component.</typeparam>
/// <returns></returns>
public T AddComponent<T>() where T : Component, new()
{
return AddComponent(new T());
}
/// <summary>
/// Add a Component to this Gameobject.
/// </summary>
/// <typeparam name="T">Type of Component.</typeparam>
/// <param name="component">The Component being added.</param>
public T AddComponent<T>(T component) where T : Component
{
if (component is SpriteRenderer)
SpriteRend = component as SpriteRenderer;
attachedComponents.Add(component);
component.ConnectedGameObject = this;
component.Start();
return component;
}
/// <summary>
/// Gets all components, that are attached to GameObjects, of a type.
/// </summary>
/// <typeparam name="T">The type of Component.</typeparam>
/// <returns></returns>
public static List<T> GetAllComponentsOfType<T>() where T : Component
{
List <T> listOfComp = new List<T>();
foreach(GameObject go in AllGameObjects)
foreach(Component co in go.attachedComponents)
if (co is T)
listOfComp.Add(co as T);
return listOfComp;
}
/// <summary>
/// Draws all GameObjects that have SpriteRenderer's attached.
/// </summary>
/// <param name="batch">The active SpriteBatch.</param>
public static void DrawAll(SpriteBatch batch)
{
// We create a sorted list here:
// We are sorting by the draw layer, if something is ordered futher back (closer to zero)
// then we will draw that first, and draw objects in order of their draw layer
BetterSortedList<int, GameObject> gameObjectsToDrawSorted = new BetterSortedList<int, GameObject>();
foreach (GameObject go in AllGameObjects)
{
// Making sure we only want to order (and draw) stuff that can be drawn (Having SpriteRenderer)
if (go.SpriteRend != null)
gameObjectsToDrawSorted.Add(go.SpriteRend.DrawLayer, go);
}
gameObjectsToDrawSorted.Sort();
foreach (Tuple<int, GameObject> goPair in gameObjectsToDrawSorted)
{
goPair.Item2.SpriteRend.Draw(batch);
}
}
/// <summary>
/// Destorys This GameObject.
/// </summary>
public void Destroy()
{
AllGameObjects.Remove(this);
}
/// <summary>
/// Update all active GameObjects.
/// </summary>
/// <param name="gt">The game time.
/// Use ElapsedGameTime.TotalSeconds to get delta time
/// </param>
public static void UpdateAll()
{
for (int i = 0; i < AllGameObjects.Count; i++)
{
GameObject go = AllGameObjects[i];
go.Update();
}
}
}
}
|
67963d511bf88b0f5a05c814e614b0214cd8a765
|
C#
|
Nilmaros/wtw-exercise
|
/WTW/CSVHandler.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using WTW.models;
using System.IO;
using System.Linq;
namespace WTW
{
public class CSVHandler
{
private readonly string _inputAddress;
private readonly string _outputAddress;
private readonly string _outputFileName;
public CSVHandler(string inputAddress, string outputAddress, string outputFileName)
{
_inputAddress = inputAddress;
_outputAddress = outputAddress;
_outputFileName = outputFileName;
}
public List<IncrementalProduct> Read()
{
List<IncrementalProduct> incrementalList = new List<IncrementalProduct> ();
int counter = 0;
using (var reader = new StreamReader(_inputAddress))
{
while (!reader.EndOfStream)
{
IncrementalProduct holder = new IncrementalProduct();
var line = reader.ReadLine();
var values = line.Split(',');
if (counter != 0) // Skip headers
{
holder.Product = values[0];
holder.OriginYear = Int32.Parse(Regex.Replace(values[1], "[^.0-9]", ""));
holder.DevYear = Int32.Parse(Regex.Replace(values[2], "[^.0-9]", ""));
holder.Value = Double.Parse(Regex.Replace(values[3], "[^.0-9]", ""));
incrementalList.Add(holder);
}
counter++;
}
return incrementalList;
}
}
public void Write(string cumulativeString)
{
List<string> lines = cumulativeString.Split(";").ToList();
using (var w = new StreamWriter(_outputAddress + "/" + _outputFileName + ".csv"))
{
foreach (string line in lines)
{
w.WriteLine(line);
w.Flush();
}
}
}
}
}
|
047ba3f22398ddffac42ea47486ee67867da4ca7
|
C#
|
ndrwrbgs/FastLinq
|
/src/Library/Collection/StayInCollection/Reverse.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Linq
{
public static partial class FastLinq
{
public static IReadOnlyCollection<T> Reverse<T>(
this IReadOnlyCollection<T> source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return new EnumerableWithCount<T>(
Enumerable.Reverse(source),
source.Count);
}
}
}
|
fd7dddecf14bb21b0fdb9073601a65226457f710
|
C#
|
Alltips/gawi-bawi-bo
|
/frmMain.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 가위바위보_게임
{
public partial class frmMain : Form
{
private Random rnd;
private int iScore = 0;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnK_Click(object sender, EventArgs e)
{
rnd = new Random();
int random = rnd.Next(3, 10);
lblHand.Text = "가위";
if (random == 1)
{
lblAiHand.Text = "가위";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
if (random == 2)
{
lblAiHand.Text = "바위";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
if (random == 3)
{
lblAiHand.Text = "보";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
}
private void btnBO_Click(object sender, EventArgs e)
{
rnd = new Random();
int random = rnd.Next(3, 10);
lblHand.Text = "바위";
if (random == 1)
{
lblAiHand.Text = "가위";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
if (random == 2)
{
lblAiHand.Text = "바위";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
if (random == 3)
{
lblAiHand.Text = "보";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
}
private void btnB_Click(object sender, EventArgs e)
{
rnd = new Random();
int random = rnd.Next(3, 10);
lblHand.Text = "보";
if (random == 1)
{
lblAiHand.Text = "가위";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
if (random == 2)
{
lblAiHand.Text = "바위";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
if (random == 3)
{
lblAiHand.Text = "보";
if (lblAiHand.Text == lblHand.Text)
{
iScore -= 1;
score.Text = iScore.ToString();
}
else
{
iScore += 1;
score.Text = iScore.ToString();
}
}
}
}
}
|
4cc3a3459a968c68e0602bac341d0b2c5e409957
|
C#
|
blish-hud/Blish-HUD
|
/Blish HUD/GameServices/Settings/SettingEntry[T].cs
| 3.0625
| 3
|
using System;
using Newtonsoft.Json;
namespace Blish_HUD.Settings {
public sealed class SettingEntry<T> : SettingEntry {
public event EventHandler<ValueChangedEventArgs<T>> SettingChanged;
private void OnSettingChanged(ValueChangedEventArgs<T> e) {
GameService.Settings.Save();
OnPropertyChanged(nameof(this.Value));
this.SettingChanged?.Invoke(this, e);
}
private T _value;
[JsonProperty(SETTINGVALUE_KEY), JsonRequired]
public T Value {
get => _value;
set {
if (object.Equals(_value, value)) return;
var prevValue = this.Value;
_value = value;
OnSettingChanged(new ValueChangedEventArgs<T>(prevValue, _value));
}
}
protected override Type GetSettingType() {
return typeof(T);
}
protected override object GetSettingValue() {
return _value;
}
public SettingEntry() { /* NOOP */ }
/// <summary>
/// Creates a new <see cref="SettingEntry"/> of type <see cref="T"/>.
/// </summary>
/// <param name="value">The default value for the <see cref="SettingEntry{T}"/> if a value has not yet been saved in the settings.</param>
protected SettingEntry(T value) {
_value = value;
}
public static SettingEntry<T> InitSetting(T value) {
var newSetting = new SettingEntry<T>(value);
return newSetting;
}
public static SettingEntry<T> InitSetting(string entryKey, T value) {
var newSetting = new SettingEntry<T>(value) {
EntryKey = entryKey,
_value = value,
};
return newSetting;
}
}
}
|
713d00ba610ccbc30c8ea1854de56e89fa5214de
|
C#
|
brittaschulte/unityrealtimeweather
|
/Assets/Sample/WeatherDataManager.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeatherDataManager : MonoBehaviour {
public void Start()
{
Invoke("CheckWeather", 3.0f);
}
private void CheckWeather()
{
Debug.Log(GetComponent<WeatherScript>().GetCurrentWeatherObject().ToString());
}
public void OnWeatherChanged(string weather)
{
Debug.Log("Weather changed to: " + weather);
}
}
|
584d6f4143c881992a5bb80e51810446f3739dd5
|
C#
|
Ivanestver/MedicCards
|
/MedicCards/Forms/Functional/Update.cs
| 2.71875
| 3
|
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MedicCards
{
public partial class Update : Form
{
int n;
DataGridView data = new DataGridView();
string form = "";
public Update(int _n, DataGridView _data, string _form)
{
InitializeComponent();
n = _n;
data = _data;
form = _form;
}
private void Update_Load(object sender, EventArgs e)
{
Loading();
ar.Text = data.Rows[n].Cells[1].Value.ToString();
number.Text = data.Rows[n].Cells[2].Value.ToString();
name.Text = data.Rows[n].Cells[3].Value.ToString();
birth.Text = data.Rows[n].Cells[4].Value.ToString();
handover.Text = data.Rows[n].Cells[5].Value.ToString();
arrive.Text = data.Rows[n].Cells[6].Value.ToString();
notes.Text = data.Rows[n].Cells[7].Value.ToString();
}
private void Update_ClientSizeChanged(object sender, EventArgs e)
{
Loading();
}
void Loading()
{
// setup of locations of named elements
const sbyte x = 30, y = 70;
number.Location = new Point((ClientSize.Width - number.Width) / 2, y);
name.Location = new Point(number.Right + x, number.Top);
ar.Location = new Point(number.Left - x - ar.Width, number.Top);
birth.Location = new Point(ar.Left, ar.Bottom + y);
handover.Location = new Point(birth.Right + x, birth.Top);
arrive.Location = new Point(handover.Right + x, birth.Top);
notes.Location = new Point(ar.Left, birth.Bottom + y);
// setup of locations of labels
const sbyte yL = 16;
label1.Location = new Point(ar.Left + ar.Width / 2 - label1.Width / 2, ar.Top - yL);
label2.Location = new Point(number.Left + number.Width / 2 - label2.Width / 2, label1.Top);
label3.Location = new Point(name.Left + name.Width / 2 - label3.Width / 2, label1.Top);
label4.Location = new Point(birth.Left + (birth.Width - label4.Width) / 2, birth.Top - yL);
label5.Location = new Point(handover.Left + (handover.Width - label5.Width) / 2, label4.Top);
label6.Location = new Point(arrive.Left + (arrive.Width - label6.Width) / 2, label4.Top);
label7.Location = new Point(notes.Left + (notes.Width - label7.Width) / 2, notes.Top - yL);
// setup of locations of buttons
back.Location = new Point(notes.Right - back.Width, notes.Bottom + 60);
up.Location = new Point(back.Left - 40 - up.Width, back.Top);
}
private void back_Click(object sender, EventArgs e)
{
Hide();
new Main().Show();
}
private void up_Click(object sender, EventArgs e)
{
Change change = new Change();
change.Update(data, ar, number, name, "Архив", n);
change.Update(data, number, number, name, "Номер_карты", n);
change.Update(data, name, number, name, "ФИО", n);
change.Update(data, birth, number, name, "Дата_рождения", n);
change.Update(data, handover, number, name, "Период_сдачи", n);
change.Update(data, arrive, number, name, "Дата_поступления", n);
change.Update(data, notes, number, name, "Особые_пометки", n);
Hide();
switch (form)
{
case "SearchNumbers":
new SearchNumbers().Show();
break;
case "Main":
new Main().Show();
break;
case "SearchNames":
new SearchNames().Show();
break;
case "SearchBirth":
new SearchBirth().Show();
break;
}
}
}
}
|
5b51635ad09c3ea42e460486bd75760c2aeac4c3
|
C#
|
syrjgc11006/asp.net-demo
|
/WebService/一个简单的web服务/App_Code/Service.cs
| 2.6875
| 3
|
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
[WebService(Namespace = "http://contoso.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod(Description = "第一个测试方法,输入学生姓名,返回学生信息")]
public string Select(string stuName)
{
//以Windows的方式进行登录的
SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=F:\\实践小组\\WEB编程\\ASP.NET\\WEBSERVICE\\一个简单的WEB服务\\APP_DATA\\DB_18.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from tb_StuInfo where stuName='" + stuName + "'", conn);
SqlDataReader dr = cmd.ExecuteReader();
string txtMessage = "";
if (dr.Read())
{
txtMessage = "学生编号:" + dr["stuID"] + " ,";
txtMessage += "姓名:" + dr["stuName"] + " ,";
txtMessage += "性别:" + dr["stuSex"] + " ,";
txtMessage += "爱好:" + dr["stuHobby"] + " ,";
}
else
{
if (String.IsNullOrEmpty(stuName))
{
txtMessage = "<Font Color='Blue'>请输入姓名</Font>";
}
else
{
txtMessage = "<Font Color='Red'>查无此人!</Font>";
}
}
cmd.Dispose();
dr.Dispose();
conn.Dispose();
return txtMessage; //返回用户详细信息
}
}
|
cfc19954a9ca4ff5fb8e217a797459f5a587bc44
|
C#
|
itrofimow/PekaDaily
|
/Back/Jobs/Jobs/Mongo/MongoContext.cs
| 2.671875
| 3
|
using System;
using System.Collections.Concurrent;
using Jobs.Models;
using MongoDB.Driver;
namespace Jobs.Mongo
{
public class MongoContext
{
private readonly MongoClient _mongoClient;
private readonly MongoUrl _mongoUrl;
private readonly ConcurrentDictionary<Type, string> _collectionNameCache =
new ConcurrentDictionary<Type, string>();
public MongoContext(string uri)
{
_mongoUrl = new MongoUrl(uri);
var settings = MongoClientSettings.FromUrl(_mongoUrl);
_mongoClient = new MongoClient(settings);
}
public IMongoCollection<T> For<T>() where T : class
{
var collectionName = _collectionNameCache.GetOrAdd(typeof(T), GetCollectionName);
return _mongoClient.GetDatabase(_mongoUrl.DatabaseName).GetCollection<T>(collectionName);
}
public string GetCollectionName(Type entity)
{
var attribute = (MongoEntity) Attribute.GetCustomAttribute(entity, typeof(MongoEntity));
if (attribute == null)
throw new Exception($"Mark {entity} with {typeof(MongoEntity)}");
return attribute.CollectionName;
}
}
}
|
ffa9f21acb69f2f6d9aac04a749e31e89f1364f1
|
C#
|
Amjadraza26/MySMS
|
/SMS/LogicKernal/ClassStudents.cs
| 2.703125
| 3
|
using System.Data;
namespace LogicKernal
{
public class ClassStudents
{
public static DataTable GetAllClassStudents()
{
try
{
DataKernal.ClassStudents objClassStudents = new DataKernal.ClassStudents();
return objClassStudents.SelectClassStudents().Tables[0];
}
catch (System.Exception ex)
{
return null;
}
}
public static DataTable ClassStudent(int ClassID, int SectionID)
{
DataTable dtStudents = GetAllClassStudents();
if(dtStudents.Rows.Count>0)
{
DataRow[] rows = dtStudents.Select("ClassID = " + ClassID.ToString());
dtStudents = new DataTable();
if (rows.Length > 0)
dtStudents = rows.CopyToDataTable();
if (dtStudents.Rows.Count > 0)
{
DataRow[] row = dtStudents.Select("SectionID = " + SectionID.ToString());
dtStudents = new DataTable();
if (rows.Length > 0)
dtStudents = row.CopyToDataTable();
return dtStudents;
}
}
else
{
dtStudents = new DataTable();
}
return dtStudents;
}
public static DataTable GetClassStudentsByID(int intClassStudentID)
{
try
{
DataKernal.ClassStudents objClassStudents = new DataKernal.ClassStudents();
return objClassStudents.SelectClassStudents(intClassStudentID).Tables[0];
}
catch (System.Exception ex)
{
return null;
}
}
public static DataTable InsertUpdateClassStudents(BusinessEntities.ClassStudents objClassStudents)
{
try
{
DataKernal.ClassStudents objDClassStudents = new DataKernal.ClassStudents();
return objDClassStudents.InsertUpdateClassStudents(objClassStudents.ClassStudentID, objClassStudents.ClassID, objClassStudents.SectionID, objClassStudents.StudentID, objClassStudents.UserID, objClassStudents.DateCreated, objClassStudents.IsEnabled, objClassStudents.Remarks, objClassStudents.RollNo).Tables[0];
}
catch (System.Exception ex)
{
return null;
}
}
public static DataTable DeleteClassStudents(int intClassStudentID)
{
try
{
DataKernal.ClassStudents objClassStudents = new DataKernal.ClassStudents();
return objClassStudents.DeleteClassStudents(intClassStudentID).Tables[0];
}
catch (System.Exception ex)
{
return null;
}
}
public static DataTable DeleteClassStudents()
{
try
{
DataKernal.ClassStudents objClassStudents = new DataKernal.ClassStudents();
return objClassStudents.DeleteClassStudents().Tables[0];
}
catch (System.Exception ex)
{
return null;
}
}
public static DataTable TruncateClassStudents()
{
try
{
DataKernal.ClassStudents objClassStudents = new DataKernal.ClassStudents();
return objClassStudents.ClassStudentsTruncate().Tables[0];
}
catch (System.Exception ex)
{
return null;
}
}
}
}
|
48023c8e9445d84a2d3bbe9ca94f60e3b098ad4f
|
C#
|
wcatykid/GeoShader
|
/Main/GeometryTutorLib/UIProblemDrawer.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using GeometryTutorLib.Area_Based_Analyses.Atomizer;
using GeometryTutorLib.ConcreteAST;
namespace GeometryTutorLib
{
/// <summary>
/// A class that can be used tell the UI to draw problems.
/// Follows a variation on the singleton pattern - must be explicitly created once.
/// </summary>
public class UIProblemDrawer
{
private static UIProblemDrawer instance = null;
private Action<ProblemDescription> invokeDraw;
private Action invokeClear;
private Action invokeReset;
/// <summary>
/// Create a new UIProblemDrawer.
/// </summary>
/// <param name="draw">The Action that handles a UI draw.</param>
/// <param name="clear">The Action that handles a UI clear.</param>
/// <param name="reset">The Action that handles a ProblemDrawer reset.</param>
private UIProblemDrawer(Action<ProblemDescription> draw, Action clear, Action reset)
{
invokeDraw = draw;
invokeClear = clear;
invokeReset = reset;
}
/// <summary>
/// Create the UIProblemDrawer.
/// This method should only be called once, and should be called before any call to getInstance().
/// </summary>
/// <param name="draw">The Action that handles a UI draw.</param>
/// <param name="clear">The Action that handles a UI clear.</param>
/// <param name="reset">The Action that handles a ProblemDrawer reset.</param>
public static void create(Action<ProblemDescription> draw, Action clear, Action reset)
{
Debug.Assert(instance == null, "create() should only be called once.");
instance = new UIProblemDrawer(draw, clear, reset);
}
/// <summary>
/// Get an instance of the UIProblemDrawer.
/// Should only be called after create has been called in the UI.
/// </summary>
/// <returns></returns>
public static UIProblemDrawer getInstance()
{
Debug.Assert(instance != null, "create() should be called before getInstance().");
return instance;
}
/// <summary>
/// Draw the given problem to the UI.
/// </summary>
/// <param name="desc"></param>
public void draw(ProblemDescription desc)
{
invokeDraw(desc);
}
/// <summary>
/// Clear all input on the UI.
/// </summary>
public void clear()
{
invokeClear();
}
/// <summary>
/// Reset the ProblemDrawer (ie clear all cached UI elements).
/// </summary>
public void reset()
{
invokeReset();
}
/// <summary>
/// A simplistic description of the problem to be drawn.
/// </summary>
public class ProblemDescription
{
public List<Point> Points { get; set; } //Points to be drawn
public List<Segment> Segments { get; set; } //Segments to be drawn
public List<Circle> Circles { get; set; } //Circles to be drawn
public List<AtomicRegion> Regions { get; set; } //Regions to be shaded
}
}
}
|
00dd48c93bdce720a4d87787bb862bd52ee6985b
|
C#
|
FancisLuo/BasicTechInGame
|
/9-CheckCollisionCircle/Scripts/CheckCircleRect.cs
| 2.71875
| 3
|
using CheckCollisionRect;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CheckCollisionCircle
{
public class CheckCircleRect : MonoBehaviour
{
[SerializeField] private RectangleTarget rectangleTarget;
[SerializeField] private CircleTarget circleTarget;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
var checkResult = CheckCollision();
Debug.Log($"result = {checkResult}");
}
private bool CheckCollision()
{
var onX = Mathf.Abs(circleTarget.Center.x - rectangleTarget.RectCenter.x);
var onY = Mathf.Abs(circleTarget.Center.y - rectangleTarget.RectCenter.y);
var totalWidth = rectangleTarget.Width * 0.5f + circleTarget.Radius;
var totalHeight = rectangleTarget.Height * 0.5f + circleTarget.Radius;
if(onX > totalWidth || onY > totalHeight)
{
return false;
}
else
{
return true;
}
}
}
}
|
5a222c56e5b8480d3cd05660646f1e616ec0a8fc
|
C#
|
AdmiralCurtiss/ToVPatcher
|
/Scripts/tools/MAPLIST/MAPLIST/MapList.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MAPLIST
{
class MapList
{
public uint Liststart;
public uint Textstart;
public List<MapName> MapNames;
public MapList(byte[] Bytes)
{
Liststart = Util.SwapEndian(BitConverter.ToUInt32(Bytes, 0x0C));
Textstart = Util.SwapEndian(BitConverter.ToUInt32(Bytes, 0x14));
MapNames = new List<MapName>();
for (uint i = Liststart; i < Textstart; i += 0x20)
{
MapName m = new MapName(Bytes, i, Textstart);
m.Name1 = Util.GetText((int)m.Pointer1, Bytes);
m.Name2 = Util.GetText((int)m.Pointer2, Bytes);
m.Name3 = Util.GetText((int)m.Pointer3, Bytes);
MapNames.Add(m);
}
}
}
}
|
e369be9afb4e8cf96285638db649f7fc76dd6b9b
|
C#
|
CynicalGrey/unity-scripts
|
/SphereTrigger.cs
| 2.546875
| 3
|
using UnityEngine;
using System.Collections;
public class SphereTrigger : MonoBehaviour {
SphereTrigger sphereWorldOneObj;
SphereTrigger sphereWorldTwoObj;
// Use this for initialization
void Start () {
Debug.Log("Sphere Trigger Script");
sphereWorldOneObj = GameObject.Find("sphereWorldOne").GetComponent<SphereTrigger>();
sphereWorldTwoObj = GameObject.Find("sphereWorldTwo").GetComponent<SphereTrigger>();
//Debug.Log("What is this: " + sphereWorldOneObj);
//sphereWorldOne = GameObject.Find("sphereWorldOne");
//Debug.Log("sphereWorldOne: " + sphereWorldOne);
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider objectThatWasHit)
{
//Debug.Log("Shit went down. The Collision object is: " + objectThatWasHit + this);
if (this == sphereWorldOneObj)
{
Debug.Log("I'm in Sphere World One " + this);
}
if (this == sphereWorldTwoObj)
{
Debug.Log("I'm in Sphere World Two " + this);
//GUI.Label(new Rect(35, 60, 150, 100), "Location: 2");
if(!audio.isPlaying)
{
audio.Play();
}
}
}
}
|
38f09bedb8b1116d15dd8735a0eafa7372ba2ce6
|
C#
|
szgerg/Swanker
|
/src/Swanker/Helpers/JsonStringifier.cs
| 2.90625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Diagnostics;
using Serilog;
namespace Swanker.Helpers
{
internal class JsonStringifier: StringifierBase
{
private readonly ILogger _logger;
private List<Type> _types = new List<Type>();
public JsonStringifier(ILogger logger)
{
_logger = logger;
}
public string Stringify(Type type, int tab, bool typeBody, string s = null)
{
var res = "";
if (_types.Contains(type))
{
_logger.Debug($"Type: {type.FullName}, already JSON stringed");
return $"{tb(tab)}{{...}}";
}
var t = type.GetInterfaces().FirstOrDefault(i => i == typeof(IEnumerable));
if (t != null)
return "";
_types.Add(type);
res += $"{tb(tab)}{{{rn}";
var ps = type.GetProperties().Where(p => p.CanRead);
if (s != null && typeBody)
res += $"{tb(tab + 1)}\"$type\": \"{s}\",{rn}";
foreach (var pi in ps)
{
_logger.Debug($"Property Name: {pi.Name}, Type: {pi.PropertyType} JSON stringing.");
if (TypeHelper.IsNumericType(pi.PropertyType))
res += $"{tb(tab + 1)}\"{pi.Name}\": 0,{rn}";
else if (pi.PropertyType == typeof(string))
res += $"{tb(tab + 1)}\"{pi.Name}\": \"string\",{rn}";
else if (pi.PropertyType == typeof(Guid))
res += $"{tb(tab + 1)}\"{pi.Name}\": \"{Guid.Empty}\",{rn}";
else if (pi.PropertyType.GetInterfaces().Any(i => i.Name == typeof(IEnumerable).Name))
{
res += $"{tb(tab + 1)}\"{pi.Name}\": [{rn}{Stringify(pi.PropertyType.GetGenericArguments().FirstOrDefault(), tab + 2, typeBody)}{rn}{tb(tab + 1)}],{rn}";
}
else if (pi.PropertyType.IsClass)
res += $"{tb(tab + 1)}\"{pi.Name}\":{Stringify(pi.PropertyType, tab + 1, typeBody)},{rn}";
}
if (ps.Any() || (s != null && typeBody))
res = res.Substring(0, res.Length - 3);
res += $"{rn}{tb(tab)}}}";
if (!ps.Any() && !typeBody)
res = $"{tb(tab)}{{}}";
return res;
}
}
}
|
5c9e376e7ba76ff92eafda73d3c4c54d0f4fe07f
|
C#
|
gamingAmee/AppProjekt
|
/AppProjekt/Repository/GenericRepository.cs
| 2.609375
| 3
|
using Newtonsoft.Json;
using Repository.Exceptions;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Repository
{
public class GenericRepository : IGenericRepository
{
private HttpClient httpClient;
HttpClientHandler httpClientHandler = new HttpClientHandler();
public GenericRepository()
{
#if DEBUG
httpClientHandler.ServerCertificateCustomValidationCallback = (message, certificate, chain, sslPolicyErrors) => true;
#endif
httpClient = new HttpClient(httpClientHandler);
}
#region GET
public async Task<T> GetAsync<T>(string uri, string authToken = "")
{
try
{
ConfigureHttpClient(authToken);
string jsonResult = string.Empty;
HttpResponseMessage responseMessage = await httpClient.GetAsync(uri);
if (responseMessage.IsSuccessStatusCode)
{
jsonResult = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
var json = JsonConvert.DeserializeObject<T>(jsonResult);
return json;
}
if (responseMessage.StatusCode == HttpStatusCode.Forbidden ||
responseMessage.StatusCode == HttpStatusCode.Unauthorized)
{
throw new ServiceAuthenticationException(jsonResult);
}
throw new HttpRequestExceptionEx(responseMessage.StatusCode, jsonResult);
}
catch (Exception e)
{
throw;
}
}
#endregion
#region POST
public async Task<T> PostAsync<T>(string uri, T data, string authToken = "")
{
try
{
ConfigureHttpClient(authToken);
var content = new StringContent(JsonConvert.SerializeObject(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string jsonResult = string.Empty;
var responseMessage = await httpClient.PostAsync(uri, content);
if (responseMessage.IsSuccessStatusCode)
{
jsonResult = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
var json = JsonConvert.DeserializeObject<T>(jsonResult);
return json;
}
if (responseMessage.StatusCode == HttpStatusCode.Forbidden ||
responseMessage.StatusCode == HttpStatusCode.Unauthorized)
{
throw new ServiceAuthenticationException(jsonResult);
}
throw new HttpRequestExceptionEx(responseMessage.StatusCode, jsonResult);
}
catch (Exception e)
{
throw;
}
}
public async Task<TR> PostAsync<T, TR>(string uri, T data, string authToken = "")
{
try
{
ConfigureHttpClient(authToken);
var content = new StringContent(JsonConvert.SerializeObject(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string jsonResult = string.Empty;
var responseMessage = await httpClient.PostAsync(uri, content);
if (responseMessage.IsSuccessStatusCode)
{
jsonResult = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
var json = JsonConvert.DeserializeObject<TR>(jsonResult);
return json;
}
if (responseMessage.StatusCode == HttpStatusCode.Forbidden ||
responseMessage.StatusCode == HttpStatusCode.Unauthorized)
{
throw new ServiceAuthenticationException(jsonResult);
}
throw new HttpRequestExceptionEx(responseMessage.StatusCode, jsonResult);
}
catch (Exception e)
{
throw;
}
}
#endregion
#region PUT
public async Task<T> PutAsync<T>(string uri, T data, string authToken = "")
{
try
{
ConfigureHttpClient(authToken);
var content = new StringContent(JsonConvert.SerializeObject(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string jsonResult = string.Empty;
var responseMessage = await httpClient.PutAsync(uri, content);
if (responseMessage.IsSuccessStatusCode)
{
jsonResult = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
var json = JsonConvert.DeserializeObject<T>(jsonResult);
return json;
}
if (responseMessage.StatusCode == HttpStatusCode.Forbidden ||
responseMessage.StatusCode == HttpStatusCode.Unauthorized ||
responseMessage.StatusCode == HttpStatusCode.MethodNotAllowed)
{
throw new ServiceAuthenticationException(jsonResult);
}
throw new HttpRequestExceptionEx(responseMessage.StatusCode, jsonResult);
}
catch (Exception e)
{
throw;
}
}
#endregion
#region DELETE
public async Task DeleteAsync(string uri, string authToken = "")
{
try
{
ConfigureHttpClient(authToken);
await httpClient.DeleteAsync(uri);
}
catch (Exception e)
{
throw;
}
}
#endregion
#region HELPER
private void ConfigureHttpClient(string authToken)
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (!string.IsNullOrEmpty(authToken))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
}
else
{
httpClient.DefaultRequestHeaders.Authorization = null;
}
}
#endregion
}
}
|
8aa34139180b53777a28e7c8aad6942b258e335e
|
C#
|
akshinde45/BackUP
|
/SecondPractMVC/SecondPractMVC/DEPART.cs
| 2.625
| 3
|
namespace SecondPractMVC
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("DEPART")]
public partial class DEPART
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DEPART()
{
EMPLOYEEs = new HashSet<EMPLOYEE>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int DEPARTMENT_ID { get; set; }
[StringLength(40)]
public string DEPT_NAME { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EMPLOYEE> EMPLOYEEs { get; set; }
}
}
|
67bbc294a46b8bbeeedb8317c7d32e43587f7785
|
C#
|
HelloZhangzy/Exercise
|
/NET/Console/设计模式/享元模式/享元模式/Program.cs
| 3.53125
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 享元模式
{
class Program
{
static void Main(string[] args)
{
IgoChessman black1, black2, black3, white1, white2;
IgoChessmanFactory factory;
//获取享元工厂对象
// factory = IgoChessmanFactory.getInstance();
//通过享元工厂获取三颗黑子
black1 = IgoChessmanFactory.getIgoChessman("b");
black2 = IgoChessmanFactory.getIgoChessman("b");
black3 = IgoChessmanFactory.getIgoChessman("b");
Console.WriteLine("判断两颗黑子是否相同:" + (black1 == black2));
//通过享元工厂获取两颗白子
white1 = IgoChessmanFactory.getIgoChessman("w");
white2 = IgoChessmanFactory.getIgoChessman("w");
Console.WriteLine("判断两颗白子是否相同:" + (white1 == white2));
//显示棋子
black1.display();
black2.display();
black3.display();
white1.display();
white2.display();
//显示棋子,同时设置棋子的坐标位置
black1.display(new Coordinates(1, 2));
black2.display(new Coordinates(3, 4));
black3.display(new Coordinates(1, 3));
white1.display(new Coordinates(2, 5));
white2.display(new Coordinates(2, 4));
Console.Read();
}
}
//围棋棋子类:抽象享元类
abstract class IgoChessman
{
public abstract String getColor();
public void display()
{
Console.WriteLine("棋子颜色:" + this.getColor());
}
public void display(Coordinates coord)
{
Console.WriteLine("棋子颜色:" + this.getColor() + ",棋子位置:" + coord.getX() + "," + coord.getY());
}
}
//黑色棋子类:具体享元类
class BlackIgoChessman : IgoChessman
{
public override String getColor()
{
return "黑色";
}
}
//白色棋子类:具体享元类
class WhiteIgoChessman : IgoChessman
{
public override String getColor()
{
return "白色";
}
}
//坐标类:外部状态类
class Coordinates
{
private int x;
private int y;
public Coordinates(int x, int y)
{
this.x = x;
this.y = y;
}
public int getX()
{
return this.x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return this.y;
}
public void setY(int y)
{
this.y = y;
}
}
//围棋棋子工厂类:享元工厂类,使用单例模式进行设计
class IgoChessmanFactory
{
private static IgoChessmanFactory instance = new IgoChessmanFactory();
private static Hashtable ht; //使用Hashtable来存储享元对象,充当享元池
private IgoChessmanFactory()
{
ht = new Hashtable();
IgoChessman black, white;
black = new BlackIgoChessman();
ht.Add("b", black);
white = new WhiteIgoChessman();
ht.Add("w", white);
}
//返回享元工厂类的唯一实例
public static IgoChessmanFactory getInstance()
{
return instance;
}
//通过key来获取存储在Hashtable中的享元对象
public static IgoChessman getIgoChessman(String color)
{
return (IgoChessman)ht[color];
}
}
}
|
a5594ff475a84831b926abbb6d72e0f296c1a3ad
|
C#
|
DmitryDolzhenkov/TrainYourKnowledge
|
/ValueTypeCA/Program.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ValueTypeCA
{
class Program
{
static void Main(string[] args)
{
List<Tabalo> listofTabalos = new List<Tabalo>();
ParseListofTabalos(listofTabalos);
LinkedList<string> listofstr = new LinkedList<string>();
ParseListofstr(listofstr);
Tabalo tablo = new Tabalo("Tabalo", 5);
Tabalo tablo2 = new Tabalo("Tabalo", 5);
if (tablo2.GetHashCode() == tablo.GetHashCode())
{
bool same = tablo.Equals(tablo2);
}
Type type = tablo.GetType();
char[] value = "second".ToCharArray();
String str3 = new String("second".ToCharArray());
String str4 = "second";
int i = str3.GetHashCode();
int i2 = str4.GetHashCode();
//UpdateString(ref );
UpdateObject(tablo);
string str = "Tabalo";
object obj1 = str;
char[] strarr = str.ToCharArray();
//UpdateString(ref str);
UpdateString(ref obj1);
UpdateString(strarr);
UpdateStr(str3);
Console.WriteLine(str3);
//Console.WriteLine(obj1);
//Console.WriteLine(strarr);
//Console.WriteLine(tablo.S);
//Console.WriteLine(tablo.I);
Console.ReadKey();
}
private static void ParseListofstr(LinkedList<string> listofstr)
{
Tabalo tablo1 = new Tabalo("Tabalo", 5);
Tabalo tablo2 = new Tabalo("Tabalo", 15);
Tabalo tablo3 = new Tabalo("Tabalo", 15);
listofstr.AddFirst("Tabalo");
listofstr.AddLast("Tabalo1");
listofstr.AddLast("Tabalo2");
}
private static void ParseListofTabalos(List<Tabalo> listofTabalos)
{
Tabalo tablo1 = new Tabalo("Tabalo", 5);
Tabalo tablo2 = new Tabalo("Tabalo", 15);
Tabalo tablo3 = new Tabalo("Tabalo", 15);
listofTabalos.Add(tablo1);
listofTabalos.Add(tablo2);
listofTabalos.Add(tablo3);
}
private static void UpdateObject<T>(T tablo)
{
Tabalo eb = tablo as Tabalo;
eb.S = "zakroi Tabalo";
eb.I = 25;
}
private static void UpdateObject(Tabalo tablo)
{
Tabalo tablo2 = tablo;
//Tabalo tablo2 = new Tabalo("naxui idi", 888);
tablo2.S = "str+";
tablo2.I = 22;
}
private static void UpdateString(ref string str)
{
string s = str + " " + "zakroi";
str = s;
}
private static void UpdateStr(String str)
{
string s = str + " " + "zakroi";
str = s;
}
private static void UpdateString(ref object str)
{
string s = str + " " + "zakroi";
str = s;
}
private static void UpdateString(char[] str)
{
char[] s =
{
'z', 'a'
};
str = s;
}
}
}
|
698bc19a3a32877513b50fe645513eca3dac9a51
|
C#
|
mejborn/Mars-City-Simulator
|
/People/ScienceField.cs
| 3
| 3
|
using UnityEngine;
using System.Collections;
public class ScienceField
{
public Scfield scfield;
private Skillset skillset;
public Skillset getSkillset(){
return skillset;
}
public enum Scfield
{
Scientist,
Engineer,
Farmer,
Tourist,
Astronaut
};
public ScienceField(Scfield scfield)
{
instantiateVariables ();
this.scfield = scfield;
}
void instantiateVariables ()
{
int science, engineering, farming;
science = Random.Range (1, 4);
engineering = Random.Range (1, 4);
farming = Random.Range (1, 4);
switch (scfield) {
case Scfield.Scientist:
science += 5;
break;
case Scfield.Engineer:
engineering += 5;
break;
case Scfield.Farmer:
farming += 5;
break;
case Scfield.Astronaut:
science += 2;
engineering += 3;
break;
default:
break;
}
this.skillset = new Skillset (science, engineering, farming);
}
}
|
38998b09de8fd6a17be314725fcbc2a99d7684f6
|
C#
|
kmycode/mastoom
|
/Mastoom.Shared/Converters/String2EmojiConverter.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Mastoom.Shared.Converters
{
public class String2EmojiConverter : SharedConverterBase
{
private static readonly Dictionary<String, EmojiSharp.Emoji> dic = EmojiSharp.Emoji.All;
public override object Convert(object value, Type targetType, object parameter, string language)
{
string text = value as string;
if (text != null && targetType == typeof(string))
{
if (string.IsNullOrWhiteSpace(text) || !text.Contains(":"))
{
return text;
}
string strRegex = @":([a-zA-Z0-9_]+):";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = text;
var succeedMatchGroups = myRegex.Matches(strTargetString)
.OfType<Match>().Where(mt => mt.Success)
.SelectMany(mt => mt.Groups.OfType<Group>());
foreach (Group group in succeedMatchGroups)
{
var key = group.Value.Substring(1, group.Value.Length - 2);
if (dic.ContainsKey(key))
{
var charCodes = dic[key].Unified.Split('-');
var newString = "";
foreach (var code in charCodes)
{
newString += ((char)(System.Convert.ToInt32(code, 16))).ToString();
}
text = text.Replace(group.Value, newString);
}
}
return text;
}
throw new NotSupportedException();
}
public override object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
|
5b13515692eef6375e3306169c77f16fb0c08304
|
C#
|
fosstheory/PongGlobe
|
/src/PongGlobe2/Core/Algorithm/RayCastHit.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Numerics;
namespace PongGlobe.Core.Algorithm
{
/// <summary>
/// Hit到哪个对象且距离对象有多远
/// </summary>
/// <typeparam name="T"></typeparam>
public struct RayCastHit<T>
{
public readonly T Item;
public readonly Vector3 Location;
public readonly float Distance;
public RayCastHit(T item, Vector3 location, float distance)
{
Item = item;
Location = location;
Distance = distance;
}
}
}
|
929777524cd867eb39403a80628bc13a8487216c
|
C#
|
casrou/ChartConverter
|
/src/ChartConverter.Core/CloneHero/CloneHeroDifficulty.cs
| 2.75
| 3
|
using ChartConverter.Core.BeatSaber;
namespace ChartConverter.Core
{
public enum CloneHeroDifficulty
{
Unknown, Easy, Medium, Hard, Expert
}
public static class CloneHeroDifficultyHelper
{
public static CloneHeroDifficulty GetCloneHeroDifficultyFromBeatSaberDifficulty(BeatSaberDifficulty beatSaberDifficulty)
{
CloneHeroDifficulty cloneHeroDifficulty;
switch (beatSaberDifficulty)
{
case BeatSaberDifficulty.Normal:
cloneHeroDifficulty = CloneHeroDifficulty.Easy;
break;
case BeatSaberDifficulty.Hard:
cloneHeroDifficulty = CloneHeroDifficulty.Medium;
break;
case BeatSaberDifficulty.Expert:
cloneHeroDifficulty = CloneHeroDifficulty.Hard;
break;
case BeatSaberDifficulty.ExpertPlus:
cloneHeroDifficulty = CloneHeroDifficulty.Expert;
break;
default:
cloneHeroDifficulty = CloneHeroDifficulty.Unknown;
break;
}
return cloneHeroDifficulty;
}
}
}
|
65c71a20badf3ab757f00873480522a8f1a3b2bf
|
C#
|
rmichak/it431-sample-trans1
|
/Trans1/Data/CourseDatabaseInitializer.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using Trans1.Models;
namespace Trans1.Data
{
public class Trans1DBInitializer : DropCreateDatabaseAlways<Trans1Context>
{
protected override void Seed(Trans1Context context)
{
IList<Course> defaultCourses = new List<Course>();
defaultCourses.Add(new Course() { Name = "Course 1", Credits=3, Term="Spring", Grade="A" });
defaultCourses.Add(new Course() { Name = "Course 2", Credits = 3, Term = "Spring", Grade = "A" });
defaultCourses.Add(new Course() { Name = "Course 3", Credits = 3, Term = "Spring", Grade = "A" });
defaultCourses.Add(new Course() { Name = "Course 4", Credits = 3, Term = "Spring", Grade = "A" });
defaultCourses.Add(new Course() { Name = "Course 5", Credits = 3, Term = "Spring", Grade = "A" });
context.Courses.AddRange(defaultCourses);
base.Seed(context);
}
}
}
|
06ec9e7e41d3c85bd6b2e416cb914ed443a915b0
|
C#
|
jan-leewx/OBJECT-ORIENTED-PROGRAMING
|
/Rewards.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Media;
using System.Windows.Forms;
namespace Snake
{
class Rewards
{
List<Position> appleList;
Board mainBoard;
List<Position> enemylist;
SoundPlayer eatpoptart;
public Rewards(int size, Board mainBoard)
{
this.mainBoard = mainBoard;
appleList = new List<Position>();
for (int i=0;i< size;i++)
{
int rowNo, colNo;
//Generate an apple at random position but not duplicated
do
{
//Generate a random number between 1 and MaxRowNo
rowNo = (new Random()).Next(1, mainBoard.getMaxRowNo()+1);
//Generate a random number between 1 and MaxColNo
colNo = (new Random()).Next(1, mainBoard.getMaxColNo()+1);
} while (isDuplicate(rowNo, colNo) == true);
appleList.Add(new Position(rowNo, colNo));
}
this.mainBoard = mainBoard;
enemylist = new List<Position>();
for (int i = 0; i < size; i++)
{
int rowNo, colNo;
do
{
rowNo = (new Random()).Next(1, mainBoard.getMaxRowNo() + 1);
colNo = (new Random()).Next(1, mainBoard.getMaxColNo() + 1);
} while (isDuplicate(rowNo, colNo) == true);
enemylist.Add(new Position(rowNo, colNo));
}
}
private Boolean isDuplicate(int row, int col)
{
Boolean result = false;
for (int i=0;i< appleList.Count;i++)
{
if (appleList[i].getRowNo() == row && appleList[i].getColNo() == col)
result = true;
}
return result;
}
private Boolean isDuplicateenemy(int row, int col)
{
Boolean result = false;
for (int i = 0; i < enemylist.Count; i++)
{
if (enemylist[i].getRowNo() == row && enemylist[i].getColNo() == col)
result = true;
}
return result;
}
public void draw()
{
for (int i = 0; i < appleList.Count; i++)
{
mainBoard.draw(appleList[i], Properties.Resources.Png);
}
}
public void drawenemy()
{
for (int i = 0; i < enemylist.Count; i++)
{
mainBoard.drawenemy(enemylist[i], Properties.Resources.tac_nayn);
}
}
public Boolean checkIFSnakeHeadEatApple(Position snakeHead)
{
Boolean result = false;
for (int i = 0; i < appleList.Count; i++)
{
if (snakeHead.getRowNo() == appleList[i].getRowNo() && snakeHead.getColNo() == appleList[i].getColNo())
result = true;
}
return result;
}
public Boolean checkIFSnakeEatenemy(Position snakeHead)
{
Boolean result = false;
for (int i = 0; i < enemylist.Count; i++)
{
if (snakeHead.getRowNo() == enemylist[i].getRowNo() && snakeHead.getColNo() == enemylist[i].getColNo())
result = true;
}
return result;
}
public Boolean checkIFSnakeEatApple(Position snakeHead)
{
Boolean result = false;
for (int i = 0; i < appleList.Count; i++)
{
if (snakeHead.getRowNo() == appleList[i].getRowNo() && snakeHead.getColNo() == appleList[i].getColNo())
result = true;
}
return result;
}
public int eatAppleAtPostion(Position p)
{
for(int i=0; i<appleList.Count; i++)
{
if(p.getRowNo()==appleList[i].getRowNo()&&p.getColNo()==appleList[i].getColNo())
{
appleList.RemoveAt(i);
eatpoptart = new SoundPlayer(Properties.Resources.Anime_wow___sound_effect);
eatpoptart.LoadAsync();
eatpoptart.Play();
}
}
return 50; //50 points per apple
}
public int eatPoopAtPosition(Position a)
{
for (int i = 0; i < enemylist.Count; i++)
{
if (a.getRowNo() == enemylist[i].getRowNo() && a.getColNo()
== enemylist[i].getColNo())
{
enemylist.RemoveAt(i);
}
}
return 100;
}
public Boolean noMoreApples()
{
if (appleList.Count > 0)
return false;
else
return true;
}
public Boolean noMoreenemy()
{
if (enemylist.Count > 0)
return false;
else
return true;
}
}
}
|
ce7be6bc64a6aa174096862e076c16fe2cf816c4
|
C#
|
ricardosleme/TestBoticario
|
/Sales.Seller.CashBack/Sales.Seller.CashBack.API/Repository/SalesRepository.cs
| 2.53125
| 3
|
using Microsoft.Extensions.Configuration;
using MongoDB.Bson;
using MongoDB.Driver;
using Sales.Seller.CashBack.API.Repository.Data;
using System.Security.Policy;
namespace Sales.Seller.CashBack.API.Repository
{
public class SalesRepository : ISalesRepository
{
private readonly IDbMongo _dbMongo;
public SalesRepository(IDbMongo dbMongo)
{
_dbMongo = dbMongo;
}
public bool DeleteSale(Vendor vendor)
{
throw new System.NotImplementedException();
}
public Vendor GetVendorCpf(string cpf)
{
var database = _dbMongo.GetDatabase();
var collection = database.GetCollection<Vendor>("Vendor");
return collection.Find(x => x.CPF.Equals(cpf)).FirstOrDefault();
}
public Vendor GetVendorSenha(string cpf, string senha)
{
var database = _dbMongo.GetDatabase();
var collection = database.GetCollection<Vendor>("Vendor");
return collection.Find(x => x.Senha.Equals(senha) && x.CPF.Equals(cpf)).FirstOrDefault();
}
public Vendor GetVendorId(string id)
{
var database = _dbMongo.GetDatabase();
var _id = new ObjectId(id);
var collection = database.GetCollection<Vendor>("Vendor");
return collection.Find(x => x._id.Equals(_id)).FirstOrDefault() ;
}
public Vendor PostVendor(Vendor vendor)
{
var database = _dbMongo.GetDatabase();
var collection = database.GetCollection<Vendor>("Vendor");
collection.InsertOne(vendor);
return vendor;
}
public Vendor PutVendor(Vendor vendor)
{
var database = _dbMongo.GetDatabase();
var collection = database.GetCollection<Vendor>("Vendor");
collection.ReplaceOne(x => x._id.Equals(vendor._id), vendor);
return vendor;
}
}
}
|
2eeca4c01395fc9c3cab98f610c18bfc1a6c5114
|
C#
|
petecallaghan/PopulationFitness
|
/DotNet/PopulationFitness/PopulationFitness/Models/Genes/BitSet/BitSetGenes.cs
| 2.890625
| 3
|
using PopulationFitness.Models.Genes.Cache;
using System;
namespace PopulationFitness.Models.Genes.BitSet
{
/**
* Extend this to provide different fitness functions that use a bitset
*
* Created by pete.callaghan on 03/07/2017.
*/
public abstract class BitSetGenes : IGenes
{
protected readonly Config Config;
private IGenesIdentifier _genesIdentifier;
private double _storedFitness = 0;
private bool _fitnessStored = false;
private readonly int _sizeOfGenes;
protected BitSetGenes(Config config)
{
Config = config;
_sizeOfGenes = config.GeneBitCount;
}
private long[] GetGenesFromCache()
{
return SharedCache.Cache.Get(_genesIdentifier);
}
private BitSet GetBitSetGenesFromCache()
{
return BitSet.ValueOf(SharedCache.Cache.Get(_genesIdentifier));
}
private void StoreGenesInCache(BitSet genes)
{
StoreGenesInCache(genes.ToLongArray());
}
private void StoreGenesInCache(long[] genes)
{
_genesIdentifier = SharedCache.Cache.Add(genes);
_fitnessStored = false;
}
public void BuildEmpty()
{
int numberOfInts = (int)((_sizeOfGenes / Long.Size) + (Long.Size % _sizeOfGenes == 0 ? 0 : 1));
long[] genes = new long[numberOfInts];
Array.Clear(genes, 0, genes.Length);
StoreGenesInCache(genes);
}
public void BuildFull()
{
BitSet genes = new BitSet(_sizeOfGenes);
genes.Set(0, _sizeOfGenes - 1);
StoreGenesInCache(genes);
}
public void BuildFromRandom()
{
BuildEmpty();
long[] genes = AsIntegers;
MutateGenesWithMutationInterval(genes, 0);
StoreGenesInCache(genes);
}
public long[] AsIntegers
{
get
{
return SharedCache.Cache.Get(_genesIdentifier);
}
}
public int GetCode(int index)
{
return GetBitSetGenesFromCache().Get(index) ? 1 : 0;
}
public int NumberOfBits
{
get
{
return _sizeOfGenes;
}
}
public int Mutate()
{
return MutateAndStore(AsIntegers);
}
private int MutateAndStore(long[] genes)
{
int mutatedCount = MutateGenes(genes);
StoreGenesInCache(genes);
return mutatedCount;
}
private int MutateGenes(long[] genes)
{
if (Config.MutationsPerGene <= 0)
{
return 0;
}
long mutation_genes_interval = 1 + (long)(genes.Length * 2.0 / Config.MutationsPerGene);
return MutateGenesWithMutationInterval(genes, mutation_genes_interval);
}
private int MutateGenesWithMutationInterval(long[] genes, long mutation_genes_interval)
{
long max = Config.MaxGeneValue;
long lastMax = Config.LastMaxGeneValue;
int last = genes.Length - 1;
int mutatedCount = 0;
for (int i = RepeatableRandom.GenerateNextInt(mutation_genes_interval);
i < genes.Length;
i += Math.Max(1, (int)RepeatableRandom.GenerateNextLong(0, mutation_genes_interval)))
{
genes[i] = GetMutatedValue(genes[i], i == last ? lastMax : max);
mutatedCount++;
}
return mutatedCount;
}
private long GetMutatedValue(long gene, long max)
{
return gene + RepeatableRandom.GenerateNextLong(0 - gene, max);
}
/**
* Call this to store a fitness
*
* @param fitness
* @return
*/
protected double StoreFitness(double fitness)
{
_storedFitness = fitness;
_fitnessStored = true;
return _storedFitness;
}
/**
* @return the stored fitness
*/
protected double StoredFitness()
{
return _storedFitness;
}
protected bool IsFitnessStored()
{
return _fitnessStored;
}
public int InheritFrom(IGenes mother, IGenes father)
{
long[] motherEncoding = ((BitSetGenes)mother.Implementation).GetGenesFromCache();
long[] fatherEncoding = ((BitSetGenes)father.Implementation).GetGenesFromCache();
long[] babyEncoding = new long[Math.Max(motherEncoding.Length, fatherEncoding.Length)];
// Randomly picks the code index that crosses over from mother to father
int cross_over_word = Math.Min(1 + RepeatableRandom.GenerateNextInt(babyEncoding.Length - 1), babyEncoding.Length - 1);
int mother_length = Math.Min(cross_over_word + 1, motherEncoding.Length);
int father_length = Math.Min(babyEncoding.Length - cross_over_word - 1, fatherEncoding.Length - cross_over_word - 1);
Array.Copy(motherEncoding, 0, babyEncoding, 0, mother_length);
if (father_length > 0)
{
Array.Copy(fatherEncoding, cross_over_word + 1, babyEncoding, cross_over_word + 1, father_length);
}
return MutateAndStore(babyEncoding);
}
public bool AreEmpty
{
get
{
return GetBitSetGenesFromCache().IsEmpty;
}
}
public bool IsEqual(IGenes other)
{
return GetBitSetGenesFromCache().Equals(((BitSetGenes)other).GetBitSetGenesFromCache());
}
public IGenes Implementation
{
get
{
return this;
}
}
public IGenesIdentifier Identifier
{
get
{
return _genesIdentifier;
}
}
public abstract double Fitness { get; }
}
}
|
988751d9ed61aa9e38f5e90a2c69cc113d5a549e
|
C#
|
kthanu/Tutorial
|
/Example_CSharp_Day3/Example_CSharp_Day3/Calculations.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Example_CSharp_Day3
{
class Calculations
{
static double a, b;
public static double add(double a, double b)
{
return a + b;
}
public static double sub(double a, double b)
{
return a - b;
}
public static double mul(double a, double b)
{
return a * b;
}
public static double div(double a, double b)
{
if (b == 0)
{
Console.WriteLine("cannot divide by zero");
return -1;
}
return a / b;
}
}
//class program
//{
// public static void Main()
// {
// double a, b;
// Console.WriteLine("Enter number 1:");
// a = Convert.ToDouble(Console.ReadLine());
// b = Convert.ToDouble(Console.ReadLine());
// Console.WriteLine("sum is : {0}", Calculation.add(a, b));
// Console.WriteLine("sub is : {0}", Calculation.sub(a, b));
// Console.WriteLine("mul is : {0}", Calculation.mul(a, b));
// Console.WriteLine("division is : {0}", Calculation.div(a, b));
// Console.ReadKey();
// }
//}
}
|
3d39276b77544a59f0ce02cc5070eec5c134ebe2
|
C#
|
Kerolyov/ProjectCaprica
|
/Assets/Scripts/Data/Config.cs
| 2.75
| 3
|
using UnityEngine;
using System.Collections;
namespace Caprica
{
public static class Config
{
// Values are coded here for now, but the goal
// will be to load in from a config file that is modable.
public static int GetInt(string Parameter)
{
switch (Parameter)
{
case "PLANET_MAX_POPULATION_Tiny":
return 4;
case "PLANET_MAX_POPULATION_Small":
return 6;
case "PLANET_MAX_POPULATION_Medium":
return 10;
case "PLANET_MAX_POPULATION_Large":
return 12;
case "PLANET_MAX_POPULATION_Huge":
return 16;
case "STAR_MAX_PLANETS":
return 6;
case "STAR_ORBIT_DISTANCE":
return 1;
default:
Debug.LogError("GetInt: No option for " + Parameter);
return 0;
}
}
public static float GetFloat(string Parameter)
{
switch (Parameter)
{
case "STAR_ORBIT_DISTANCE":
return 1.0f;
default:
Debug.LogError("GetFloat: No option for " + Parameter);
return 0;
}
}
}
}
|
a5b240ea14f9dff400cadb558cbab1b7e1622058
|
C#
|
koljagrudinin/OldVkParser
|
/classlibraryvkontaktechecker/classlibraryvkontaktechecker/WorkClasses/MemoryWorker.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace ClassLibraryVkontakteChecker.WorkClasses
{
/// <summary>
/// Класс, реализующий кеширование на диск
/// </summary>
class MemoryWorker
{
int i = 0;
string fileName = "";
public MemoryWorker( string fileName )
{
this.fileName = fileName;
}
/// <summary>
/// Сохраняет данные из списка
/// </summary>
/// <param name="arrOfData"></param>
/// <returns></returns>
public void saveData( IEnumerable<object> arrOfData )
{
if ( i == 0 )
i = 1;
object[] arrOfObj = arrOfData.ToArray();
string path = fileName + i + ".dat";
using ( FileStream FS = new FileStream( path , FileMode.Create ) )
{
BinaryFormatter BF = new BinaryFormatter();
BF.Serialize( FS , typeof( object[] ) );
FS.Close();
}
i++;
}
/// <summary>
/// Загружает данные
/// </summary>
/// <returns></returns>
public object[] LoadData( )
{
if ( i == 0 )
{
return new List<object>().ToArray();
}
List<object> arrOfObjects = new List<object>();
for ( int k = 1 ; k <= i ; k++ )
{
object[] tempList = null;
string path = fileName + k + ".dat";
using ( FileStream FS = new FileStream( path , FileMode.Open ) )
{
BinaryFormatter BF = new BinaryFormatter();
tempList = (object[])BF.Deserialize( FS );
FS.Close();
}
System.IO.File.Delete( path );
arrOfObjects.AddRange( tempList.ToArray() );
}
return arrOfObjects.ToArray();
}
}
}
|
a539e1f69d629c33b78a7faee3fbe6b04e1cb03a
|
C#
|
Cosmic-Deluxe-Adventure-Limited/CosmicDeluxeAdventureLTD
|
/CosmicDeluxeAdventure/Model/Trip.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CosmicDeluxeAdventure.Model
{
public class Trip
{
[Required]
public int ID { get; set; }
public int UserID { get; set; }
public int FlightID { get; set; }
public DateTime Added { get; set; }
// #2 int value in and out of database
public int FlightStatus
{
get
{
return (int)this.TripStatus;
}
set
{
TripStatus = (TripCondition)value;
}
}
//Navigation Properties
public List<UserInfo> UserInfo { get; set; }
public List<Flight> Flights { get; set; }
//Enum Method and definition
//#3 this will be what will be called when we need to use the enum
public TripCondition TripStatus { get; set; }
//#1 Enum Definition
public enum TripCondition
{
Saved = 1,
Booked = 2,
Completed = 3
}
}
}
|
ae3006f47286f1dc479fa3a48828e68569c95301
|
C#
|
gon93/ShapeApp
|
/CreateForm.cs
| 2.6875
| 3
|
using System;
using System.Data.OleDb;
using System.Drawing;
using System.Windows.Forms;
using LoginLib;
namespace ShapeApp1
{
public partial class CreateForm : Form
{
private readonly OleDbConnection _conn;
public CreateForm(OleDbConnection conn)
{
InitializeComponent();
accountBox.Select();
_conn = conn;
}
private void cancelButton_Click(object sender, EventArgs e)
{
Close();
}
private void CreateForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Color.DeepSkyBlue, 3),
DisplayRectangle);
}
//Drag the form without border
private bool _dragging;
private Point _dragCursorPoint;
private Point _dragFormPoint;
private void CreateForm_MouseDown(object sender, MouseEventArgs e)
{
_dragging = true;
_dragCursorPoint = Cursor.Position;
_dragFormPoint = Location;
}
private void CreateForm_MouseMove(object sender, MouseEventArgs e)
{
if (_dragging)
{
Point dif = Point.Subtract(Cursor.Position, new Size(_dragCursorPoint));
Location = Point.Add(_dragFormPoint, new Size(dif));
}
}
private void CreateForm_MouseUp(object sender, MouseEventArgs e)
{
_dragging = false;
}
private void createButton_Click(object sender, EventArgs e)
{
//insert into the db
var cred = new Credentials(accountBox.Text, pw1Box.Text, emailBox.Text);
var isSuccess = LoginAuthentication.IsInsertDb(_conn, cred);
if (isSuccess)
{
this.Close();
}
}
}
}
|
d584a69a0e3e00df1bb288a07259262d1830c3c9
|
C#
|
Niconpapas/Cheatsheets
|
/DelegatesAndEvents/DelegatesAndEvents/Program.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegatesAndEvents
{
class Program
{
static void Main(string[] args)
{
//Person newPerson1 = new Person() { FirstName = "Paul", LastName = "McDuck" };
Video newVideo = new Video() { Name = "DirHard.mp4" };
VideoEncoder videoEncoder = new VideoEncoder();//Publisher
NotificationService notificationService = new NotificationService();//Subscriber
EmailService emailService = new EmailService();
videoEncoder.VideoEncoded += notificationService.OnVideoEncoded;
videoEncoder.VideoEncoded += emailService.OnVideoEncoded;
videoEncoder.Encode(newVideo);
Console.WriteLine("-----");
Console.WriteLine(newVideo.Name + ", " + newVideo.EmailState + ", " + newVideo.TextState);
Console.ReadKey();
}
}
public class EmailService
{
public void OnVideoEncoded(object source,VideoEventArgs arg)
{
Console.WriteLine("Text Sent!");
arg.Video.EmailState = Video.NotificationState.Sent;
}
}
}
|
ee86eacb3301dcf073ace42f08e6ee32ff163701
|
C#
|
losttech/TypeNum
|
/samples/Tensors/Program.cs
| 2.578125
| 3
|
namespace Tensors
{
using System.Diagnostics;
using TypeNum;
using N39 = TypeNum.Sum<TypeNum.Sum<TypeNum.Sum<
TypeNum.N32,
TypeNum.N4>,
TypeNum.N2>,
TypeNum.N1>;
class Program
{
static void Main(string[] args)
{
var diag1 = new MutableTensor<N2, N2> {
[0, 0] = 1,
[1, 1] = 1,
};
var all1 = new MutableTensor<N2, N2> {
[0,0] = 1,
[0,1] = 1,
[1,0] = 1,
[1,1] = 1,
};
var sum = new MutableTensor<N2, N2>();
sum.Add(diag1);
sum.Add(all1);
var mul = new MutableTensor<N2, N2>();
sum.Mul(all1, result: mul);
// OK
var mulByFail = new MutableTensor<N2, Sum<N2, N1>>();
// sum.Mul(mulByFail, result: mul);
// error CS0411: The type arguments for method
// 'Tensor<N2, N2>.Mul<NOtherRows>(Tensor<N2, NOtherRows>, MutableTensor<N2, NOtherRows>)'
// cannot be inferred from the usage. Try specifying the type arguments explicitly.
Debug.Assert(N39.Num == 39);
var thirtyNine = new Tensor<N39, N39>();
}
}
}
|
970b622661a96be31ada46f6cc6985145302b47b
|
C#
|
Antonite/EternalChess
|
/EternalChess/Move.cs
| 3.359375
| 3
|
namespace EternalChess
{
class Move
{
public Location before;
public Location after;
public string color;
public string piece;
public string stringMove;
public Move(Location before, Location after, string color, string piece)
{
this.before = before;
this.after = after;
this.color = color;
this.piece = piece;
stringMove = toString();
}
public string toString()
{
var isProtion = piece.Equals("Pawn") && (after.row == 7 || after.row == 0);
var tempPiece = isProtion ? "Pawn" : piece;
var output = color + " " + tempPiece + " " + Utils.ColumnToLetter(after.column) + (after.row + 1) + " from " + Utils.ColumnToLetter(before.column) + (before.row + 1);
if (isProtion) output += ", Promoted to " + piece;
return output;
}
public string ToStringMove()
{
return Utils.ColumnToLetter(before.column) + (before.row + 1) + Utils.ColumnToLetter(after.column) + (after.row + 1);
}
}
}
|
fb4892a46743c014ab28cfc55487879c4ade0cf7
|
C#
|
rock117/file-downloader
|
/FileDownloader/FileDownloader/NumberUtil.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileDownloader
{
public class NumberUtil
{
public static string toFixed(float num, int len)
{
return toFixed(num + "", len);
}
public static string toFixed(double num, int len)
{
return toFixed(num + "", len);
}
public static string toFixed(long num, int len)
{
return toFixed(num + "", len);
}
private static string toFixed(string num, int len)
{
int index = num.IndexOf('.');
if (index < 0)
{
return num + "." + nString("0", len);
}
else
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < num.Length; i++)
{
if (i > index + 2)
{
break;
}
sb.Append(num.Substring(i, 1));
}
return sb.ToString();
}
}
private static string nString(string s, int n)
{
if (n <= 0)
return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
{
sb.Append(s);
}
return sb.ToString();
}
}
}
|
905e58a41f124f4d7434a017401b34a0703ffcfa
|
C#
|
barnabasMatrai/Threading
|
/SimpleThreadingDemo/SimpleThreadingDemo/Program.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleThreadingDemo
{
class Program
{
static void Main(string[] args)
{
ThreadStart threadStart = new ThreadStart(Counting);
Thread thread = new Thread(threadStart);
Thread thread1 = new Thread(threadStart);
thread.Start();
thread1.Start();
thread.Join();
thread1.Join();
Console.ReadKey();
}
public static void Counting()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}
}
}
}
|
f6d7f8ab7a52a4b908f4417cde502292dc111cb2
|
C#
|
mintsticks/lodcooking
|
/Assets/Scripts/Recipe.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Recipe : MonoBehaviour
{
public List<string> tasks;
public void finishStack() {
if(tasks.Contains("stack")) {
tasks.Remove("stack");
}
}
public void finishGrill() {
if(tasks.Contains("grill")) {
tasks.Remove("grill");
}
}
public void finishFry() {
if(tasks.Contains("fry")) {
tasks.Remove("fry");
}
}
public void finishChop() {
if(tasks.Contains("cut")) {
tasks.Remove("cut");
}
}
public bool isDone() {
return tasks.Count == 0;
}
}
|
de6d4deabf725de5637ebddfeaaf0d2347d41a32
|
C#
|
gunnersperos/Lockdown
|
/Lockdown/frmReminders.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace Lockdown
{
public partial class frmReminders : Form
{
private bool isLoading = true;
private bool isListClicked = false;
public Form pForm;
private List<Reminder> _defaultReminders = new List<Reminder>();
public List<Reminder> _myReminders = new List<Reminder>();
private const string REMINDERS_FILE_PATH = @"C:\Program Files\Lockdown\Reminders\Reminders.json";
public frmReminders()
{
InitializeComponent();
Profiles profile = new Profiles();
profile.CreateSaveFiles(); // for some reason reminders loads first despite Program.cs saying to start with frmMain...
UpdateMyRemindersList();
StartReminders();
}
private void frmReminders_Load(object sender, EventArgs e)
{
UpdateMyRemindersList();
this.isLoading = false;
}
public void UpdateMyRemindersList()
{
LoadMyReminders();
clbMyReminders.Items.Clear();
foreach (var reminder in _myReminders)
{
clbMyReminders.Items.Add(reminder.name);
}
//annoyingly long amount of code to make sure reminder checkstate is correct
int reminderListCount = clbMyReminders.Items.Count;
for (int i = 0; i < reminderListCount; i++)
{
clbMyReminders.SetItemCheckState(i, BoolToCheckState(_myReminders[i].isReminderOn));
}
}
private void lblExit_Click(object sender, EventArgs e)
{
this.Hide();
}
private void lblMinimize_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void lblBack_Click(object sender, EventArgs e)
{
this.pForm.Show();
this.Hide();
}
private void lblAddReminder_Click(object sender, EventArgs e)
{
frmAddReminder addReminder = new frmAddReminder();
addReminder.parentForm = this;
addReminder.Show();
}
private void LoadMyReminders()
{
_myReminders.Clear();
string[] jsonArray = System.IO.File.ReadAllLines(REMINDERS_FILE_PATH);
foreach (var line in jsonArray)
{
Reminder tempReminder = JsonSerializer.Deserialize<Reminder>(line);
_myReminders.Add(tempReminder);
}
}
private void StartReminders()
{
foreach (var reminder in _myReminders)
{
if (reminder.isReminderOn)
{
reminder.ReminderTimer();
}
}
}
private void UpdateReminderOnOff(int reminderIndex, CheckState reminderSwitch)
{
//changes the reminder object enabled field then updates the clbMyReminders
_myReminders[reminderIndex].isReminderOn = CheckStateToBool(reminderSwitch);
//need to save over the reminders file
List<string> jsonStringArray = new List<string>();
System.IO.File.WriteAllText(REMINDERS_FILE_PATH, string.Empty);
foreach (var reminder in _myReminders)
{
string jsonString = JsonSerializer.Serialize(reminder);
jsonStringArray.Add(jsonString);
}
foreach (var jsonString in jsonStringArray)
{
System.IO.File.AppendAllText(REMINDERS_FILE_PATH, jsonString + '\n');
}
}
private void clbMyReminders_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (isLoading || !isListClicked)
{
return; // don't want to double do this when loading the app or checkstate not actually changing
}
UpdateReminderOnOff(e.Index, e.NewValue);
_myReminders[e.Index].StartStopReminder(e.NewValue);
isListClicked = false;
}
private bool CheckStateToBool(CheckState checkState)
{
// just converting CheckState object to bool
bool onOff = checkState is CheckState.Checked ? true : false;
return onOff;
}
private CheckState BoolToCheckState(bool checkState)
{
// just converting bool object to CheckState
CheckState onOff = checkState is true ? CheckState.Checked : CheckState.Unchecked;
return onOff;
}
#region moved this to reminder class
//private void DisplayReminder(string reminderText)
//{
// // from stackoverflow
// var notification = new System.Windows.Forms.NotifyIcon()
// {
// Visible = true,
// Icon = Properties.Resources.LockdownIcon,//System.Drawing.SystemIcons.Application,
// // optional - BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info,
// // optional - BalloonTipTitle = "My Title",
// BalloonTipText = reminderText,
// };
// // Display for 5 seconds.
// notification.ShowBalloonTip(5000);
// // This will let the balloon close after it's 5 second timeout
// // for demonstration purposes. Comment this out to see what happens
// // when dispose is called while a balloon is still visible.
// System.Threading.Thread.Sleep(10000);
// // The notification should be disposed when you don't need it anymore,
// // but doing so will immediately close the balloon if it's visible.
// notification.Dispose();
//}
//private void ReminderTimer() // this is going to be needed for each reminder
//{
// int time = DateTime.Now.Minute;
// int[] fifteenMinuteIntervals = { 0, 15, 30, 40, 45 };
// if (fifteenMinuteIntervals.Contains(time))
// {
// //DisplayReminder();
// }
//}
//private void TheTimer()
//{
// //double currentSecond = 60 - DateTime.Now.Second;
// var startTimeSpan = TimeSpan.Zero;//FromSeconds(currentSecond);
// var interval = TimeSpan.FromMinutes(1);
// var timer = new System.Threading.Timer((e) =>
// {
// ReminderTimer();
// }, null, startTimeSpan, interval);
//}
#endregion
private void clbMyReminders_Click(object sender, EventArgs e)
{
this.isListClicked = true;
}
private void clbMyReminders_SelectedIndexChanged(object sender, EventArgs e)
{
this.isListClicked = false;
}
}
}
|
f24e85c280348b3cf81539cfdc5eeea1d0b468ac
|
C#
|
ssh352/cppcode
|
/DotNet/CSharpForDummies-master/Book 2 Object Oriented Principles/Chapter 8/PassInterface/Program.cs
| 3.53125
| 4
|
// PassInterface - Given an object that implements two interfaces,
// IBase and IDerived (which inherits IBase), can you
// pass an IDerived object through an IBase parameter? Yes.
// Can you add IDerived objects to an IBase collection? Yes.
// Can you use polymorphism as you would with classes? No.
using System;
using System.Collections.Generic;
namespace PassInterface
{
// Here's the base interface.
public interface IBase
{
void SayHello();
}
// Here's a derived interface that "inherits" from IBase.
public interface IDerived : IBase
{
int GetValue();
}
// Here's a class that implements both interfaces.
public class Thing : IDerived // Only need to mention the most derived interface type here.
{
public void SayHello()
{
Console.WriteLine("Hello");
}
public int GetValue()
{
return 1;
}
}
public class ThingDerived : Thing // Is also an IDerived and an IBase by inheritance.
{
}
class Program
{
static void Main(string[] args)
{
// Create an IDerived reference to a Thing.
// IDerived is an interface that "inherits" from IBase via
// interface inheritance.
Console.WriteLine("Pass a derived interface object "
+ "through a base interface parameter: ");
IDerived id = (IDerived)new Thing();
// Now try to pass id through a reference to IBase (not IDerived).
TestInheritedInterfacePassing(id);
Console.WriteLine("\nYou can add an IDerived object to an IBase collection.");
List<IBase> bases = new List<IBase>();
bases.Add(id);
Console.WriteLine("After adding an IDerived item, collection length is {0}.",
bases.Count);
Console.WriteLine();
// "Polymorphic" behavior is different for classes and interfaces.
Console.WriteLine("\nDemonstrating class polymorphism.");
Thing t = new Thing();
// Install an instance of the derived class in t.
t = new ThingDerived();
// OK to call Thing method through Thing reference
// even though the reference points to a ThingDerived object.
// ThingDerived inherits Thing.SayHello().
Console.Write("Calling base method through base class reference: ");
t.SayHello();
// Also OK to call ThingDerived method through Thing
// reference.
Console.WriteLine("Calling derived method through base class reference: {0}",
t.GetValue());
ThingDerived td = new ThingDerived();
Console.Write("Calling base method through derived object: ");
td.SayHello();
Console.WriteLine("Calling derived method through derived object: {0}",
td.GetValue());
Console.WriteLine("\nDemonstrating interface 'polymorphism.'");
// Thing implements IBase, so this cast is fine.
IBase ib = (IBase)new Thing();
// OK to call SayHello() through the interface because
// Thing implements IBase's SayHello() method.
Console.Write("Calling base method through derived interface reference: ");
ib.SayHello();
// Install an IDerived in the IBase reference.
ib = (IDerived)ib;
Console.Write("Attempting to call derived method through base reference ...");
// The following doesn't compile because
// ib knows nothing about IDerived.GetValue().
//ib.GetValue();
Console.WriteLine(" fails.");
// Cast the base reference to a derived reference.
IDerived id2 = (IDerived)ib;
// However, this works because IDerived defines GetValue().
Console.WriteLine("Calling derived method through converted base reference: {0}",
id2.GetValue());
Console.WriteLine("Press Enter to terminate...");
Console.Read();
}
// TestInheritedInterfacePassing - This method takes a parameter of type
// IBase, the base interface type. The code shows that you
// can pass an object of a derived interface type through this parameter.
static void TestInheritedInterfacePassing(IBase ib)
{
ib.SayHello();
Console.WriteLine("Yes, you can pass an IDerived reference via an IBase reference.");
// But interface inheritance involves no polymorphism.
// In class inheritance, the base class provides a public interface that all good
// subclasses adhere to even if they override the inherited methods. Thus you
// can call all public/protected methods (except any added in subclasses)
// in either base or derived classes. That's polymorphism.
// But although the underlying Thing class has both interfaces' methods,
// you can't call both sets through either of the interface references.
// The IBase interface exposes only the SayHello() method, and
// the IDerived interface exposes only the GetValue() method. Looking at
// the Thing underneath through either reference is like looking through a
// polarizing lens. You can only see what belongs to that interface.
// If you could see both methods through either reference, you'd have
// polymorphism here too. But you'd lose the ability to hide parts of the
// underlying class's public interface by handing out selective interfaces.
// Next call won't work because ib is an IBase reference, even though the
// underlying object implements IDerived and has a GetValue() method.
//Console.WriteLine(ib.GetValue());
// However, the following does work:
int value = ((IDerived)ib).GetValue(); // Note the fancy footwork with parentheses.
// (IDerived)ib does the cast. Then the extra
// parentheses wrap the cast object.
// That cast object is an IDerived reference.
// That's what you call the method on.
Console.WriteLine(value.ToString());
}
}
}
|
51ad9c691aa7d2eb2e71aba306504638ddeb5f4b
|
C#
|
shendongnian/download4
|
/code6/1078443-28038756-81949000-2.cs
| 3.21875
| 3
|
public enum SerialSignal
{
SendSync = 0x33,
ReceiveSync = 0x8A,
}
private static SerialPort _arduinoSerialPort ;
/// <summary>
/// Polls all serial port and check for our device connected or not
/// </summary>
/// <returns>True: if our device is connected</returns>
public static bool Initialize()
{
var serialPortNames = SerialPort.GetPortNames();
foreach (var serialPortName in serialPortNames)
{
try
{
_arduinoSerialPort = new SerialPort(serialPortName) { BaudRate = 9600 };
_arduinoSerialPort.Open();
_arduinoSerialPort.DiscardInBuffer();
_arduinoSerialPort.Write(new byte[] { (int)SerialSignal.SendSync }, 0, 1);
var readBuffer = new byte[1];
Thread.Sleep(500);
_arduinoSerialPort.ReadTimeout = 5000;
_arduinoSerialPort.WriteTimeout = 5000;
_arduinoSerialPort.Read(readBuffer, 0, 1);
// Check if it is our device or Not;
if (readBuffer[0] == (byte)SerialSignal.ReceiveSync){
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception at Serial Port:" + serialPortName + Environment.NewLine +
"Additional Message: " + ex.Message);
}
// if the send Sync repply not received just release resourceses
if (_arduinoSerialPort != null) _arduinoSerialPort.Dispose();
}
return false;
}
|
bfae48cc65d23efcfe440f30875632594eead694
|
C#
|
trbenning/Foundatio
|
/src/Core/Utility/DataDictionary.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Foundatio.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Foundatio.Utility {
public class DataDictionary : Dictionary<string, object> {
public DataDictionary() : base(StringComparer.OrdinalIgnoreCase) {}
public DataDictionary(IEnumerable<KeyValuePair<string, object>> values) : base(StringComparer.OrdinalIgnoreCase) {
foreach (var kvp in values)
Add(kvp.Key, kvp.Value);
}
public object GetValueOrDefault(string key) {
object value;
return TryGetValue(key, out value) ? value : null;
}
public object GetValueOrDefault(string key, object defaultValue) {
object value;
return TryGetValue(key, out value) ? value : defaultValue;
}
public object GetValueOrDefault(string key, Func<object> defaultValueProvider) {
object value;
return TryGetValue(key, out value) ? value : defaultValueProvider();
}
public T GetValue<T>(string key) {
if (!ContainsKey(key))
throw new KeyNotFoundException($"Key \"{key}\" not found in the dictionary.");
return GetValueOrDefault<T>(key);
}
public T GetValueOrDefault<T>(string key, T defaultValue = default(T)) {
if (!ContainsKey(key))
return defaultValue;
object data = this[key];
if (data is T)
return (T)data;
if (data is string) {
try {
return JsonConvert.DeserializeObject<T>((string)data);
} catch {}
}
if (data is JObject) {
try {
return JsonConvert.DeserializeObject<T>(data.ToString());
} catch {}
}
try {
return data.ToType<T>();
} catch {}
return defaultValue;
}
public string GetString(string name) {
return GetString(name, String.Empty);
}
public string GetString(string name, string @default) {
object value;
if (!TryGetValue(name, out value))
return @default;
if (value is string)
return (string)value;
return String.Empty;
}
public void ConvertJObjectToDataDictionary() {
foreach (var kvp in this.ToList()) {
if (kvp.Value is JObject) {
this[kvp.Key] = DeserializeToDictionary(kvp.Value.ToString());
} else {
this[kvp.Key] = kvp.Value;
}
}
}
public void RemoveSensitiveData() {
Keys.Where(k => k.StartsWith("-")).ToArray().ForEach(key => Remove(key));
}
private static Dictionary<string, object> DeserializeToDictionary(string json) {
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values) {
if (d.Value is JObject) {
values2.Add(d.Key, DeserializeToDictionary(d.Value.ToString()));
} else {
values2.Add(d.Key, d.Value);
}
}
return values2;
}
}
}
|
5ebd94537904224d2b560f7e88707f340e97e4fa
|
C#
|
fpermeti/coding_school_2021
|
/misc/DevExpressApp1/WindowsFormsApp4/Form1.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp4 {
public partial class Form1 : DevExpress.XtraBars.TabForm {
public Form1() {
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e) {
string message1 = "Only alphabet characters are allowed.\n\n";
string message2 = "Numbers, symbols and spacing are not allowed.";
Regex onlyAlphabetLetters = new Regex(@"^[a-zA-Z]+$");
MatchCollection matches = onlyAlphabetLetters.Matches(textEdit1.Text);
if (matches.Count > 0) {
int nameLength = textEdit1.Text.Length;
string firstLetterOfName = textEdit1.Text.Substring(0, 1).ToUpper();
string nameWithoutFirstLetter = textEdit1.Text.Substring(1, nameLength - firstLetterOfName.Length).ToLower();
string processedName = string.Format("{0}{1}", firstLetterOfName, nameWithoutFirstLetter);
if (!listBoxControl1.Items.Contains(processedName)) {
listBoxControl1.Items.Add(processedName);
}
else {
MessageBox.Show("The name you are trying to add already exists.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else {
MessageBox.Show(message1 + message2, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void listBoxControl1_MouseDoubleClick(object sender, MouseEventArgs e) {
int index = this.listBoxControl1.IndexFromPoint(e.Location);
if (index != -1) {
MessageBox.Show(listBoxControl1.SelectedItem.ToString(), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
|
ace8e13574ffbf7d50b9aa8980dcbf6349ca7120
|
C#
|
michaelswells/FontAwesomeAttribute
|
/FontAwesome/FontAwesome.UserEdit.cs
| 2.609375
| 3
|
using System;
namespace FontAwesome
{
/// <summary>
/// The unicode values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Unicode
{
/// <summary>
/// fa-user-edit unicode value ("\uf4ff").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/user-edit
/// </summary>
public const string UserEdit = "\uf4ff";
}
/// <summary>
/// The Css values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Css
{
/// <summary>
/// UserEdit unicode value ("fa-user-edit").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/user-edit
/// </summary>
public const string UserEdit = "fa-user-edit";
}
/// <summary>
/// The Icon names for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Icon
{
/// <summary>
/// fa-user-edit unicode value ("\uf4ff").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/user-edit
/// </summary>
public const string UserEdit = "UserEdit";
}
}
|
8c9796209be07b440e76fabbb9993918a56ecc2b
|
C#
|
ufcpp/BitFields
|
/experimental/TypeClassBits/LogicalOperators.cs
| 2.984375
| 3
|
namespace TypeClassBits
{
public struct LogicalOperator8 : ILogicalOperator<byte>
{
public byte One => 1;
public byte As(ulong value) => unchecked((byte)value);
public byte Not(byte value) => unchecked((byte)~value);
public void And(ref byte x, byte y) => x &= y;
public void Or(ref byte x, byte y) => x |= y;
public void LeftShift(ref byte x, int i) => x <<= i;
public void RightShift(ref byte x, int i) => x >>= i;
public bool IsZero(byte x) => x == 0;
}
public struct LogicalOperator16 : ILogicalOperator<ushort>
{
public ushort One => 1;
public ushort As(ulong value) => unchecked((ushort)value);
public ushort Not(ushort value) => unchecked((ushort)~value);
public void And(ref ushort x, ushort y) => x &= y;
public void Or(ref ushort x, ushort y) => x |= y;
public void LeftShift(ref ushort x, int i) => x <<= i;
public void RightShift(ref ushort x, int i) => x >>= i;
public bool IsZero(ushort x) => x == 0;
}
public struct LogicalOperator32 : ILogicalOperator<uint>
{
public uint One => 1;
public uint As(ulong value) => unchecked((uint)value);
public uint Not(uint value) => ~value;
public void And(ref uint x, uint y) => x &= y;
public void Or(ref uint x, uint y) => x |= y;
public void LeftShift(ref uint x, int i) => x <<= i;
public void RightShift(ref uint x, int i) => x >>= i;
public bool IsZero(uint x) => x == 0;
}
public struct LogicalOperator64 : ILogicalOperator<ulong>
{
public ulong One => 1;
public ulong As(ulong value) => value;
public ulong Not(ulong value) => ~value;
public void And(ref ulong x, ulong y) => x &= y;
public void Or(ref ulong x, ulong y) => x |= y;
public void LeftShift(ref ulong x, int i) => x <<= i;
public void RightShift(ref ulong x, int i) => x >>= i;
public bool IsZero(ulong x) => x == 0;
}
}
|
0c3d4a035b6d2c7d0899c40dfdc221c61b48fc9a
|
C#
|
alonsodev/SSR
|
/Business.Logic/DraftLawStatusBL.cs
| 2.65625
| 3
|
using Domain.Entities;
using Infrastructure.Data;
using Infrastructure.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business.Logic
{
public class DraftLawStatusBL
{
private static DraftLawStatusRepository oRepositorio;
private static UnitOfWork oUnitOfWork;
public DraftLawStatusBL()
{
oUnitOfWork = new UnitOfWork(ConfigurationManager.ConnectionStrings["SSREntities"].ConnectionString);
oRepositorio = oUnitOfWork.DraftLawStatusRepository;
}
public Dictionary<string, DraftLawStatusViewModel> ObtenerDiccionarioPorNombre(List<string> lista, int user_id)
{
var olista = oRepositorio.ObtenerTodos();
Dictionary<string, DraftLawStatusViewModel> dictionary = new Dictionary<string, DraftLawStatusViewModel>();
foreach (var item in olista)
{
dictionary.Add(item.name, item);
}
foreach (var name in lista)
{
if (!String.IsNullOrEmpty(name) && !dictionary.ContainsKey(name))
{
draft_laws_status odraft_laws_status = new draft_laws_status
{
draft_law_status_id = 0,
name = name,
notifiable = false,
};
odraft_laws_status = oRepositorio.Add(odraft_laws_status);
oUnitOfWork.SaveChanges();
DraftLawStatusViewModel oDraftLawStatusViewModel = new DraftLawStatusViewModel();
oDraftLawStatusViewModel.draft_law_status_id = odraft_laws_status.draft_law_status_id;
oDraftLawStatusViewModel.name = odraft_laws_status.name;
oDraftLawStatusViewModel.notifiable = odraft_laws_status.notifiable;
dictionary.Add(odraft_laws_status.name, oDraftLawStatusViewModel);
}
}
return dictionary;
}
}
}
|
d999a43733fb4038ca14d5d09aef7796220cf1df
|
C#
|
Ktaliken/Test
|
/MethodSortArray.cs
| 3.75
| 4
|
using System;
namespace ConsoleApp7
{
class Program
{
public static void Main(string[] args)
{
int[] array = GetArrayFromConsole();
SortArray(array);
foreach (int item in array)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
static int[] GetArrayFromConsole()
{
var result = new int[5];
for (int i = 0; i < result.Length; i++)
{
Console.WriteLine("Enter array item № {0}", i);
result[i] = Convert.ToInt32(Console.ReadLine());
}
return result;
}
static int[] SortArray(int[] result)
{
int temp;
for (int k = 0; k < result.Length; k++)
{
for (int h = k + 1; h < result.Length; h++)
{
if (result[k] > result[h])
{
temp = result[k];
result[k] = result[h];
result[h] = temp;
}
}
}
return result;
}
}
}
|
aaaa4f88607c842e88e5243dfa207eeff3b885fa
|
C#
|
sun-wise-man/Publish-Subscribe
|
/Receive/Receive.cs
| 3
| 3
|
using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
class ReceiveLogs
{
public static void Main()
{
/* Membuat koneksi, dengan host lokal*/
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
/*Membuat kanal untuk komunikasi*/
using (var channel = connection.CreateModel())
{
/*Pertukaran di kanal dinamakan "logs", dan bertipe fanout.*/
/*Tipe fanout akan membroadcast pesan ke semua queue.*/
channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout);
/*Membuat queue yang akan menerima pesan*/
var antrianPesan = channel.QueueDeclare().QueueName;
/*Melanggan ke "logs"*/
channel.QueueBind(queue: antrianPesan,
exchange: "logs",
routingKey: "");
/*Indikator queue sudah siap, dan sedang menunggu*/
Console.WriteLine(" Menunggu pesan...");
/*Membuat penerima pesan*/
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
//Pesan di decode
var message = Encoding.UTF8.GetString(body);
//Pesan ditangkap dan ditampilkan
Console.WriteLine(" Isi pesan: {0}", message);
Console.WriteLine(" Pesan diterima!");
Console.WriteLine(" [enter] untuk keluar.\n");
};
channel.BasicConsume(queue: antrianPesan,
autoAck: true,
consumer: consumer);
Console.WriteLine(" [enter] untuk keluar.\n");
Console.ReadLine();
}
}
}
|
4e3d93baf812d49528a7d94704a06055b265b33e
|
C#
|
Haricane2000/ZIiNIS
|
/2semestr/Lab3/ThirdLab/Program.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace ThirdLab
{
class Program
{
static string textForEncode = "цввяткоу ";
static string secondTextForEncode = "мыкалай";
static string text = "";
static void Main(string[] args)
{
var startTime = System.Diagnostics.Stopwatch.StartNew();
Console.OutputEncoding = System.Text.Encoding.Unicode;
try
{
using(StreamReader sr=new StreamReader(@"D:\3c2s\ЗИ_\2sem\ThirdLab\ThirdLab\bin\Debug\in.txt"))
{
text = sr.ReadToEnd();
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
char[,] matrica=new char[text.Length,textForEncode.Length+2];
int prov = 0;
for (int i = 0; i < text.Length ; i++)
{
if (prov == 0)
{
prov++;
for (int j = 0; j < textForEncode.Length +2; j++)
{
if (j < textForEncode.Length)
{
matrica[i, j] = textForEncode[j];
}
else
{
matrica[i, j] = text[0];
text = text.Remove(0, 1);
}
}
}
else
{
for (int j = 0; j < textForEncode.Length + 2; j++)
{
matrica[i, j] = text[0];
text = text.Remove(0, 1);
}
}
}
//for (int i = 0; i < textForEncode.Length + 2; i++)
//{
// for (int j = 0; j < text.Length; j++)
// {
// Console.Write(matrica[j, i]);
// }
// Console.WriteLine();
//}
Console.WriteLine("_____________________________________________________________________");
char[,] secondMatrica= new char[textForEncode.Length + 2,text.Length];
for(int i = 0; i < textForEncode.Length + 2; i++)
{
for(int j = 0; j < text.Length; j++)
{
secondMatrica[i, j] = matrica[j, i];
}
}
for (int i = 0; i < textForEncode.Length + 2; i++)
{
for (int j = 0; j < text.Length; j++)
{
Console.Write(secondMatrica[i, j]);
}
Console.WriteLine();
}
startTime.Stop();
var resultTime = startTime.Elapsed;
// elapsedTime - строка, которая будет содержать значение затраченного времени
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
resultTime.Hours,
resultTime.Minutes,
resultTime.Seconds,
resultTime.Milliseconds);
Console.WriteLine();
Console.WriteLine("Encode Time: " + elapsedTime.ToString());
Console.WriteLine();
var startTime1 = System.Diagnostics.Stopwatch.StartNew();
char[,] thirdMatrica = new char[text.Length, textForEncode.Length + 2];
for(int i = 0; i < text.Length; i++)
{
for(int j = 0; j < textForEncode.Length + 2; j++)
{
thirdMatrica[i, j] = secondMatrica[j, i];
}
}
for (int i = 0; i < text.Length; i++)
{
for (int j = 0; j < textForEncode.Length + 2; j++)
{
Console.Write(thirdMatrica[i, j]);
}
Console.WriteLine();
}
startTime1.Stop();
var resultTime1 = startTime1.Elapsed;
// elapsedTime - строка, которая будет содержать значение затраченного времени
string elapsedTime1 = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
resultTime1.Hours,
resultTime1.Minutes,
resultTime1.Seconds,
resultTime1.Milliseconds);
Console.WriteLine();
Console.WriteLine("Decode Time: " + elapsedTime1.ToString());
Console.WriteLine();
Console.WriteLine("_______________________________________________________________________________");
// Первый ключ, количество столбцов
string firstKey = "Цвяткоу";
// Второй ключ, количество строк
string secondKey = "Мыкалай";
// Предложение которое шифруем
string stringUser = "На бясконцым беразе, перад разгубленым малым застаюцца.";
// Матрица в которой производим шифрование
char[,] matrix = new char[secondKey.Length, firstKey.Length];
// Счетчик символов в строке
int countSymbols = 0;
// Переводим строки в массивы типа char
char[] charsFirstKey = firstKey.ToCharArray();
char[] charsSecondKey = secondKey.ToCharArray();
char[] charStringUser = stringUser.ToCharArray();
// Создаем списки в которых будут храниться символы и порядковы номера символов
List<CharNum> listCharNumFirst =
new List<CharNum>(firstKey.Length);
List<CharNum> listCharNumSecond =
new List<CharNum>(secondKey.Length);
// Заполняем символами из ключей
listCharNumFirst = FillListKey(charsFirstKey);
listCharNumSecond = FillListKey(charsSecondKey);
// Заполняем порядковыми номерами
listCharNumFirst = FillingSerialsNumber(listCharNumFirst);
listCharNumSecond = FillingSerialsNumber(listCharNumSecond);
ShowKey(listCharNumFirst, "Первый ключ: ");
ShowKey(listCharNumSecond, "Второй ключ: ");
// Заполнение матрицы строкой пользователя
for (int i = 0; i < listCharNumSecond.Count; i++)
{
for (int j = 0; j < listCharNumFirst.Count; j++)
{
matrix[i, j] = charStringUser[countSymbols++];
}
}
ShowMatrix(matrix, "Первоначальное значение: ");
countSymbols = 0;
// Заполнение матрицы с учетом шифрования.
// Переставляем столбцы по порядку следования в первом ключе.
// Затем переставляем строки по порядку следования во втором ключа.
for (int i = 0; i < listCharNumSecond.Count; i++)
{
for (int j = 0; j < listCharNumFirst.Count; j++)
{
matrix[listCharNumSecond[i].NumberInWord,
listCharNumFirst[j].NumberInWord] = charStringUser[countSymbols++];
}
}
var startTime2 = System.Diagnostics.Stopwatch.StartNew();
ShowMatrix(matrix, "Зашифрованное значение: ");
startTime2.Stop();
var resultTime2 = startTime2.Elapsed;
// elapsedTime - строка, которая будет содержать значение затраченного времени
string elapsedTime2 = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
resultTime.Hours,
resultTime.Minutes,
resultTime.Seconds,
resultTime.Milliseconds);
Console.WriteLine("Encode Time: " + elapsedTime2.ToString());
Console.ReadKey();
}
public static int GetNumberInThealphabet(char s)
{
string str = @"АаБбВвГгДдЕеЁёЖжЗзІіЙйКкЛлМмНнОоПпРрСсТтУуЎўФфХхЦцЧчШшЫыЬьЭэЮюЯя";
int number = str.IndexOf(s) / 2;
return number;
}
/// <summary>
/// Заполнение символами списка с ключом.
/// </summary>
/// <param name="chars">массив символов.</param>
/// <returns>Список символов.</returns>
public static List<CharNum> FillListKey(char[] chars)
{
List<CharNum> listKey = new List<CharNum>(chars.Length);
for (int i = 0; i < chars.Length; i++)
{
CharNum charNum = new CharNum()
{
Ch = chars[i],
NumberInWord = GetNumberInThealphabet(chars[i])
};
listKey.Add(charNum);
}
return listKey;
}
/// <summary>
/// Отображение ключа.
/// </summary>
/// <param name="listCharNum">Список в котором содержатся символы с порядковыми номерами.</param>
public static void ShowKey(List<CharNum> listCharNum, string message)
{
Console.WriteLine(message);
foreach (var i in listCharNum)
{
Console.Write(i.Ch + " ");
}
Console.WriteLine();
foreach (var i in listCharNum)
{
Console.Write(i.NumberInWord + " ");
}
Console.WriteLine();
Console.WriteLine();
}
/// <summary>
/// Заполнение символов ключей, порядковыми номерами.
/// </summary>
/// <param name="listCharNum"></param>
/// <returns></returns>
public static List<CharNum> FillingSerialsNumber(
List<CharNum> listCharNum)
{
int count = 0;
var result = listCharNum.OrderBy(a =>
a.NumberInWord);
foreach (var i in result)
{
i.NumberInWord = count++;
}
return listCharNum;
}
/// <summary>
/// Отображение матрицы.
/// </summary>
/// <param name="matrix">Матрица с символами.</param>
public static void ShowMatrix(char[,] matrix, string message)
{
Console.WriteLine(message);
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
}
}
class CharNum
{
#region Fields
/// <summary>
/// Символ.
/// </summary>
private char _ch;
/// <summary>
/// Порядковый номер зависящий от алфавита.
/// </summary>
private int _numberInWord;
#endregion Fieds
#region Properties
/// <summary>
/// Символ.
/// </summary>
public char Ch
{
get { return _ch; }
set
{
if (_ch == value)
return;
_ch = value;
}
}
/// <summary>
/// Порядковый номер в строке, зависящий от алфавита.
/// </summary>
public int NumberInWord
{
get { return _numberInWord; }
set
{
if (_numberInWord == value)
return;
_numberInWord = value;
}
}
#endregion Properties
}
}
|
cc9ed40235bb47613440b710f40999581cd75d90
|
C#
|
hristodobrev/SU
|
/Advanced C#/Exams/Exam Problems Practice/02. String Matrix Rotation/StringMatrixRotation.cs
| 3.625
| 4
|
using System;
using System.Text;
using System.Collections.Generic;
class StringMatrixRotation
{
static void Main()
{
// Input
List<string> list = new List<string>();
StringBuilder rotation = new StringBuilder(Console.ReadLine());
string text = Console.ReadLine();
while (text.ToUpper() != "END")
{
list.Add(text);
text = Console.ReadLine();
}
// Logic
rotation.Remove(0, 7);
for (int i = 0; i < rotation.Length; i++)
{
if (rotation[i] == ')')
{
rotation.Remove(i, 1);
}
}
int degrees = int.Parse(rotation.ToString());
degrees %= 360;
if (degrees == -90)
{
degrees = 270;
}
else if (degrees == -180)
{
degrees = 180;
}
else if (degrees == -270)
{
degrees = 90;
}
char[,] matrix = new char[list.Count, GetLongestLenght(list)];
for (int y = 0; y < list.Count; y++)
{
for (int x = 0; x < list[y].Length; x++)
{
matrix[y, x] = list[y][x];
}
}
if (degrees == 90)
{
matrix = Rotate90(matrix);
}
else if (degrees == 180)
{
matrix = Rotate180(matrix);
}
else if (degrees == 270)
{
matrix = Rotate270(matrix);
}
// Output
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j]);
}
Console.WriteLine();
}
}
static int GetLongestLenght(List<string> list)
{
int maxLenght = int.MinValue;
for (int i = 0; i < list.Count; i++)
{
if (maxLenght < list[i].Length)
{
maxLenght = list[i].Length;
}
}
return maxLenght;
}
static char[,] Rotate90(char[,] matrix)
{
int rows = matrix.GetLength(1);
int cols = matrix.GetLength(0);
char[,] rotatedMatrix = new char[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = cols - 1; j >= 0; j--)
{
rotatedMatrix[i, j] = matrix[i, j];
}
}
return rotatedMatrix;
}
static char[,] Rotate180(char[,] matrix)
{
char[,] rotatedMatrix = new char[matrix.GetLength(0), matrix.GetLength(1)];
for (int i = 0; i < rotatedMatrix.GetLength(0); i++)
{
for (int j = 0; j < rotatedMatrix.GetLength(1); j++)
{
rotatedMatrix[i, j] = matrix[matrix.GetLength(0) - 1 - i, matrix.GetLength(1) - 1 - j];
}
}
return rotatedMatrix;
}
static char[,] Rotate270(char[,] matrix)
{
char[,] rotatedMatrix = new char[matrix.GetLength(1), matrix.GetLength(0)];
for (int i = 0; i < rotatedMatrix.GetLength(0); i++)
{
for (int j = 0; j < rotatedMatrix.GetLength(1); j++)
{
rotatedMatrix[i, j] = matrix[j, matrix.GetLength(1) - 1 - i];
}
}
return rotatedMatrix;
}
}
|
f495ffda8123fdf5548696459e68139747ee1281
|
C#
|
dbcdiogo/SiteCenbrap
|
/Biblioteca/DB/CategoriaDB.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Biblioteca.Entidades;
namespace Biblioteca.DB
{
public class CategoriaDB
{
public void Salvar(Categoria variavel)
{
try
{
DBSession session = new DBSession();
Query query = session.CreateQuery("INSERT INTO categoria (titulo) VALUES (@titulo) ");
query.SetParameter("titulo", variavel.titulo);
query.ExecuteUpdate();
session.Close();
}
catch (Exception error)
{
throw error;
}
}
public int SalvarRetornar(Categoria variavel)
{
try
{
Salvar(variavel);
return Buscar(variavel.titulo).categoria_id;
}
catch (Exception error)
{
throw error;
}
}
public void Alterar(Categoria variavel)
{
try
{
DBSession session = new DBSession();
Query query = session.CreateQuery("UPDATE categoria SET titulo = @titulo WHERE categoria_id = @categoria_id");
query.SetParameter("titulo", variavel.titulo)
.SetParameter("categoria_id", variavel.categoria_id);
query.ExecuteUpdate();
session.Close();
}
catch (Exception error)
{
throw error;
}
}
public void Excluir(Categoria variavel)
{
try
{
DBSession session = new DBSession();
Query query = session.CreateQuery("DELETE FROM categoria WHERE categoria_id = @categoria_id; DELETE FROM video_categoria WHERE categoria_id = @categoria_id;");
query.SetParameter("categoria_id", variavel.categoria_id);
query.ExecuteUpdate();
session.Close();
}
catch (Exception error)
{
throw error;
}
}
public List<Categoria> Listar()
{
try
{
List<Categoria> categoria = new List<Categoria>();
DBSession session = new DBSession();
Query query = session.CreateQuery("select isnull(categoria_id, 0) as categoria_id, isnull(titulo, '') as titulo FROM categoria ORDER BY titulo");
IDataReader reader = query.ExecuteQuery();
while (reader.Read())
{
categoria.Add(new Categoria(Convert.ToInt32(reader["categoria_id"]), Convert.ToString(reader["titulo"])));
}
reader.Close();
session.Close();
return categoria;
}
catch (Exception error)
{
throw error;
}
}
public List<Categoria> ListarComVideo()
{
try
{
List<Categoria> categoria = new List<Categoria>();
DBSession session = new DBSession();
Query query = session.CreateQuery("select isnull(categoria_id, 0) as categoria_id, isnull(titulo, '') as titulo FROM categoria WHERE EXISTS (SELECT * FROM video_categoria WHERE categoria.categoria_id = video_categoria.categoria_id) ORDER BY titulo");
IDataReader reader = query.ExecuteQuery();
while (reader.Read())
{
categoria.Add(new Categoria(Convert.ToInt32(reader["categoria_id"]), Convert.ToString(reader["titulo"])));
}
reader.Close();
session.Close();
return categoria;
}
catch (Exception error)
{
throw error;
}
}
public List<Categoria> Listar(Video video)
{
try
{
List<Categoria> categoria = new List<Categoria>();
DBSession session = new DBSession();
Query query = session.CreateQuery("select isnull(c.categoria_id, 0) as categoria_id, isnull(c.titulo, '') as titulo FROM categoria as c INNER JOIN video_categoria as vc ON c.categoria_id = vc.categoria_id WHERE vc.video_id = @video_id ORDER BY c.titulo").SetParameter("video_id", video.video_id);
IDataReader reader = query.ExecuteQuery();
while (reader.Read())
{
categoria.Add(new Categoria(Convert.ToInt32(reader["categoria_id"]), Convert.ToString(reader["titulo"])));
}
reader.Close();
session.Close();
return categoria;
}
catch (Exception error)
{
throw error;
}
}
public Categoria Buscar(int id)
{
try
{
Categoria categoria = null;
DBSession session = new DBSession();
Query query = session.CreateQuery("select isnull(categoria_id, 0) as categoria_id, isnull(titulo, '') as titulo FROM categoria WHERE categoria_id = @categoria_id ORDER BY titulo");
query.SetParameter("categoria_id", id);
IDataReader reader = query.ExecuteQuery();
if (reader.Read())
{
categoria = new Categoria(Convert.ToInt32(reader["categoria_id"]), Convert.ToString(reader["titulo"]));
}
reader.Close();
session.Close();
return categoria;
}
catch (Exception error)
{
throw error;
}
}
public Categoria Buscar(string titulo)
{
try
{
Categoria categoria = null;
DBSession session = new DBSession();
Query query = session.CreateQuery("select isnull(categoria_id, 0) as categoria_id, isnull(titulo, '') as titulo FROM categoria WHERE titulo = @titulo ORDER BY titulo");
query.SetParameter("titulo", titulo);
IDataReader reader = query.ExecuteQuery();
if (reader.Read())
{
categoria = new Categoria(Convert.ToInt32(reader["categoria_id"]), Convert.ToString(reader["titulo"]));
}
reader.Close();
session.Close();
return categoria;
}
catch (Exception error)
{
throw error;
}
}
public int ListarAleatorio()
{
try
{
int retorno = 0;
DBSession session = new DBSession();
Query query = session.CreateQuery("select TOP 1 categoria_id from categoria where categoria_id <> 12 ORDER BY NEWID()");
IDataReader reader = query.ExecuteQuery();
if (reader.Read())
{
retorno = Convert.ToInt32(reader["categoria_id"]);
}
reader.Close();
session.Close();
return retorno;
}
catch (Exception error)
{
throw error;
}
}
public List<Categoria> ListarTimeline(int pagina = 1)
{
try
{
List<Categoria> dataLote = new List<Categoria>();
DBSession session = new DBSession();
Query quey = session.CreateQuery("SELECT * FROM categoria ORDER BY titulo OFFSET 10 * (@pagina - 1) ROWS FETCH NEXT 10 ROWS ONLY");
quey.SetParameter("pagina", pagina);
IDataReader reader = quey.ExecuteQuery();
while (reader.Read())
{
dataLote.Add(new Categoria(Convert.ToInt32(reader["categoria_id"]), Convert.ToString(reader["titulo"])));
}
reader.Close();
session.Close();
return dataLote;
}
catch (Exception error)
{
throw error;
}
}
public List<Categoria> ListarTimeline(int pagina = 1, string titulo = "")
{
try
{
List<Categoria> dataLote = new List<Categoria>();
DBSession session = new DBSession();
Query quey = session.CreateQuery("SELECT * FROM categoria WHERE titulo like '%" + titulo.Replace(" ", "%") + "%' ORDER BY titulo OFFSET 10 * (@pagina - 1) ROWS FETCH NEXT 10 ROWS ONLY");
quey.SetParameter("titulo", titulo);
quey.SetParameter("pagina", pagina);
IDataReader reader = quey.ExecuteQuery();
while (reader.Read())
{
dataLote.Add(new Categoria(Convert.ToInt32(reader["categoria_id"]), Convert.ToString(reader["titulo"])));
}
reader.Close();
session.Close();
return dataLote;
}
catch (Exception error)
{
throw error;
}
}
public int Total()
{
int r = 0;
DBSession session = new DBSession();
Query quey = session.CreateQuery("SELECT count(*) as total FROM categoria");
IDataReader reader = quey.ExecuteQuery();
if (reader.Read())
{
r = Convert.ToInt32(reader["total"]);
}
reader.Close();
session.Close();
return r;
}
public int Total(string titulo = "")
{
int r = 0;
DBSession session = new DBSession();
Query quey = session.CreateQuery("SELECT count(*) as total FROM categoria WHERE titulo like '%" + titulo.Replace(" ", "%") + "%'");
quey.SetParameter("titulo", titulo);
IDataReader reader = quey.ExecuteQuery();
if (reader.Read())
{
r = Convert.ToInt32(reader["total"]);
}
reader.Close();
session.Close();
return r;
}
public void ExcluirCategoriasBlog(int id)
{
try
{
DBSession session = new DBSession();
Query query = session.CreateQuery("DELETE FROM blog_categoria WHERE idblog = @id");
query.SetParameter("id", id);
query.ExecuteUpdate();
session.Close();
}
catch (Exception error)
{
throw error;
}
}
public void SalvarCategoriaBlog(int id, string categoria)
{
try
{
DBSession session = new DBSession();
Query query = session.CreateQuery("INSERT INTO blog_categoria (idblog, txcategoria) VALUES (@id, @categoria) ");
query.SetParameter("id", id);
query.SetParameter("categoria", categoria);
query.ExecuteUpdate();
session.Close();
}
catch (Exception error)
{
throw error;
}
}
}
}
|
6ac1ec76b22ece6d72eaea6171069be98b0b86ed
|
C#
|
stanislavstoyanov99/SoftUni-Software-Engineering
|
/DB-with-C#/Exams/Entity Framework Core/01. C# DB Advanced Exam - 07.04.19/Cinema/DataProcessor/Deserializer.cs
| 2.6875
| 3
|
namespace Cinema.DataProcessor
{
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using Newtonsoft.Json;
using Data;
using Cinema.Data.Models;
using Cinema.Data.Models.Enums;
using Cinema.DataProcessor.ImportDto;
public class Deserializer
{
private const string ErrorMessage = "Invalid data!";
private const string SuccessfulImportMovie
= "Successfully imported {0} with genre {1} and rating {2}!";
private const string SuccessfulImportHallSeat
= "Successfully imported {0}({1}) with {2} seats!";
private const string SuccessfulImportProjection
= "Successfully imported projection {0} on {1}!";
private const string SuccessfulImportCustomerTicket
= "Successfully imported customer {0} {1} with bought tickets: {2}!";
public static string ImportMovies(CinemaContext context, string jsonString)
{
Movie[] movies = JsonConvert.DeserializeObject<Movie[]>(jsonString);
StringBuilder sb = new StringBuilder();
foreach (var movie in movies)
{
bool isValidGenre = Enum.IsDefined(typeof(Genre), movie.Genre);
bool isMovieTitleExists = context.Movies
.Any(m => m.Title == movie.Title);
if (isValidGenre == false || isMovieTitleExists == true)
{
sb.AppendLine(ErrorMessage);
continue;
}
bool isMovieValid = IsValid(movie);
if (isMovieValid == false)
{
sb.AppendLine(ErrorMessage);
continue;
}
context.Movies.Add(movie);
sb.AppendLine(string.Format(SuccessfulImportMovie,
movie.Title,
movie.Genre.ToString(),
movie.Rating.ToString("F2")));
}
context.SaveChanges();
return sb.ToString().TrimEnd();
}
public static string ImportHallSeats(CinemaContext context, string jsonString)
{
ImportHallWithSeatsDto[] hallsDto = JsonConvert.DeserializeObject<ImportHallWithSeatsDto[]>(jsonString);
StringBuilder sb = new StringBuilder();
foreach (var hallDto in hallsDto)
{
bool isHallDtoValid = IsValid(hallDto);
Hall hall = Mapper.Map<Hall>(hallDto);
bool isHallValid = IsValid(hall);
if (isHallDtoValid == false || isHallValid == false)
{
sb.AppendLine(ErrorMessage);
continue;
}
// Fill seats table with a seat for the current hall
for (int i = 0; i < hallDto.SeatsCount; i++)
{
hall.Seats.Add(new Seat());
}
context.Halls.Add(hall);
string projectionType = string.Empty;
if (hall.Is3D == true && hall.Is4Dx == true)
{
projectionType = "4Dx/3D";
}
else if (hall.Is3D == true && hall.Is4Dx == false)
{
projectionType = "3D";
}
else if (hall.Is3D == false && hall.Is4Dx == true)
{
projectionType = "4Dx";
}
else if (hall.Is3D == false && hall.Is4Dx == false)
{
projectionType = "Normal";
}
sb.AppendLine(string.Format(SuccessfulImportHallSeat,
hall.Name,
projectionType,
hall.Seats.Count));
}
context.SaveChanges();
return sb.ToString().TrimEnd();
}
public static string ImportProjections(CinemaContext context, string xmlString)
{
var rootAttribute = new XmlRootAttribute("Projections");
var xmlSerializer = new XmlSerializer(typeof(ImportProjectionsDto[]), rootAttribute);
using var stringReader = new StringReader(xmlString);
var projectionsDto = (ImportProjectionsDto[])xmlSerializer
.Deserialize(stringReader);
StringBuilder sb = new StringBuilder();
foreach (var projectionDto in projectionsDto)
{
var projection = Mapper.Map<Projection>(projectionDto);
bool isProjectionValid = IsValid(projection);
var hall = context.Halls
.FirstOrDefault(h => h.Id == projection.HallId);
var movie = context.Movies
.FirstOrDefault(m => m.Id == projection.MovieId);
if (isProjectionValid == false || hall == null || movie == null)
{
sb.AppendLine(ErrorMessage);
continue;
}
context.Projections.Add(projection);
sb.AppendLine(string.Format(SuccessfulImportProjection,
projection.Movie.Title,
projection.DateTime.ToString("MM/dd/yyyy")));
}
context.SaveChanges();
return sb.ToString().TrimEnd();
}
public static string ImportCustomerTickets(CinemaContext context, string xmlString)
{
var rootAttribute = new XmlRootAttribute("Customers");
var xmlSerializer = new XmlSerializer(typeof(ImportCustomersDto[]), rootAttribute);
using var stringReader = new StringReader(xmlString);
var customersDto = (ImportCustomersDto[])xmlSerializer.Deserialize(stringReader);
StringBuilder sb = new StringBuilder();
foreach (var customerDto in customersDto)
{
var customer = Mapper.Map<Customer>(customerDto);
bool isCustomerValid = IsValid(customer);
if (isCustomerValid == false)
{
sb.AppendLine(ErrorMessage);
continue;
}
var customerTicketsDto = customerDto.Tickets;
foreach (var ticketDto in customerTicketsDto)
{
var ticket = Mapper.Map<Ticket>(ticketDto);
bool isTicketValid = IsValid(ticket);
if (isTicketValid == false)
{
sb.AppendLine(ErrorMessage);
continue;
}
var projection = context.Projections
.FirstOrDefault(p => p.Id == ticket.ProjectionId);
if (projection == null)
{
sb.AppendLine(ErrorMessage);
continue;
}
}
context.Customers.Add(customer);
sb.AppendLine(string.Format(SuccessfulImportCustomerTicket,
customer.FirstName,
customer.LastName,
customer.Tickets.Count));
}
context.SaveChanges();
return sb.ToString().TrimEnd();
}
private static bool IsValid(object obj)
{
var validationContext = new System
.ComponentModel
.DataAnnotations
.ValidationContext(obj);
var validationResult = new List<ValidationResult>();
return Validator.TryValidateObject(obj, validationContext, validationResult, true);
}
}
}
|
9e3acbe8cd759150333ed213f2c6edfdd588ad5b
|
C#
|
MatthewBregg/Assignment1VrforSocialGood
|
/Assets/Assignment 1/scripts/TriggerIfPlayerEnters.cs
| 2.828125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
abstract public class TriggerIfPlayerEntersAction : MonoBehaviour {
public abstract void performEnterAction(Collider platform, Collider other);
public abstract void performExitAction(Collider platform, Collider other);
};
// Looks for any attached trigger if player enters action types, and runs them all.
public class TriggerIfPlayerEnters : MonoBehaviour {
private TriggerIfPlayerEntersAction[] actions;
// Use this for initialization
void Start () {
actions = GetComponents<TriggerIfPlayerEntersAction>();
}
// Update is called once per frame
void Update () {
}
bool playerInside = false;
void OnTriggerEnter(Collider other) {
if (other.tag == "Player" ) {
foreach (TriggerIfPlayerEntersAction action in actions ) {
action.performEnterAction(this.GetComponent<Collider>(), other);
}
playerInside = true; // Do this to avoid running our actions repeadetly!
}
}
void OnTriggerExit(Collider other) {
if (other.tag == "Player") {
playerInside = false;
foreach (TriggerIfPlayerEntersAction action in actions) {
action.performExitAction(this.GetComponent<Collider>(), other);
}
}
}
}
|
528f3bc34d08b0c39530591d8edcecc4e22482c1
|
C#
|
gokul-repo/DataStructureAlgorithm
|
/Leetcode/24_SwapNodesinPairs.cs
| 3.828125
| 4
|
namespace DataStructureAlgorithm.Leetcode
{
//24. Swap Nodes in Pairs
//https://leetcode.com/problems/swap-nodes-in-pairs/
public class SwapNodesinPairs
{
//Recursion
//Time - O(n)
//Space - O(n)
public ListNode SwapPairs(ListNode head)
{
if (head == null || head.next == null)
{
return head;
}
var first = head;
var second = head.next;
first.next = SwapPairs(second.next);
second.next = first;
return second;
}
//Iterative
//Time - O(n)
//Space - O(1) - no recursive stack
public ListNode SwapPairs1(ListNode head)
{
ListNode dummy = new ListNode(-1);
dummy.next = head;
var prev = dummy;
while (head != null && head.next != null)
{
var firstNode = head;
var secondNode = head.next;
firstNode.next = secondNode.next;
secondNode.next = prev.next;
prev.next = secondNode;
prev = firstNode;
head = firstNode.next;
}
return dummy.next;
}
}
}
|
1eea0433f74fb7db17b58b5b3046515f3bc27aa2
|
C#
|
mizutoki79/AOJ
|
/ALDS_InttroductionToAlgorithmsAndDataStructures/ALDS1_3_D_AreasOnTheCross-SectionDiagram.cs
| 3.28125
| 3
|
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
class Program{
static void Main(){
string s = Console.ReadLine();
Stack<int> startStk = new Stack<int>(s.Length);
//Stack<Tuple<int, int>> areaStk = new Stack<Tuple<int, int>>(s.Length / 2);
Stack<int[]> astk = new Stack<int[]>(s.Length / 2);
int area = 0;
int totalArea = 0;
int currentPosition = 0;
foreach (char ch in s)
{
if(ch == '\\') startStk.Push(currentPosition);
else if(ch == '/' && startStk.Count() > 0){
int startPosition = startStk.Pop();
area = currentPosition - startPosition;
totalArea += area;
int areaStart = startPosition;
//while(areaStk.Count() > 0 && startPosition < areaStk.Peek().Item1){
while(astk.Count() > 0 && startPosition < astk.Peek()[0]){
//var tmp = areaStk.Pop();
var tmp = astk.Pop();
//areaStart = tmp.Item1;
areaStart = tmp[0];
//area += tmp.Item2;
area += tmp[1];
}
//areaStk.Push(Tuple.Create(areaStart, area));
astk.Push(new int[]{areaStart, area});
}
currentPosition++;
}
Console.WriteLine(totalArea);
//Console.Write(areaStk.Count());
Console.Write(astk.Count());
//if(areaStack.Count() > 0) Console.Write(" {0}", string.Join(" ", areaStk.Select(val => val.Item2).Reverse()));
if(astk.Count() > 0) Console.Write(" {0}", string.Join(" ", astk.Select(val => val[1].ToString() ).Reverse().ToArray() ) );
Console.WriteLine();
}
}
|
318aab4d3cbb8ab8def25fb88ad95892dba41e68
|
C#
|
BalanaguYashwanth/C-Sharp
|
/Arrays.cs
| 3.53125
| 4
|
using System;
namespace Arrays
{
class Numbers
{
static void Main(string[] args)
{
var name = new string[3] { "yash","bash","dash"};
Console.WriteLine(name[0]);
Console.WriteLine(name[1]);
Console.WriteLine(name[2]);
var fullname = String.Format("My name is {0} {1} {2}", name[0],name[1],name[2]);
}
}
}
|
07024565a439c73a176a283ad71657908d8b1548
|
C#
|
mbargolani/InterceptorDemo
|
/TestInterceptor/LogInterceptor.cs
| 2.859375
| 3
|
using System;
using System.Reflection;
using Castle.DynamicProxy;
namespace TestInterceptor
{
public class LogInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var method = invocation.GetConcreteMethod();
method = invocation.InvocationTarget.GetType().
GetMethod(method.Name);
if (method != null)
{
var attribute = method.GetCustomAttribute<MyLogAttribute>();
try
{
if (attribute != null)
{
Console.WriteLine("Starting the log");
invocation.Proceed();
Console.WriteLine("Ending the log");
}
else
invocation.Proceed();
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred: " + ex);
}
}
}
}
}
|
7960515df9ac9b52dc6456cc12dbbf0c13a0cf0f
|
C#
|
David-Hanna/ProjectGunpowder
|
/Unity/Assets/Scripts/Test/EventTest.cs
| 2.546875
| 3
|
using UnityEngine;
using System.Collections;
public class EventTest : MonoBehaviour {
double timeSinceStart = 0;
// Use this for initialization
void Start () {
GameEventDelegate<TimeEvent> oneOff = OneOffTime;
EventManager.Instance.AddSubscriber(oneOff);
GameEventDelegate<TimeEvent> persistent = PersistentTime;
EventManager.Instance.AddSubscriber(persistent, true);
}
void Update()
{
timeSinceStart += Time.deltaTime;
if (timeSinceStart > 5)
EventManager.Instance.Raise(new TimeEvent(timeSinceStart));
}
private void OneOffTime(TimeEvent e)
{
Debug.Log(string.Format("One Off time Event, {0}", e.time));
//GameEventDelegate<TimeEvent> ge = OneOffTime;
//EventManager.Instance.RemoveSubscriber(ge);
Application.LoadLevel("EventManagerTestSecond");
}
private void PersistentTime(TimeEvent e)
{
Debug.Log(string.Format("Presistant time Event"));
if (e.time >= 20)
{
GameEventDelegate<TimeEvent> ge = PersistentTime;
EventManager.Instance.RemoveSubscriber(ge);
}
}
}
public class TimeEvent : GameEvent
{
public double time;
public TimeEvent(double time)
{
this.time = time;
}
}
|
c47255f9870281e00090f8f395cdaefd114e445c
|
C#
|
mbsky/dotnetmarcheproject
|
/src/Common/Infrastructure/DotNetMarche.Infrastructure/Caching/NullCache.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DotNetMarche.Infrastructure.Caching
{
/// <summary>
/// null cache implementation. Null Object Pattern.
/// </summary>
public class NullCache : ICache
{
#region ICache Members
public object Get(object key)
{
return null;
}
public T Get<T>(object key)
{
return default(T);
}
public object this[object key]
{
get { return Get(key); }
}
public object Insert(object key, object areaKey, object value, DateTime? absoluteExpirationDate, TimeSpan? slidingExpirationDate)
{
return value;
}
public void Evict(object key)
{
}
public void EvictArea(object areaKey)
{
}
public void Clear()
{
}
#endregion
}
}
|
2b6d72c7413299d440c55b4dc627478441615ede
|
C#
|
NadyaNikol/PatternVisitor
|
/ConsoleApp1/ConsoleApp1/Program.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Room room1 = new Room(101);
Room room2 = new Room(102);
Room room3 = new Room(103);
Room room4 = new Room(104);
Room room5 = new Room(105);
Floor floor1 = new Floor(1);
floor1.AddRoom(room1);
floor1.AddRoom(room2);
floor1.AddRoom(room3);
floor1.AddRoom(room4);
floor1.AddRoom(room5);
Building building = new Building();
building.AddFloor(floor1);
IVisitor visitor = new Electrician();
visitor.VisitBuilding(building);
Console.ReadKey();
}
}
}
|
4cf5951f580461fd0ea92d40c9c0469f18fcbc13
|
C#
|
ParadoxGameConverters/ImperatorToCK3
|
/ImperatorToCK3.UnitTests/CommonUtils/Genes/GenesDBTests.cs
| 2.6875
| 3
|
using commonItems;
using ImperatorToCK3.CommonUtils.Genes;
using Xunit;
namespace ImperatorToCK3.UnitTests.CommonUtils.Genes;
public class GenesDBTests {
[Fact]
public void GenesDefaultToEmpty() {
var reader = new BufferedReader("={}");
var genesDB = new GenesDB(reader);
Assert.Empty(genesDB.AccessoryGenes);
Assert.Empty(genesDB.MorphGenes);
}
[Fact]
public void AccessoryGenesCanBeLoadedInsideGeneGroup() {
var reader = new BufferedReader(
"accessory_genes = {\n" +
"\thairstyles={ index = 1}\n" +
"\tclothes={ index =2}\n" +
"}"
);
var genesDB = new GenesDB(reader);
Assert.Equal(2, genesDB.AccessoryGenes.Count);
Assert.Equal((uint)1, genesDB.AccessoryGenes["hairstyles"].Index);
Assert.Equal((uint)2, genesDB.AccessoryGenes["clothes"].Index);
}
[Fact]
public void AccessoryGenesAreProperlyLoaded() {
var reader = new BufferedReader(
"accessory_genes = {\n" +
"\thairstyles = {\n" +
"\t\tindex = 1\n" +
"\t}\n" +
"\tclothes = {\n" +
"\t\tindex = 2\n" +
"\t}\n" +
"}"
);
var genesDB = new GenesDB(reader);
Assert.Equal(2, genesDB.AccessoryGenes.Count);
Assert.Equal((uint)1, genesDB.AccessoryGenes["hairstyles"].Index);
Assert.Equal((uint)2, genesDB.AccessoryGenes["clothes"].Index);
}
}
|
4c7bf35be4fad1c25aa9a2a9019745bb0b32e58f
|
C#
|
bigiayomide/DontWaste
|
/Dontwaste.Api.Data/Repositories/CategoryRepository.cs
| 2.609375
| 3
|
using DontWaste.Api.Data.Contracts.IDataRepositories;
using DontWaste.Api.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
namespace Dontwaste.Api.Data.Repositories
{
public class CategoryRepository : RepositoryService<Category>, ICategoryRepository
{
protected override Category AddEntity(DontWasteContext entityContext, Category entity)
{
return entityContext.Categories.Add(entity).Entity;
}
protected override IEnumerable<Category> GetEntities(DontWasteContext entityContext)
{
return from e in entityContext.Categories
select e;
}
protected override Category GetEntity(DontWasteContext entityContext, string id)
{
var query = (from e in entityContext.Categories
where e.Id == id
select e);
var results = query.FirstOrDefault();
return results;
}
protected override Category UpdateEntity(DontWasteContext entityContext, Category entity)
{
return GetEntity(entityContext, entity.Id);
}
public DbSet<Category> CategoryDbSet(DontWasteContext entityContext)
{
return entityContext.Categories;
}
}
}
|
e865267a19c228df438753549352a842cd2a59e0
|
C#
|
Ellpeck/Evolvinary
|
/Main/Worlds/Entities/Paths/SubWaypoint.cs
| 2.75
| 3
|
using System;
using Evolvinary.Helper;
using Microsoft.Xna.Framework;
namespace Evolvinary.Main.Worlds.Entities.Paths{
public class SubWaypoint{
public Vector2 Pos;
public SubWaypoint Parent;
public int CostFromStart; //The G cost
public int CostToEnd; //The H cost
public SubWaypoint(Vector2 pos, SubWaypoint parent, Vector2 endPos){
this.Pos = pos;
this.Parent = parent;
this.calculateCosts(endPos);
}
public void calculateCosts(Vector2 endPos){
this.CostFromStart = this.Parent == null ? 0 : this.Parent.CostFromStart+10;
var costToEndX = Math.Abs(endPos.X-this.Pos.X);
var costToEndY = Math.Abs(endPos.Y-this.Pos.Y);
this.CostToEnd = MathHelp.floor((costToEndX+costToEndY) * 10);
}
}
}
|
8dcee0713cba99042c4e1fc85b7ecca393e3852f
|
C#
|
Shouko-Nishimiya/xBrute
|
/Program.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace xBrute
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Console.Title = "xBrute v0.02";
Brute();
}
public static void Brute()
{
Console.Clear();
Colorful.Console.Write(" [-] ", Color.Aqua);
Colorful.Console.Write("How many threads: ", Color.White);
try
{
Request.threads = int.Parse(Console.ReadLine());
}
catch
{
Request.threads = 80;
}
Console.Clear();
for (; ; )
{
Colorful.Console.Write(" [-] ", Color.Aqua);
Colorful.Console.Write("What type of proxies - HTTP | SOCKS4 | SOCKS5 -: ", Color.White);
Request.proxyType = Console.ReadLine();
Request.proxyType = Request.proxyType.ToUpper();
if (Request.proxyType.Contains("HTTP") || Request.proxyType.Contains("SOCKS4") || Request.proxyType.Contains("SOCKS5"))
{
break;
}
Colorful.Console.Write(" > Please select a valid proxyType", Color.Red);
}
Thread.Sleep(2000);
Console.Clear();
Task.Factory.StartNew(delegate ()
{
Request.updateTitle();
});
string fileName;
OpenFileDialog openFileDialog = new OpenFileDialog();
do
{
Colorful.Console.Write(" [-] ", Color.Aqua);
Colorful.Console.Write("Load your combos..", Color.White);
Thread.Sleep(500);
openFileDialog.Title = "Select Combo List";
openFileDialog.DefaultExt = "txt";
openFileDialog.Filter = "Text files|*.txt";
openFileDialog.RestoreDirectory = true;
openFileDialog.ShowDialog();
fileName = openFileDialog.FileName;
}
while (!File.Exists(fileName));
Request.comboList = new List<string>(File.ReadAllLines(fileName));
Request.LoadCombos(fileName);
Colorful.Console.Write("\n > ", Color.Aqua);
Colorful.Console.Write("Succesfully Loaded " + Request.totalCounter + " Combo lines", Color.White);
Thread.Sleep(1000);
Console.Clear();
do
{
Colorful.Console.Write(" [-] ", Color.Aqua);
Colorful.Console.Write("Load your proxies..", Color.White);
Thread.Sleep(500);
openFileDialog.Title = "Select Proxy List";
openFileDialog.DefaultExt = "txt";
openFileDialog.Filter = "Text files|*.txt";
openFileDialog.RestoreDirectory = true;
openFileDialog.ShowDialog();
fileName = openFileDialog.FileName;
}
while (!File.Exists(fileName));
Request.proxyList = new List<string>(File.ReadAllLines(fileName));
Request.Loadproxies(fileName);
Colorful.Console.Clear();
Colorful.Console.Write(" > ", Color.Aqua);
Colorful.Console.Write("Succesfully Loaded " + Request.proxyTotalCounter + " Proxy lines", Color.White);
Thread.Sleep(1000);
Console.Clear();
for (int i = 0; i <= Request.threads; i++)
{
new Thread(new ThreadStart(Request.Check)).Start();
}
Colorful.Console.ReadLine();
Environment.Exit(0);
}
}
}
|
7f53b6d13e40528a7697afd63ec2eb9f64e7ad05
|
C#
|
maximgorbachiov/Mentoring-L2
|
/Multithreading/Tasks/ThreadTasks/Task3/Task3.cs
| 3.5625
| 4
|
using System;
using System.Threading.Tasks;
namespace ThreadTasks.Task3
{
public static class Task3
{
public static void RunMatrixMultiplication()
{
int[][] firstMatrix = CreateMatrix();
int[][] secondMatrix = CreateMatrix(firstMatrix[0].Length, firstMatrix.Length);
Console.WriteLine("First Matrix");
PrintMatrix(firstMatrix);
Console.WriteLine("Second Matrix");
PrintMatrix(secondMatrix);
Console.WriteLine("Result Matrix");
MultiplyMatrixes(firstMatrix, secondMatrix);
}
public static void MultiplyMatrixes(int[][] matrix1, int[][] matrix2)
{
int[][] result;
if (matrix1 == null)
{
throw new ArgumentNullException(nameof(matrix1));
} else if (matrix1.Length == 0)
{
throw new ArgumentException($"{nameof(matrix1)} is empty");
}
if (matrix2 == null)
{
throw new ArgumentNullException(nameof(matrix2));
} else if (matrix2.Length == 0)
{
throw new ArgumentException($"{nameof(matrix2)} is empty");
}
if (!CheckArrayOnMatrix(matrix1))
{
throw new ArgumentException($"{nameof(matrix1)} is not a matrix");
}
if (!CheckArrayOnMatrix(matrix2))
{
throw new ArgumentException($"{nameof(matrix2)} is not a matrix");
}
int height = matrix1.Length;
int width = matrix2[0].Length;
if (height != width)
{
throw new ArgumentException($"{nameof(matrix1)} and {nameof(matrix2)} matrixes can't be multiplay.");
}
result = new int[height][];
Parallel.ForEach(matrix1, (vector, state, index) =>
{
int[] resultVector = new int[width];
for (int k = 0; k < width; k++)
{
int temp = 0;
for (int j = 0; j < vector.Length; j++)
{
temp += vector[j] * matrix2[j][k];
}
resultVector[k] = temp;
}
result[index] = resultVector;
});
PrintMatrix(result);
}
private static int[][] CreateMatrix(int height = -1, int width = -1)
{
Random random = new Random();
if (height < 0)
{
height = random.Next(1, 10);
}
if (width < 0)
{
width = random.Next(1, 10);
}
int[][] matrix = new int[height][];
for (int i = 0; i < height; i++)
{
matrix[i] = new int[width];
for (int j = 0; j < width; j++)
{
matrix[i][j] = random.Next(0, 100);
}
}
return matrix;
}
private static bool CheckArrayOnMatrix(int[][] matrix)
{
bool result = true;
if (matrix.Length > 1)
{
for (int i = 1; i < matrix.Length; i++)
{
if (matrix[i - 1].Length != matrix[i].Length)
{
result = false;
break;
}
}
}
return result;
}
private static void PrintMatrix(int[][] matrix)
{
for (int i = 0; i < matrix.Length; i++)
{
for (int j = 0; j < matrix[i].Length; j++)
{
Console.Write($" {matrix[i][j]} ");
}
Console.WriteLine();
}
}
}
}
|
ee28db15c7734ef75c5ebfbd9abbe56014c6310b
|
C#
|
Lupiac/WebServices
|
/MathsLibrary/ClientSOAP/Program.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClientSOAP.VelibService;
namespace ClientSOAP
{
////////////////// Objects used /////////////////////
class Program
{
/* Private methods */
private static void help()
{
Console.WriteLine("\n" +
"Ce service permet d'obtenir la liste des villes de l'API de JCDecaux ainsi que leurs différentes stations et les détails de ces stations.\n" +
"Suivez les différentes étapes du programme pour obtenir les informations que vous souhaiter\n");
}
private static void processCity(VelibWSClient client)
{
Console.WriteLine("\nVeuillez choisir une ville");
string city = Console.ReadLine();
string stations = client.PickCity(city);
if (stations != "null")
{
displayStations(city, client);
getStation(stations, client, city);
}
else
{
Console.Write("\nLa ville demandée n'existe pas.\n");
Console.WriteLine("Voulez-vous trouver une autre ville? (O/N)");
string resp;
if ((resp = Console.ReadLine()) != null)
{
if (resp == "O" || resp == "o")
{
displayCities(client);
processCity(client);
}
else
{
Console.WriteLine("Au revoir...");
System.Environment.Exit(-1);
}
}
}
}
private static void displayCities(VelibWSClient client)
{
Console.WriteLine("Voulez-vous voir la liste des villes disponibles? (O/N)");
string resp;
if ((resp = Console.ReadLine()) != null)
{
if (resp == "O" || resp == "o")
{
Console.WriteLine(client.GetCities());
}
}
}
private static void displayStations(string city, VelibWSClient client)
{
Console.WriteLine("\nVoulez-vous voir la liste des stations disponibles? (O/N)");
string resp;
if ((resp = Console.ReadLine()) != null)
{
if (resp == "O" || resp == "o")
{
Console.WriteLine(client.DisplayStations(city));
}
}
}
private static void getStation(string stations, VelibWSClient client, string city)
{
string id;
Boolean tryAgain = true;
while (tryAgain)
{
Console.WriteLine("\nVeuillez entrer le nom d'une station à " + city);
if ((id = Console.ReadLine()) != null)
{
Console.WriteLine(client.GetStation(id, city));
Console.WriteLine("\nVoulez-vous trouver une autre station? (O/N)");
if ((id = Console.ReadLine()) != null)
{
if (id == "O" || id == "o") { tryAgain = true; }
else { tryAgain = false; }
}
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Pour voir le guide, tapez \"help\", sinon appuyer sur une touche");
string resp;
if ((resp = Console.ReadLine()) != null)
{
if (resp == "help")
{
help();
}
}
VelibWSClient client = new VelibWSClient();
Console.WriteLine("Voulez-vous voir la liste des villes disponibles? (O/N)");
if ((resp = Console.ReadLine()) != null)
{
if (resp == "O" || resp == "o")
{
Console.WriteLine(client.GetCities());
}
}
processCity(client);
}
}
}
|
35c561d9f6e56c719c06925f889f2ec6803cfa95
|
C#
|
Daniguillot/Hanoi
|
/Torres_de_Hanoi/Pila.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Torres_de_Hanoi
{
class Pila
{
public int Size {
get { return this.Elementos.Count; }
set { Size = value; }
}
public int Top {
get { return this.Elementos[this.Elementos.Count].Tam; }
set { Top = value; }
}
public List<Disco> Elementos {
get { return this.Elementos; }
set { Elementos = value; }
}
/* TODO: Implementar métodos */
public Pila()
{
this.Elementos = { };
}
public void push(Disco d)
{
this.Elementos.Add(d);
}
public Disco pop()
{
this.Elementos.RemoveAt(Size);
return null;
}
public bool isEmpty()
{
if(this.Elementos.Count == 0)
{
return true;
}
else
{
return false;
}
}
}
}
|
70bb6676e643f599fef450ac1e15eecd086fa060
|
C#
|
socketlabs/socketlabs-csharp
|
/Example Projects/dotNetCoreExample/Examples/Basic/Invalid/BasicSendWithInvalidAttachment.cs
| 2.578125
| 3
|
using System;
using SocketLabs.InjectionApi;
using SocketLabs.InjectionApi.Message;
namespace dotNetCoreExample.Examples.Basic.Invalid
{
public class BasicSendWithInvalidAttachment : IExample
{
public SendResponse RunExample()
{
var message = new BasicMessage();
message.Subject = "Sending A Test Message";
message.HtmlBody = "<html>This is the Html Body of my message.</html>";
message.PlainTextBody = "This is the Plain Text Body of my message.";
message.From.Email = "from@example.com";
message.ReplyTo.Email = "replyto@example.com";
message.To.Add("recipient1@example.com");
message.To.Add("recipient2@example.com");
message.Attachments.Add("bus", MimeType.PNG, new byte[]{});
using (var client = new SocketLabsClient(ExampleConfig.ServerId, ExampleConfig.ApiKey)
{
EndpointUrl = ExampleConfig.TargetApi
})
{
try
{
var response = client.Send(message);
return response;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
}
|
9a97b4cd3d166c315944bc6f86e97aebaa7e6b39
|
C#
|
rabbit33/PRGS_SendingEmails
|
/Holidays/Holidays/Program.cs
| 2.546875
| 3
|
using System;
namespace Holidays
{
class Program
{
static void Main()
{
var request = new HolidayRequest
{
Employee = new Employee
{
Name = "Alexandra",
Email = "alexandra.popescu@iquestgroup.com",
Manager = new Employee
{
Name = "John Doe",
Email = "alexandra.popescu@iquestgroup.com"
}
},
Interval = new Interval
{
StartDate = DateTime.Now,
EndDate = DateTime.Now.AddDays(4)
}
};
var serviceLocator = new ServiceLocator();
var emailNotifier = new EmailNotifier(serviceLocator);
var processor = new HolidayRequestProcessor(emailNotifier, new RegisterHolidayRequestMessage(request));
processor.HandleHolidayRequest();
processor = new HolidayRequestProcessor(emailNotifier, new ApproveHolidayRequestMessage(request));
processor.HandleHolidayRequest();
processor = new HolidayRequestProcessor(emailNotifier, new RejectHolidayRequestMessage(request));
processor.HandleHolidayRequest();
}
}
}
|
b117e5373631b55e1c18e580eb8aa504aa6f7964
|
C#
|
neurohunter/ImageImporter
|
/src/ImageImporter/FileProcessor/IFileProcessor.cs
| 2.90625
| 3
|
using System.IO;
namespace ImageImporter.FileProcessor
{
/// <summary>
/// Processes a specific file kind according to rules specific to it
/// </summary>
public interface IFileProcessor
{
/// <summary>
/// Process a single file
/// </summary>
/// <param name="inputFile">File descriptor to process</param>
/// <param name="fileKind">File kind to process</param>
/// <param name="outputDirectory">Directory to put file to</param>
/// <returns>Path to put file to</returns>
string Process(FileInfo inputFile, FileKind fileKind, string outputDirectory);
}
}
|
41b3f22fee5ce693bdb83baa5273d580f36d964e
|
C#
|
Georadix/Georadix.NET
|
/src/Georadix.Web/HttpRequestExtensions.cs
| 3.234375
| 3
|
namespace System.Web
{
using System.Linq;
using System.Net;
/// <summary>
/// Defines methods that extend the <see cref="HttpRequest"/> class.
/// </summary>
public static class HttpRequestExtensions
{
private const string ForwardedFor = "X-Forwarded-For";
/// <summary>
/// Gets the IP host address of the remote client, taking the X-Forwarded-For HTTP header into consideration
/// in load-balancing scenarios.
/// </summary>
/// <param name="request">The HTTP request.</param>
/// <returns>
/// A <see cref="string"/> containing the client IP address if it can be derived; otherwise,
/// <see langword="null"/>.
/// </returns>
public static string GetClientIpAddress(this HttpRequest request)
{
var address = request.UserHostAddress;
var forwardedFor = request.Headers.GetValues(ForwardedFor);
// If the X-Forwarded-For HTTP header is not present, return the user host address.
if ((forwardedFor == null) || !forwardedFor.Any())
{
return address;
}
// Get a list of public IP addresses in the X-Forwarded-For header.
var publicForwardingIps = forwardedFor.Where(ip =>
{
IPAddress parsedId;
return IPAddress.TryParse(ip, out parsedId) ? !parsedId.IsPrivate() : false;
});
// If we find any, return the first one. Otherwise, return the user host address.
return publicForwardingIps.Any() ? publicForwardingIps.First() : address;
}
}
}
|
f0c433ddfecffcff19785429ed95e3b5c721ce18
|
C#
|
AndrewGitHabSource/Calculator
|
/Calc/Calculator.cs
| 3.5625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calc
{
class Calculator
{
private List<float> listValues = new List<float>();
private List<string> listOperators = new List<string>();
public Calculator(List<float> values, List<string> operators)
{
this.listValues = values;
this.listOperators = operators;
}
public string calculate()
{
string resultString = "0";
int index = 0;
float result = listValues.ElementAt(index);
foreach (string operate in listOperators)
{
switch (operate)
{
case "+":
result += listValues.ElementAt(index + 1);
break;
case "-":
result -= listValues.ElementAt(index + 1);
break;
case "*":
result *= listValues.ElementAt(index + 1);
break;
case "/":
result /= listValues.ElementAt(index + 1);
break;
}
index++;
}
resultString = result.ToString();
return resultString;
}
}
}
|
7392a8a97386f871c42092ce515752c5de80e6a7
|
C#
|
dragosc02/comunityManagement
|
/ComunityMembers/ComunityMembersModels/MembershipModels/Details/Phone.cs
| 2.546875
| 3
|
using System;
using CommunityMembersModels.Contracts;
using CommunityModels.MembershipModels.Enums;
namespace CommunityModels.MembershipModels.Details
{
/// <summary>Stores phone information</summary>
public class Phone : IModel
{
/// <summary>Gets or sets the date when the record was created.</summary>
public DateTime CreationDate { get; set; }
/// <summary>Gets or sets description.</summary>
public string Description { get; set; }
/// <summary>Gets or sets the id of the record.</summary>
public int Id { get; set; }
/// <summary>Gets or sets if is the main phone.</summary>
public bool IsMain { get; set; }
/// <summary>The principal, parent entity. The <see cref="Member"/> who has this specific address.</summary>
public virtual Member Member { get; set; }
/// <summary>The foreign key to the <see cref="Member"/> entity.</summary>
public int MemberId { get; set; }
/// <summary>Gets or sets the phone number.</summary>
public string PhoneNumber { get; set; }
/// <summary>Gets or sets the phone type.</summary>
public PhoneType PhoneType { get; set; }
/// <summary>Gets or sets the id of the user that created the record.</summary>
public int UserCreated { get; set; }
}
}
|
d7a64b868a9e4f5e3ba3533b91888ac865eac1a7
|
C#
|
g-yonchev/TelerikAcademy
|
/Homeworks/C# OOP/05. OOP Principles Part 02/Exceptions/RangeException.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exceptions
{
class RangeException<T> : ApplicationException
{
private T startRange;
private T endRange;
public RangeException(string message, T start, T end)
: this(message, start, end, null)
{
this.StartRange = start;
this.EndRange = end;
}
public RangeException(string message, T start, T end, Exception exception)
: base(message, exception)
{
this.StartRange = start;
this.EndRange = end;
}
public T StartRange
{
get
{
return this.startRange;
}
set
{
this.startRange = value;
}
}
public T EndRange
{
get
{
return this.endRange;
}
set
{
this.endRange = value;
}
}
}
}
|
e4f716551bc8ed23e827328a9a9a8925592bc71e
|
C#
|
AndyBrizhak/GB_Arch-Patterns_HW01_Brizhak
|
/GB_Arch+Patterns_HW01_02/Program.cs
| 3.546875
| 4
|
using System;
using System.Collections.Generic;
//ДЗ по курсу Архитектуры и шаблоны проектирования на C# Брижак Андрей
//2. Реализовать программу из раздела «Повторяющиеся фрагменты кода» с помощью делегата Func.
namespace GB_Arch_Patterns_HW01_02
{
class Program
{
public static readonly string _Address = Constants.address;
public static readonly string _Format = Constants.format;
/// <summary>
/// Функция возвращает отформатированную строку
/// </summary>
/// <returns></returns>
private static string DummyFunc()
{
return string.Format(_Format, "Петя", "школьный друг", _Address, 30);
}
private static string DummyFuncAgain()
{
return string.Format(_Format, "Вася", "сосед", _Address, 54);
}
private static string DummyFuncMore()
{
return string.Format(_Format, "Николай", "сын", _Address, 4);
}
/// <summary>
/// Функция выводит метод
/// </summary>
/// <param name="func">делегат</param>
private static void MakeF(Func<string> func)
{
string NameMeth = func.Method.Name;
Console.WriteLine("Start", NameMeth);
Console.WriteLine(func());
Console.WriteLine("Finish", NameMeth);
}
/// <summary>
/// Возвращает список обобщенных делегатов
/// </summary>
/// <returns></returns>
private static IEnumerable<Func<string>> GetFuncSteps()
{
return new List<Func<string>>()
{
DummyFunc, DummyFuncAgain, DummyFuncMore
};
}
static void Main(string[] args)
{
IEnumerable<Func<string>> actions = GetFuncSteps();
foreach (var action in actions)
{
MakeF(action);
}
Console.ReadLine();
}
}
}
|
9ac3f7aae38d18cd3872de088df63aa6b69dfecf
|
C#
|
msruzy/WickedEngine-1
|
/CameraDemo/CameraDemo/FrameRateComponent.cs
| 3.015625
| 3
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CameraDemo
{
/// <summary>
/// A real basic frame rate counter.
/// </summary>
public class FrameRateComponent : DrawableGameComponent
{
private int drawCount;
private float drawTimer;
private string drawString = "FPS: ";
private SpriteBatch spriteBatch;
private SpriteFont font;
public FrameRateComponent(Game game)
: base(game)
{
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Game.Content.Load<SpriteFont>("Font");
}
public override void Draw(GameTime gameTime)
{
drawCount++;
drawTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (drawTimer >= 1f)
{
drawTimer -= 1f;
drawString = "FPS: " + drawCount;
drawCount = 0;
}
spriteBatch.Begin();
spriteBatch.DrawString(font, drawString, new Vector2(10f, 10f), Color.White);
spriteBatch.End();
}
}
}
|
e0864db124cb2f270ddcb628a34f84c17db251c0
|
C#
|
MuraiMisaki/HALProject
|
/Project_C/Assets/Scripts/SceneManager/SceneManagerCS.cs
| 2.546875
| 3
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement; // シーンマネージャを使えるようにする。
public class SceneManagerCS : MonoBehaviour {
public string[] nextScene = new string[1];
public string prevScene;
public int selectScene;
protected GameObject bgmManager;
// フェード用
protected float fadeTime = 1.0f;
public Fade fade = null;
// Use this for initialization
void Start () {
fade = GameObject.Find("FadeImage").GetComponent<Fade>();
bgmManager = GameObject.Find("BgmManager");
selectScene = 0;
fade.FadeOut(fadeTime);
}
// Update is called once per frame
void Update () {
// 決定キーが押されたら
if (Input.GetButtonDown("Submit"))
{
// 次のシーンへ移動
MoveNextScene(selectScene);
}
// キャンセルキーが押されたら
if (Input.GetButtonDown("Cancel"))
{
// 前のシーンへ移動
MovePrevScene();
}
if (Input.GetKeyDown(KeyCode.Delete)) {
// 前のシーンへ移動
MovePrevScene();
}
}
virtual public void MoveNextScene(int i = 0)
{
if (i < 0 || i >= nextScene.Length)
{
Debug.Log("ERROR SCENE TRANSITION!");
return;
}
// 文字列が入っていなければ
if (nextScene[i].Length == 0)
return;
fade.FadeIn(fadeTime, () =>
{
SceneManager.LoadScene(nextScene[i]);
});
}
public void MovePrevScene()
{
// 文字列が入っていなければ
if (prevScene.Length == 0)
return;
fade.FadeIn(fadeTime, () =>
{
SceneManager.LoadScene(prevScene);
});
}
}
|
4d7fcd0818a01bd31730d2829d0c37299908a6aa
|
C#
|
tugiss11/AjouraDemo
|
/Desktop/Ajourakonedemo/Model/GraphVertexClass.cs
| 2.65625
| 3
|
using System;
using Esri.ArcGISRuntime.Geometry;
namespace ArcGISRuntime.Samples.DesktopViewer.Model
{
public class GraphVertexClass
{
public int ID { get; set; }
public double? X { get; set; }
public double? Y { get; set; }
/// <summary>
/// Puumäärä dm3
/// </summary>
public int Puumaara { get; set; }
public GraphVertexClass(int id)
{
ID = id;
}
public GraphVertexClass(int id, double x, double y)
{
ID = id;
X = x;
Y = y;
Puumaara = 1;
}
public override string ToString()
{
return string.Format("{0}: X:{1} Y:{2}", ID, X, Y);
}
public MapPoint AsMapPoint()
{
if (X != null && Y != null)
{
return new MapPoint((double)X, (double)Y, new SpatialReference(3067));
}
return null;
}
public bool EqualsMapPointCoordinates(MapPoint mapPoint)
{
return Convert.ToInt32(X) == Convert.ToInt32(mapPoint.X) && Convert.ToInt32(Y) == Convert.ToInt32(mapPoint.Y);
}
public long[] Distances;
public int[] Neighbours;
}
}
|
81920ac95d827f5f3ec7f841614e7d5d871795c5
|
C#
|
hirabayashi-k/sample_cs
|
/VisualStudio2015_Sample/TaskTest/TaskTest/Form1.cs
| 2.875
| 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 TaskTest
{
public partial class Form1 : Form
{
Task task;
bool testflg = false;
public Form1()
{
InitializeComponent();
task = TempHumTask();
}
private void button1_Click(object sender, EventArgs e)
{
task = TempHumTask();
task.Start();
}
private void button2_Click(object sender, EventArgs e)
{
testflg = false;
if(task.Status == TaskStatus.Running)
{
task.Wait();
}
textBox1.AppendText("End\r\n");
}
private Task TempHumTask()
{
Task task = new Task(() =>
{
TempHumMonitorWakeUp();
});
return task;
}
public void TempHumMonitorWakeUp()
{
testflg = true;
while (testflg)
{
this.Invoke(new Action(() =>
{
// サイクル表示
textBox1.AppendText("TEST\r\n");
}));
System.Threading.Thread.Sleep(1000); // 停止待ち
}
}
}
}
|
ccfb084e0728da4b4987a31102d07ce4d04cb82b
|
C#
|
Shyryp/ProductionManage
|
/ProductionManagement/Program.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProductionManagement
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
User worker = new User();
Company company = new Company();
Role role = new Role();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new StartWindow(worker, company, role));
if (worker.LoginUser != "None" && worker.LoginUser != " "
&& worker.LoginUser != "")
{
if (company.NameCompany == "None")
{
Application.Run(new StartNewCompany(company));
}
if (!(company.NameCompany == "None"))
{
Application.Run(new ProcessWindow(worker, company, role));
}
}
}
}
}
|
3c003e8ff839a66f33d155a0d64eaa5fc3f5c6d4
|
C#
|
lawilson5589/geolabvirtualmaps
|
/VirtualEarth/VELibrary/VEMapEnumerations.cs
| 2.84375
| 3
|
// Author: J.Baltikauskas
// This source is subject to the Microsoft Reference License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/communitylicense.mspx
using System;
using System.Collections.Generic;
using System.Text;
namespace VELibrary
{
/// <summary>
/// An enumeration of map styles.
/// </summary>
[Flags]
public enum VEMapStyle
{
/// <summary>
/// Sets the map style to a traditional road map
/// </summary>
Road = 'r',
/// <summary>
/// Sets the map style to aerial (satellite and aerial imagery)
/// </summary>
Aerial = 'a',
/// <summary>
/// Sets the map style to a combination of aerial images with labels overlaid (also known as hybrid)
/// </summary>
Hybrid = 'h',
/// <summary>
/// Sets the map style to use bird's eye imagery
/// </summary>
Birdseye = 'o'
}
/// <summary>
/// An enumeration of map modes.
/// </summary>
[Flags]
public enum VEMapMode
{
/// <summary>
/// Displays the map in the traditional two dimensions
/// </summary>
Mode2D = 1,
/// <summary>
/// Loads the Virtual Earth 3D control, displays the map in three dimensions, and displays the 3D navigation control
/// </summary>
Mode3D = 2
}
/// <summary>
/// An enumeration of the distance unit used for generating routes and itineraries.
/// </summary>
[Flags]
public enum VEDistanceUnit
{
Miles = 'm',
Kilometers = 'k'
}
/// <summary>
/// This enumeration represents the size of the mini map.
/// </summary>
[Flags]
public enum VEMiniMapSize
{
/// <summary>
/// This represents a small mini map.
/// <remarks>Virtual Earth Map equivalent is VEMiniMapSize.Small</remarks>
/// </summary>
Small,
/// <summary>
/// This represents a large mini map.
/// <remarks>Virtual Earth Map equivalent is VEMiniMapSize.Large</remarks>
/// </summary>
Large
}
/// <summary>
/// An enumeration that represents the size and type of dashboard to be displayed on the map
/// </summary>
[Flags]
public enum VEDashboardSize
{
/// <summary>
/// This is the dashboard that is used by default
/// <remarks>Virtual Earth Map equivalent is VEDashboardSize.Normal</remarks>
/// </summary>
Normal,
/// <summary>
/// This is a dashboard smaller than the default: it only contains + and - zoom buttons and road, aerial, and hybrid buttons for changing the map style
/// <remarks>Virtual Earth Map equivalent is VEDashboardSize.Small</remarks>
/// </summary>
Small,
/// <summary>
/// This is the smallest dashboard option available. This dashboard only contains zoom-out (+) and zoom-in (-) zoom buttons
/// <remarks>Virtual Earth Map equivalent is VEDashboardSize.Tiny</remarks>
/// </summary>
Tiny,
}
}
|
72d428b60a089b965a89a3fb4ab22c29ec13fd37
|
C#
|
AndrewSherstyuk/C-CourseAdvanced
|
/_Examples/007_Input_Output/022_StringWriter/Program.cs
| 3.59375
| 4
|
using System;
using System.IO;
/// <summary>
/// StringWriter - обертка над StringBuilder
/// </summary>
namespace _022_StringWriter
{
class Program
{
static void Main()
{
// StringWriter - обертка над StringBuilder
// StringWriter - Реализует объект System.IO.TextWriter для записи сведений в строку. Сведения
// хранятся в базовом System.Text.StringBuilder.
StringWriter writer = new StringWriter();
writer.WriteLine("Hello all ");
writer.Write("This is a multi-line ");
writer.WriteLine("text string.");
Console.WriteLine(writer.ToString());
// Задержка.
Console.ReadKey();
}
}
}
|
3f1d7d6a1b3b87c946a8950d188efede50db9473
|
C#
|
ElementCraft/GreedySnack-CSharp
|
/GreedySnack/Utils/Clock.cs
| 3.375
| 3
|
using System;
namespace GreedySnack.Utils
{
/// <summary>
/// 时钟计时类
/// </summary>
public class Clock
{
private static DateTime nowTick;
private static DateTime preTick;
private static TimeSpan passTick;
private static double totalTick;
/// <summary>
/// 初始化时钟
/// </summary>
public static void Init()
{
preTick = DateTime.Now;
totalTick = 0;
}
/// <summary>
/// 计时打点
/// </summary>
/// <returns>距上一次打点过去的时间 毫秒</returns>
public static float Tick()
{
nowTick = DateTime.Now;
passTick = nowTick.Subtract(preTick);
preTick = nowTick;
double passMS = passTick.TotalMilliseconds;
totalTick += passMS;
return (float)passMS;
}
/// <summary>
/// 从初始化开始总共经过的时间,毫秒
/// </summary>
/// <returns></returns>
public static double GetTotalTick()
{
return totalTick;
}
}
}
|
1c06ffa2848d55ff19f25f101a7c24ede37fa9a4
|
C#
|
kingwaytek/SqlSugar
|
/NewTest/Demos/Filter.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewTest.Dao;
using Models;
using System.Data.SqlClient;
using SqlSugar;
namespace NewTest.Demos
{
//过滤器用法
//使用场合(例如:假删除查询,这个时候就可以设置一个过滤器,不需要每次都 .Where(it=>it.IsDelete==true))
public class Filter : IDemos
{
public void Init()
{
Console.WriteLine("启动Filter.Init");
using (SqlSugarClient db = SugarDaoFilter.GetInstance())//开启数据库连接
{
//设置走哪个过滤器
db.CurrentFilterKey = "role,role2"; //支持多个过滤器以逗号隔开
//queryable
var list = db.Queryable<Student>().ToList(); //通过全局过滤器对需要权限验证的数据进行过滤
//相当于db.Queryable<Student>().Where("id=@id",new{id=1})
//sqlable
var list2 = db.Sqlable().From<Student>("s").SelectToList<Student>("*");
//同上
//sqlQuery
var list3 = db.SqlQuery<Student>("select * from Student WHERE 1=1");
//同上
}
}
/// <summary>
/// 扩展SqlSugarClient
/// </summary>
public class SugarDaoFilter
{
//禁止实例化
private SugarDaoFilter()
{
}
/// <summary>
/// 页面所需要的过滤函数
/// </summary>
private static Dictionary<string, Func<KeyValueObj>> _filterParas = new Dictionary<string, Func<KeyValueObj>>()
{
{ "role",()=>{
return new KeyValueObj(){ Key=" id=@id" , Value=new{ id=1}};
}
},
{ "role2",()=>{
return new KeyValueObj(){ Key=" id>0"};
}
},
};
public static SqlSugarClient GetInstance()
{
string connection = SugarDao.ConnectionString; //这里可以动态根据cookies或session实现多库切换
var db = new SqlSugarClient(connection);
db.SetFilterItems(_filterParas);
db.IsEnableLogEvent = true;//启用日志事件
db.LogEventStarting = (sql, par) => { Console.WriteLine(sql + " " + par + "\r\n"); };
return db;
}
}
}
}
|
54662795a840ea702bace9a4908f4f28cc251596
|
C#
|
eksotama/Simple.Data.Firebird
|
/Simple.Data.Firebird/TypeMap.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using FirebirdSql.Data.FirebirdClient;
namespace Simple.Data.Firebird
{
public class TypeMap
{
public static TypeEntry GetTypeEntry(string dataTypeName)
{
if (!FbTypeToTypeEntry.ContainsKey(dataTypeName))
throw new ArgumentException(String.Format("Unknown data type name: {0}", dataTypeName));
return FbTypeToTypeEntry[dataTypeName];
}
/// <exception cref="ArgumentException">Throws when typeId and subTypeId do not match any expected type.</exception>
public static TypeEntry GetTypeEntry(string typeId, string subTypeId)
{
if (typeId == "7" && subTypeId == "0") return GetTypeEntry("smallint");
if (typeId == "7" && subTypeId == "1") return GetTypeEntry("numeric s");
if (typeId == "7" && subTypeId == "2") return GetTypeEntry("decimal s");
if (typeId == "8" && subTypeId == "0") return GetTypeEntry("integer");
if (typeId == "8" && subTypeId == "1") return GetTypeEntry("numeric s");
if (typeId == "8" && subTypeId == "2") return GetTypeEntry("decimal s");
if (typeId == "10") return GetTypeEntry("float");
if (typeId == "12") return GetTypeEntry("date");
if (typeId == "13") return GetTypeEntry("time");
if (typeId == "14") return GetTypeEntry("char");
if (typeId == "16" && subTypeId == "1") return GetTypeEntry("numeric");
if (typeId == "16" && subTypeId == "2") return GetTypeEntry("decimal");
if (typeId == "16") return GetTypeEntry("bigint"); //on some system tables bigint fields don't have subTypeId
if (typeId == "27") return GetTypeEntry("double precision");
if (typeId == "35") return GetTypeEntry("timestamp");
if (typeId == "37") return GetTypeEntry("varchar");
if (typeId == "261" && subTypeId == "0") return GetTypeEntry("blob sub_type binary");
if (typeId == "261" && subTypeId == "1") return GetTypeEntry("blob sub_type text");
if (typeId == "261" && subTypeId == "2") return GetTypeEntry("blob sub_type blr");
if (typeId == "261") return GetTypeEntry("blob sub_type binary"); // we'll just cast other blob subtypes used in system tables to binary
throw new ArgumentException(String.Format("Unknown data type name for typeId:{0}, subTypeId:{1}", typeId, subTypeId));
}
private static readonly Dictionary<string, TypeEntry> FbTypeToTypeEntry =
new Dictionary<string, TypeEntry>
{
{"smallint", new TypeEntry("smallint", DbType.Int16, FbDbType.SmallInt, typeof (Int16), true, true)},
{"integer", new TypeEntry("integer", DbType.Int32, FbDbType.Integer, typeof (Int32), false, false)},
{"char", new TypeEntry("char", DbType.StringFixedLength, FbDbType.Char, typeof (String), true, false)},
{"varchar", new TypeEntry("varchar", DbType.String, FbDbType.VarChar, typeof (String), true, false)},
{"float", new TypeEntry("float", DbType.Single, FbDbType.Float, typeof (Single), false, false)},
{"numeric s", new TypeEntry("numeric", DbType.Double, FbDbType.Numeric, typeof (Decimal), true, true)},
{"decimal s", new TypeEntry("decimal", DbType.Double, FbDbType.Decimal, typeof (Decimal), true, true)},
{"double precision", new TypeEntry("double precision", DbType.Double, FbDbType.Double, typeof (Double), false, false)},
{"numeric", new TypeEntry("numeric", DbType.Decimal, FbDbType.Numeric, typeof (Decimal), true, true)},
{"decimal", new TypeEntry("decimal", DbType.Decimal, FbDbType.Decimal, typeof (Decimal), true, true)},
{"timestamp", new TypeEntry("timestamp", DbType.DateTime, FbDbType.TimeStamp, typeof (DateTime), false, false)},
{"date", new TypeEntry("date", DbType.Date, FbDbType.Date, typeof (DateTime), false, false)},
{"time", new TypeEntry("time", DbType.Time, FbDbType.Time, typeof (TimeSpan), false, false)},
{"bigint", new TypeEntry("bigint", DbType.Int64, FbDbType.BigInt, typeof (Int64), false, false)},
{"blob sub_type binary", new TypeEntry("blob sub_type binary", DbType.Binary, FbDbType.Binary, typeof (byte[]), false, false)},
{"blob sub_type text", new TypeEntry("blob sub_type text",DbType.Binary, FbDbType.Binary, typeof (String), false, false)},
{"blob sub_type blr", new TypeEntry("blob sub_type blr", DbType.Binary, FbDbType.Binary, typeof (byte[]), false, false)},
};
}
public class TypeEntry
{
public string FbTypeName { get; private set; }
public DbType DbType { get; private set; }
public FbDbType FbDbType { get; private set; }
public Type ClrType { get; private set; }
public bool WithLength { get; set; }
public bool WithPrecision { get; set; }
public TypeEntry(string fbTypeName, DbType dbType, FbDbType fbDbType, Type clrType, bool withLength, bool withPrecision)
{
FbTypeName = fbTypeName;
DbType = dbType;
FbDbType = fbDbType;
ClrType = clrType;
WithLength = withLength;
WithPrecision = withPrecision;
}
}
}
|
75685816a6f5dc7c83d5783e5b4057f4551c49cb
|
C#
|
NanoFabricFX/dotNext
|
/src/DotNext.Metaprogramming/Runtime/CompilerServices/AsyncStateMachine.cs
| 2.578125
| 3
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace DotNext.Runtime.CompilerServices
{
/// <summary>
/// Provides manual control over asynchronous state machine.
/// </summary>
/// <remarks>
/// This type allows to implement custom async/await flow
/// and intended for expert-level developers.
/// </remarks>
/// <typeparam name="TState">The local state of async function used to store computation state.</typeparam>
[StructLayout(LayoutKind.Auto)]
internal struct AsyncStateMachine<TState> : IAsyncStateMachine<TState>
where TState : struct
{
private readonly Transition<TState, AsyncStateMachine<TState>> transition;
/// <summary>
/// Runtime state associated with this state machine.
/// </summary>
public TState State;
private AsyncValueTaskMethodBuilder builder;
private ExceptionDispatchInfo? exception;
private bool suspended;
private uint guardedRegionsCounter; // number of entries into try-clause
private AsyncStateMachine(Transition<TState, AsyncStateMachine<TState>> transition, TState state)
{
builder = AsyncValueTaskMethodBuilder.Create();
this.transition = transition;
State = state;
StateId = IAsyncStateMachine<TState>.FinalState;
exception = null;
suspended = false;
guardedRegionsCounter = 0;
suspended = false;
}
readonly TState IAsyncStateMachine<TState>.State => State;
/// <summary>
/// Gets state identifier.
/// </summary>
public uint StateId
{
readonly get;
private set;
}
/// <summary>
/// Enters guarded code block which represents <c>try</c> block of code
/// inside of async lambda function.
/// </summary>
/// <param name="newState">The identifier of the async state machine representing guarded code.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnterGuardedCode(uint newState)
{
StateId = newState;
guardedRegionsCounter += 1;
}
/// <summary>
/// Leaves guarded code block.
/// </summary>
/// <param name="previousState">The identifier of the async state machine before invocation of <see cref="EnterGuardedCode(uint)"/>.</param>
/// <param name="suspendException"><see langword="true"/> to suspend exception then entering finally block; otherwise, <see langword="false"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ExitGuardedCode(uint previousState, bool suspendException)
{
StateId = previousState;
guardedRegionsCounter -= 1;
suspended = exception is not null && suspendException;
}
/// <summary>
/// Attempts to recover from the exception and indicating prologue of <c>try</c> statement
/// inside of async lambda function.
/// </summary>
/// <typeparam name="TException">Type of expression to be caught.</typeparam>
/// <param name="restoredException">Reference to the captured exception.</param>
/// <returns><see langword="true"/>, if caught exception is of type <typeparamref name="TException"/>; otherwise, <see langword="false"/>.</returns>
public bool TryRecover<TException>([NotNullWhen(true)] out TException? restoredException)
where TException : Exception
{
if (exception?.SourceException is TException typed)
{
exception = null;
restoredException = typed;
return true;
}
restoredException = null;
return false;
}
/// <summary>
/// Indicates that this async state machine is not in exceptional state.
/// </summary>
public readonly bool HasNoException
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => exception is null || suspended;
}
/// <summary>
/// Re-throws captured exception.
/// </summary>
public void Rethrow()
{
suspended = false;
exception?.Throw();
}
void IAsyncStateMachine.MoveNext()
{
begin:
try
{
transition(ref this);
}
catch (Exception e)
{
suspended = false;
exception = ExceptionDispatchInfo.Capture(e);
// try to recover from exception and re-enter into state machine
if (guardedRegionsCounter > 0)
goto begin;
// no exception handlers - just finalize state machine
StateId = IAsyncStateMachine<TState>.FinalState;
}
// finalize state machine
if (StateId == IAsyncStateMachine<TState>.FinalState)
{
if (exception is null)
builder.SetResult();
else
builder.SetException(exception.SourceException);
// perform cleanup after resuming of all suspended tasks
guardedRegionsCounter = 0;
exception = null;
State = default;
}
}
/// <summary>
/// Performs transition.
/// </summary>
/// <typeparam name="TAwaiter">Type of asynchronous control flow object.</typeparam>
/// <param name="awaiter">Asynchronous result obtained from another method to await.</param>
/// <param name="stateId">A new state identifier.</param>
/// <returns><see langword="true"/> if awaiter is completed synchronously; otherwise, <see langword="false"/>.</returns>
public bool MoveNext<TAwaiter>(ref TAwaiter awaiter, uint stateId)
where TAwaiter : INotifyCompletion
{
StateId = stateId;
// avoid boxing of this state machine through continuation action if awaiter is completed already
if (Awaiter<TAwaiter>.IsCompleted(ref awaiter))
return true;
builder.AwaitOnCompleted(ref awaiter, ref this);
return false;
}
/// <summary>
/// Turns this state machine into final state.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Complete() => StateId = IAsyncStateMachine<TState>.FinalState;
private ValueTask Start()
{
builder.Start(ref this);
return builder.Task;
}
/// <summary>
/// Executes async state machine.
/// </summary>
/// <param name="transition">Async function which execution is controlled by state machine.</param>
/// <param name="initialState">Initial state.</param>
/// <returns>The task representing execution of async function.</returns>
public static ValueTask Start(Transition<TState, AsyncStateMachine<TState>> transition, TState initialState = default)
=> new AsyncStateMachine<TState>(transition, initialState).Start();
readonly void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) => builder.SetStateMachine(stateMachine);
}
/// <summary>
/// Provides manual control over asynchronous state machine.
/// </summary>
/// <remarks>
/// This type allows to implement custom async/await flow
/// and intended for expert-level developers.
/// </remarks>
/// <typeparam name="TState">The local state of async function used to store computation state.</typeparam>
/// <typeparam name="TResult">Result type of asynchronous function.</typeparam>
[StructLayout(LayoutKind.Auto)]
internal struct AsyncStateMachine<TState, TResult> : IAsyncStateMachine<TState>
where TState : struct
{
private readonly Transition<TState, AsyncStateMachine<TState, TResult>> transition;
/// <summary>
/// Represents internal state.
/// </summary>
public TState State;
private AsyncValueTaskMethodBuilder<TResult?> builder;
private ExceptionDispatchInfo? exception;
private bool suspended;
private uint guardedRegionsCounter; // number of entries into try-clause
private TResult? result;
private AsyncStateMachine(Transition<TState, AsyncStateMachine<TState, TResult>> transition, TState state)
{
builder = AsyncValueTaskMethodBuilder<TResult?>.Create();
StateId = IAsyncStateMachine<TState>.FinalState;
State = state;
this.transition = transition;
suspended = false;
guardedRegionsCounter = 0;
exception = null;
result = default;
}
readonly TState IAsyncStateMachine<TState>.State => State;
/// <summary>
/// Gets state identifier.
/// </summary>
public uint StateId
{
readonly get;
private set;
}
/// <summary>
/// Enters guarded code block which represents <c>try</c> block of code
/// inside of async lambda function.
/// </summary>
/// <param name="newState">The identifier of the async machine state representing guarded code.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnterGuardedCode(uint newState)
{
StateId = newState;
guardedRegionsCounter += 1;
}
/// <summary>
/// Leaves guarded code block.
/// </summary>
/// <param name="previousState">The identifier of the async state machine before invocation of <see cref="EnterGuardedCode(uint)"/>.</param>
/// <param name="suspendException"><see langword="true"/> to suspend exception then entering finally block; otherwise, <see langword="false"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ExitGuardedCode(uint previousState, bool suspendException)
{
StateId = previousState;
guardedRegionsCounter -= 1;
suspended = exception is not null && suspendException;
}
/// <summary>
/// Attempts to recover from the exception and indicating prologue of <c>try</c> statement
/// inside of async lambda function.
/// </summary>
/// <typeparam name="TException">Type of expression to be caught.</typeparam>
/// <param name="restoredException">Reference to the captured exception.</param>
/// <returns><see langword="true"/>, if caught exception is of type <typeparamref name="TException"/>; otherwise, <see langword="false"/>.</returns>
public bool TryRecover<TException>([NotNullWhen(true)] out TException? restoredException)
where TException : Exception
{
if (exception?.SourceException is TException typed)
{
exception = null;
restoredException = typed;
return true;
}
restoredException = null;
return false;
}
/// <summary>
/// Indicates that this async state machine is not in exceptional state.
/// </summary>
public readonly bool HasNoException
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => exception is null || suspended;
}
/// <summary>
/// Re-throws captured exception.
/// </summary>
public void Rethrow()
{
suspended = false;
exception?.Throw();
}
private ValueTask<TResult?> Start()
{
builder.Start(ref this);
return builder.Task;
}
/// <summary>
/// Executes async state machine.
/// </summary>
/// <param name="transition">Async function which execution is controlled by state machine.</param>
/// <param name="initialState">Initial state.</param>
/// <returns>The task representing execution of async function.</returns>
public static ValueTask<TResult?> Start(Transition<TState, AsyncStateMachine<TState, TResult>> transition, TState initialState = default)
=> new AsyncStateMachine<TState, TResult>(transition, initialState).Start();
/// <summary>
/// Sets result of async state machine and marks current state as final state.
/// </summary>
public TResult Result
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
StateId = IAsyncStateMachine<TState>.FinalState;
exception = null;
result = value;
}
}
/// <summary>
/// Performs transition.
/// </summary>
/// <typeparam name="TAwaiter">Type of asynchronous control flow object.</typeparam>
/// <param name="awaiter">Asynchronous result obtained from another method to await.</param>
/// <param name="stateId">A new state identifier.</param>
/// <returns><see langword="true"/> if awaiter is completed synchronously; otherwise, <see langword="false"/>.</returns>
public bool MoveNext<TAwaiter>(ref TAwaiter awaiter, uint stateId)
where TAwaiter : INotifyCompletion
{
StateId = stateId;
// avoid boxing of this state machine through continuation action if awaiter is completed already
if (Awaiter<TAwaiter>.IsCompleted(ref awaiter))
return true;
builder.AwaitOnCompleted(ref awaiter, ref this);
return false;
}
void IAsyncStateMachine.MoveNext()
{
begin:
try
{
transition(ref this);
}
catch (Exception e)
{
suspended = false;
exception = ExceptionDispatchInfo.Capture(e);
// try to recover from exception and re-enter into state machine
if (guardedRegionsCounter > 0)
goto begin;
// no exception handlers - just finalize state machine
StateId = IAsyncStateMachine<TState>.FinalState;
}
// finalize state machine
if (StateId == IAsyncStateMachine<TState>.FinalState)
{
if (exception is null)
builder.SetResult(result);
else
builder.SetException(exception.SourceException);
// perform cleanup after resuming of all suspended tasks
guardedRegionsCounter = 0;
exception = null;
result = default;
State = default;
}
}
readonly void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) => builder.SetStateMachine(stateMachine);
}
}
|
4fa404e8059562bb56e41cd617d1a2ec5716d6c7
|
C#
|
gopa810/Text2Tree
|
/OtherProjects/COBOLparser/CobolToCsharp/MainText.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace CobolToCsharp
{
public class MainText
{
public class LineRef
{
public int Index;
public string Text;
public override string ToString()
{
return Text;
}
}
public List<string> lines = new List<string>();
public List<LineRef> takecareIndexes = new List<LineRef>();
public void OpenFile(string file)
{
string [] lin = File.ReadAllLines(file);
lines.Clear();
takecareIndexes.Clear();
StringBuilder buf = new StringBuilder();
foreach (string s in lin)
{
string h = s.Trim();
if (StartsWithJoin(ref h))
{
buf.Append(" ");
buf.Append(h);
}
else
{
if (buf.Length > 0)
{
lines.Add(buf.ToString());
}
buf.Clear();
buf.Append(s);
if (StartWithSpecial(ref h))
{
LineRef lr = new LineRef();
lr.Index = lines.Count;
lr.Text = buf.ToString();
takecareIndexes.Add(lr);
}
}
}
if (buf.Length > 0)
{
lines.Add(buf.ToString());
}
}
public string[] joinStarters = new string[] {
"TO ", "AND ", "OR ", "USING ",
"FROM ", "GIVING "
};
public bool StartsWithJoin(ref string h)
{
foreach (string s in joinStarters)
{
if (h.StartsWith(s))
return true;
}
return false;
}
public string[] specialStarters = new string[] {
"ENTER ", "STRING ", "PERFORM "
};
public bool StartWithSpecial(ref string h)
{
foreach (string s in specialStarters)
{
if (h.StartsWith(s))
return true;
}
return false;
}
public List<string> Converted = new List<string>();
private List<string> currParts = new List<string>();
public void Convert()
{
int indent = 0;
string nl = string.Empty;
Converted.Clear();
foreach (string s in lines)
{
indent = CalcIndent(s);
nl = ConvertLine(indent, s);
if (nl.IndexOf('\n') >= 0)
{
string[] line2 = nl.Split('\n');
foreach (string h in line2)
{
Converted.Add(h);
}
}
else
{
Converted.Add(nl);
}
}
if (openMethod)
Converted.Add("}");
if (openClass)
Converted.Add("}");
if (openNamespace)
Converted.Add("}");
}
private int CalcIndent(string s)
{
int c = 0;
foreach (char ch in s)
{
if (Char.IsWhiteSpace(ch))
c++;
else
return c;
}
return c;
}
public string ConvertLine(int indent, string line)
{
if (line.Length < 1)
return string.Empty;
if (line[0] == ' ')
{
SplitIntoParts(line);
switch (divisionNo)
{
case 0:
if (PartsMatches(0, "IDENTIFICATION", "DIVISION"))
{
line = "namespace AVT\n{";
openNamespace = true;
divisionNo = 1;
}
break;
case 1:
if (PartsMatches(0, "PROGRAM-ID"))
{
line = "public class " + TokenAt(1) + "\n{";
openClass = true;
}
else if (PartsMatches(0, "ENVIRONMENT", "DIVISION"))
{
line = "// " + line;
divisionNo = 2;
}
else
{
line = "// " + line;
}
break;
case 2:
if (PartsMatches(0, "DATA", "DIVISION"))
{
line = "// " + line;
divisionNo = 3;
}
else
{
line = "// " + line;
}
break;
case 3:
if (PartsMatches(0, "PROCEDURE", "DIVISION"))
{
line = "// " + line;
divisionNo = 4;
}
else
{
line = "// " + line;
}
break;
case 4:
if (indent == 1)
{
if (PartsMatches(0, "WHENEVER-SECTION"))
{
line = "public void WheneverSection()\n{";
openMethod = true;
}
else if (currParts.Count > 1 && currParts[1].Equals("SECTION"))
{
if (openMethod)
line = "}\n\n";
else
line = "";
line += "public void " + Camelise(currParts[0]) + "()\n{";
openMethod = true;
}
else if (currParts.Count == 1)
{
line = Camelise(currParts[0]) + ":";
}
else
{
line = "// " + line;
}
}
else
{
if (sqlExecStarted)
{
if (Equals(0, "END-EXEC"))
{
line = ");";
sqlExecString = false;
sqlExecStarted = false;
}
else
{
if (sqlExecString)
{
line = string.Format("+ \"{0}\"", line.Trim().Replace("\"", "\\\""));
}
else
{
line = string.Format("\"{0}\"", line.Trim().Replace("\"", "\\\""));
}
sqlExecString = true;
}
}
else if (Equals(0, "EXIT"))
line = "return;";
else if (Equals(0, "SET"))
{
ReduceOF();
if (Equals(2, "TO") && CurrCount == 4)
line = string.Format("{0} = {1};", Camelise(TokenAt(1)), Camelise(TokenAt(3)));
else
line = "// " + line;
}
else if (Equals(0, "MOVE"))
{
ReduceOF();
if (Equals(2, "TO") && CurrCount == 4)
line = string.Format("{0} = {1};", Camelise(TokenAt(3)), Camelise(TokenAt(1)));
else
line = "// " + line;
}
else if (Equals(0, "STRING"))
{
ReduceOF();
ReduceSeq(0, null, "DELIMITED", "BY", "SIZE");
ReduceSeq(0, null, "DELIMITED", "BY", "SIZE,");
StringBuilder sb = new StringBuilder();
StringBuilder sba = new StringBuilder();
int ari = 0;
line = "// " + line;
for (int i = 1; i < currParts.Count; i++)
{
if (currParts[i].Equals("INTO"))
{
line = string.Format("{0} = string.Format(\"{1}\", {2});", Camelise(currParts[i+1]), sb.ToString(), sba.ToString().Replace(",,", ",").TrimEnd(','));
break;
}
else if (currParts[i].StartsWith("\""))
{
sb.Append(currParts[i].Trim('\"'));
}
else
{
sb.Append('{');
sb.Append(ari.ToString());
sb.Append('}');
sba.AppendFormat("{0},", Camelise(currParts[i]));
}
}
}
else if (Equals(0, "ENTER"))
{
ReduceOF();
line = ProcessProcCall(line, "ENTER", "Enter");
}
else if (Equals(0, "CALL"))
{
ReduceOF();
line = ProcessProcCall(line, "CALL", "Call");
}
else if (Equals(0, "IF"))
{
ReduceOF();
ReduceConds(1);
StringBuilder sb = new StringBuilder();
sb.Clear();
sb.Append("if (");
for (int j = 1; j < currParts.Count; j++)
{
sb.AppendFormat(" {0}", Camelise(currParts[j]));
}
sb.Append(")\n{");
line = sb.ToString();
}
else if (Equals(0, "ELSE"))
{
line = "} else {";
}
else if (Equals(0, "END-IF"))
{
line = "}";
}
else if (Equals(0, "EXEC") && Equals(1, "SQL"))
{
sqlExecStarted = true;
sqlExecString = false;
if (CurrCount > 2)
{
StringBuilder sb = new StringBuilder();
sb.Append("Process.ExecSql(");
for (int k = 2; k < currParts.Count; k++)
{
sb.AppendFormat(" {0}", currParts[k]);
}
sb.Append("\"");
}
else
{
line = "Process.ExecSql(";
}
}
else if (Equals(0, "PERFORM") && CurrCount == 2)
line = string.Format("{0}();", Camelise(TokenAt(1)));
else if (PartsMatches(0, "STOP", "RUN"))
line = "return;";
else
{
if (line.Trim().Equals("."))
{
line = "";
}
else
{
line = "//= " + line;
}
}
}
break;
}
return line;
}
else
{
return string.Format("// {0}", line.Substring(1));
}
}
private bool sqlExecStarted = false;
private bool sqlExecString = false;
private string ProcessProcCall(string line, string ppn, string iMethod)
{
int mode = 0;
string method = iMethod;
string procname = null;
List<string> args = new List<string>();
string resName = null;
foreach (string s in currParts)
{
if (mode == 0)
{
if (s.Equals(ppn))
{
if (Equals(1, "TAL"))
{
method += "Tal";
mode = 10;
}
else
mode = 1;
}
if (s.Equals("USING"))
mode = 2;
if (s.Equals("GIVING"))
mode = 3;
}
else if (mode == 10)
{
mode = 1;
}
else if (mode == 1)
{
procname = s;
mode = 0;
}
else if (mode == 2)
{
if (s.Equals("GIVING"))
mode = 3;
else
{
string sh = Camelise(s);
if (sh.EndsWith(","))
sh = sh.Substring(0, sh.Length - 1);
args.Add(sh);
}
}
else if (mode == 3)
resName = Camelise(s);
}
StringBuilder sb = new StringBuilder();
if (resName != null)
sb.AppendFormat("{0} = ", resName);
sb.AppendFormat("Process.{0}({1}", method, procname);
foreach (string a in args)
{
sb.AppendFormat(", {0}", a);
}
sb.Append(");");
line = sb.ToString();
return line;
}
private int divisionNo = 0;
private StringBuilder currpart = new StringBuilder();
private bool openNamespace = false;
private bool openClass = false;
private bool openMethod = false;
private StringBuilder cameliseBuilder = new StringBuilder();
private int CurrCount
{
get { return currParts.Count; }
}
private string Camelise(string s)
{
cameliseBuilder.Clear();
if (s.IndexOf('-') < 0)
return s;
if (s.StartsWith("\""))
return s;
if (s.IndexOf(':') > 0)
{
int a = s.IndexOf('(');
int b = s.IndexOf(':');
int c = s.IndexOf(')');
if (a > 0 && b > a && c > b && c == s.Length - 1)
{
s = string.Format("{0}.Substring({1},{2})", s.Substring(0, a), s.Substring(a + 1, b - a - 1), s.Substring(b + 1, c - b - 1));
}
}
return s.Replace('-', '_');
}
private void ReduceConds(int i)
{
ReduceSeq(i, "!=", "NOT", "=");
ReduceSeq(i, "!=", "NOT", "EQUAL");
ReduceSeq(i, "==", "EQUAL");
ReduceSeq(i, "&&", "AND");
ReduceSeq(i, "||", "OR");
ReduceSeq(i, "==", "=");
}
private void ReduceSeq(int startIndex, string newValue, params string[] args)
{
for (int i = startIndex; i < currParts.Count - args.Length; i++)
{
if (PartsMatches(i, args))
{
currParts.RemoveRange(i, args.Length);
if (newValue != null)
currParts.Insert(i, newValue);
}
}
}
private void ReduceOF()
{
bool hit = false;
do
{
hit = false;
for (int i = currParts.Count - 2; i > 0; i--)
{
if (currParts[i].Equals("OF"))
{
string a = Camelise(currParts[i - 1]);
string b = Camelise(currParts[i + 1]);
string pref = "";
string post = "";
if (b.EndsWith(","))
{
post = "," + post;
b = b.Substring(0, b.Length - 1);
}
string s = string.Format("{0}.{1}", b, a);
currParts.RemoveRange(i - 1, 3);
currParts.Insert(i - 1, s);
hit = true;
}
}
} while (hit);
}
private string TokenAt(int i)
{
if (i >= currParts.Count)
return string.Empty;
return currParts[i];
}
private bool Equals(int i, string value)
{
if (i >= currParts.Count)
return false;
return currParts[i].Equals(value);
}
private bool PartsMatches(int startIndex, params string[] args)
{
if (args.Length > currParts.Count)
return false;
for (int i = startIndex; i < startIndex + args.Length; i++)
{
if (!currParts[i].Equals(args[i-startIndex]))
return false;
}
return true;
}
private int SplitIntoParts(string line)
{
StringBuilder sb = currpart;
List<string> tokens = currParts;
currpart.Clear();
currParts.Clear();
int mode = 0;
bool retry = false;
foreach (char c in line)
{
do
{
retry = false;
if (mode == 0) // ---
{
if (c == '(' || c == ')' || c == ',')
{
if (sb.Length > 0)
AddToken(sb);
sb.Clear();
AddToken(c);
}
else if (c == '\'')
{
sb.Append(c);
mode = 6;
}
else if (c == '"')
{
sb.Append(c);
mode = 2;
}
else if (Char.IsWhiteSpace(c))
{
}
else
{
sb.Append(c);
mode = 1;
}
}
else if (mode == 1) // --- identifier ---
{
if (Char.IsWhiteSpace(c))
{
AddToken(sb);
sb.Clear();
mode = 0;
}
else
{
sb.Append(c);
}
}
else if (mode == 2) // --- string ----
{
sb.Append(c);
if (c == '"')
{
mode = 201;
}
}
else if (mode == 201)
{
mode = ProcessCharInStringLiteral('\"', 2, sb, tokens, c);
retry = (mode == 0);
}
else if (mode == 6) // --- string ----
{
sb.Append(c);
if (c == '\'')
{
mode = 601;
}
}
else if (mode == 601)
{
mode = ProcessCharInStringLiteral('\'', 6, sb, tokens, c);
retry = (mode == 0);
}
} while (retry);
}
if (sb.Length > 0)
AddToken(sb);
return mode;
}
private void AddToken(object a)
{
string s = a.ToString().TrimEnd('.');
currParts.Add(s);
}
private int ProcessCharInStringLiteral(char ss, int remode, StringBuilder sb, List<string> tokens, char c)
{
if (c == ss)
{
sb.Append(c);
return remode;
}
else if (Char.IsWhiteSpace(c))
{
AddToken(sb);
sb.Clear();
}
return 0;
}
}
}
|
223c34a7cf1c28bc7250e9ea074f8c21236fab2f
|
C#
|
mmpranathi/skinet1
|
/API/Controllers/ProductsController.cs
| 2.59375
| 3
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Core.Entities;
using Core.Interfaces;
using Infrastructure.Data;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace API.Controllers
{
[ApiController]
[Route("api/[Controller]")]
public class ProductsController:ControllerBase
{
public IProductRepository _repo { get; }
public ProductsController(IProductRepository repo)
{
_repo = repo;
}
[HttpGet]
public async Task<ActionResult<List<Product>>> GetProducts(){
var products= await _repo.GetProductAsync();
return Ok(products);
}
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
return await _repo.GetProductByIdAsync(id);
}
[HttpGet("brands")]
public async Task<ActionResult<IReadOnlyList<ProductBand>>> GetProductBands(){
return Ok(await _repo.GetProductBandAsync());
}
[HttpGet("types")]
public async Task<ActionResult<IReadOnlyList<ProductType>>> GetProductTypes(){
return Ok(await _repo.GetProductTypeAsync());
}
}
}
|
052b2a5509ad4ad1c3101f4aaaf99a0cfa5d89bc
|
C#
|
rusleysantos/spaceways
|
/services/ManageUser/InsertUser.cs
| 2.796875
| 3
|
using data_source.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using web_spaceways.Models;
namespace services.ManageUser
{
public class InsertUser
{
/// <summary>
/// Metodo responsável por inserir usuário na base de dados.
/// </summary>
/// <param name="user">Usuário a ser inserido.</param>
/// <returns></returns>
public bool Inserir(User user)
{
var optionsBuilder = new DbContextOptions<EmployeeDbContext>();
try
{
using (var context = new EmployeeDbContext(optionsBuilder))
{
context.Add(user);
context.SaveChanges();
}
return true;
}
catch
{
return false;
}
}
}
}
|
792b280655160229cade56653c76442b61badf39
|
C#
|
jessalbesshero/DAR_Jesus
|
/Lab_3/leer_FIFO.cs
| 3.1875
| 3
|
using System;
/*Programa para Leer FIFO*/
public class leer_FIFO
{
public leer_FIFO()
{
}
int main(void){
int descriptor_archivo; /*Descriptor del FIFO*/
int num_bytes; /*Número de bytes leídos desde el FIFO*/
char buf[PIPE_BUF];
acde_t nodo = 8666;
if((mkfifo("fifo!", nodo)) < 0){
perror("mkfifo");
exit(EXIT_FAILURE);
}
/*Abrir el FIFO para solo lectura*/
if((descriptor_archivo = open("fifo!", O_RDONLY)) < 0){
perror("open");
exit(EXIT_FAILURE);
}
/*Leer el FIFO y mostrar su salida de datos hasta encontrar EOF*/
while([num_bytes = read(descriptor_archivo, buf, PIPE_BUF, 1)] > 0){
printf("leer_fifo leyo: %s", buff);
}
close(descriptor_archivo);
exit(EXIT_SUCCESS);
} /*Fin de leer_fifo*/
}
|